const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-B44w5nol.js","assets/useLeadSiteSearchSuggestions-fqQFd5L9.js","assets/CityPagesModule-CNrNqIfo.js","assets/imageOptimization-Csrlnz8M.js","assets/LeadSiteLuxuryHome-Ccm5ywM1.js","assets/LeadSiteLandRanchHome-CdftC7sf.js","assets/LeadSiteSearch-B7yGozJa.js","assets/LeadSiteListingCardImage-D3rbQpc1.js","assets/LeadSiteMap-BUbZ6KKG.js","assets/LeadSiteLuxurySearch-ARli2576.js","assets/LeadSiteListingDetail-vlQ28mlB.js","assets/ListingVideoTour-CbnMsALT.js","assets/useListingVideos-DdA15pbu.js","assets/LeadSiteLuxuryListingDetail-DmnNYjtm.js","assets/LeadSiteCityPage-CTglHG4J.js","assets/LeadSiteSubdivisionPage-CjviRCcE.js","assets/PublicLiveEvent-CbXgYQpP.js","assets/useLiveEngagement-CVr-HhoY.js","assets/LiveEventConsole-C7J-jO2H.js","assets/PostcardManager-CfSIQEZe.js","assets/usePostcardZones-B7HSe_-R.js","assets/DirectMail-Cfu_tgQa.js","assets/jspdf.es.min-BLM8Hy8p.js","assets/LeadSiteEditor-DoYRSZbg.js","assets/ImageUrlField-Ck991xmk.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-BjQxPhs5.js","assets/MLSListingDetail-D8GOvUhE.js","assets/EmailCampaignComposer-CU791KCb.js","assets/EditorModeSelector-Cy9tz7N5.js","assets/SharedCampaignTemplates-BLu5AaZE.js","assets/TemplateEditorDialog-BxCqQsvp.js","assets/AgentTemplates-ByH2_noi.js","assets/TheLocalMoveHome-BouUjk8k.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-D5OxXViE.js"])))=>i.map(i=>d[i]); var bTt=Object.defineProperty;var M7e=s=>{throw TypeError(s)};var _Tt=(s,t,n)=>t in s?bTt(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n;var Ma=(s,t,n)=>_Tt(s,typeof t!="symbol"?t+"":t,n),owe=(s,t,n)=>t.has(s)||M7e("Cannot "+n);var Zs=(s,t,n)=>(owe(s,t,"read from private field"),n?n.call(s):t.get(s)),Ui=(s,t,n)=>t.has(s)?M7e("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,n),qa=(s,t,n,r)=>(owe(s,t,"write to private field"),r?r.call(s,n):t.set(s,n),n),Yo=(s,t,n)=>(owe(s,t,"access private method"),n);var _V=(s,t,n,r)=>({set _(a){qa(s,t,a,n)},get _(){return Zs(s,t,r)}});function wTt(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 jTt="modulepreload",NTt=function(s){return"/"+s},I7e={},yi=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=NTt(c),c in I7e)return;I7e[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":jTt,d||(h.as="script"),h.crossOrigin="",h.href=c,o&&h.setAttribute("nonce",o),document.head.appendChild(h),d)return new Promise((p,f)=>{h.addEventListener("load",p),h.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=l,window.dispatchEvent(o),!o.defaultPrevented)throw l}return a.then(l=>{for(const o of l||[])o.status==="rejected"&&i(o.reason);return t().catch(i)})};var Eh=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function wl(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function kTt(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 ztt={exports:{}},d0e={},Btt={exports:{}},xl={};/** * @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 P$=Symbol.for("react.element"),STt=Symbol.for("react.portal"),CTt=Symbol.for("react.fragment"),TTt=Symbol.for("react.strict_mode"),ETt=Symbol.for("react.profiler"),ATt=Symbol.for("react.provider"),MTt=Symbol.for("react.context"),ITt=Symbol.for("react.forward_ref"),PTt=Symbol.for("react.suspense"),LTt=Symbol.for("react.memo"),DTt=Symbol.for("react.lazy"),P7e=Symbol.iterator;function RTt(s){return s===null||typeof s!="object"?null:(s=P7e&&s[P7e]||s["@@iterator"],typeof s=="function"?s:null)}var $tt={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Utt=Object.assign,qtt={};function kD(s,t,n){this.props=s,this.context=t,this.refs=qtt,this.updater=n||$tt}kD.prototype.isReactComponent={};kD.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")};kD.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function Vtt(){}Vtt.prototype=kD.prototype;function dEe(s,t,n){this.props=s,this.context=t,this.refs=qtt,this.updater=n||$tt}var uEe=dEe.prototype=new Vtt;uEe.constructor=dEe;Utt(uEe,kD.prototype);uEe.isPureReactComponent=!0;var L7e=Array.isArray,Htt=Object.prototype.hasOwnProperty,hEe={current:null},Gtt={key:!0,ref:!0,__self:!0,__source:!0};function Wtt(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)Htt.call(t,r)&&!Gtt.hasOwnProperty(r)&&(a[r]=t[r]);var o=arguments.length-2;if(o===1)a.children=n;else if(1>>1,ve=he[le];if(0>>1;lea(Me,pe))Cea(Ae,Me)?(he[le]=Ae,he[Ce]=pe,le=Ce):(he[le]=Me,he[Te]=pe,le=Te);else if(Cea(Ae,pe))he[le]=Ae,he[Ce]=pe,le=Ce;else break e}}return ce}function a(he,ce){var pe=he.sortIndex-ce.sortIndex;return pe!==0?pe:he.id-ce.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;s.unstable_now=function(){return i.now()}}else{var l=Date,o=l.now();s.unstable_now=function(){return l.now()-o}}var c=[],d=[],u=1,h=null,p=3,f=!1,g=!1,_=!1,v=typeof setTimeout=="function"?setTimeout:null,j=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function S(he){for(var ce=n(d);ce!==null;){if(ce.callback===null)r(d);else if(ce.startTime<=he)r(d),ce.sortIndex=ce.expirationTime,t(c,ce);else break;ce=n(d)}}function A(he){if(_=!1,S(he),!g)if(n(c)!==null)g=!0,ne(T);else{var ce=n(d);ce!==null&&ie(A,ce.startTime-he)}}function T(he,ce){g=!1,_&&(_=!1,j(M),M=-1),f=!0;var pe=p;try{for(S(ce),h=n(c);h!==null&&(!(h.expirationTime>ce)||he&&!V());){var le=h.callback;if(typeof le=="function"){h.callback=null,p=h.priorityLevel;var ve=le(h.expirationTime<=ce);ce=s.unstable_now(),typeof ve=="function"?h.callback=ve:h===n(c)&&r(c),S(ce)}else r(c);h=n(c)}if(h!==null)var ge=!0;else{var Te=n(d);Te!==null&&ie(A,Te.startTime-ce),ge=!1}return ge}finally{h=null,p=pe,f=!1}}var L=!1,D=null,M=-1,F=5,z=-1;function V(){return!(s.unstable_now()-zhe||125le?(he.sortIndex=pe,t(d,he),n(c)===null&&he===n(d)&&(_?(j(M),M=-1):_=!0,ie(A,pe-le))):(he.sortIndex=ve,t(c,he),g||f||(g=!0,ne(T))),he},s.unstable_shouldYield=V,s.unstable_wrapCallback=function(he){var ce=p;return function(){var pe=p;p=ce;try{return he.apply(this,arguments)}finally{p=pe}}}})(Xtt);Qtt.exports=Xtt;var P7=Qtt.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 WTt=N,vy=P7;function Kr(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"),$ke=Object.prototype.hasOwnProperty,KTt=/^[: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]*$/,R7e={},O7e={};function YTt(s){return $ke.call(O7e,s)?!0:$ke.call(R7e,s)?!1:KTt.test(s)?O7e[s]=!0:(R7e[s]=!0,!1)}function ZTt(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 QTt(s,t,n,r){if(t===null||typeof t>"u"||ZTt(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 og(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 jf={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){jf[s]=new og(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];jf[t]=new og(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){jf[s]=new og(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){jf[s]=new og(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){jf[s]=new og(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){jf[s]=new og(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){jf[s]=new og(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){jf[s]=new og(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){jf[s]=new og(s,5,!1,s.toLowerCase(),null,!1,!1)});var fEe=/[\-:]([a-z])/g;function xEe(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(fEe,xEe);jf[t]=new og(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(fEe,xEe);jf[t]=new og(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(fEe,xEe);jf[t]=new og(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){jf[s]=new og(s,1,!1,s.toLowerCase(),null,!1,!1)});jf.xlinkHref=new og("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){jf[s]=new og(s,1,!1,s.toLowerCase(),null,!0,!0)});function gEe(s,t,n,r){var a=jf.hasOwnProperty(t)?jf[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{dwe=!1,Error.prepareStackTrace=n}return(s=s?s.displayName||s.name:"")?r7(s):""}function XTt(s){switch(s.tag){case 5:return r7(s.type);case 16:return r7("Lazy");case 13:return r7("Suspense");case 19:return r7("SuspenseList");case 0:case 2:case 15:return s=uwe(s.type,!1),s;case 11:return s=uwe(s.type.render,!1),s;case 1:return s=uwe(s.type,!0),s;default:return""}}function Hke(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 pP:return"Fragment";case mP:return"Portal";case Uke:return"Profiler";case yEe:return"StrictMode";case qke:return"Suspense";case Vke:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case tst:return(s.displayName||"Context")+".Consumer";case est:return(s._context.displayName||"Context")+".Provider";case vEe:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case bEe:return t=s.displayName||null,t!==null?t:Hke(s.type)||"Memo";case Gk:t=s._payload,s=s._init;try{return Hke(s(t))}catch{}}return null}function JTt(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 Hke(t);case 8:return t===yEe?"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 N4(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function nst(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function eEt(s){var t=nst(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 NV(s){s._valueTracker||(s._valueTracker=eEt(s))}function rst(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return s&&(r=nst(s)?s.checked?"true":"false":s.value),s=r,s!==n?(t.setValue(s),!0):!1}function bpe(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 Gke(s,t){var n=t.checked;return $u({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??s._wrapperState.initialChecked})}function z7e(s,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=N4(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 ast(s,t){t=t.checked,t!=null&&gEe(s,"checked",t,!1)}function Wke(s,t){ast(s,t);var n=N4(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")?Kke(s,t.type,n):t.hasOwnProperty("defaultValue")&&Kke(s,t.type,N4(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function B7e(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 Kke(s,t,n){(t!=="number"||bpe(s.ownerDocument)!==s)&&(n==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+n&&(s.defaultValue=""+n))}var a7=Array.isArray;function VP(s,t,n,r){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=kV.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function Rz(s,t){if(t){var n=s.firstChild;if(n&&n===s.lastChild&&n.nodeType===3){n.nodeValue=t;return}}s.textContent=t}var L7={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},tEt=["Webkit","ms","Moz","O"];Object.keys(L7).forEach(function(s){tEt.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),L7[t]=L7[s]})});function cst(s,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||L7.hasOwnProperty(s)&&L7[s]?(""+t).trim():t+"px"}function dst(s,t){s=s.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,a=cst(n,t[n],r);n==="float"&&(n="cssFloat"),r?s.setProperty(n,a):s[n]=a}}var sEt=$u({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 Qke(s,t){if(t){if(sEt[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Kr(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Kr(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Kr(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Kr(62))}}function Xke(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 Jke=null;function _Ee(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var eSe=null,HP=null,GP=null;function q7e(s){if(s=R$(s)){if(typeof eSe!="function")throw Error(Kr(280));var t=s.stateNode;t&&(t=f0e(t),eSe(s.stateNode,s.type,t))}}function ust(s){HP?GP?GP.push(s):GP=[s]:HP=s}function hst(){if(HP){var s=HP,t=GP;if(GP=HP=null,q7e(s),t)for(s=0;s>>=0,s===0?32:31-(mEt(s)/pEt|0)|0}var SV=64,CV=4194304;function i7(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 Npe(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=i7(o):(i&=l,i!==0&&(r=i7(i)))}else l=n&~a,l!==0?r=i7(l):i!==0&&(r=i7(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 L$(s,t,n){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-db(t),s[t]=n}function yEt(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=R7),X7e=" ",J7e=!1;function Ist(s,t){switch(s){case"keyup":return GEt.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Pst(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var fP=!1;function KEt(s,t){switch(s){case"compositionend":return Pst(t);case"keypress":return t.which!==32?null:(J7e=!0,X7e);case"textInput":return s=t.data,s===X7e&&J7e?null:s;default:return null}}function YEt(s,t){if(fP)return s==="compositionend"||!EEe&&Ist(s,t)?(s=Ast(),fW=SEe=TS=null,fP=!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=n9e(n)}}function Ost(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?Ost(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function Fst(){for(var s=window,t=bpe();t instanceof s.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)s=t.contentWindow;else break;t=bpe(s.document)}return t}function AEe(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 rAt(s){var t=Fst(),n=s.focusedElem,r=s.selectionRange;if(t!==n&&n&&n.ownerDocument&&Ost(n.ownerDocument.documentElement,n)){if(r!==null&&AEe(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=r9e(n,i);var l=r9e(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,xP=null,iSe=null,F7=null,oSe=!1;function a9e(s,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;oSe||xP==null||xP!==bpe(r)||(r=xP,"selectionStart"in r&&AEe(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}),F7&&Uz(F7,r)||(F7=r,r=Cpe(iSe,"onSelect"),0vP||(s.current=mSe[vP],mSe[vP]=null,vP--)}function bd(s,t){vP++,mSe[vP]=s.current,s.current=t}var k4={},nx=q4(k4),Bg=q4(!1),oM=k4;function c8(s,t){var n=s.type.contextTypes;if(!n)return k4;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 $g(s){return s=s.childContextTypes,s!=null}function Epe(){Bd(Bg),Bd(nx)}function h9e(s,t,n){if(nx.current!==k4)throw Error(Kr(168));bd(nx,t),bd(Bg,n)}function Wst(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(Kr(108,JTt(s)||"Unknown",a));return $u({},n,r)}function Ape(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||k4,oM=nx.current,bd(nx,s),bd(Bg,Bg.current),!0}function m9e(s,t,n){var r=s.stateNode;if(!r)throw Error(Kr(169));n?(s=Wst(s,t,oM),r.__reactInternalMemoizedMergedChildContext=s,Bd(Bg),Bd(nx),bd(nx,s)):Bd(Bg),bd(Bg,n)}var S2=null,x0e=!1,kwe=!1;function Kst(s){S2===null?S2=[s]:S2.push(s)}function xAt(s){x0e=!0,Kst(s)}function V4(){if(!kwe&&S2!==null){kwe=!0;var s=0,t=Lc;try{var n=S2;for(Lc=1;s>=l,a-=l,L2=1<<32-db(t)+a|n<M?(F=D,D=null):F=D.sibling;var z=p(j,D,S[M],A);if(z===null){D===null&&(D=F);break}s&&D&&z.alternate===null&&t(j,D),b=i(z,b,M),L===null?T=z:L.sibling=z,L=z,D=F}if(M===S.length)return n(j,D),ou&&w3(j,M),T;if(D===null){for(;MM?(F=D,D=null):F=D.sibling;var V=p(j,D,z.value,A);if(V===null){D===null&&(D=F);break}s&&D&&V.alternate===null&&t(j,D),b=i(V,b,M),L===null?T=V:L.sibling=V,L=V,D=F}if(z.done)return n(j,D),ou&&w3(j,M),T;if(D===null){for(;!z.done;M++,z=S.next())z=h(j,z.value,A),z!==null&&(b=i(z,b,M),L===null?T=z:L.sibling=z,L=z);return ou&&w3(j,M),T}for(D=r(j,D);!z.done;M++,z=S.next())z=f(D,j,M,z.value,A),z!==null&&(s&&z.alternate!==null&&D.delete(z.key===null?M:z.key),b=i(z,b,M),L===null?T=z:L.sibling=z,L=z);return s&&D.forEach(function(W){return t(j,W)}),ou&&w3(j,M),T}function v(j,b,S,A){if(typeof S=="object"&&S!==null&&S.type===pP&&S.key===null&&(S=S.props.children),typeof S=="object"&&S!==null){switch(S.$$typeof){case jV:e:{for(var T=S.key,L=b;L!==null;){if(L.key===T){if(T=S.type,T===pP){if(L.tag===7){n(j,L.sibling),b=a(L,S.props.children),b.return=j,j=b;break e}}else if(L.elementType===T||typeof T=="object"&&T!==null&&T.$$typeof===Gk&&x9e(T)===L.type){n(j,L.sibling),b=a(L,S.props),b.ref=YO(j,L,S),b.return=j,j=b;break e}n(j,L);break}else t(j,L);L=L.sibling}S.type===pP?(b=vA(S.props.children,j.mode,A,S.key),b.return=j,j=b):(A=jW(S.type,S.key,S.props,null,j.mode,A),A.ref=YO(j,b,S),A.return=j,j=A)}return l(j);case mP:e:{for(L=S.key;b!==null;){if(b.key===L)if(b.tag===4&&b.stateNode.containerInfo===S.containerInfo&&b.stateNode.implementation===S.implementation){n(j,b.sibling),b=a(b,S.children||[]),b.return=j,j=b;break e}else{n(j,b);break}else t(j,b);b=b.sibling}b=Pwe(S,j.mode,A),b.return=j,j=b}return l(j);case Gk:return L=S._init,v(j,b,L(S._payload),A)}if(a7(S))return g(j,b,S,A);if(VO(S))return _(j,b,S,A);LV(j,S)}return typeof S=="string"&&S!==""||typeof S=="number"?(S=""+S,b!==null&&b.tag===6?(n(j,b.sibling),b=a(b,S),b.return=j,j=b):(n(j,b),b=Iwe(S,j.mode,A),b.return=j,j=b),l(j)):n(j,b)}return v}var u8=Xst(!0),Jst=Xst(!1),Ppe=q4(null),Lpe=null,wP=null,LEe=null;function DEe(){LEe=wP=Lpe=null}function REe(s){var t=Ppe.current;Bd(Ppe),s._currentValue=t}function xSe(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 KP(s,t){Lpe=s,LEe=wP=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(Dg=!0),s.firstContext=null)}function Hv(s){var t=s._currentValue;if(LEe!==s)if(s={context:s,memoizedValue:t,next:null},wP===null){if(Lpe===null)throw Error(Kr(308));wP=s,Lpe.dependencies={lanes:0,firstContext:s}}else wP=wP.next=s;return t}var VE=null;function OEe(s){VE===null?VE=[s]:VE.push(s)}function ent(s,t,n,r){var a=t.interleaved;return a===null?(n.next=n,OEe(t)):(n.next=a.next,a.next=n),t.interleaved=n,cN(s,r)}function cN(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 Wk=!1;function FEe(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function tnt(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 V2(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function qS(s,t,n){var r=s.updateQueue;if(r===null)return null;if(r=r.shared,Ul&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,cN(s,n)}return a=r.interleaved,a===null?(t.next=t,OEe(r)):(t.next=a.next,a.next=t),r.interleaved=t,cN(s,n)}function gW(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,jEe(s,n)}}function g9e(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 Dpe(s,t,n,r){var a=s.updateQueue;Wk=!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 p=o.lane,f=o.eventTime;if((r&p)===p){u!==null&&(u=u.next={eventTime:f,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var g=s,_=o;switch(p=t,f=n,_.tag){case 1:if(g=_.payload,typeof g=="function"){h=g.call(f,h,p);break e}h=g;break e;case 3:g.flags=g.flags&-65537|128;case 0:if(g=_.payload,p=typeof g=="function"?g.call(f,h,p):g,p==null)break e;h=$u({},h,p);break e;case 2:Wk=!0}}o.callback!==null&&o.lane!==0&&(s.flags|=64,p=a.effects,p===null?a.effects=[o]:p.push(o))}else f={eventTime:f,lane:p,tag:o.tag,payload:o.payload,callback:o.callback,next:null},u===null?(d=u=f,c=h):u=u.next=f,l|=p;if(o=o.next,o===null){if(o=a.shared.pending,o===null)break;p=o,o=p.next,p.next=null,a.lastBaseUpdate=p,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);dM|=l,s.lanes=l,s.memoizedState=h}}function y9e(s,t,n){if(s=t.effects,t.effects=null,s!==null)for(t=0;tn?n:4,s(!0);var r=Cwe.transition;Cwe.transition={};try{s(!1),t()}finally{Lc=n,Cwe.transition=r}}function ynt(){return Gv().memoizedState}function bAt(s,t,n){var r=HS(s);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},vnt(s))bnt(t,n);else if(n=ent(s,t,n,r),n!==null){var a=tg();ub(n,s,r,a),_nt(n,t,r)}}function _At(s,t,n){var r=HS(s),a={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(vnt(s))bnt(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,Sb(o,l)){var c=t.interleaved;c===null?(a.next=a,OEe(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}n=ent(s,t,a,r),n!==null&&(a=tg(),ub(n,s,r,a),_nt(n,t,r))}}function vnt(s){var t=s.alternate;return s===Du||t!==null&&t===Du}function bnt(s,t){z7=Ope=!0;var n=s.pending;n===null?t.next=t:(t.next=n.next,n.next=t),s.pending=t}function _nt(s,t,n){if(n&4194240){var r=t.lanes;r&=s.pendingLanes,n|=r,t.lanes=n,jEe(s,n)}}var Fpe={readContext:Hv,useCallback:Vf,useContext:Vf,useEffect:Vf,useImperativeHandle:Vf,useInsertionEffect:Vf,useLayoutEffect:Vf,useMemo:Vf,useReducer:Vf,useRef:Vf,useState:Vf,useDebugValue:Vf,useDeferredValue:Vf,useTransition:Vf,useMutableSource:Vf,useSyncExternalStore:Vf,useId:Vf,unstable_isNewReconciler:!1},wAt={readContext:Hv,useCallback:function(s,t){return F_().memoizedState=[s,t===void 0?null:t],s},useContext:Hv,useEffect:b9e,useImperativeHandle:function(s,t,n){return n=n!=null?n.concat([s]):null,vW(4194308,4,mnt.bind(null,t,s),n)},useLayoutEffect:function(s,t){return vW(4194308,4,s,t)},useInsertionEffect:function(s,t){return vW(4,2,s,t)},useMemo:function(s,t){var n=F_();return t=t===void 0?null:t,s=s(),n.memoizedState=[s,t],s},useReducer:function(s,t,n){var r=F_();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=bAt.bind(null,Du,s),[r.memoizedState,s]},useRef:function(s){var t=F_();return s={current:s},t.memoizedState=s},useState:v9e,useDebugValue:GEe,useDeferredValue:function(s){return F_().memoizedState=s},useTransition:function(){var s=v9e(!1),t=s[0];return s=vAt.bind(null,s[1]),F_().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,n){var r=Du,a=F_();if(ou){if(n===void 0)throw Error(Kr(407));n=n()}else{if(n=t(),Sp===null)throw Error(Kr(349));cM&30||ant(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,b9e(ont.bind(null,r,i,s),[s]),r.flags|=2048,Zz(9,int.bind(null,r,i,n,t),void 0,null),n},useId:function(){var s=F_(),t=Sp.identifierPrefix;if(ou){var n=D2,r=L2;n=(r&~(1<<32-db(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Kz++,0<\/script>",s=s.removeChild(s.firstChild)):typeof r.is=="string"?s=l.createElement(n,{is:r.is}):(s=l.createElement(n),n==="select"&&(l=s,r.multiple?l.multiple=!0:r.size&&(l.size=r.size))):s=l.createElementNS(s,n),s[X_]=t,s[Hz]=r,Mnt(s,t,!1,!1),t.stateNode=s;e:{switch(l=Xke(n,r),n){case"dialog":Pd("cancel",s),Pd("close",s),a=r;break;case"iframe":case"object":case"embed":Pd("load",s),a=r;break;case"video":case"audio":for(a=0;ap8&&(t.flags|=128,r=!0,ZO(i,!1),t.lanes=4194304)}else{if(!r)if(s=Rpe(l),s!==null){if(t.flags|=128,r=!0,n=s.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),ZO(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!ou)return Hf(t),null}else 2*Ch()-i.renderingStartTime>p8&&n!==1073741824&&(t.flags|=128,r=!0,ZO(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=Ch(),t.sibling=null,n=Tu.current,bd(Tu,r?n&1|2:n&1),t):(Hf(t),null);case 22:case 23:return XEe(),r=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?U0&1073741824&&(Hf(t),t.subtreeFlags&6&&(t.flags|=8192)):Hf(t),null;case 24:return null;case 25:return null}throw Error(Kr(156,t.tag))}function AAt(s,t){switch(IEe(t),t.tag){case 1:return $g(t.type)&&Epe(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return h8(),Bd(Bg),Bd(nx),$Ee(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return BEe(t),null;case 13:if(Bd(Tu),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error(Kr(340));d8()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return Bd(Tu),null;case 4:return h8(),null;case 10:return REe(t.type._context),null;case 22:case 23:return XEe(),null;case 24:return null;default:return null}}var RV=!1,Zf=!1,MAt=typeof WeakSet=="function"?WeakSet:Set,ti=null;function jP(s,t){var n=s.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){nh(s,t,r)}else n.current=null}function kSe(s,t,n){try{n()}catch(r){nh(s,t,r)}}var M9e=!1;function IAt(s,t){if(lSe=kpe,s=Fst(),AEe(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,p=null;t:for(;;){for(var f;h!==n||a!==0&&h.nodeType!==3||(o=l+a),h!==i||r!==0&&h.nodeType!==3||(c=l+r),h.nodeType===3&&(l+=h.nodeValue.length),(f=h.firstChild)!==null;)p=h,h=f;for(;;){if(h===s)break t;if(p===n&&++d===a&&(o=l),p===i&&++u===r&&(c=l),(f=h.nextSibling)!==null)break;h=p,p=h.parentNode}h=f}n=o===-1||c===-1?null:{start:o,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(cSe={focusedElem:s,selectionRange:n},kpe=!1,ti=t;ti!==null;)if(t=ti,s=t.child,(t.subtreeFlags&1028)!==0&&s!==null)s.return=t,ti=s;else for(;ti!==null;){t=ti;try{var g=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var _=g.memoizedProps,v=g.memoizedState,j=t.stateNode,b=j.getSnapshotBeforeUpdate(t.elementType===t.type?_:H1(t.type,_),v);j.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var S=t.stateNode.containerInfo;S.nodeType===1?S.textContent="":S.nodeType===9&&S.documentElement&&S.removeChild(S.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Kr(163))}}catch(A){nh(t,t.return,A)}if(s=t.sibling,s!==null){s.return=t.return,ti=s;break}ti=t.return}return g=M9e,M9e=!1,g}function B7(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&&kSe(t,n,i)}a=a.next}while(a!==r)}}function v0e(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 SSe(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 Lnt(s){var t=s.alternate;t!==null&&(s.alternate=null,Lnt(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[X_],delete t[Hz],delete t[hSe],delete t[pAt],delete t[fAt])),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 Dnt(s){return s.tag===5||s.tag===3||s.tag===4}function I9e(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||Dnt(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 CSe(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=Tpe));else if(r!==4&&(s=s.child,s!==null))for(CSe(s,t,n),s=s.sibling;s!==null;)CSe(s,t,n),s=s.sibling}function TSe(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(TSe(s,t,n),s=s.sibling;s!==null;)TSe(s,t,n),s=s.sibling}var Jp=null,K1=!1;function bk(s,t,n){for(n=n.child;n!==null;)Rnt(s,t,n),n=n.sibling}function Rnt(s,t,n){if(uw&&typeof uw.onCommitFiberUnmount=="function")try{uw.onCommitFiberUnmount(u0e,n)}catch{}switch(n.tag){case 5:Zf||jP(n,t);case 6:var r=Jp,a=K1;Jp=null,bk(s,t,n),Jp=r,K1=a,Jp!==null&&(K1?(s=Jp,n=n.stateNode,s.nodeType===8?s.parentNode.removeChild(n):s.removeChild(n)):Jp.removeChild(n.stateNode));break;case 18:Jp!==null&&(K1?(s=Jp,n=n.stateNode,s.nodeType===8?Nwe(s.parentNode,n):s.nodeType===1&&Nwe(s,n),Bz(s)):Nwe(Jp,n.stateNode));break;case 4:r=Jp,a=K1,Jp=n.stateNode.containerInfo,K1=!0,bk(s,t,n),Jp=r,K1=a;break;case 0:case 11:case 14:case 15:if(!Zf&&(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)&&kSe(n,t,l),a=a.next}while(a!==r)}bk(s,t,n);break;case 1:if(!Zf&&(jP(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){nh(n,t,o)}bk(s,t,n);break;case 21:bk(s,t,n);break;case 22:n.mode&1?(Zf=(r=Zf)||n.memoizedState!==null,bk(s,t,n),Zf=r):bk(s,t,n);break;default:bk(s,t,n)}}function P9e(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var n=s.stateNode;n===null&&(n=s.stateNode=new MAt),t.forEach(function(r){var a=$At.bind(null,s,r);n.has(r)||(n.add(r),r.then(a,a))})}}function R1(s,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=l),r&=~i}if(r=a,r=Ch()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*LAt(r/1960))-r,10s?16:s,ES===null)var r=!1;else{if(s=ES,ES=null,$pe=0,Ul&6)throw Error(Kr(331));var a=Ul;for(Ul|=4,ti=s.current;ti!==null;){var i=ti,l=i.child;if(ti.flags&16){var o=i.deletions;if(o!==null){for(var c=0;cCh()-ZEe?yA(s,0):YEe|=n),Ug(s,t)}function Vnt(s,t){t===0&&(s.mode&1?(t=CV,CV<<=1,!(CV&130023424)&&(CV=4194304)):t=1);var n=tg();s=cN(s,t),s!==null&&(L$(s,t,n),Ug(s,n))}function BAt(s){var t=s.memoizedState,n=0;t!==null&&(n=t.retryLane),Vnt(s,n)}function $At(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(Kr(314))}r!==null&&r.delete(t),Vnt(s,n)}var Hnt;Hnt=function(s,t,n){if(s!==null)if(s.memoizedProps!==t.pendingProps||Bg.current)Dg=!0;else{if(!(s.lanes&n)&&!(t.flags&128))return Dg=!1,TAt(s,t,n);Dg=!!(s.flags&131072)}else Dg=!1,ou&&t.flags&1048576&&Yst(t,Ipe,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;bW(s,t),s=t.pendingProps;var a=c8(t,nx.current);KP(t,n),a=qEe(null,t,r,s,a,n);var i=VEe();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,$g(r)?(i=!0,Ape(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,FEe(t),a.updater=y0e,t.stateNode=a,a._reactInternals=t,ySe(t,r,s,n),t=_Se(null,t,r,!0,i,n)):(t.tag=0,ou&&i&&MEe(t),Ux(null,t,a,n),t=t.child),t;case 16:r=t.elementType;e:{switch(bW(s,t),s=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=qAt(r),s=H1(r,s),a){case 0:t=bSe(null,t,r,s,n);break e;case 1:t=T9e(null,t,r,s,n);break e;case 11:t=S9e(null,t,r,s,n);break e;case 14:t=C9e(null,t,r,H1(r.type,s),n);break e}throw Error(Kr(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:H1(r,a),bSe(s,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:H1(r,a),T9e(s,t,r,a,n);case 3:e:{if(Tnt(t),s===null)throw Error(Kr(387));r=t.pendingProps,i=t.memoizedState,a=i.element,tnt(s,t),Dpe(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=m8(Error(Kr(423)),t),t=E9e(s,t,r,n,a);break e}else if(r!==a){a=m8(Error(Kr(424)),t),t=E9e(s,t,r,n,a);break e}else for(ey=US(t.stateNode.containerInfo.firstChild),ty=t,ou=!0,eb=null,n=Jst(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(d8(),r===a){t=dN(s,t,n);break e}Ux(s,t,r,n)}t=t.child}return t;case 5:return snt(t),s===null&&fSe(t),r=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,dSe(r,a)?l=null:i!==null&&dSe(r,i)&&(t.flags|=32),Cnt(s,t),Ux(s,t,l,n),t.child;case 6:return s===null&&fSe(t),null;case 13:return Ent(s,t,n);case 4:return zEe(t,t.stateNode.containerInfo),r=t.pendingProps,s===null?t.child=u8(t,null,r,n):Ux(s,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:H1(r,a),S9e(s,t,r,a,n);case 7:return Ux(s,t,t.pendingProps,n),t.child;case 8:return Ux(s,t,t.pendingProps.children,n),t.child;case 12:return Ux(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,bd(Ppe,r._currentValue),r._currentValue=l,i!==null)if(Sb(i.value,l)){if(i.children===a.children&&!Bg.current){t=dN(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=V2(-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),xSe(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(Kr(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),xSe(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}Ux(s,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,KP(t,n),a=Hv(a),r=r(a),t.flags|=1,Ux(s,t,r,n),t.child;case 14:return r=t.type,a=H1(r,t.pendingProps),a=H1(r.type,a),C9e(s,t,r,a,n);case 15:return knt(s,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:H1(r,a),bW(s,t),t.tag=1,$g(r)?(s=!0,Ape(t)):s=!1,KP(t,n),wnt(t,r,a),ySe(t,r,a,n),_Se(null,t,r,!0,s,n);case 19:return Ant(s,t,n);case 22:return Snt(s,t,n)}throw Error(Kr(156,t.tag))};function Gnt(s,t){return vst(s,t)}function UAt(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 Tv(s,t,n,r){return new UAt(s,t,n,r)}function eAe(s){return s=s.prototype,!(!s||!s.isReactComponent)}function qAt(s){if(typeof s=="function")return eAe(s)?1:0;if(s!=null){if(s=s.$$typeof,s===vEe)return 11;if(s===bEe)return 14}return 2}function GS(s,t){var n=s.alternate;return n===null?(n=Tv(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 jW(s,t,n,r,a,i){var l=2;if(r=s,typeof s=="function")eAe(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case pP:return vA(n.children,a,i,t);case yEe:l=8,a|=8;break;case Uke:return s=Tv(12,n,t,a|2),s.elementType=Uke,s.lanes=i,s;case qke:return s=Tv(13,n,t,a),s.elementType=qke,s.lanes=i,s;case Vke:return s=Tv(19,n,t,a),s.elementType=Vke,s.lanes=i,s;case sst:return _0e(n,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case est:l=10;break e;case tst:l=9;break e;case vEe:l=11;break e;case bEe:l=14;break e;case Gk:l=16,r=null;break e}throw Error(Kr(130,s==null?s:typeof s,""))}return t=Tv(l,n,t,a),t.elementType=s,t.type=r,t.lanes=i,t}function vA(s,t,n,r){return s=Tv(7,s,r,t),s.lanes=n,s}function _0e(s,t,n,r){return s=Tv(22,s,r,t),s.elementType=sst,s.lanes=n,s.stateNode={isHidden:!1},s}function Iwe(s,t,n){return s=Tv(6,s,null,t),s.lanes=n,s}function Pwe(s,t,n){return t=Tv(4,s.children!==null?s.children:[],s.key,t),t.lanes=n,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function VAt(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=mwe(0),this.expirationTimes=mwe(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=mwe(0),this.identifierPrefix=r,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function tAe(s,t,n,r,a,i,l,o,c){return s=new VAt(s,t,n,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Tv(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},FEe(i),s}function HAt(s,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Znt)}catch(s){console.error(s)}}Znt(),Ztt.exports=Ny;var Hx=Ztt.exports;const aAe=wl(Hx);var Qnt,$9e=Hx;Qnt=$9e.createRoot,$9e.hydrateRoot;const ZAt=1,QAt=1e6;let Lwe=0;function XAt(){return Lwe=(Lwe+1)%Number.MAX_SAFE_INTEGER,Lwe.toString()}const Dwe=new Map,U9e=s=>{if(Dwe.has(s))return;const t=setTimeout(()=>{Dwe.delete(s),q7({type:"REMOVE_TOAST",toastId:s})},QAt);Dwe.set(s,t)},JAt=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,ZAt)};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?U9e(n):s.toasts.forEach(r=>{U9e(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)}}},NW=[];let kW={toasts:[]};function q7(s){kW=JAt(kW,s),NW.forEach(t=>{t(kW)})}function Pr({...s}){const t=XAt(),n=a=>q7({type:"UPDATE_TOAST",toast:{...a,id:t}}),r=()=>q7({type:"DISMISS_TOAST",toastId:t});return q7({type:"ADD_TOAST",toast:{...s,id:t,open:!0,onOpenChange:a=>{a||r()}}}),{id:t,dismiss:r,update:n}}function Ba(){const[s,t]=N.useState(kW);return N.useEffect(()=>(NW.push(t),()=>{const n=NW.indexOf(t);n>-1&&NW.splice(n,1)}),[s]),{...s,toast:Pr,dismiss:n=>q7({type:"DISMISS_TOAST",toastId:n})}}function _r(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 q9e(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function uN(...s){return t=>{let n=!1;const r=s.map(a=>{const i=q9e(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{children:l,...o}=i,c=N.useMemo(()=>o,Object.values(o));return e.jsx(n.Provider,{value:c,children:l})};r.displayName=s+"Provider";function a(i){const l=N.useContext(n);if(l)return l;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${s}\``)}return[r,a]}function pu(s,t=[]){let n=[];function r(i,l){const o=N.createContext(l),c=n.length;n=[...n,l];const d=h=>{var j;const{scope:p,children:f,...g}=h,_=((j=p==null?void 0:p[s])==null?void 0:j[c])||o,v=N.useMemo(()=>g,Object.values(g));return e.jsx(_.Provider,{value:v,children:f})};d.displayName=i+"Provider";function u(h,p){var _;const f=((_=p==null?void 0:p[s])==null?void 0:_[c])||o,g=N.useContext(f);if(g)return g;if(l!==void 0)return l;throw new Error(`\`${h}\` must be used within \`${i}\``)}return[d,u]}const a=()=>{const i=n.map(l=>N.createContext(l));return function(o){const c=(o==null?void 0:o[s])||i;return N.useMemo(()=>({[`__scope${s}`]:{...o,[s]:c}}),[o,c])}};return a.scopeName=s,[r,tMt(a,...t)]}function tMt(...s){const t=s[0];if(s.length===1)return t;const n=()=>{const r=s.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(i){const l=r.reduce((o,{useScope:c,scopeName:d})=>{const h=c(i)[`__scope${d}`];return{...o,...h}},{});return N.useMemo(()=>({[`__scope${t.scopeName}`]:l}),[l])}};return n.scopeName=t.scopeName,n}function S4(s){const t=sMt(s),n=N.forwardRef((r,a)=>{const{children:i,...l}=r,o=N.Children.toArray(i),c=o.find(nMt);if(c){const d=c.props.children,u=o.map(h=>h===c?N.Children.count(d)>1?N.Children.only(null):N.isValidElement(d)?d.props.children:null:h);return e.jsx(t,{...l,ref:a,children:N.isValidElement(d)?N.cloneElement(d,void 0,u):null})}return e.jsx(t,{...l,ref:a,children:i})});return n.displayName=`${s}.Slot`,n}var iAe=S4("Slot");function sMt(s){const t=N.forwardRef((n,r)=>{const{children:a,...i}=n;if(N.isValidElement(a)){const l=aMt(a),o=rMt(i,a.props);return a.type!==N.Fragment&&(o.ref=r?uN(r,l):l),N.cloneElement(a,o)}return N.Children.count(a)>1?N.Children.only(null):null});return t.displayName=`${s}.SlotClone`,t}var Xnt=Symbol("radix.slottable");function Jnt(s){const t=({children:n})=>e.jsx(e.Fragment,{children:n});return t.displayName=`${s}.Slottable`,t.__radixId=Xnt,t}function nMt(s){return N.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===Xnt}function rMt(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 aMt(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 TD(s){const t=s+"CollectionProvider",[n,r]=pu(t),[a,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),l=_=>{const{scope:v,children:j}=_,b=St.useRef(null),S=St.useRef(new Map).current;return e.jsx(a,{scope:v,itemMap:S,collectionRef:b,children:j})};l.displayName=t;const o=s+"CollectionSlot",c=S4(o),d=St.forwardRef((_,v)=>{const{scope:j,children:b}=_,S=i(o,j),A=Si(v,S.collectionRef);return e.jsx(c,{ref:A,children:b})});d.displayName=o;const u=s+"CollectionItemSlot",h="data-radix-collection-item",p=S4(u),f=St.forwardRef((_,v)=>{const{scope:j,children:b,...S}=_,A=St.useRef(null),T=Si(v,A),L=i(u,j);return St.useEffect(()=>(L.itemMap.set(A,{ref:A,...S}),()=>void L.itemMap.delete(A))),e.jsx(p,{[h]:"",ref:T,children:b})});f.displayName=u;function g(_){const v=i(s+"CollectionConsumer",_);return St.useCallback(()=>{const b=v.collectionRef.current;if(!b)return[];const S=Array.from(b.querySelectorAll(`[${h}]`));return Array.from(v.itemMap.values()).sort((L,D)=>S.indexOf(L.ref.current)-S.indexOf(D.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:l,Slot:d,ItemSlot:f},g,r]}var iMt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Jr=iMt.reduce((s,t)=>{const n=S4(`Primitive.${t}`),r=N.forwardRef((a,i)=>{const{asChild:l,...o}=a,c=l?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),e.jsx(c,{...o,ref:i})});return r.displayName=`Primitive.${t}`,{...s,[t]:r}},{});function oAe(s,t){s&&Hx.flushSync(()=>s.dispatchEvent(t))}function lh(s){const t=N.useRef(s);return N.useEffect(()=>{t.current=s}),N.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function oMt(s,t=globalThis==null?void 0:globalThis.document){const n=lh(s);N.useEffect(()=>{const r=a=>{a.key==="Escape"&&n(a)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var lMt="DismissableLayer",PSe="dismissableLayer.update",cMt="dismissableLayer.pointerDownOutside",dMt="dismissableLayer.focusOutside",V9e,ert=N.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),H4=N.forwardRef((s,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,onDismiss:o,...c}=s,d=N.useContext(ert),[u,h]=N.useState(null),p=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=N.useState({}),g=Si(t,D=>h(D)),_=Array.from(d.layers),[v]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),j=_.indexOf(v),b=u?_.indexOf(u):-1,S=d.layersWithOutsidePointerEventsDisabled.size>0,A=b>=j,T=hMt(D=>{const M=D.target,F=[...d.branches].some(z=>z.contains(M));!A||F||(a==null||a(D),l==null||l(D),D.defaultPrevented||o==null||o())},p),L=mMt(D=>{const M=D.target;[...d.branches].some(z=>z.contains(M))||(i==null||i(D),l==null||l(D),D.defaultPrevented||o==null||o())},p);return oMt(D=>{b===d.layers.size-1&&(r==null||r(D),!D.defaultPrevented&&o&&(D.preventDefault(),o()))},p),N.useEffect(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(V9e=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),H9e(),()=>{n&&d.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=V9e)}},[u,p,n,d]),N.useEffect(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),H9e())},[u,d]),N.useEffect(()=>{const D=()=>f({});return document.addEventListener(PSe,D),()=>document.removeEventListener(PSe,D)},[]),e.jsx(Jr.div,{...c,ref:g,style:{pointerEvents:S?A?"auto":"none":void 0,...s.style},onFocusCapture:_r(s.onFocusCapture,L.onFocusCapture),onBlurCapture:_r(s.onBlurCapture,L.onBlurCapture),onPointerDownCapture:_r(s.onPointerDownCapture,T.onPointerDownCapture)})});H4.displayName=lMt;var uMt="DismissableLayerBranch",trt=N.forwardRef((s,t)=>{const n=N.useContext(ert),r=N.useRef(null),a=Si(t,r);return N.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),e.jsx(Jr.div,{...s,ref:a})});trt.displayName=uMt;function hMt(s,t=globalThis==null?void 0:globalThis.document){const n=lh(s),r=N.useRef(!1),a=N.useRef(()=>{});return N.useEffect(()=>{const i=o=>{if(o.target&&!r.current){let c=function(){srt(cMt,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 mMt(s,t=globalThis==null?void 0:globalThis.document){const n=lh(s),r=N.useRef(!1);return N.useEffect(()=>{const a=i=>{i.target&&!r.current&&srt(dMt,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 H9e(){const s=new CustomEvent(PSe);document.dispatchEvent(s)}function srt(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?oAe(a,i):a.dispatchEvent(i)}var pMt=H4,fMt=trt,mh=globalThis!=null&&globalThis.document?N.useLayoutEffect:()=>{},xMt="Portal",ED=N.forwardRef((s,t)=>{var o;const{container:n,...r}=s,[a,i]=N.useState(!1);mh(()=>i(!0),[]);const l=n||a&&((o=globalThis==null?void 0:globalThis.document)==null?void 0:o.body);return l?aAe.createPortal(e.jsx(Jr.div,{...r,ref:t}),l):null});ED.displayName=xMt;function gMt(s,t){return N.useReducer((n,r)=>t[n][r]??n,s)}var Rh=s=>{const{present:t,children:n}=s,r=yMt(t),a=typeof n=="function"?n({present:r.isPresent}):N.Children.only(n),i=Si(r.ref,vMt(a));return typeof n=="function"||r.isPresent?N.cloneElement(a,{ref:i}):null};Rh.displayName="Presence";function yMt(s){const[t,n]=N.useState(),r=N.useRef(null),a=N.useRef(s),i=N.useRef("none"),l=s?"mounted":"unmounted",[o,c]=gMt(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return N.useEffect(()=>{const d=zV(r.current);i.current=o==="mounted"?d:"none"},[o]),mh(()=>{const d=r.current,u=a.current;if(u!==s){const p=i.current,f=zV(d);s?c("MOUNT"):f==="none"||(d==null?void 0:d.display)==="none"?c("UNMOUNT"):c(u&&p!==f?"ANIMATION_OUT":"UNMOUNT"),a.current=s}},[s,c]),mh(()=>{if(t){let d;const u=t.ownerDocument.defaultView??window,h=f=>{const _=zV(r.current).includes(f.animationName);if(f.target===t&&_&&(c("ANIMATION_END"),!a.current)){const v=t.style.animationFillMode;t.style.animationFillMode="forwards",d=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=v)})}},p=f=>{f.target===t&&(i.current=zV(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{u.clearTimeout(d),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(o),ref:N.useCallback(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function zV(s){return(s==null?void 0:s.animationName)||"none"}function vMt(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 bMt=pEe[" useInsertionEffect ".trim().toString()]||mh;function hm({prop:s,defaultProp:t,onChange:n=()=>{},caller:r}){const[a,i,l]=_Mt({defaultProp:t,onChange:n}),o=s!==void 0,c=o?s:a;{const u=N.useRef(s!==void 0);N.useEffect(()=>{const h=u.current;h!==o&&console.warn(`${r} is changing from ${h?"controlled":"uncontrolled"} to ${o?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=o},[o,r])}const d=N.useCallback(u=>{var h;if(o){const p=wMt(u)?u(s):u;p!==s&&((h=l.current)==null||h.call(l,p))}else i(u)},[o,s,i,l]);return[c,d]}function _Mt({defaultProp:s,onChange:t}){const[n,r]=N.useState(s),a=N.useRef(n),i=N.useRef(t);return bMt(()=>{i.current=t},[t]),N.useEffect(()=>{var l;a.current!==n&&((l=i.current)==null||l.call(i,n),a.current=n)},[n,a]),[n,r,i]}function wMt(s){return typeof s=="function"}var nrt=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"}),jMt="VisuallyHidden",S0e=N.forwardRef((s,t)=>e.jsx(Jr.span,{...s,ref:t,style:{...nrt,...s.style}}));S0e.displayName=jMt;var NMt=S0e,lAe="ToastProvider",[cAe,kMt,SMt]=TD("Toast"),[rrt,ixn]=pu("Toast",[SMt]),[CMt,C0e]=rrt(lAe),art=s=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:a="right",swipeThreshold:i=50,children:l}=s,[o,c]=N.useState(null),[d,u]=N.useState(0),h=N.useRef(!1),p=N.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${lAe}\`. Expected non-empty \`string\`.`),e.jsx(cAe.Provider,{scope:t,children:e.jsx(CMt,{scope:t,label:n,duration:r,swipeDirection:a,swipeThreshold:i,toastCount:d,viewport:o,onViewportChange:c,onToastAdd:N.useCallback(()=>u(f=>f+1),[]),onToastRemove:N.useCallback(()=>u(f=>f-1),[]),isFocusedToastEscapeKeyDownRef:h,isClosePausedRef:p,children:l})})};art.displayName=lAe;var irt="ToastViewport",TMt=["F8"],LSe="toast.viewportPause",DSe="toast.viewportResume",ort=N.forwardRef((s,t)=>{const{__scopeToast:n,hotkey:r=TMt,label:a="Notifications ({hotkey})",...i}=s,l=C0e(irt,n),o=kMt(n),c=N.useRef(null),d=N.useRef(null),u=N.useRef(null),h=N.useRef(null),p=Si(t,h,l.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),g=l.toastCount>0;N.useEffect(()=>{const v=j=>{var S;r.length!==0&&r.every(A=>j[A]||j.code===A)&&((S=h.current)==null||S.focus())};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[r]),N.useEffect(()=>{const v=c.current,j=h.current;if(g&&v&&j){const b=()=>{if(!l.isClosePausedRef.current){const L=new CustomEvent(LSe);j.dispatchEvent(L),l.isClosePausedRef.current=!0}},S=()=>{if(l.isClosePausedRef.current){const L=new CustomEvent(DSe);j.dispatchEvent(L),l.isClosePausedRef.current=!1}},A=L=>{!v.contains(L.relatedTarget)&&S()},T=()=>{v.contains(document.activeElement)||S()};return v.addEventListener("focusin",b),v.addEventListener("focusout",A),v.addEventListener("pointermove",b),v.addEventListener("pointerleave",T),window.addEventListener("blur",b),window.addEventListener("focus",S),()=>{v.removeEventListener("focusin",b),v.removeEventListener("focusout",A),v.removeEventListener("pointermove",b),v.removeEventListener("pointerleave",T),window.removeEventListener("blur",b),window.removeEventListener("focus",S)}}},[g,l.isClosePausedRef]);const _=N.useCallback(({tabbingDirection:v})=>{const b=o().map(S=>{const A=S.ref.current,T=[A,...$Mt(A)];return v==="forwards"?T:T.reverse()});return(v==="forwards"?b.reverse():b).flat()},[o]);return N.useEffect(()=>{const v=h.current;if(v){const j=b=>{var T,L,D;const S=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!S){const M=document.activeElement,F=b.shiftKey;if(b.target===v&&F){(T=d.current)==null||T.focus();return}const W=_({tabbingDirection:F?"backwards":"forwards"}),Y=W.findIndex(K=>K===M);Rwe(W.slice(Y+1))?b.preventDefault():F?(L=d.current)==null||L.focus():(D=u.current)==null||D.focus()}};return v.addEventListener("keydown",j),()=>v.removeEventListener("keydown",j)}},[o,_]),e.jsxs(fMt,{ref:c,role:"region","aria-label":a.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:g?void 0:"none"},children:[g&&e.jsx(RSe,{ref:d,onFocusFromOutsideViewport:()=>{const v=_({tabbingDirection:"forwards"});Rwe(v)}}),e.jsx(cAe.Slot,{scope:n,children:e.jsx(Jr.ol,{tabIndex:-1,...i,ref:p})}),g&&e.jsx(RSe,{ref:u,onFocusFromOutsideViewport:()=>{const v=_({tabbingDirection:"backwards"});Rwe(v)}})]})});ort.displayName=irt;var lrt="ToastFocusProxy",RSe=N.forwardRef((s,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...a}=s,i=C0e(lrt,n);return e.jsx(S0e,{"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()}})});RSe.displayName=lrt;var F$="Toast",EMt="toast.swipeStart",AMt="toast.swipeMove",MMt="toast.swipeCancel",IMt="toast.swipeEnd",crt=N.forwardRef((s,t)=>{const{forceMount:n,open:r,defaultOpen:a,onOpenChange:i,...l}=s,[o,c]=hm({prop:r,defaultProp:a??!0,onChange:i,caller:F$});return e.jsx(Rh,{present:n||o,children:e.jsx(DMt,{open:o,...l,ref:t,onClose:()=>c(!1),onPause:lh(s.onPause),onResume:lh(s.onResume),onSwipeStart:_r(s.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:_r(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:_r(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:_r(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)})})})});crt.displayName=F$;var[PMt,LMt]=rrt(F$,{onClose(){}}),DMt=N.forwardRef((s,t)=>{const{__scopeToast:n,type:r="foreground",duration:a,open:i,onClose:l,onEscapeKeyDown:o,onPause:c,onResume:d,onSwipeStart:u,onSwipeMove:h,onSwipeCancel:p,onSwipeEnd:f,...g}=s,_=C0e(F$,n),[v,j]=N.useState(null),b=Si(t,K=>j(K)),S=N.useRef(null),A=N.useRef(null),T=a||_.duration,L=N.useRef(0),D=N.useRef(T),M=N.useRef(0),{onToastAdd:F,onToastRemove:z}=_,V=lh(()=>{var J;(v==null?void 0:v.contains(document.activeElement))&&((J=_.viewport)==null||J.focus()),l()}),W=N.useCallback(K=>{!K||K===1/0||(window.clearTimeout(M.current),L.current=new Date().getTime(),M.current=window.setTimeout(V,K))},[V]);N.useEffect(()=>{const K=_.viewport;if(K){const J=()=>{W(D.current),d==null||d()},ne=()=>{const ie=new Date().getTime()-L.current;D.current=D.current-ie,window.clearTimeout(M.current),c==null||c()};return K.addEventListener(LSe,ne),K.addEventListener(DSe,J),()=>{K.removeEventListener(LSe,ne),K.removeEventListener(DSe,J)}}},[_.viewport,T,c,d,W]),N.useEffect(()=>{i&&!_.isClosePausedRef.current&&W(T)},[i,T,_.isClosePausedRef,W]),N.useEffect(()=>(F(),()=>z()),[F,z]);const Y=N.useMemo(()=>v?xrt(v):null,[v]);return _.viewport?e.jsxs(e.Fragment,{children:[Y&&e.jsx(RMt,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0,children:Y}),e.jsx(PMt,{scope:n,onClose:V,children:Hx.createPortal(e.jsx(cAe.ItemSlot,{scope:n,children:e.jsx(pMt,{asChild:!0,onEscapeKeyDown:_r(o,()=>{_.isFocusedToastEscapeKeyDownRef.current||V(),_.isFocusedToastEscapeKeyDownRef.current=!1}),children:e.jsx(Jr.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":_.swipeDirection,...g,ref:b,style:{userSelect:"none",touchAction:"none",...s.style},onKeyDown:_r(s.onKeyDown,K=>{K.key==="Escape"&&(o==null||o(K.nativeEvent),K.nativeEvent.defaultPrevented||(_.isFocusedToastEscapeKeyDownRef.current=!0,V()))}),onPointerDown:_r(s.onPointerDown,K=>{K.button===0&&(S.current={x:K.clientX,y:K.clientY})}),onPointerMove:_r(s.onPointerMove,K=>{if(!S.current)return;const J=K.clientX-S.current.x,ne=K.clientY-S.current.y,ie=!!A.current,he=["left","right"].includes(_.swipeDirection),ce=["left","up"].includes(_.swipeDirection)?Math.min:Math.max,pe=he?ce(0,J):0,le=he?0:ce(0,ne),ve=K.pointerType==="touch"?10:2,ge={x:pe,y:le},Te={originalEvent:K,delta:ge};ie?(A.current=ge,BV(AMt,h,Te,{discrete:!1})):G9e(ge,_.swipeDirection,ve)?(A.current=ge,BV(EMt,u,Te,{discrete:!1}),K.target.setPointerCapture(K.pointerId)):(Math.abs(J)>ve||Math.abs(ne)>ve)&&(S.current=null)}),onPointerUp:_r(s.onPointerUp,K=>{const J=A.current,ne=K.target;if(ne.hasPointerCapture(K.pointerId)&&ne.releasePointerCapture(K.pointerId),A.current=null,S.current=null,J){const ie=K.currentTarget,he={originalEvent:K,delta:J};G9e(J,_.swipeDirection,_.swipeThreshold)?BV(IMt,f,he,{discrete:!0}):BV(MMt,p,he,{discrete:!0}),ie.addEventListener("click",ce=>ce.preventDefault(),{once:!0})}})})})}),_.viewport)})]}):null}),RMt=s=>{const{__scopeToast:t,children:n,...r}=s,a=C0e(F$,t),[i,l]=N.useState(!1),[o,c]=N.useState(!1);return zMt(()=>l(!0)),N.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(ED,{asChild:!0,children:e.jsx(S0e,{...r,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",n]})})})},OMt="ToastTitle",drt=N.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(Jr.div,{...r,ref:t})});drt.displayName=OMt;var FMt="ToastDescription",urt=N.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(Jr.div,{...r,ref:t})});urt.displayName=FMt;var hrt="ToastAction",mrt=N.forwardRef((s,t)=>{const{altText:n,...r}=s;return n.trim()?e.jsx(frt,{altText:n,asChild:!0,children:e.jsx(dAe,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${hrt}\`. Expected non-empty \`string\`.`),null)});mrt.displayName=hrt;var prt="ToastClose",dAe=N.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s,a=LMt(prt,n);return e.jsx(frt,{asChild:!0,children:e.jsx(Jr.button,{type:"button",...r,ref:t,onClick:_r(s.onClick,a.onClose)})})});dAe.displayName=prt;var frt=N.forwardRef((s,t)=>{const{__scopeToast:n,altText:r,...a}=s;return e.jsx(Jr.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...a,ref:t})});function xrt(s){const t=[];return Array.from(s.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),BMt(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(...xrt(r))}}),t}function BV(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?oAe(a,i):a.dispatchEvent(i)}var G9e=(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 zMt(s=()=>{}){const t=lh(s);mh(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function BMt(s){return s.nodeType===s.ELEMENT_NODE}function $Mt(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 Rwe(s){const t=document.activeElement;return s.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var UMt=art,grt=ort,yrt=crt,vrt=drt,brt=urt,_rt=mrt,wrt=dAe;function jrt(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,K9e=So,UM=(s,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return K9e(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 p=W9e(u)||W9e(h);return a[d][p]}),o=n&&Object.entries(n).reduce((d,u)=>{let[h,p]=u;return p===void 0||(d[h]=p),d},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,u)=>{let{class:h,className:p,...f}=u;return Object.entries(f).every(g=>{let[_,v]=g;return Array.isArray(v)?v.includes({...i,...o}[_]):{...i,...o}[_]===v})?[...d,h,p]:d},[]);return K9e(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 qMt=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Nrt=(...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 VMt={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 krt=N.forwardRef(({color:s="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:i,iconNode:l,...o},c)=>N.createElement("svg",{ref:c,...VMt,width:t,height:t,stroke:s,strokeWidth:r?Number(n)*24/Number(t):n,className:Nrt("lucide",a),...o},[...l.map(([d,u])=>N.createElement(d,u)),...Array.isArray(i)?i:[i]]));/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const re=(s,t)=>{const n=N.forwardRef(({className:r,...a},i)=>N.createElement(krt,{ref:i,iconNode:t,className:Nrt(`lucide-${qMt(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 SW=re("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 CW=re("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 TW=re("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 EW=re("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 nm=re("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 AW=re("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 MW=re("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 N3=re("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 k3=re("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 IW=re("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 S3=re("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 PW=re("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 LW=re("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 DW=re("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 RW=re("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 OW=re("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 bA=re("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 FW=re("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 zW=re("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 BW=re("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 $W=re("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 UW=re("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 qW=re("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 VW=re("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 HW=re("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 GW=re("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 WW=re("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 KW=re("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 _A=re("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 wA=re("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 YW=re("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 ZW=re("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 QW=re("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 XW=re("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 JW=re("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 eK=re("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 tK=re("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 sK=re("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 nK=re("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 rK=re("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 aK=re("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 iK=re("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 oK=re("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 lK=re("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 cK=re("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 dK=re("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 uK=re("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 hK=re("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 mK=re("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 pK=re("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 fK=re("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 xK=re("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 gK=re("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 ZP=re("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 yK=re("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 rm=re("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 vK=re("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 bK=re("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 _K=re("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 wK=re("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 jK=re("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 NK=re("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 kK=re("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 SK=re("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 CK=re("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 TK=re("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 EK=re("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 C3=re("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 AK=re("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 MK=re("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 IK=re("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 V7=re("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 PK=re("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 LK=re("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 DK=re("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 T3=re("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 E3=re("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 am=re("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 RK=re("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 OK=re("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 FK=re("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 Hr=re("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 zK=re("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 mw=re("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 BK=re("ArrowRightToLine",[["path",{d:"M17 12H3",key:"8awo09"}],["path",{d:"m11 18 6-6-6-6",key:"8c2y43"}],["path",{d:"M21 5v14",key:"nzette"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Oa=re("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 $K=re("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 UK=re("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 A3=re("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 em=re("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 qK=re("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 VK=re("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 HK=re("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 M3=re("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 QP=re("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 GK=re("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 WK=re("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 I3=re("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 Ru=re("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 KK=re("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 YK=re("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 ZK=re("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 QK=re("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 XK=re("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 JK=re("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 bc=re("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 eY=re("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 P3=re("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 tY=re("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 sY=re("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 nY=re("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 rY=re("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 L3=re("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 aY=re("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 iY=re("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 oY=re("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 lY=re("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 cY=re("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 dY=re("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 uY=re("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 hY=re("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 mY=re("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 pY=re("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 fY=re("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 xY=re("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 gY=re("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 yY=re("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 vY=re("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 XP=re("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 bY=re("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 _Y=re("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 wY=re("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 jY=re("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 NY=re("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 Cp=re("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 kY=re("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 SY=re("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 CY=re("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 TY=re("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 EY=re("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 AY=re("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 H7=re("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 MY=re("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 IY=re("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 H2=re("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 PY=re("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 sy=re("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 LY=re("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 DY=re("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 RY=re("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 OY=re("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 FY=re("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 zY=re("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 pw=re("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 BY=re("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 WS=re("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 im=re("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 D3=re("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 R3=re("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 $Y=re("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 UY=re("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 qY=re("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 VY=re("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 HY=re("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 GY=re("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 WY=re("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 KY=re("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 YY=re("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 ZY=re("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 QY=re("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 XY=re("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 JY=re("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 eZ=re("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 tZ=re("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 sZ=re("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 KS=re("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 nZ=re("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 rZ=re("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 aZ=re("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 iZ=re("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 oZ=re("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 lZ=re("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 cZ=re("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 O3=re("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 dZ=re("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 uZ=re("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 hZ=re("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 mZ=re("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 pZ=re("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 fZ=re("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 xZ=re("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 gZ=re("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 yZ=re("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 vZ=re("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 Ou=re("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 bZ=re("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 _Z=re("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 wZ=re("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 jZ=re("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 NZ=re("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 kZ=re("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 SZ=re("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 CZ=re("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 TZ=re("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 EZ=re("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 JP=re("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 AZ=re("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 Lv=re("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 MZ=re("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 IZ=re("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 PZ=re("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 YS=re("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 G7=re("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 LZ=re("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 F3=re("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 DZ=re("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 RZ=re("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 OZ=re("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 W7=re("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 FZ=re("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 zZ=re("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 BZ=re("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 $Z=re("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 qm=re("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 UZ=re("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 qZ=re("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 VZ=re("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 HZ=re("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 GZ=re("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 Va=re("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 jA=re("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 WZ=re("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 KZ=re("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 YZ=re("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 ZZ=re("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 QZ=re("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 cu=re("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 fw=re("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 XZ=re("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 JZ=re("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 eQ=re("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 tQ=re("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 ZS=re("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 om=re("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 sQ=re("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 Tl=re("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 nQ=re("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 hb=re("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 rQ=re("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 aQ=re("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 K7=re("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 iQ=re("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 Rg=re("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 oQ=re("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 lQ=re("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 cQ=re("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 dQ=re("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 Y7=re("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 yr=re("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 uQ=re("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 mf=re("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 hQ=re("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 mQ=re("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 pQ=re("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 fQ=re("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 xQ=re("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 z3=re("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 gQ=re("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 yQ=re("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 vQ=re("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 bQ=re("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 _Q=re("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 wQ=re("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 jQ=re("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 NQ=re("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 kQ=re("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 SQ=re("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 CQ=re("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 TQ=re("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 EQ=re("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 B3=re("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 $3=re("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 AQ=re("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 MQ=re("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 IQ=re("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 U3=re("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 q3=re("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 V3=re("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 PQ=re("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 H3=re("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 LQ=re("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 yo=re("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 DQ=re("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 G3=re("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 RQ=re("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 OQ=re("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 W3=re("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 K3=re("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 FQ=re("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 Y3=re("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 Z3=re("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 Q3=re("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 zQ=re("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 Z7=re("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 Ir=re("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 BQ=re("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 $Q=re("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 io=re("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 UQ=re("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 qQ=re("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 pl=re("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 xa=re("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 tx=re("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 VQ=re("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 HQ=re("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 GQ=re("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 WQ=re("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 KQ=re("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 YQ=re("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 ZQ=re("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 qg=re("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 QQ=re("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 NA=re("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 XQ=re("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 JQ=re("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 eX=re("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 Gi=re("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 X3=re("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 J3=re("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 e5=re("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 t5=re("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 s5=re("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 n5=re("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 r5=re("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 a5=re("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 Ri=re("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 xr=re("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 i5=re("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 o5=re("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 l5=re("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 c5=re("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 tX=re("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 d5=re("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 sX=re("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 nX=re("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 rX=re("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 aX=re("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 iX=re("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 oX=re("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 lX=re("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 u5=re("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 K_=re("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 h5=re("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 cX=re("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 m5=re("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 p5=re("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 f5=re("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 x5=re("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 Au=re("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 g5=re("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 y5=re("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 v5=re("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 dX=re("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 b5=re("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 _5=re("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 w5=re("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 Hc=re("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 lm=re("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 uX=re("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 hX=re("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 mX=re("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 G2=re("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 pX=re("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 Dv=re("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 fX=re("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 xX=re("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 j5=re("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 N5=re("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 gX=re("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 yX=re("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 vX=re("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 bX=re("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 _X=re("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 wX=re("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 jX=re("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 NX=re("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 kX=re("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 Q7=re("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 SX=re("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 CX=re("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 TX=re("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 EX=re("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 AX=re("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 MX=re("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 IX=re("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 PX=re("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 LX=re("ClockArrowUp",[["path",{d:"M13.228 21.925A10 10 0 1 1 21.994 12.338",key:"1fzlyi"}],["path",{d:"M12 6v6l1.562.781",key:"1ujuk9"}],["path",{d:"m14 18 4-4 4 4",key:"ftkppy"}],["path",{d:"M18 22v-8",key:"su0gjh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gr=re("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 DX=re("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 RX=re("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 k5=re("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 OX=re("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 FX=re("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 zX=re("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 BX=re("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 $X=re("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 UX=re("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 qX=re("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 VX=re("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 HX=re("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 GX=re("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 WX=re("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 KX=re("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 S5=re("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 YX=re("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 ZX=re("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 R2=re("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 QX=re("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 C2=re("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 kA=re("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 XX=re("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 JX=re("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 ny=re("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 eJ=re("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 X7=re("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 C5=re("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 Kk=re("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 tJ=re("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 sJ=re("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 nJ=re("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 eL=re("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 rJ=re("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 aJ=re("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 iJ=re("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 oJ=re("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 lJ=re("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 T5=re("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 SA=re("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 cJ=re("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 dJ=re("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 uJ=re("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 hJ=re("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 mJ=re("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 pJ=re("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 fJ=re("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 xJ=re("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 gJ=re("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 Xr=re("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 yJ=re("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 vJ=re("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 bJ=re("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 _J=re("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 wJ=re("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 jJ=re("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 NJ=re("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 kJ=re("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 SJ=re("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 CJ=re("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 TJ=re("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 EJ=re("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 pf=re("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 AJ=re("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 MJ=re("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 IJ=re("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 PJ=re("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 ff=re("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 LJ=re("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 DJ=re("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 RJ=re("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 OJ=re("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 FJ=re("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 zJ=re("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 BJ=re("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 J7=re("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 $J=re("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 UJ=re("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 qJ=re("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 VJ=re("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 E5=re("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 HJ=re("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 GJ=re("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 WJ=re("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 KJ=re("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 YJ=re("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 ZJ=re("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 QJ=re("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 XJ=re("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 JJ=re("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 eee=re("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 tee=re("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 see=re("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 nee=re("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 ree=re("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 aee=re("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 iee=re("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 oee=re("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 lee=re("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 cee=re("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 Zl=re("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 dee=re("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 uee=re("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 xw=re("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 hee=re("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 Pa=re("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 mee=re("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 pee=re("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 fee=re("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 xee=re("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 gee=re("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 mb=re("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 yee=re("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 vee=re("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 bee=re("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 _ee=re("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 wee=re("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 jee=re("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 A5=re("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 Nee=re("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 kee=re("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 See=re("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 tL=re("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 Ig=re("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 Qf=re("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 Cee=re("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 Tee=re("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 Eee=re("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 Aee=re("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 Mee=re("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 Iee=re("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 Pee=re("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=re("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 Lee=re("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 xf=re("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 Er=re("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 Lh=re("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 Dee=re("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 Ree=re("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 Oee=re("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 Fee=re("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 zee=re("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 Bee=re("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 $ee=re("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 Uee=re("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 qee=re("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 Vee=re("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 M5=re("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 Hee=re("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 Gee=re("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 Wee=re("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 I5=re("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 P5=re("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 L5=re("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 D5=re("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 Kee=re("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 e9=re("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 Yee=re("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 Zee=re("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 Qee=re("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 R5=re("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 Xee=re("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 Jee=re("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 CA=re("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 ete=re("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 W2=re("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 tte=re("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 ste=re("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 nte=re("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 rte=re("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 ate=re("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 ite=re("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 ote=re("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 lte=re("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 cte=re("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 dte=re("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 ute=re("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 Yk=re("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 O5=re("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 hte=re("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 mte=re("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 pte=re("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 fte=re("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 xte=re("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 gte=re("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 yte=re("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 gw=re("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 t9=re("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 vte=re("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 bte=re("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 Nr=re("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 _te=re("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 wte=re("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 jte=re("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 Nte=re("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 kte=re("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 s9=re("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 Ste=re("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 Cte=re("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 Tte=re("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 Ete=re("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 Ate=re("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 sL=re("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 Mte=re("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 Ah=re("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 Ite=re("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 Rv=re("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 Pte=re("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 Lte=re("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 Dte=re("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 Rte=re("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 Ote=re("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 Fte=re("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 zte=re("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 Bte=re("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 K2=re("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 $te=re("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 Dc=re("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 Ute=re("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 qte=re("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 Vte=re("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 QS=re("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 Hte=re("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 Gte=re("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 n9=re("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 Wte=re("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 Kte=re("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 ob=re("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 Yte=re("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 Zte=re("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 Qte=re("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 Xte=re("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 Jte=re("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 ese=re("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 tse=re("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 sse=re("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 nse=re("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 F5=re("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 rse=re("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 ase=re("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 ise=re("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 ose=re("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 lse=re("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 cse=re("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 dse=re("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 use=re("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 hse=re("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 mse=re("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 pse=re("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 gf=re("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 fse=re("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 z5=re("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 xse=re("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 gse=re("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 yse=re("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 vse=re("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 bse=re("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 _se=re("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 wse=re("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 jse=re("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 Nse=re("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 kse=re("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 Sse=re("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 Cse=re("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 Tse=re("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 Ese=re("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 Ase=re("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 Mse=re("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 Ise=re("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 Pse=re("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 Lse=re("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 Dse=re("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 Rse=re("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 Ose=re("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 Fse=re("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 zse=re("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 Bse=re("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 $se=re("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 Use=re("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 qse=re("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 Vse=re("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 TA=re("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 Oi=re("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 Hse=re("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 Gse=re("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 B5=re("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 Wse=re("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 Kse=re("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 Yse=re("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 Zse=re("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 Qse=re("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 Xse=re("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 Jse=re("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 ene=re("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 tne=re("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 sne=re("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 nne=re("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 rne=re("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 ane=re("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 ine=re("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 one=re("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 lne=re("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 cne=re("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 lc=re("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 dne=re("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 une=re("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 _d=re("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 hne=re("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 mne=re("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 $5=re("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 pne=re("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 U5=re("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 pv=re("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 fne=re("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 Fu=re("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 xne=re("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 gne=re("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 yne=re("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 vne=re("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 r9=re("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 bne=re("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 EA=re("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 tb=re("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 _ne=re("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 wne=re("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 a9=re("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 pb=re("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 jne=re("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 Nne=re("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 i9=re("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 kne=re("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 XS=re("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 Sne=re("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 Cne=re("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 nL=re("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 rL=re("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 o9=re("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 Tne=re("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 Ene=re("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 Ane=re("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 Mne=re("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 Ine=re("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 Pne=re("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 Lne=re("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 Dne=re("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 AA=re("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 Rne=re("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 One=re("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 gi=re("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 Fne=re("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 zne=re("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 Bne=re("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 MA=re("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 $ne=re("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 Une=re("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 qne=re("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 Vne=re("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 Hne=re("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 Gne=re("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 Wne=re("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 Or=re("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 q5=re("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 V5=re("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 Kne=re("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 Yne=re("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 Zne=re("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 Qne=re("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 Xne=re("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 ry=re("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 Jne=re("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 ere=re("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 nl=re("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 tre=re("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 sre=re("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 Y2=re("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 H5=re("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 G5=re("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 nre=re("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 rre=re("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 yw=re("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 are=re("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 du=re("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 JS=re("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 ire=re("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 ore=re("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 lre=re("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 cre=re("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 Z2=re("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 IA=re("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 dre=re("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 Vg=re("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 ure=re("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 hre=re("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 mre=re("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 pre=re("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 fre=re("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 xre=re("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 gre=re("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 yre=re("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 vre=re("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 bre=re("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 _re=re("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 wre=re("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 jre=re("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 W5=re("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 Nre=re("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 kre=re("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 Sre=re("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 Cre=re("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 Tre=re("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 Ere=re("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 l9=re("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 e4=re("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 yf=re("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 Are=re("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 Mre=re("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 Ire=re("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 t4=re("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 Pre=re("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 Lre=re("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 Dre=re("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 Rre=re("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 Ore=re("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 Hg=re("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 aL=re("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 Fre=re("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 zre=re("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 vw=re("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 Bre=re("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 El=re("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 Jo=re("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 vf=re("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 $re=re("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 uu=re("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 Ure=re("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 qre=re("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 c9=re("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 Vre=re("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 Hre=re("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 Ov=re("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 Gre=re("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 Wre=re("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 Kre=re("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 Yre=re("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 Zre=re("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 Qre=re("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 Xre=re("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 Tp=re("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 ts=re("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 Jre=re("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 eae=re("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 tae=re("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 sae=re("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 iL=re("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 K5=re("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 nae=re("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 Y5=re("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 Kc=re("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 PA=re("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 LA=re("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 rae=re("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 aae=re("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 iae=re("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 oae=re("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 oL=re("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 lae=re("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 lL=re("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 d9=re("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 cae=re("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 dae=re("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 uae=re("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 cL=re("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 Vs=re("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 hae=re("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 mae=re("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 pae=re("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 fae=re("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 xae=re("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 gae=re("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 yae=re("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 vae=re("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 bae=re("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 _ae=re("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 wae=re("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 jae=re("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 ka=re("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 Nae=re("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 DA=re("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 kae=re("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 u9=re("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 RA=re("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 Q2=re("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 Sae=re("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 $d=re("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 Cae=re("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 Tae=re("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 s4=re("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 Eae=re("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 Aae=re("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 Mae=re("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 dL=re("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 Iae=re("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 Pae=re("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 Lae=re("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 h9=re("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 Dae=re("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 Rae=re("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 Oae=re("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 Ql=re("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 Fae=re("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 zae=re("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 Bae=re("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 $ae=re("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 uL=re("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 Uae=re("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 m9=re("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 qae=re("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 nw=re("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 bw=re("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 Vae=re("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 Hae=re("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 Gae=re("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 Wae=re("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 Kae=re("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 Ei=re("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 hL=re("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 Yae=re("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 Z5=re("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 Fv=re("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 Zae=re("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 Qae=re("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 Xae=re("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 Jae=re("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 eie=re("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 tie=re("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 sie=re("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 nie=re("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 fb=re("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 rie=re("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 aie=re("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 iie=re("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 oie=re("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 lie=re("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 cie=re("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 mL=re("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 die=re("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 uie=re("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 hie=re("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 OA=re("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 mie=re("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 xb=re("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 pie=re("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 fie=re("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 xie=re("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 gie=re("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 yie=re("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 vie=re("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 bie=re("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 oc=re("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 Om=re("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 _ie=re("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 Q5=re("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 wie=re("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 jie=re("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 Nie=re("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 kie=re("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 Sie=re("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 Cie=re("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 Tie=re("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 Eie=re("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 Aie=re("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 Mie=re("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 Iie=re("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 Pie=re("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 Lie=re("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 Die=re("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 Rie=re("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 Oie=re("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 pL=re("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 Fie=re("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 zie=re("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 Bie=re("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 p9=re("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 $ie=re("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 ay=re("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 Uie=re("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 qie=re("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 Vie=re("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 Hie=re("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 Gie=re("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 Wie=re("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 Kie=re("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 Yie=re("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 Zie=re("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 Y_=re("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 Qie=re("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 X5=re("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 J5=re("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 Xie=re("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 Jie=re("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 eoe=re("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 toe=re("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 soe=re("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 noe=re("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 roe=re("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 aoe=re("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 ioe=re("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 f9=re("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 ooe=re("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 loe=re("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 Rc=re("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 coe=re("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 doe=re("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 eT=re("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 uoe=re("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 fl=re("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 hoe=re("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 tT=re("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 moe=re("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 poe=re("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 sT=re("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 nT=re("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 rT=re("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 aT=re("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 foe=re("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 iT=re("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 xoe=re("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 goe=re("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 yoe=re("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 oT=re("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 voe=re("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 boe=re("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 _oe=re("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 woe=re("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 T2=re("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 n4=re("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 joe=re("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 Noe=re("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 ch=re("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 bf=re("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 koe=re("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 Soe=re("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 sb=re("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 Coe=re("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 r4=re("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 wv=re("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 x9=re("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 Toe=re("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 Eoe=re("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 _a=re("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 Aoe=re("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 a4=re("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 Moe=re("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 Ioe=re("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 g9=re("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 Poe=re("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 Loe=re("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 Doe=re("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 Roe=re("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 Ooe=re("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 Ar=re("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 Foe=re("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 zoe=re("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 Boe=re("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 $oe=re("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 Uoe=re("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 qoe=re("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 Voe=re("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 Hoe=re("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 Goe=re("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 Woe=re("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 Koe=re("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 y9=re("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 i4=re("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 Yoe=re("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 Zoe=re("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 Qoe=re("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 Xoe=re("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 v9=re("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 Al=re("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 Joe=re("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 lT=re("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 X2=re("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 Is=re("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 ele=re("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 tle=re("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 sle=re("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 nle=re("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 rle=re("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 ale=re("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 ile=re("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 ole=re("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 lle=re("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 b9=re("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 iy=re("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 cle=re("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 _9=re("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 dle=re("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 ule=re("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 hle=re("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 mle=re("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 oy=re("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 gb=re("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 ple=re("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 FA=re("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 fle=re("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 xle=re("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 gle=re("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 yle=re("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 _f=re("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 vle=re("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 ble=re("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 _le=re("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 wle=re("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 jle=re("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 Nle=re("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 kle=re("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 Sle=re("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 Cle=re("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 Tle=re("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 Ele=re("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 Ale=re("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 Mle=re("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 Ile=re("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 cT=re("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 Ple=re("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 Lle=re("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 Dle=re("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 Rle=re("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 Ole=re("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 o4=re("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 Fle=re("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 fL=re("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 zle=re("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 Ti=re("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 Ble=re("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 $le=re("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 Ule=re("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 qle=re("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 Vle=re("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 xL=re("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 Hle=re("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 Gle=re("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 Wle=re("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 w9=re("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 Kle=re("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 Yle=re("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 sx=re("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 Zle=re("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 Qle=re("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 dT=re("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 Xle=re("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 cm=re("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 Jle=re("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 zA=re("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 ece=re("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 j9=re("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 tce=re("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 uT=re("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 hT=re("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 sce=re("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 nce=re("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 J2=re("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 rce=re("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 ace=re("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 ice=re("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 oce=re("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 lce=re("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 cce=re("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 dce=re("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 uce=re("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 qo=re("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 mT=re("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 N9=re("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 hce=re("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 mce=re("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 pce=re("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 fce=re("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 xce=re("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 gce=re("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 yce=re("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 vce=re("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 bce=re("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 _ce=re("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 wce=re("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 jce=re("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 Nce=re("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 kce=re("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 k9=re("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 Sce=re("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 Cce=re("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 Tce=re("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 Ece=re("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 S9=re("SearchX",[["path",{d:"m13.5 8.5-5 5",key:"1cs55j"}],["path",{d:"m8.5 8.5 5 5",key:"a8mexj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vr=re("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 Ace=re("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 pT=re("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 Mce=re("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 cr=re("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 Ice=re("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 Pce=re("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 Lce=re("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 Dce=re("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 Rce=re("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 Oce=re("Server",[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const C9=re("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 Xo=re("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 Fce=re("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 Hl=re("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 T9=re("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 zce=re("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 Bce=re("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 gL=re("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 $ce=re("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 sg=re("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 Uce=re("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 qce=re("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 Vce=re("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 BA=re("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 Hce=re("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 Gce=re("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 fT=re("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 dh=re("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 Wce=re("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 Kce=re("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 Yce=re("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 _w=re("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 Zce=re("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 Og=re("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 Qce=re("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 Xce=re("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 Jce=re("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 ede=re("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 $A=re("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 tde=re("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 sde=re("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 nde=re("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 rde=re("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 ade=re("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 ide=re("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 ode=re("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 lde=re("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 cde=re("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 dde=re("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 ude=re("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 hde=re("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 mde=re("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 pde=re("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 fde=re("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 xde=re("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 l4=re("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 xT=re("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 gde=re("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 yde=re("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 ng=re("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 vde=re("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 bde=re("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 _de=re("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 Ev=re("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 wde=re("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 jde=re("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 Nde=re("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 kde=re("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 eN=re("Sparkle",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const un=re("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 Sde=re("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 Cde=re("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 Tde=re("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 Ede=re("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 Ade=re("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 Mde=re("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 Ide=re("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 UA=re("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 gT=re("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 yT=re("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 vT=re("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 bT=re("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 _T=re("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 wT=re("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 jT=re("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 NT=re("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 kT=re("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 ST=re("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 CT=re("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 TT=re("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 ET=re("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 AT=re("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 MT=re("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 L_=re("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 E2=re("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 IT=re("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 PT=re("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 LT=re("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 DT=re("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 RT=re("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 OT=re("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 Pde=re("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 Lde=re("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 FT=re("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 zT=re("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 BT=re("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 $T=re("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 UT=re("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 qT=re("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 VT=re("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 HT=re("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 GT=re("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 WT=re("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 KT=re("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 YT=re("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 ZT=re("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 QT=re("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 XT=re("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 ku=re("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 JT=re("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 eE=re("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 tE=re("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 sE=re("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 nE=re("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 rE=re("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 Dde=re("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 aE=re("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 iE=re("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 oE=re("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 lE=re("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 cE=re("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 Rde=re("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 Ode=re("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 dE=re("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 uE=re("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 hE=re("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 mE=re("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 ly=re("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 Fde=re("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 zde=re("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 Bde=re("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 $de=re("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 Ude=re("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 ca=re("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 qde=re("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 Vde=re("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 Hde=re("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 Gde=re("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 E9=re("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 A9=re("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 Wde=re("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 Kde=re("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 M9=re("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 Yde=re("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 Zde=re("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 Qde=re("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 Xde=re("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 Jde=re("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 yb=re("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 eue=re("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 tue=re("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 sue=re("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 nue=re("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 rue=re("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 aue=re("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 iue=re("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 oue=re("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 lue=re("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 yL=re("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 cue=re("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 due=re("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 uue=re("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 hue=re("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 mue=re("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 pue=re("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 vL=re("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 fue=re("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 bL=re("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 xue=re("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 uh=re("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 I9=re("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 gue=re("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 yue=re("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 vue=re("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 bue=re("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 _ue=re("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 wue=re("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 Oc=re("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 jue=re("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 Nue=re("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 kue=re("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 Sue=re("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 pE=re("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 Cue=re("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 Tue=re("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 Eue=re("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 Aue=re("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 Mue=re("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 Iue=re("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 fE=re("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 Pue=re("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 Lue=re("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 Due=re("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 Rue=re("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 P9=re("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 L9=re("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 Vm=re("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 Oue=re("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 Fue=re("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 zue=re("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 Bue=re("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 $ue=re("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 Uue=re("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 D9=re("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 que=re("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 Vue=re("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 Hue=re("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 Gue=re("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 Wue=re("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 Kue=re("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 Yue=re("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 Zue=re("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 Que=re("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 Xue=re("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 Jue=re("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 ehe=re("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 the=re("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 she=re("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 nhe=re("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 rhe=re("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 ahe=re("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 ihe=re("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 ohe=re("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 xE=re("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 _n=re("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 lhe=re("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 che=re("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 gE=re("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 c4=re("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 dhe=re("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 uhe=re("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 vb=re("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 hhe=re("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 mo=re("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 $l=re("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 mhe=re("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 phe=re("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 vo=re("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 R9=re("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 fhe=re("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 xhe=re("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 yE=re("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 ghe=re("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 yhe=re("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 vhe=re("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 bhe=re("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 _he=re("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 whe=re("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 jhe=re("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 _L=re("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 Nhe=re("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 khe=re("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 d4=re("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 She=re("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 Che=re("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 The=re("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 vE=re("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 Ehe=re("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 qA=re("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 Ahe=re("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 Na=re("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 Mhe=re("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 bb=re("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 O9=re("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 F9=re("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 Ihe=re("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 Fo=re("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 bE=re("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 _E=re("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 wE=re("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 Phe=re("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 jE=re("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 Lhe=re("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 NE=re("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 kE=re("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 Dhe=re("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 Rhe=re("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 Xi=re("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 G0=re("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 Nn=re("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 SE=re("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 CE=re("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 Ohe=re("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 wL=re("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 Fhe=re("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 zhe=re("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 Bhe=re("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 $he=re("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 Uhe=re("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 qhe=re("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 br=re("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 Vhe=re("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 Hhe=re("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 Ghe=re("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 Whe=re("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 Khe=re("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 z9=re("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 Yhe=re("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 B9=re("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 Zhe=re("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 Qhe=re("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 Xhe=re("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 TE=re("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 jL=re("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 Jhe=re("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 Dm=re("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 eme=re("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 tme=re("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 sme=re("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 nme=re("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 rme=re("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 ame=re("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 ime=re("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 ome=re("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 lme=re("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 cme=re("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 dme=re("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 ume=re("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 hme=re("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 mme=re("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 pme=re("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 fme=re("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 xme=re("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 gme=re("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 yme=re("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 vme=re("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 bme=re("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 $9=re("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 U9=re("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 _me=re("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 wme=re("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 _b=re("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 Bn=re("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 jme=re("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 Nme=re("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 hh=re("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 u4=re("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 NL=re("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 HMt=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:SW,AArrowUp:CW,ALargeSmall:TW,Accessibility:EW,Activity:nm,AirVent:AW,Airplay:MW,AlarmClock:PW,AlarmClockCheck:N3,AlarmClockMinus:k3,AlarmClockOff:IW,AlarmClockPlus:S3,AlarmSmoke:LW,Album:DW,AlignCenter:bA,AlignCenterHorizontal:RW,AlignCenterVertical:OW,AlignEndHorizontal:FW,AlignEndVertical:zW,AlignHorizontalDistributeCenter:BW,AlignHorizontalDistributeEnd:$W,AlignHorizontalDistributeStart:UW,AlignHorizontalJustifyCenter:qW,AlignHorizontalJustifyEnd:VW,AlignHorizontalJustifyStart:HW,AlignHorizontalSpaceAround:GW,AlignHorizontalSpaceBetween:WW,AlignJustify:KW,AlignLeft:_A,AlignRight:wA,AlignStartHorizontal:YW,AlignStartVertical:ZW,AlignVerticalDistributeCenter:QW,AlignVerticalDistributeEnd:XW,AlignVerticalDistributeStart:JW,AlignVerticalJustifyCenter:eK,AlignVerticalJustifyEnd:tK,AlignVerticalJustifyStart:sK,AlignVerticalSpaceAround:nK,AlignVerticalSpaceBetween:rK,Ambulance:aK,Ampersand:iK,Ampersands:oK,Amphora:lK,Anchor:cK,Angry:dK,Annoyed:uK,Antenna:hK,Anvil:mK,Aperture:pK,AppWindow:xK,AppWindowMac:fK,Apple:gK,Archive:rm,ArchiveRestore:ZP,ArchiveX:yK,Armchair:vK,ArrowBigDown:_K,ArrowBigDownDash:bK,ArrowBigLeft:jK,ArrowBigLeftDash:wK,ArrowBigRight:kK,ArrowBigRightDash:NK,ArrowBigUp:CK,ArrowBigUpDash:SK,ArrowDown:am,ArrowDown01:TK,ArrowDown10:EK,ArrowDownAZ:C3,ArrowDownFromLine:AK,ArrowDownLeft:MK,ArrowDownNarrowWide:IK,ArrowDownRight:V7,ArrowDownToDot:PK,ArrowDownToLine:LK,ArrowDownUp:DK,ArrowDownWideNarrow:T3,ArrowDownZA:E3,ArrowLeft:Hr,ArrowLeftFromLine:RK,ArrowLeftRight:OK,ArrowLeftToLine:FK,ArrowRight:Oa,ArrowRightFromLine:zK,ArrowRightLeft:mw,ArrowRightToLine:BK,ArrowUp:Ru,ArrowUp01:$K,ArrowUp10:UK,ArrowUpAZ:A3,ArrowUpDown:em,ArrowUpFromDot:qK,ArrowUpFromLine:VK,ArrowUpLeft:HK,ArrowUpNarrowWide:M3,ArrowUpRight:QP,ArrowUpToLine:GK,ArrowUpWideNarrow:WK,ArrowUpZA:I3,ArrowsUpFromLine:KK,Asterisk:YK,AtSign:ZK,Atom:QK,AudioLines:XK,AudioWaveform:JK,Award:bc,Axe:eY,Axis3d:P3,Baby:tY,Backpack:sY,Badge:yY,BadgeAlert:nY,BadgeCent:rY,BadgeCheck:L3,BadgeDollarSign:aY,BadgeEuro:iY,BadgeHelp:oY,BadgeIndianRupee:lY,BadgeInfo:cY,BadgeJapaneseYen:dY,BadgeMinus:uY,BadgePercent:hY,BadgePlus:mY,BadgePoundSterling:pY,BadgeRussianRuble:fY,BadgeSwissFranc:xY,BadgeX:gY,BaggageClaim:vY,Ban:XP,Banana:bY,Bandage:_Y,Banknote:wY,Barcode:jY,Baseline:NY,Bath:Cp,Battery:AY,BatteryCharging:kY,BatteryFull:SY,BatteryLow:CY,BatteryMedium:TY,BatteryWarning:EY,Beaker:H7,Bean:IY,BeanOff:MY,Bed:sy,BedDouble:H2,BedSingle:PY,Beef:LY,Beer:RY,BeerOff:DY,Bell:im,BellDot:OY,BellElectric:FY,BellMinus:zY,BellOff:pw,BellPlus:BY,BellRing:WS,BetweenHorizontalEnd:D3,BetweenHorizontalStart:R3,BetweenVerticalEnd:$Y,BetweenVerticalStart:UY,BicepsFlexed:qY,Bike:VY,Binary:HY,Binoculars:GY,Biohazard:WY,Bird:KY,Bitcoin:YY,Blend:ZY,Blinds:QY,Blocks:XY,Bluetooth:sZ,BluetoothConnected:JY,BluetoothOff:eZ,BluetoothSearching:tZ,Bold:KS,Bolt:nZ,Bomb:rZ,Bone:aZ,Book:CZ,BookA:iZ,BookAudio:oZ,BookCheck:lZ,BookCopy:cZ,BookDashed:O3,BookDown:dZ,BookHeadphones:uZ,BookHeart:hZ,BookImage:mZ,BookKey:pZ,BookLock:fZ,BookMarked:xZ,BookMinus:gZ,BookOpen:Ou,BookOpenCheck:yZ,BookOpenText:vZ,BookPlus:bZ,BookText:_Z,BookType:wZ,BookUp:NZ,BookUp2:jZ,BookUser:kZ,BookX:SZ,Bookmark:Lv,BookmarkCheck:TZ,BookmarkMinus:EZ,BookmarkPlus:JP,BookmarkX:AZ,BoomBox:MZ,Bot:YS,BotMessageSquare:IZ,BotOff:PZ,Box:G7,Boxes:LZ,Braces:F3,Brackets:DZ,Brain:W7,BrainCircuit:RZ,BrainCog:OZ,BrickWall:FZ,Briefcase:qm,BriefcaseBusiness:zZ,BriefcaseConveyorBelt:BZ,BriefcaseMedical:$Z,BringToFront:UZ,Brush:qZ,Bug:GZ,BugOff:VZ,BugPlay:HZ,Building:jA,Building2:Va,Bus:KZ,BusFront:WZ,Cable:ZZ,CableCar:YZ,Cake:cu,CakeSlice:QZ,Calculator:fw,Calendar:yr,Calendar1:XZ,CalendarArrowDown:JZ,CalendarArrowUp:eQ,CalendarCheck:ZS,CalendarCheck2:tQ,CalendarClock:om,CalendarCog:sQ,CalendarDays:Tl,CalendarFold:nQ,CalendarHeart:hb,CalendarMinus:aQ,CalendarMinus2:rQ,CalendarOff:K7,CalendarPlus:Rg,CalendarPlus2:iQ,CalendarRange:oQ,CalendarSearch:lQ,CalendarSync:cQ,CalendarX:Y7,CalendarX2:dQ,Camera:mf,CameraOff:uQ,Candy:pQ,CandyCane:hQ,CandyOff:mQ,Cannabis:fQ,Captions:z3,CaptionsOff:xQ,Car:vQ,CarFront:gQ,CarTaxiFront:yQ,Caravan:bQ,Carrot:_Q,CaseLower:wQ,CaseSensitive:jQ,CaseUpper:NQ,CassetteTape:kQ,Cast:SQ,Castle:CQ,Cat:TQ,Cctv:EQ,ChartArea:B3,ChartBar:U3,ChartBarBig:$3,ChartBarDecreasing:AQ,ChartBarIncreasing:MQ,ChartBarStacked:IQ,ChartCandlestick:q3,ChartColumn:yo,ChartColumnBig:V3,ChartColumnDecreasing:PQ,ChartColumnIncreasing:H3,ChartColumnStacked:LQ,ChartGantt:DQ,ChartLine:G3,ChartNetwork:RQ,ChartNoAxesColumn:K3,ChartNoAxesColumnDecreasing:OQ,ChartNoAxesColumnIncreasing:W3,ChartNoAxesCombined:FQ,ChartNoAxesGantt:Y3,ChartPie:Z3,ChartScatter:Q3,ChartSpline:zQ,Check:Ir,CheckCheck:Z7,ChefHat:BQ,Cherry:$Q,ChevronDown:io,ChevronFirst:UQ,ChevronLast:qQ,ChevronLeft:pl,ChevronRight:xa,ChevronUp:tx,ChevronsDown:HQ,ChevronsDownUp:VQ,ChevronsLeft:KQ,ChevronsLeftRight:WQ,ChevronsLeftRightEllipsis:GQ,ChevronsRight:ZQ,ChevronsRightLeft:YQ,ChevronsUp:QQ,ChevronsUpDown:qg,Chrome:NA,Church:XQ,Cigarette:eX,CigaretteOff:JQ,Circle:lm,CircleAlert:Gi,CircleArrowDown:X3,CircleArrowLeft:J3,CircleArrowOutDownLeft:e5,CircleArrowOutDownRight:t5,CircleArrowOutUpLeft:s5,CircleArrowOutUpRight:n5,CircleArrowRight:r5,CircleArrowUp:a5,CircleCheck:xr,CircleCheckBig:Ri,CircleChevronDown:i5,CircleChevronLeft:o5,CircleChevronRight:l5,CircleChevronUp:c5,CircleDashed:tX,CircleDivide:d5,CircleDollarSign:sX,CircleDot:rX,CircleDotDashed:nX,CircleEllipsis:aX,CircleEqual:iX,CircleFadingArrowUp:oX,CircleFadingPlus:lX,CircleGauge:u5,CircleHelp:K_,CircleMinus:h5,CircleOff:cX,CircleParking:p5,CircleParkingOff:m5,CirclePause:f5,CirclePercent:x5,CirclePlay:Au,CirclePlus:g5,CirclePower:y5,CircleSlash:dX,CircleSlash2:v5,CircleStop:b5,CircleUser:w5,CircleUserRound:_5,CircleX:Hc,CircuitBoard:uX,Citrus:hX,Clapperboard:mX,Clipboard:bX,ClipboardCheck:G2,ClipboardCopy:pX,ClipboardList:Dv,ClipboardMinus:fX,ClipboardPaste:xX,ClipboardPen:N5,ClipboardPenLine:j5,ClipboardPlus:gX,ClipboardType:yX,ClipboardX:vX,Clock:gr,Clock1:_X,Clock10:wX,Clock11:jX,Clock12:NX,Clock2:kX,Clock3:Q7,Clock4:SX,Clock5:CX,Clock6:TX,Clock7:EX,Clock8:AX,Clock9:MX,ClockAlert:IX,ClockArrowDown:PX,ClockArrowUp:LX,Cloud:YX,CloudAlert:DX,CloudCog:RX,CloudDownload:k5,CloudDrizzle:OX,CloudFog:FX,CloudHail:zX,CloudLightning:BX,CloudMoon:UX,CloudMoonRain:$X,CloudOff:qX,CloudRain:HX,CloudRainWind:VX,CloudSnow:GX,CloudSun:KX,CloudSunRain:WX,CloudUpload:S5,Cloudy:ZX,Clover:R2,Club:QX,Code:kA,CodeXml:C2,Codepen:XX,Codesandbox:JX,Coffee:ny,Cog:eJ,Coins:X7,Columns2:C5,Columns3:Kk,Columns4:tJ,Combine:sJ,Command:nJ,Compass:eL,Component:rJ,Computer:aJ,ConciergeBell:iJ,Cone:oJ,Construction:lJ,Contact:SA,ContactRound:T5,Container:cJ,Contrast:dJ,Cookie:uJ,CookingPot:hJ,Copy:Xr,CopyCheck:mJ,CopyMinus:pJ,CopyPlus:fJ,CopySlash:xJ,CopyX:gJ,Copyleft:yJ,Copyright:vJ,CornerDownLeft:bJ,CornerDownRight:_J,CornerLeftDown:wJ,CornerLeftUp:jJ,CornerRightDown:NJ,CornerRightUp:kJ,CornerUpLeft:SJ,CornerUpRight:CJ,Cpu:TJ,CreativeCommons:EJ,CreditCard:pf,Croissant:AJ,Crop:MJ,Cross:IJ,Crosshair:PJ,Crown:ff,Cuboid:LJ,CupSoda:DJ,Currency:RJ,Cylinder:OJ,Dam:FJ,Database:J7,DatabaseBackup:zJ,DatabaseZap:BJ,Delete:$J,Dessert:UJ,Diameter:qJ,Diamond:GJ,DiamondMinus:VJ,DiamondPercent:E5,DiamondPlus:HJ,Dice1:WJ,Dice2:KJ,Dice3:YJ,Dice4:ZJ,Dice5:QJ,Dice6:XJ,Dices:JJ,Diff:eee,Disc:ree,Disc2:tee,Disc3:see,DiscAlbum:nee,Divide:aee,Dna:oee,DnaOff:iee,Dock:lee,Dog:cee,DollarSign:Zl,Donut:dee,DoorClosed:uee,DoorOpen:xw,Dot:hee,Download:Pa,DraftingCompass:mee,Drama:pee,Dribbble:fee,Drill:xee,Droplet:gee,Droplets:mb,Drum:yee,Drumstick:vee,Dumbbell:bee,Ear:wee,EarOff:_ee,Earth:A5,EarthLock:jee,Eclipse:Nee,Egg:tL,EggFried:kee,EggOff:See,Ellipsis:Qf,EllipsisVertical:Ig,Equal:Eee,EqualApproximately:Cee,EqualNot:Tee,Eraser:Aee,EthernetPort:Mee,Euro:Iee,Expand:Pee,ExternalLink:tr,Eye:Er,EyeClosed:Lee,EyeOff:xf,Facebook:Lh,Factory:Dee,Fan:Ree,FastForward:Oee,Feather:Fee,Fence:zee,FerrisWheel:Bee,Figma:$ee,File:sL,FileArchive:Uee,FileAudio:Vee,FileAudio2:qee,FileAxis3d:M5,FileBadge:Gee,FileBadge2:Hee,FileBox:Wee,FileChartColumn:P5,FileChartColumnIncreasing:I5,FileChartLine:L5,FileChartPie:D5,FileCheck:e9,FileCheck2:Kee,FileClock:Yee,FileCode:Qee,FileCode2:Zee,FileCog:R5,FileDiff:Xee,FileDigit:Jee,FileDown:CA,FileHeart:ete,FileImage:W2,FileInput:tte,FileJson:nte,FileJson2:ste,FileKey:ate,FileKey2:rte,FileLock:ote,FileLock2:ite,FileMinus:cte,FileMinus2:lte,FileMusic:dte,FileOutput:ute,FilePen:O5,FilePenLine:Yk,FilePlus:mte,FilePlus2:hte,FileQuestion:pte,FileScan:fte,FileSearch:gte,FileSearch2:xte,FileSliders:yte,FileSpreadsheet:gw,FileStack:t9,FileSymlink:vte,FileTerminal:bte,FileText:Nr,FileType:wte,FileType2:_te,FileUp:jte,FileUser:Nte,FileVideo:s9,FileVideo2:kte,FileVolume:Cte,FileVolume2:Ste,FileWarning:Tte,FileX:Ate,FileX2:Ete,Files:Mte,Film:Ah,Filter:Rv,FilterX:Ite,Fingerprint:Pte,FireExtinguisher:Lte,Fish:Ote,FishOff:Dte,FishSymbol:Rte,Flag:K2,FlagOff:Fte,FlagTriangleLeft:zte,FlagTriangleRight:Bte,Flame:Dc,FlameKindling:$te,Flashlight:qte,FlashlightOff:Ute,FlaskConical:QS,FlaskConicalOff:Vte,FlaskRound:Hte,FlipHorizontal:n9,FlipHorizontal2:Gte,FlipVertical:Kte,FlipVertical2:Wte,Flower:Yte,Flower2:ob,Focus:Zte,FoldHorizontal:Qte,FoldVertical:Xte,Folder:kse,FolderArchive:Jte,FolderCheck:ese,FolderClock:tse,FolderClosed:sse,FolderCode:nse,FolderCog:F5,FolderDot:rse,FolderDown:ase,FolderGit:ose,FolderGit2:ise,FolderHeart:lse,FolderInput:cse,FolderKanban:dse,FolderKey:use,FolderLock:hse,FolderMinus:mse,FolderOpen:gf,FolderOpenDot:pse,FolderOutput:fse,FolderPen:z5,FolderPlus:xse,FolderRoot:gse,FolderSearch:vse,FolderSearch2:yse,FolderSymlink:bse,FolderSync:_se,FolderTree:wse,FolderUp:jse,FolderX:Nse,Folders:Sse,Footprints:Cse,Forklift:Tse,Forward:Ese,Frame:Ase,Framer:Mse,Frown:Ise,Fuel:Pse,Fullscreen:Lse,GalleryHorizontal:Rse,GalleryHorizontalEnd:Dse,GalleryThumbnails:Ose,GalleryVertical:zse,GalleryVerticalEnd:Fse,Gamepad:$se,Gamepad2:Bse,Gauge:Use,Gavel:qse,Gem:Vse,Ghost:TA,Gift:Oi,GitBranch:Gse,GitBranchPlus:Hse,GitCommitHorizontal:B5,GitCommitVertical:Wse,GitCompare:Yse,GitCompareArrows:Kse,GitFork:Zse,GitGraph:Qse,GitMerge:Xse,GitPullRequest:rne,GitPullRequestArrow:Jse,GitPullRequestClosed:ene,GitPullRequestCreate:sne,GitPullRequestCreateArrow:tne,GitPullRequestDraft:nne,Github:ane,Gitlab:ine,GlassWater:one,Glasses:lne,Globe:lc,GlobeLock:cne,Goal:dne,Grab:une,GraduationCap:_d,Grape:hne,Grid2x2:U5,Grid2x2Check:mne,Grid2x2Plus:$5,Grid2x2X:pne,Grid3x3:pv,Grip:xne,GripHorizontal:fne,GripVertical:Fu,Group:gne,Guitar:yne,Ham:vne,Hammer:r9,Hand:a9,HandCoins:bne,HandHeart:EA,HandHelping:tb,HandMetal:_ne,HandPlatter:wne,Handshake:pb,HardDrive:i9,HardDriveDownload:jne,HardDriveUpload:Nne,HardHat:kne,Hash:XS,Haze:Sne,HdmiPort:Cne,Heading:Mne,Heading1:nL,Heading2:rL,Heading3:o9,Heading4:Tne,Heading5:Ene,Heading6:Ane,HeadphoneOff:Ine,Headphones:Pne,Headset:Lne,Heart:gi,HeartCrack:Dne,HeartHandshake:AA,HeartOff:Rne,HeartPulse:One,Heater:Fne,Hexagon:zne,Highlighter:Bne,History:MA,Hop:Une,HopOff:$ne,Hospital:qne,Hotel:Vne,Hourglass:Hne,House:Or,HousePlug:Gne,HousePlus:Wne,IceCreamBowl:q5,IceCreamCone:V5,IdCard:Kne,Image:nl,ImageDown:Yne,ImageMinus:Zne,ImageOff:Qne,ImagePlay:Xne,ImagePlus:ry,ImageUp:Jne,ImageUpscale:ere,Images:tre,Import:sre,Inbox:Y2,IndentDecrease:H5,IndentIncrease:G5,IndianRupee:nre,Infinity:rre,Info:yw,InspectionPanel:are,Instagram:du,Italic:JS,IterationCcw:ire,IterationCw:ore,JapaneseYen:lre,Joystick:cre,Kanban:Z2,Key:Vg,KeyRound:IA,KeySquare:dre,Keyboard:mre,KeyboardMusic:ure,KeyboardOff:hre,Lamp:vre,LampCeiling:pre,LampDesk:fre,LampFloor:xre,LampWallDown:gre,LampWallUp:yre,LandPlot:bre,Landmark:_re,Languages:wre,Laptop:Nre,LaptopMinimal:W5,LaptopMinimalCheck:jre,Lasso:Sre,LassoSelect:kre,Laugh:Cre,Layers:l9,Layers2:Tre,Layers3:Ere,LayoutDashboard:e4,LayoutGrid:yf,LayoutList:Are,LayoutPanelLeft:Mre,LayoutPanelTop:Ire,LayoutTemplate:t4,Leaf:Pre,LeafyGreen:Lre,Lectern:Dre,LetterText:Rre,Library:Hg,LibraryBig:Ore,LifeBuoy:aL,Ligature:Fre,Lightbulb:vw,LightbulbOff:zre,Link:Jo,Link2:El,Link2Off:Bre,Linkedin:vf,List:Tp,ListCheck:$re,ListChecks:uu,ListCollapse:Ure,ListEnd:qre,ListFilter:c9,ListMinus:Vre,ListMusic:Hre,ListOrdered:Ov,ListPlus:Gre,ListRestart:Wre,ListStart:Kre,ListTodo:Yre,ListTree:Zre,ListVideo:Qre,ListX:Xre,Loader:eae,LoaderCircle:ts,LoaderPinwheel:Jre,Locate:iL,LocateFixed:tae,LocateOff:sae,Lock:Kc,LockKeyhole:nae,LockKeyholeOpen:K5,LockOpen:Y5,LogIn:PA,LogOut:LA,Logs:rae,Lollipop:aae,Luggage:iae,Magnet:oae,Mail:Vs,MailCheck:oL,MailMinus:lae,MailOpen:lL,MailPlus:d9,MailQuestion:cae,MailSearch:dae,MailWarning:uae,MailX:cL,Mailbox:hae,Mails:mae,Map:DA,MapPin:ka,MapPinCheck:fae,MapPinCheckInside:pae,MapPinHouse:xae,MapPinMinus:yae,MapPinMinusInside:gae,MapPinOff:vae,MapPinPlus:_ae,MapPinPlusInside:bae,MapPinX:jae,MapPinXInside:wae,MapPinned:Nae,Martini:kae,Maximize:RA,Maximize2:u9,Medal:Q2,Megaphone:$d,MegaphoneOff:Sae,Meh:Cae,MemoryStick:Tae,Menu:s4,Merge:Eae,MessageCircle:Ql,MessageCircleCode:Aae,MessageCircleDashed:Mae,MessageCircleHeart:dL,MessageCircleMore:Iae,MessageCircleOff:Pae,MessageCirclePlus:Lae,MessageCircleQuestion:h9,MessageCircleReply:Dae,MessageCircleWarning:Rae,MessageCircleX:Oae,MessageSquare:Ei,MessageSquareCode:Fae,MessageSquareDashed:zae,MessageSquareDiff:Bae,MessageSquareDot:$ae,MessageSquareHeart:uL,MessageSquareLock:Uae,MessageSquareMore:m9,MessageSquareOff:qae,MessageSquarePlus:nw,MessageSquareQuote:bw,MessageSquareReply:Vae,MessageSquareShare:Hae,MessageSquareText:Gae,MessageSquareWarning:Wae,MessageSquareX:Kae,MessagesSquare:hL,Mic:Fv,MicOff:Yae,MicVocal:Z5,Microchip:Zae,Microscope:Qae,Microwave:Xae,Milestone:Jae,Milk:tie,MilkOff:eie,Minimize:nie,Minimize2:sie,Minus:fb,Monitor:xb,MonitorCheck:rie,MonitorCog:aie,MonitorDot:iie,MonitorDown:oie,MonitorOff:lie,MonitorPause:cie,MonitorPlay:mL,MonitorSmartphone:die,MonitorSpeaker:uie,MonitorStop:hie,MonitorUp:OA,MonitorX:mie,Moon:fie,MoonStar:pie,Mountain:gie,MountainSnow:xie,Mouse:_ie,MouseOff:yie,MousePointer:Om,MousePointer2:vie,MousePointerBan:bie,MousePointerClick:oc,Move:Lie,Move3d:Q5,MoveDiagonal:jie,MoveDiagonal2:wie,MoveDown:Sie,MoveDownLeft:Nie,MoveDownRight:kie,MoveHorizontal:Cie,MoveLeft:Tie,MoveRight:Eie,MoveUp:Iie,MoveUpLeft:Aie,MoveUpRight:Mie,MoveVertical:Pie,Music:pL,Music2:Die,Music3:Rie,Music4:Oie,Navigation:p9,Navigation2:zie,Navigation2Off:Fie,NavigationOff:Bie,Network:$ie,Newspaper:ay,Nfc:Uie,Notebook:Gie,NotebookPen:qie,NotebookTabs:Vie,NotebookText:Hie,NotepadText:Kie,NotepadTextDashed:Wie,Nut:Zie,NutOff:Yie,Octagon:Xie,OctagonAlert:Y_,OctagonMinus:Qie,OctagonPause:X5,OctagonX:J5,Omega:Jie,Option:eoe,Orbit:toe,Origami:soe,Package:Rc,Package2:noe,PackageCheck:roe,PackageMinus:aoe,PackageOpen:ioe,PackagePlus:f9,PackageSearch:ooe,PackageX:loe,PaintBucket:coe,PaintRoller:doe,Paintbrush:uoe,PaintbrushVertical:eT,Palette:fl,PanelBottom:poe,PanelBottomClose:hoe,PanelBottomDashed:tT,PanelBottomOpen:moe,PanelLeft:aT,PanelLeftClose:sT,PanelLeftDashed:nT,PanelLeftOpen:rT,PanelRight:goe,PanelRightClose:foe,PanelRightDashed:iT,PanelRightOpen:xoe,PanelTop:boe,PanelTopClose:yoe,PanelTopDashed:oT,PanelTopOpen:voe,PanelsLeftBottom:_oe,PanelsRightBottom:woe,PanelsTopLeft:T2,Paperclip:n4,Parentheses:joe,ParkingMeter:Noe,PartyPopper:ch,Pause:bf,PawPrint:koe,PcCase:Soe,Pen:wv,PenLine:sb,PenOff:Coe,PenTool:r4,Pencil:_a,PencilLine:x9,PencilOff:Toe,PencilRuler:Eoe,Pentagon:Aoe,Percent:a4,PersonStanding:Moe,PhilippinePeso:Ioe,Phone:Ar,PhoneCall:g9,PhoneForwarded:Poe,PhoneIncoming:Loe,PhoneMissed:Doe,PhoneOff:Roe,PhoneOutgoing:Ooe,Pi:Foe,Piano:zoe,Pickaxe:Boe,PictureInPicture:Uoe,PictureInPicture2:$oe,PiggyBank:qoe,Pilcrow:Goe,PilcrowLeft:Voe,PilcrowRight:Hoe,Pill:Koe,PillBottle:Woe,Pin:i4,PinOff:y9,Pipette:Yoe,Pizza:Zoe,Plane:v9,PlaneLanding:Qoe,PlaneTakeoff:Xoe,Play:Al,Plug:X2,Plug2:Joe,PlugZap:lT,Plus:Is,Pocket:tle,PocketKnife:ele,Podcast:sle,Pointer:rle,PointerOff:nle,Popcorn:ale,Popsicle:ile,PoundSterling:ole,Power:b9,PowerOff:lle,Presentation:iy,Printer:_9,PrinterCheck:cle,Projector:dle,Proportions:ule,Puzzle:hle,Pyramid:mle,QrCode:oy,Quote:gb,Rabbit:ple,Radar:FA,Radiation:fle,Radical:xle,Radio:_f,RadioReceiver:gle,RadioTower:yle,Radius:vle,RailSymbol:ble,Rainbow:_le,Rat:wle,Ratio:jle,Receipt:Ile,ReceiptCent:Nle,ReceiptEuro:kle,ReceiptIndianRupee:Sle,ReceiptJapaneseYen:Cle,ReceiptPoundSterling:Tle,ReceiptRussianRuble:Ele,ReceiptSwissFranc:Ale,ReceiptText:Mle,RectangleEllipsis:cT,RectangleHorizontal:Ple,RectangleVertical:Lle,Recycle:Dle,Redo:o4,Redo2:Rle,RedoDot:Ole,RefreshCcw:fL,RefreshCcwDot:Fle,RefreshCw:Ti,RefreshCwOff:zle,Refrigerator:Ble,Regex:$le,RemoveFormatting:Ule,Repeat:xL,Repeat1:qle,Repeat2:Vle,Replace:Gle,ReplaceAll:Hle,Reply:w9,ReplyAll:Wle,Rewind:Kle,Ribbon:Yle,Rocket:sx,RockingChair:Zle,RollerCoaster:Qle,Rotate3d:dT,RotateCcw:cm,RotateCcwSquare:Xle,RotateCw:zA,RotateCwSquare:Jle,Route:j9,RouteOff:ece,Router:tce,Rows2:uT,Rows3:hT,Rows4:sce,Rss:nce,Ruler:J2,RussianRuble:rce,Sailboat:ace,Salad:ice,Sandwich:oce,Satellite:cce,SatelliteDish:lce,Save:qo,SaveAll:dce,SaveOff:uce,Scale:N9,Scale3d:mT,Scaling:hce,Scan:bce,ScanBarcode:mce,ScanEye:pce,ScanFace:fce,ScanLine:xce,ScanQrCode:gce,ScanSearch:yce,ScanText:vce,School:_ce,Scissors:jce,ScissorsLineDashed:wce,ScreenShare:kce,ScreenShareOff:Nce,Scroll:Sce,ScrollText:k9,Search:vr,SearchCheck:Cce,SearchCode:Tce,SearchSlash:Ece,SearchX:S9,Section:Ace,Send:cr,SendHorizontal:pT,SendToBack:Mce,SeparatorHorizontal:Ice,SeparatorVertical:Pce,Server:Oce,ServerCog:Lce,ServerCrash:Dce,ServerOff:Rce,Settings:Xo,Settings2:C9,Shapes:Fce,Share:T9,Share2:Hl,Sheet:zce,Shell:Bce,Shield:dh,ShieldAlert:gL,ShieldBan:$ce,ShieldCheck:sg,ShieldEllipsis:Uce,ShieldHalf:qce,ShieldMinus:Vce,ShieldOff:BA,ShieldPlus:Hce,ShieldQuestion:Gce,ShieldX:fT,Ship:Kce,ShipWheel:Wce,Shirt:Yce,ShoppingBag:_w,ShoppingBasket:Zce,ShoppingCart:Og,Shovel:Qce,ShowerHead:Xce,Shrink:Jce,Shrub:ede,Shuffle:$A,Sigma:tde,Signal:ide,SignalHigh:sde,SignalLow:nde,SignalMedium:rde,SignalZero:ade,Signature:ode,Signpost:cde,SignpostBig:lde,Siren:dde,SkipBack:ude,SkipForward:hde,Skull:mde,Slack:pde,Slash:fde,Slice:xde,SlidersHorizontal:l4,SlidersVertical:xT,Smartphone:ng,SmartphoneCharging:gde,SmartphoneNfc:yde,Smile:bde,SmilePlus:vde,Snail:_de,Snowflake:Ev,Sofa:wde,Soup:jde,Space:Nde,Spade:kde,Sparkle:eN,Sparkles:un,Speaker:Sde,Speech:Cde,SpellCheck:Ede,SpellCheck2:Tde,Spline:Ade,Split:Mde,SprayCan:Ide,Sprout:UA,Square:ly,SquareActivity:gT,SquareArrowDown:bT,SquareArrowDownLeft:yT,SquareArrowDownRight:vT,SquareArrowLeft:_T,SquareArrowOutDownLeft:wT,SquareArrowOutDownRight:jT,SquareArrowOutUpLeft:NT,SquareArrowOutUpRight:kT,SquareArrowRight:ST,SquareArrowUp:ET,SquareArrowUpLeft:CT,SquareArrowUpRight:TT,SquareAsterisk:AT,SquareBottomDashedScissors:MT,SquareChartGantt:L_,SquareCheck:IT,SquareCheckBig:E2,SquareChevronDown:PT,SquareChevronLeft:LT,SquareChevronRight:DT,SquareChevronUp:RT,SquareCode:OT,SquareDashed:BT,SquareDashedBottom:Lde,SquareDashedBottomCode:Pde,SquareDashedKanban:FT,SquareDashedMousePointer:zT,SquareDivide:$T,SquareDot:UT,SquareEqual:qT,SquareFunction:VT,SquareKanban:HT,SquareLibrary:GT,SquareM:WT,SquareMenu:KT,SquareMinus:YT,SquareMousePointer:ZT,SquareParking:XT,SquareParkingOff:QT,SquarePen:ku,SquarePercent:JT,SquarePi:eE,SquarePilcrow:tE,SquarePlay:sE,SquarePlus:nE,SquarePower:rE,SquareRadical:Dde,SquareScissors:aE,SquareSigma:iE,SquareSlash:oE,SquareSplitHorizontal:lE,SquareSplitVertical:cE,SquareSquare:Rde,SquareStack:Ode,SquareTerminal:dE,SquareUser:hE,SquareUserRound:uE,SquareX:mE,Squircle:Fde,Squirrel:zde,Stamp:Bde,Star:ca,StarHalf:$de,StarOff:Ude,StepBack:qde,StepForward:Vde,Stethoscope:Hde,Sticker:Gde,StickyNote:E9,Store:A9,StretchHorizontal:Wde,StretchVertical:Kde,Strikethrough:M9,Subscript:Yde,Sun:yb,SunDim:Zde,SunMedium:Qde,SunMoon:Xde,SunSnow:Jde,Sunrise:eue,Sunset:tue,Superscript:sue,SwatchBook:nue,SwissFranc:rue,SwitchCamera:aue,Sword:iue,Swords:oue,Syringe:lue,Table:vL,Table2:yL,TableCellsMerge:cue,TableCellsSplit:due,TableColumnsSplit:uue,TableOfContents:hue,TableProperties:mue,TableRowsSplit:pue,Tablet:bL,TabletSmartphone:fue,Tablets:xue,Tag:uh,Tags:I9,Tally1:gue,Tally2:yue,Tally3:vue,Tally4:bue,Tally5:_ue,Tangent:wue,Target:Oc,Telescope:jue,Tent:kue,TentTree:Nue,Terminal:Sue,TestTube:Cue,TestTubeDiagonal:pE,TestTubes:Tue,Text:Pue,TextCursor:Aue,TextCursorInput:Eue,TextQuote:Mue,TextSearch:Iue,TextSelect:fE,Theater:Lue,Thermometer:P9,ThermometerSnowflake:Due,ThermometerSun:Rue,ThumbsDown:L9,ThumbsUp:Vm,Ticket:D9,TicketCheck:Oue,TicketMinus:Fue,TicketPercent:zue,TicketPlus:Bue,TicketSlash:$ue,TicketX:Uue,Tickets:Vue,TicketsPlane:que,Timer:Wue,TimerOff:Hue,TimerReset:Gue,ToggleLeft:Kue,ToggleRight:Yue,Toilet:Zue,Tornado:Que,Torus:Xue,Touchpad:ehe,TouchpadOff:Jue,TowerControl:the,ToyBrick:she,Tractor:nhe,TrafficCone:rhe,TrainFront:ihe,TrainFrontTunnel:ahe,TrainTrack:ohe,TramFront:xE,Trash:lhe,Trash2:_n,TreeDeciduous:che,TreePalm:gE,TreePine:c4,Trees:dhe,Trello:uhe,TrendingDown:vb,TrendingUp:mo,TrendingUpDown:hhe,Triangle:phe,TriangleAlert:$l,TriangleRight:mhe,Trophy:vo,Truck:R9,Turtle:fhe,Tv:ghe,TvMinimal:yE,TvMinimalPlay:xhe,Twitch:yhe,Twitter:vhe,Type:_he,TypeOutline:bhe,Umbrella:jhe,UmbrellaOff:whe,Underline:_L,Undo:d4,Undo2:Nhe,UndoDot:khe,UnfoldHorizontal:She,UnfoldVertical:Che,Ungroup:The,University:vE,Unlink:qA,Unlink2:Ehe,Unplug:Ahe,Upload:Na,Usb:Mhe,User:Xi,UserCheck:bb,UserCog:O9,UserMinus:F9,UserPen:Ihe,UserPlus:Fo,UserRound:kE,UserRoundCheck:bE,UserRoundCog:_E,UserRoundMinus:wE,UserRoundPen:Phe,UserRoundPlus:jE,UserRoundSearch:Lhe,UserRoundX:NE,UserSearch:Dhe,UserX:Rhe,Users:Nn,UsersRound:G0,Utensils:CE,UtensilsCrossed:SE,UtilityPole:Ohe,Variable:wL,Vault:Fhe,Vegan:zhe,VenetianMask:Bhe,Vibrate:Uhe,VibrateOff:$he,Video:br,VideoOff:qhe,Videotape:Vhe,View:Hhe,Voicemail:Ghe,Volleyball:Whe,Volume:Zhe,Volume1:Khe,Volume2:z9,VolumeOff:Yhe,VolumeX:B9,Vote:Qhe,Wallet:jL,WalletCards:Xhe,WalletMinimal:TE,Wallpaper:Jhe,Wand:eme,WandSparkles:Dm,Warehouse:tme,WashingMachine:sme,Watch:nme,Waves:rme,Waypoints:ame,Webcam:ime,Webhook:lme,WebhookOff:ome,Weight:cme,Wheat:ume,WheatOff:dme,WholeWord:hme,Wifi:gme,WifiHigh:mme,WifiLow:pme,WifiOff:fme,WifiZero:xme,Wind:vme,WindArrowDown:yme,Wine:$9,WineOff:bme,Workflow:U9,Worm:_me,WrapText:wme,Wrench:_b,X:Bn,Youtube:jme,Zap:hh,ZapOff:Nme,ZoomIn:u4,ZoomOut:NL},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 T0e=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:SW,AArrowDownIcon:SW,AArrowUp:CW,AArrowUpIcon:CW,ALargeSmall:TW,ALargeSmallIcon:TW,Accessibility:EW,AccessibilityIcon:EW,Activity:nm,ActivityIcon:nm,ActivitySquare:gT,ActivitySquareIcon:gT,AirVent:AW,AirVentIcon:AW,Airplay:MW,AirplayIcon:MW,AlarmCheck:N3,AlarmCheckIcon:N3,AlarmClock:PW,AlarmClockCheck:N3,AlarmClockCheckIcon:N3,AlarmClockIcon:PW,AlarmClockMinus:k3,AlarmClockMinusIcon:k3,AlarmClockOff:IW,AlarmClockOffIcon:IW,AlarmClockPlus:S3,AlarmClockPlusIcon:S3,AlarmMinus:k3,AlarmMinusIcon:k3,AlarmPlus:S3,AlarmPlusIcon:S3,AlarmSmoke:LW,AlarmSmokeIcon:LW,Album:DW,AlbumIcon:DW,AlertCircle:Gi,AlertCircleIcon:Gi,AlertOctagon:Y_,AlertOctagonIcon:Y_,AlertTriangle:$l,AlertTriangleIcon:$l,AlignCenter:bA,AlignCenterHorizontal:RW,AlignCenterHorizontalIcon:RW,AlignCenterIcon:bA,AlignCenterVertical:OW,AlignCenterVerticalIcon:OW,AlignEndHorizontal:FW,AlignEndHorizontalIcon:FW,AlignEndVertical:zW,AlignEndVerticalIcon:zW,AlignHorizontalDistributeCenter:BW,AlignHorizontalDistributeCenterIcon:BW,AlignHorizontalDistributeEnd:$W,AlignHorizontalDistributeEndIcon:$W,AlignHorizontalDistributeStart:UW,AlignHorizontalDistributeStartIcon:UW,AlignHorizontalJustifyCenter:qW,AlignHorizontalJustifyCenterIcon:qW,AlignHorizontalJustifyEnd:VW,AlignHorizontalJustifyEndIcon:VW,AlignHorizontalJustifyStart:HW,AlignHorizontalJustifyStartIcon:HW,AlignHorizontalSpaceAround:GW,AlignHorizontalSpaceAroundIcon:GW,AlignHorizontalSpaceBetween:WW,AlignHorizontalSpaceBetweenIcon:WW,AlignJustify:KW,AlignJustifyIcon:KW,AlignLeft:_A,AlignLeftIcon:_A,AlignRight:wA,AlignRightIcon:wA,AlignStartHorizontal:YW,AlignStartHorizontalIcon:YW,AlignStartVertical:ZW,AlignStartVerticalIcon:ZW,AlignVerticalDistributeCenter:QW,AlignVerticalDistributeCenterIcon:QW,AlignVerticalDistributeEnd:XW,AlignVerticalDistributeEndIcon:XW,AlignVerticalDistributeStart:JW,AlignVerticalDistributeStartIcon:JW,AlignVerticalJustifyCenter:eK,AlignVerticalJustifyCenterIcon:eK,AlignVerticalJustifyEnd:tK,AlignVerticalJustifyEndIcon:tK,AlignVerticalJustifyStart:sK,AlignVerticalJustifyStartIcon:sK,AlignVerticalSpaceAround:nK,AlignVerticalSpaceAroundIcon:nK,AlignVerticalSpaceBetween:rK,AlignVerticalSpaceBetweenIcon:rK,Ambulance:aK,AmbulanceIcon:aK,Ampersand:iK,AmpersandIcon:iK,Ampersands:oK,AmpersandsIcon:oK,Amphora:lK,AmphoraIcon:lK,Anchor:cK,AnchorIcon:cK,Angry:dK,AngryIcon:dK,Annoyed:uK,AnnoyedIcon:uK,Antenna:hK,AntennaIcon:hK,Anvil:mK,AnvilIcon:mK,Aperture:pK,ApertureIcon:pK,AppWindow:xK,AppWindowIcon:xK,AppWindowMac:fK,AppWindowMacIcon:fK,Apple:gK,AppleIcon:gK,Archive:rm,ArchiveIcon:rm,ArchiveRestore:ZP,ArchiveRestoreIcon:ZP,ArchiveX:yK,ArchiveXIcon:yK,AreaChart:B3,AreaChartIcon:B3,Armchair:vK,ArmchairIcon:vK,ArrowBigDown:_K,ArrowBigDownDash:bK,ArrowBigDownDashIcon:bK,ArrowBigDownIcon:_K,ArrowBigLeft:jK,ArrowBigLeftDash:wK,ArrowBigLeftDashIcon:wK,ArrowBigLeftIcon:jK,ArrowBigRight:kK,ArrowBigRightDash:NK,ArrowBigRightDashIcon:NK,ArrowBigRightIcon:kK,ArrowBigUp:CK,ArrowBigUpDash:SK,ArrowBigUpDashIcon:SK,ArrowBigUpIcon:CK,ArrowDown:am,ArrowDown01:TK,ArrowDown01Icon:TK,ArrowDown10:EK,ArrowDown10Icon:EK,ArrowDownAZ:C3,ArrowDownAZIcon:C3,ArrowDownAz:C3,ArrowDownAzIcon:C3,ArrowDownCircle:X3,ArrowDownCircleIcon:X3,ArrowDownFromLine:AK,ArrowDownFromLineIcon:AK,ArrowDownIcon:am,ArrowDownLeft:MK,ArrowDownLeftFromCircle:e5,ArrowDownLeftFromCircleIcon:e5,ArrowDownLeftFromSquare:wT,ArrowDownLeftFromSquareIcon:wT,ArrowDownLeftIcon:MK,ArrowDownLeftSquare:yT,ArrowDownLeftSquareIcon:yT,ArrowDownNarrowWide:IK,ArrowDownNarrowWideIcon:IK,ArrowDownRight:V7,ArrowDownRightFromCircle:t5,ArrowDownRightFromCircleIcon:t5,ArrowDownRightFromSquare:jT,ArrowDownRightFromSquareIcon:jT,ArrowDownRightIcon:V7,ArrowDownRightSquare:vT,ArrowDownRightSquareIcon:vT,ArrowDownSquare:bT,ArrowDownSquareIcon:bT,ArrowDownToDot:PK,ArrowDownToDotIcon:PK,ArrowDownToLine:LK,ArrowDownToLineIcon:LK,ArrowDownUp:DK,ArrowDownUpIcon:DK,ArrowDownWideNarrow:T3,ArrowDownWideNarrowIcon:T3,ArrowDownZA:E3,ArrowDownZAIcon:E3,ArrowDownZa:E3,ArrowDownZaIcon:E3,ArrowLeft:Hr,ArrowLeftCircle:J3,ArrowLeftCircleIcon:J3,ArrowLeftFromLine:RK,ArrowLeftFromLineIcon:RK,ArrowLeftIcon:Hr,ArrowLeftRight:OK,ArrowLeftRightIcon:OK,ArrowLeftSquare:_T,ArrowLeftSquareIcon:_T,ArrowLeftToLine:FK,ArrowLeftToLineIcon:FK,ArrowRight:Oa,ArrowRightCircle:r5,ArrowRightCircleIcon:r5,ArrowRightFromLine:zK,ArrowRightFromLineIcon:zK,ArrowRightIcon:Oa,ArrowRightLeft:mw,ArrowRightLeftIcon:mw,ArrowRightSquare:ST,ArrowRightSquareIcon:ST,ArrowRightToLine:BK,ArrowRightToLineIcon:BK,ArrowUp:Ru,ArrowUp01:$K,ArrowUp01Icon:$K,ArrowUp10:UK,ArrowUp10Icon:UK,ArrowUpAZ:A3,ArrowUpAZIcon:A3,ArrowUpAz:A3,ArrowUpAzIcon:A3,ArrowUpCircle:a5,ArrowUpCircleIcon:a5,ArrowUpDown:em,ArrowUpDownIcon:em,ArrowUpFromDot:qK,ArrowUpFromDotIcon:qK,ArrowUpFromLine:VK,ArrowUpFromLineIcon:VK,ArrowUpIcon:Ru,ArrowUpLeft:HK,ArrowUpLeftFromCircle:s5,ArrowUpLeftFromCircleIcon:s5,ArrowUpLeftFromSquare:NT,ArrowUpLeftFromSquareIcon:NT,ArrowUpLeftIcon:HK,ArrowUpLeftSquare:CT,ArrowUpLeftSquareIcon:CT,ArrowUpNarrowWide:M3,ArrowUpNarrowWideIcon:M3,ArrowUpRight:QP,ArrowUpRightFromCircle:n5,ArrowUpRightFromCircleIcon:n5,ArrowUpRightFromSquare:kT,ArrowUpRightFromSquareIcon:kT,ArrowUpRightIcon:QP,ArrowUpRightSquare:TT,ArrowUpRightSquareIcon:TT,ArrowUpSquare:ET,ArrowUpSquareIcon:ET,ArrowUpToLine:GK,ArrowUpToLineIcon:GK,ArrowUpWideNarrow:WK,ArrowUpWideNarrowIcon:WK,ArrowUpZA:I3,ArrowUpZAIcon:I3,ArrowUpZa:I3,ArrowUpZaIcon:I3,ArrowsUpFromLine:KK,ArrowsUpFromLineIcon:KK,Asterisk:YK,AsteriskIcon:YK,AsteriskSquare:AT,AsteriskSquareIcon:AT,AtSign:ZK,AtSignIcon:ZK,Atom:QK,AtomIcon:QK,AudioLines:XK,AudioLinesIcon:XK,AudioWaveform:JK,AudioWaveformIcon:JK,Award:bc,AwardIcon:bc,Axe:eY,AxeIcon:eY,Axis3D:P3,Axis3DIcon:P3,Axis3d:P3,Axis3dIcon:P3,Baby:tY,BabyIcon:tY,Backpack:sY,BackpackIcon:sY,Badge:yY,BadgeAlert:nY,BadgeAlertIcon:nY,BadgeCent:rY,BadgeCentIcon:rY,BadgeCheck:L3,BadgeCheckIcon:L3,BadgeDollarSign:aY,BadgeDollarSignIcon:aY,BadgeEuro:iY,BadgeEuroIcon:iY,BadgeHelp:oY,BadgeHelpIcon:oY,BadgeIcon:yY,BadgeIndianRupee:lY,BadgeIndianRupeeIcon:lY,BadgeInfo:cY,BadgeInfoIcon:cY,BadgeJapaneseYen:dY,BadgeJapaneseYenIcon:dY,BadgeMinus:uY,BadgeMinusIcon:uY,BadgePercent:hY,BadgePercentIcon:hY,BadgePlus:mY,BadgePlusIcon:mY,BadgePoundSterling:pY,BadgePoundSterlingIcon:pY,BadgeRussianRuble:fY,BadgeRussianRubleIcon:fY,BadgeSwissFranc:xY,BadgeSwissFrancIcon:xY,BadgeX:gY,BadgeXIcon:gY,BaggageClaim:vY,BaggageClaimIcon:vY,Ban:XP,BanIcon:XP,Banana:bY,BananaIcon:bY,Bandage:_Y,BandageIcon:_Y,Banknote:wY,BanknoteIcon:wY,BarChart:W3,BarChart2:K3,BarChart2Icon:K3,BarChart3:yo,BarChart3Icon:yo,BarChart4:H3,BarChart4Icon:H3,BarChartBig:V3,BarChartBigIcon:V3,BarChartHorizontal:U3,BarChartHorizontalBig:$3,BarChartHorizontalBigIcon:$3,BarChartHorizontalIcon:U3,BarChartIcon:W3,Barcode:jY,BarcodeIcon:jY,Baseline:NY,BaselineIcon:NY,Bath:Cp,BathIcon:Cp,Battery:AY,BatteryCharging:kY,BatteryChargingIcon:kY,BatteryFull:SY,BatteryFullIcon:SY,BatteryIcon:AY,BatteryLow:CY,BatteryLowIcon:CY,BatteryMedium:TY,BatteryMediumIcon:TY,BatteryWarning:EY,BatteryWarningIcon:EY,Beaker:H7,BeakerIcon:H7,Bean:IY,BeanIcon:IY,BeanOff:MY,BeanOffIcon:MY,Bed:sy,BedDouble:H2,BedDoubleIcon:H2,BedIcon:sy,BedSingle:PY,BedSingleIcon:PY,Beef:LY,BeefIcon:LY,Beer:RY,BeerIcon:RY,BeerOff:DY,BeerOffIcon:DY,Bell:im,BellDot:OY,BellDotIcon:OY,BellElectric:FY,BellElectricIcon:FY,BellIcon:im,BellMinus:zY,BellMinusIcon:zY,BellOff:pw,BellOffIcon:pw,BellPlus:BY,BellPlusIcon:BY,BellRing:WS,BellRingIcon:WS,BetweenHorizonalEnd:D3,BetweenHorizonalEndIcon:D3,BetweenHorizonalStart:R3,BetweenHorizonalStartIcon:R3,BetweenHorizontalEnd:D3,BetweenHorizontalEndIcon:D3,BetweenHorizontalStart:R3,BetweenHorizontalStartIcon:R3,BetweenVerticalEnd:$Y,BetweenVerticalEndIcon:$Y,BetweenVerticalStart:UY,BetweenVerticalStartIcon:UY,BicepsFlexed:qY,BicepsFlexedIcon:qY,Bike:VY,BikeIcon:VY,Binary:HY,BinaryIcon:HY,Binoculars:GY,BinocularsIcon:GY,Biohazard:WY,BiohazardIcon:WY,Bird:KY,BirdIcon:KY,Bitcoin:YY,BitcoinIcon:YY,Blend:ZY,BlendIcon:ZY,Blinds:QY,BlindsIcon:QY,Blocks:XY,BlocksIcon:XY,Bluetooth:sZ,BluetoothConnected:JY,BluetoothConnectedIcon:JY,BluetoothIcon:sZ,BluetoothOff:eZ,BluetoothOffIcon:eZ,BluetoothSearching:tZ,BluetoothSearchingIcon:tZ,Bold:KS,BoldIcon:KS,Bolt:nZ,BoltIcon:nZ,Bomb:rZ,BombIcon:rZ,Bone:aZ,BoneIcon:aZ,Book:CZ,BookA:iZ,BookAIcon:iZ,BookAudio:oZ,BookAudioIcon:oZ,BookCheck:lZ,BookCheckIcon:lZ,BookCopy:cZ,BookCopyIcon:cZ,BookDashed:O3,BookDashedIcon:O3,BookDown:dZ,BookDownIcon:dZ,BookHeadphones:uZ,BookHeadphonesIcon:uZ,BookHeart:hZ,BookHeartIcon:hZ,BookIcon:CZ,BookImage:mZ,BookImageIcon:mZ,BookKey:pZ,BookKeyIcon:pZ,BookLock:fZ,BookLockIcon:fZ,BookMarked:xZ,BookMarkedIcon:xZ,BookMinus:gZ,BookMinusIcon:gZ,BookOpen:Ou,BookOpenCheck:yZ,BookOpenCheckIcon:yZ,BookOpenIcon:Ou,BookOpenText:vZ,BookOpenTextIcon:vZ,BookPlus:bZ,BookPlusIcon:bZ,BookTemplate:O3,BookTemplateIcon:O3,BookText:_Z,BookTextIcon:_Z,BookType:wZ,BookTypeIcon:wZ,BookUp:NZ,BookUp2:jZ,BookUp2Icon:jZ,BookUpIcon:NZ,BookUser:kZ,BookUserIcon:kZ,BookX:SZ,BookXIcon:SZ,Bookmark:Lv,BookmarkCheck:TZ,BookmarkCheckIcon:TZ,BookmarkIcon:Lv,BookmarkMinus:EZ,BookmarkMinusIcon:EZ,BookmarkPlus:JP,BookmarkPlusIcon:JP,BookmarkX:AZ,BookmarkXIcon:AZ,BoomBox:MZ,BoomBoxIcon:MZ,Bot:YS,BotIcon:YS,BotMessageSquare:IZ,BotMessageSquareIcon:IZ,BotOff:PZ,BotOffIcon:PZ,Box:G7,BoxIcon:G7,BoxSelect:BT,BoxSelectIcon:BT,Boxes:LZ,BoxesIcon:LZ,Braces:F3,BracesIcon:F3,Brackets:DZ,BracketsIcon:DZ,Brain:W7,BrainCircuit:RZ,BrainCircuitIcon:RZ,BrainCog:OZ,BrainCogIcon:OZ,BrainIcon:W7,BrickWall:FZ,BrickWallIcon:FZ,Briefcase:qm,BriefcaseBusiness:zZ,BriefcaseBusinessIcon:zZ,BriefcaseConveyorBelt:BZ,BriefcaseConveyorBeltIcon:BZ,BriefcaseIcon:qm,BriefcaseMedical:$Z,BriefcaseMedicalIcon:$Z,BringToFront:UZ,BringToFrontIcon:UZ,Brush:qZ,BrushIcon:qZ,Bug:GZ,BugIcon:GZ,BugOff:VZ,BugOffIcon:VZ,BugPlay:HZ,BugPlayIcon:HZ,Building:jA,Building2:Va,Building2Icon:Va,BuildingIcon:jA,Bus:KZ,BusFront:WZ,BusFrontIcon:WZ,BusIcon:KZ,Cable:ZZ,CableCar:YZ,CableCarIcon:YZ,CableIcon:ZZ,Cake:cu,CakeIcon:cu,CakeSlice:QZ,CakeSliceIcon:QZ,Calculator:fw,CalculatorIcon:fw,Calendar:yr,Calendar1:XZ,Calendar1Icon:XZ,CalendarArrowDown:JZ,CalendarArrowDownIcon:JZ,CalendarArrowUp:eQ,CalendarArrowUpIcon:eQ,CalendarCheck:ZS,CalendarCheck2:tQ,CalendarCheck2Icon:tQ,CalendarCheckIcon:ZS,CalendarClock:om,CalendarClockIcon:om,CalendarCog:sQ,CalendarCogIcon:sQ,CalendarDays:Tl,CalendarDaysIcon:Tl,CalendarFold:nQ,CalendarFoldIcon:nQ,CalendarHeart:hb,CalendarHeartIcon:hb,CalendarIcon:yr,CalendarMinus:aQ,CalendarMinus2:rQ,CalendarMinus2Icon:rQ,CalendarMinusIcon:aQ,CalendarOff:K7,CalendarOffIcon:K7,CalendarPlus:Rg,CalendarPlus2:iQ,CalendarPlus2Icon:iQ,CalendarPlusIcon:Rg,CalendarRange:oQ,CalendarRangeIcon:oQ,CalendarSearch:lQ,CalendarSearchIcon:lQ,CalendarSync:cQ,CalendarSyncIcon:cQ,CalendarX:Y7,CalendarX2:dQ,CalendarX2Icon:dQ,CalendarXIcon:Y7,Camera:mf,CameraIcon:mf,CameraOff:uQ,CameraOffIcon:uQ,CandlestickChart:q3,CandlestickChartIcon:q3,Candy:pQ,CandyCane:hQ,CandyCaneIcon:hQ,CandyIcon:pQ,CandyOff:mQ,CandyOffIcon:mQ,Cannabis:fQ,CannabisIcon:fQ,Captions:z3,CaptionsIcon:z3,CaptionsOff:xQ,CaptionsOffIcon:xQ,Car:vQ,CarFront:gQ,CarFrontIcon:gQ,CarIcon:vQ,CarTaxiFront:yQ,CarTaxiFrontIcon:yQ,Caravan:bQ,CaravanIcon:bQ,Carrot:_Q,CarrotIcon:_Q,CaseLower:wQ,CaseLowerIcon:wQ,CaseSensitive:jQ,CaseSensitiveIcon:jQ,CaseUpper:NQ,CaseUpperIcon:NQ,CassetteTape:kQ,CassetteTapeIcon:kQ,Cast:SQ,CastIcon:SQ,Castle:CQ,CastleIcon:CQ,Cat:TQ,CatIcon:TQ,Cctv:EQ,CctvIcon:EQ,ChartArea:B3,ChartAreaIcon:B3,ChartBar:U3,ChartBarBig:$3,ChartBarBigIcon:$3,ChartBarDecreasing:AQ,ChartBarDecreasingIcon:AQ,ChartBarIcon:U3,ChartBarIncreasing:MQ,ChartBarIncreasingIcon:MQ,ChartBarStacked:IQ,ChartBarStackedIcon:IQ,ChartCandlestick:q3,ChartCandlestickIcon:q3,ChartColumn:yo,ChartColumnBig:V3,ChartColumnBigIcon:V3,ChartColumnDecreasing:PQ,ChartColumnDecreasingIcon:PQ,ChartColumnIcon:yo,ChartColumnIncreasing:H3,ChartColumnIncreasingIcon:H3,ChartColumnStacked:LQ,ChartColumnStackedIcon:LQ,ChartGantt:DQ,ChartGanttIcon:DQ,ChartLine:G3,ChartLineIcon:G3,ChartNetwork:RQ,ChartNetworkIcon:RQ,ChartNoAxesColumn:K3,ChartNoAxesColumnDecreasing:OQ,ChartNoAxesColumnDecreasingIcon:OQ,ChartNoAxesColumnIcon:K3,ChartNoAxesColumnIncreasing:W3,ChartNoAxesColumnIncreasingIcon:W3,ChartNoAxesCombined:FQ,ChartNoAxesCombinedIcon:FQ,ChartNoAxesGantt:Y3,ChartNoAxesGanttIcon:Y3,ChartPie:Z3,ChartPieIcon:Z3,ChartScatter:Q3,ChartScatterIcon:Q3,ChartSpline:zQ,ChartSplineIcon:zQ,Check:Ir,CheckCheck:Z7,CheckCheckIcon:Z7,CheckCircle:Ri,CheckCircle2:xr,CheckCircle2Icon:xr,CheckCircleIcon:Ri,CheckIcon:Ir,CheckSquare:E2,CheckSquare2:IT,CheckSquare2Icon:IT,CheckSquareIcon:E2,ChefHat:BQ,ChefHatIcon:BQ,Cherry:$Q,CherryIcon:$Q,ChevronDown:io,ChevronDownCircle:i5,ChevronDownCircleIcon:i5,ChevronDownIcon:io,ChevronDownSquare:PT,ChevronDownSquareIcon:PT,ChevronFirst:UQ,ChevronFirstIcon:UQ,ChevronLast:qQ,ChevronLastIcon:qQ,ChevronLeft:pl,ChevronLeftCircle:o5,ChevronLeftCircleIcon:o5,ChevronLeftIcon:pl,ChevronLeftSquare:LT,ChevronLeftSquareIcon:LT,ChevronRight:xa,ChevronRightCircle:l5,ChevronRightCircleIcon:l5,ChevronRightIcon:xa,ChevronRightSquare:DT,ChevronRightSquareIcon:DT,ChevronUp:tx,ChevronUpCircle:c5,ChevronUpCircleIcon:c5,ChevronUpIcon:tx,ChevronUpSquare:RT,ChevronUpSquareIcon:RT,ChevronsDown:HQ,ChevronsDownIcon:HQ,ChevronsDownUp:VQ,ChevronsDownUpIcon:VQ,ChevronsLeft:KQ,ChevronsLeftIcon:KQ,ChevronsLeftRight:WQ,ChevronsLeftRightEllipsis:GQ,ChevronsLeftRightEllipsisIcon:GQ,ChevronsLeftRightIcon:WQ,ChevronsRight:ZQ,ChevronsRightIcon:ZQ,ChevronsRightLeft:YQ,ChevronsRightLeftIcon:YQ,ChevronsUp:QQ,ChevronsUpDown:qg,ChevronsUpDownIcon:qg,ChevronsUpIcon:QQ,Chrome:NA,ChromeIcon:NA,Church:XQ,ChurchIcon:XQ,Cigarette:eX,CigaretteIcon:eX,CigaretteOff:JQ,CigaretteOffIcon:JQ,Circle:lm,CircleAlert:Gi,CircleAlertIcon:Gi,CircleArrowDown:X3,CircleArrowDownIcon:X3,CircleArrowLeft:J3,CircleArrowLeftIcon:J3,CircleArrowOutDownLeft:e5,CircleArrowOutDownLeftIcon:e5,CircleArrowOutDownRight:t5,CircleArrowOutDownRightIcon:t5,CircleArrowOutUpLeft:s5,CircleArrowOutUpLeftIcon:s5,CircleArrowOutUpRight:n5,CircleArrowOutUpRightIcon:n5,CircleArrowRight:r5,CircleArrowRightIcon:r5,CircleArrowUp:a5,CircleArrowUpIcon:a5,CircleCheck:xr,CircleCheckBig:Ri,CircleCheckBigIcon:Ri,CircleCheckIcon:xr,CircleChevronDown:i5,CircleChevronDownIcon:i5,CircleChevronLeft:o5,CircleChevronLeftIcon:o5,CircleChevronRight:l5,CircleChevronRightIcon:l5,CircleChevronUp:c5,CircleChevronUpIcon:c5,CircleDashed:tX,CircleDashedIcon:tX,CircleDivide:d5,CircleDivideIcon:d5,CircleDollarSign:sX,CircleDollarSignIcon:sX,CircleDot:rX,CircleDotDashed:nX,CircleDotDashedIcon:nX,CircleDotIcon:rX,CircleEllipsis:aX,CircleEllipsisIcon:aX,CircleEqual:iX,CircleEqualIcon:iX,CircleFadingArrowUp:oX,CircleFadingArrowUpIcon:oX,CircleFadingPlus:lX,CircleFadingPlusIcon:lX,CircleGauge:u5,CircleGaugeIcon:u5,CircleHelp:K_,CircleHelpIcon:K_,CircleIcon:lm,CircleMinus:h5,CircleMinusIcon:h5,CircleOff:cX,CircleOffIcon:cX,CircleParking:p5,CircleParkingIcon:p5,CircleParkingOff:m5,CircleParkingOffIcon:m5,CirclePause:f5,CirclePauseIcon:f5,CirclePercent:x5,CirclePercentIcon:x5,CirclePlay:Au,CirclePlayIcon:Au,CirclePlus:g5,CirclePlusIcon:g5,CirclePower:y5,CirclePowerIcon:y5,CircleSlash:dX,CircleSlash2:v5,CircleSlash2Icon:v5,CircleSlashIcon:dX,CircleSlashed:v5,CircleSlashedIcon:v5,CircleStop:b5,CircleStopIcon:b5,CircleUser:w5,CircleUserIcon:w5,CircleUserRound:_5,CircleUserRoundIcon:_5,CircleX:Hc,CircleXIcon:Hc,CircuitBoard:uX,CircuitBoardIcon:uX,Citrus:hX,CitrusIcon:hX,Clapperboard:mX,ClapperboardIcon:mX,Clipboard:bX,ClipboardCheck:G2,ClipboardCheckIcon:G2,ClipboardCopy:pX,ClipboardCopyIcon:pX,ClipboardEdit:N5,ClipboardEditIcon:N5,ClipboardIcon:bX,ClipboardList:Dv,ClipboardListIcon:Dv,ClipboardMinus:fX,ClipboardMinusIcon:fX,ClipboardPaste:xX,ClipboardPasteIcon:xX,ClipboardPen:N5,ClipboardPenIcon:N5,ClipboardPenLine:j5,ClipboardPenLineIcon:j5,ClipboardPlus:gX,ClipboardPlusIcon:gX,ClipboardSignature:j5,ClipboardSignatureIcon:j5,ClipboardType:yX,ClipboardTypeIcon:yX,ClipboardX:vX,ClipboardXIcon:vX,Clock:gr,Clock1:_X,Clock10:wX,Clock10Icon:wX,Clock11:jX,Clock11Icon:jX,Clock12:NX,Clock12Icon:NX,Clock1Icon:_X,Clock2:kX,Clock2Icon:kX,Clock3:Q7,Clock3Icon:Q7,Clock4:SX,Clock4Icon:SX,Clock5:CX,Clock5Icon:CX,Clock6:TX,Clock6Icon:TX,Clock7:EX,Clock7Icon:EX,Clock8:AX,Clock8Icon:AX,Clock9:MX,Clock9Icon:MX,ClockAlert:IX,ClockAlertIcon:IX,ClockArrowDown:PX,ClockArrowDownIcon:PX,ClockArrowUp:LX,ClockArrowUpIcon:LX,ClockIcon:gr,Cloud:YX,CloudAlert:DX,CloudAlertIcon:DX,CloudCog:RX,CloudCogIcon:RX,CloudDownload:k5,CloudDownloadIcon:k5,CloudDrizzle:OX,CloudDrizzleIcon:OX,CloudFog:FX,CloudFogIcon:FX,CloudHail:zX,CloudHailIcon:zX,CloudIcon:YX,CloudLightning:BX,CloudLightningIcon:BX,CloudMoon:UX,CloudMoonIcon:UX,CloudMoonRain:$X,CloudMoonRainIcon:$X,CloudOff:qX,CloudOffIcon:qX,CloudRain:HX,CloudRainIcon:HX,CloudRainWind:VX,CloudRainWindIcon:VX,CloudSnow:GX,CloudSnowIcon:GX,CloudSun:KX,CloudSunIcon:KX,CloudSunRain:WX,CloudSunRainIcon:WX,CloudUpload:S5,CloudUploadIcon:S5,Cloudy:ZX,CloudyIcon:ZX,Clover:R2,CloverIcon:R2,Club:QX,ClubIcon:QX,Code:kA,Code2:C2,Code2Icon:C2,CodeIcon:kA,CodeSquare:OT,CodeSquareIcon:OT,CodeXml:C2,CodeXmlIcon:C2,Codepen:XX,CodepenIcon:XX,Codesandbox:JX,CodesandboxIcon:JX,Coffee:ny,CoffeeIcon:ny,Cog:eJ,CogIcon:eJ,Coins:X7,CoinsIcon:X7,Columns:C5,Columns2:C5,Columns2Icon:C5,Columns3:Kk,Columns3Icon:Kk,Columns4:tJ,Columns4Icon:tJ,ColumnsIcon:C5,Combine:sJ,CombineIcon:sJ,Command:nJ,CommandIcon:nJ,Compass:eL,CompassIcon:eL,Component:rJ,ComponentIcon:rJ,Computer:aJ,ComputerIcon:aJ,ConciergeBell:iJ,ConciergeBellIcon:iJ,Cone:oJ,ConeIcon:oJ,Construction:lJ,ConstructionIcon:lJ,Contact:SA,Contact2:T5,Contact2Icon:T5,ContactIcon:SA,ContactRound:T5,ContactRoundIcon:T5,Container:cJ,ContainerIcon:cJ,Contrast:dJ,ContrastIcon:dJ,Cookie:uJ,CookieIcon:uJ,CookingPot:hJ,CookingPotIcon:hJ,Copy:Xr,CopyCheck:mJ,CopyCheckIcon:mJ,CopyIcon:Xr,CopyMinus:pJ,CopyMinusIcon:pJ,CopyPlus:fJ,CopyPlusIcon:fJ,CopySlash:xJ,CopySlashIcon:xJ,CopyX:gJ,CopyXIcon:gJ,Copyleft:yJ,CopyleftIcon:yJ,Copyright:vJ,CopyrightIcon:vJ,CornerDownLeft:bJ,CornerDownLeftIcon:bJ,CornerDownRight:_J,CornerDownRightIcon:_J,CornerLeftDown:wJ,CornerLeftDownIcon:wJ,CornerLeftUp:jJ,CornerLeftUpIcon:jJ,CornerRightDown:NJ,CornerRightDownIcon:NJ,CornerRightUp:kJ,CornerRightUpIcon:kJ,CornerUpLeft:SJ,CornerUpLeftIcon:SJ,CornerUpRight:CJ,CornerUpRightIcon:CJ,Cpu:TJ,CpuIcon:TJ,CreativeCommons:EJ,CreativeCommonsIcon:EJ,CreditCard:pf,CreditCardIcon:pf,Croissant:AJ,CroissantIcon:AJ,Crop:MJ,CropIcon:MJ,Cross:IJ,CrossIcon:IJ,Crosshair:PJ,CrosshairIcon:PJ,Crown:ff,CrownIcon:ff,Cuboid:LJ,CuboidIcon:LJ,CupSoda:DJ,CupSodaIcon:DJ,CurlyBraces:F3,CurlyBracesIcon:F3,Currency:RJ,CurrencyIcon:RJ,Cylinder:OJ,CylinderIcon:OJ,Dam:FJ,DamIcon:FJ,Database:J7,DatabaseBackup:zJ,DatabaseBackupIcon:zJ,DatabaseIcon:J7,DatabaseZap:BJ,DatabaseZapIcon:BJ,Delete:$J,DeleteIcon:$J,Dessert:UJ,DessertIcon:UJ,Diameter:qJ,DiameterIcon:qJ,Diamond:GJ,DiamondIcon:GJ,DiamondMinus:VJ,DiamondMinusIcon:VJ,DiamondPercent:E5,DiamondPercentIcon:E5,DiamondPlus:HJ,DiamondPlusIcon:HJ,Dice1:WJ,Dice1Icon:WJ,Dice2:KJ,Dice2Icon:KJ,Dice3:YJ,Dice3Icon:YJ,Dice4:ZJ,Dice4Icon:ZJ,Dice5:QJ,Dice5Icon:QJ,Dice6:XJ,Dice6Icon:XJ,Dices:JJ,DicesIcon:JJ,Diff:eee,DiffIcon:eee,Disc:ree,Disc2:tee,Disc2Icon:tee,Disc3:see,Disc3Icon:see,DiscAlbum:nee,DiscAlbumIcon:nee,DiscIcon:ree,Divide:aee,DivideCircle:d5,DivideCircleIcon:d5,DivideIcon:aee,DivideSquare:$T,DivideSquareIcon:$T,Dna:oee,DnaIcon:oee,DnaOff:iee,DnaOffIcon:iee,Dock:lee,DockIcon:lee,Dog:cee,DogIcon:cee,DollarSign:Zl,DollarSignIcon:Zl,Donut:dee,DonutIcon:dee,DoorClosed:uee,DoorClosedIcon:uee,DoorOpen:xw,DoorOpenIcon:xw,Dot:hee,DotIcon:hee,DotSquare:UT,DotSquareIcon:UT,Download:Pa,DownloadCloud:k5,DownloadCloudIcon:k5,DownloadIcon:Pa,DraftingCompass:mee,DraftingCompassIcon:mee,Drama:pee,DramaIcon:pee,Dribbble:fee,DribbbleIcon:fee,Drill:xee,DrillIcon:xee,Droplet:gee,DropletIcon:gee,Droplets:mb,DropletsIcon:mb,Drum:yee,DrumIcon:yee,Drumstick:vee,DrumstickIcon:vee,Dumbbell:bee,DumbbellIcon:bee,Ear:wee,EarIcon:wee,EarOff:_ee,EarOffIcon:_ee,Earth:A5,EarthIcon:A5,EarthLock:jee,EarthLockIcon:jee,Eclipse:Nee,EclipseIcon:Nee,Edit:ku,Edit2:wv,Edit2Icon:wv,Edit3:sb,Edit3Icon:sb,EditIcon:ku,Egg:tL,EggFried:kee,EggFriedIcon:kee,EggIcon:tL,EggOff:See,EggOffIcon:See,Ellipsis:Qf,EllipsisIcon:Qf,EllipsisVertical:Ig,EllipsisVerticalIcon:Ig,Equal:Eee,EqualApproximately:Cee,EqualApproximatelyIcon:Cee,EqualIcon:Eee,EqualNot:Tee,EqualNotIcon:Tee,EqualSquare:qT,EqualSquareIcon:qT,Eraser:Aee,EraserIcon:Aee,EthernetPort:Mee,EthernetPortIcon:Mee,Euro:Iee,EuroIcon:Iee,Expand:Pee,ExpandIcon:Pee,ExternalLink:tr,ExternalLinkIcon:tr,Eye:Er,EyeClosed:Lee,EyeClosedIcon:Lee,EyeIcon:Er,EyeOff:xf,EyeOffIcon:xf,Facebook:Lh,FacebookIcon:Lh,Factory:Dee,FactoryIcon:Dee,Fan:Ree,FanIcon:Ree,FastForward:Oee,FastForwardIcon:Oee,Feather:Fee,FeatherIcon:Fee,Fence:zee,FenceIcon:zee,FerrisWheel:Bee,FerrisWheelIcon:Bee,Figma:$ee,FigmaIcon:$ee,File:sL,FileArchive:Uee,FileArchiveIcon:Uee,FileAudio:Vee,FileAudio2:qee,FileAudio2Icon:qee,FileAudioIcon:Vee,FileAxis3D:M5,FileAxis3DIcon:M5,FileAxis3d:M5,FileAxis3dIcon:M5,FileBadge:Gee,FileBadge2:Hee,FileBadge2Icon:Hee,FileBadgeIcon:Gee,FileBarChart:I5,FileBarChart2:P5,FileBarChart2Icon:P5,FileBarChartIcon:I5,FileBox:Wee,FileBoxIcon:Wee,FileChartColumn:P5,FileChartColumnIcon:P5,FileChartColumnIncreasing:I5,FileChartColumnIncreasingIcon:I5,FileChartLine:L5,FileChartLineIcon:L5,FileChartPie:D5,FileChartPieIcon:D5,FileCheck:e9,FileCheck2:Kee,FileCheck2Icon:Kee,FileCheckIcon:e9,FileClock:Yee,FileClockIcon:Yee,FileCode:Qee,FileCode2:Zee,FileCode2Icon:Zee,FileCodeIcon:Qee,FileCog:R5,FileCog2:R5,FileCog2Icon:R5,FileCogIcon:R5,FileDiff:Xee,FileDiffIcon:Xee,FileDigit:Jee,FileDigitIcon:Jee,FileDown:CA,FileDownIcon:CA,FileEdit:O5,FileEditIcon:O5,FileHeart:ete,FileHeartIcon:ete,FileIcon:sL,FileImage:W2,FileImageIcon:W2,FileInput:tte,FileInputIcon:tte,FileJson:nte,FileJson2:ste,FileJson2Icon:ste,FileJsonIcon:nte,FileKey:ate,FileKey2:rte,FileKey2Icon:rte,FileKeyIcon:ate,FileLineChart:L5,FileLineChartIcon:L5,FileLock:ote,FileLock2:ite,FileLock2Icon:ite,FileLockIcon:ote,FileMinus:cte,FileMinus2:lte,FileMinus2Icon:lte,FileMinusIcon:cte,FileMusic:dte,FileMusicIcon:dte,FileOutput:ute,FileOutputIcon:ute,FilePen:O5,FilePenIcon:O5,FilePenLine:Yk,FilePenLineIcon:Yk,FilePieChart:D5,FilePieChartIcon:D5,FilePlus:mte,FilePlus2:hte,FilePlus2Icon:hte,FilePlusIcon:mte,FileQuestion:pte,FileQuestionIcon:pte,FileScan:fte,FileScanIcon:fte,FileSearch:gte,FileSearch2:xte,FileSearch2Icon:xte,FileSearchIcon:gte,FileSignature:Yk,FileSignatureIcon:Yk,FileSliders:yte,FileSlidersIcon:yte,FileSpreadsheet:gw,FileSpreadsheetIcon:gw,FileStack:t9,FileStackIcon:t9,FileSymlink:vte,FileSymlinkIcon:vte,FileTerminal:bte,FileTerminalIcon:bte,FileText:Nr,FileTextIcon:Nr,FileType:wte,FileType2:_te,FileType2Icon:_te,FileTypeIcon:wte,FileUp:jte,FileUpIcon:jte,FileUser:Nte,FileUserIcon:Nte,FileVideo:s9,FileVideo2:kte,FileVideo2Icon:kte,FileVideoIcon:s9,FileVolume:Cte,FileVolume2:Ste,FileVolume2Icon:Ste,FileVolumeIcon:Cte,FileWarning:Tte,FileWarningIcon:Tte,FileX:Ate,FileX2:Ete,FileX2Icon:Ete,FileXIcon:Ate,Files:Mte,FilesIcon:Mte,Film:Ah,FilmIcon:Ah,Filter:Rv,FilterIcon:Rv,FilterX:Ite,FilterXIcon:Ite,Fingerprint:Pte,FingerprintIcon:Pte,FireExtinguisher:Lte,FireExtinguisherIcon:Lte,Fish:Ote,FishIcon:Ote,FishOff:Dte,FishOffIcon:Dte,FishSymbol:Rte,FishSymbolIcon:Rte,Flag:K2,FlagIcon:K2,FlagOff:Fte,FlagOffIcon:Fte,FlagTriangleLeft:zte,FlagTriangleLeftIcon:zte,FlagTriangleRight:Bte,FlagTriangleRightIcon:Bte,Flame:Dc,FlameIcon:Dc,FlameKindling:$te,FlameKindlingIcon:$te,Flashlight:qte,FlashlightIcon:qte,FlashlightOff:Ute,FlashlightOffIcon:Ute,FlaskConical:QS,FlaskConicalIcon:QS,FlaskConicalOff:Vte,FlaskConicalOffIcon:Vte,FlaskRound:Hte,FlaskRoundIcon:Hte,FlipHorizontal:n9,FlipHorizontal2:Gte,FlipHorizontal2Icon:Gte,FlipHorizontalIcon:n9,FlipVertical:Kte,FlipVertical2:Wte,FlipVertical2Icon:Wte,FlipVerticalIcon:Kte,Flower:Yte,Flower2:ob,Flower2Icon:ob,FlowerIcon:Yte,Focus:Zte,FocusIcon:Zte,FoldHorizontal:Qte,FoldHorizontalIcon:Qte,FoldVertical:Xte,FoldVerticalIcon:Xte,Folder:kse,FolderArchive:Jte,FolderArchiveIcon:Jte,FolderCheck:ese,FolderCheckIcon:ese,FolderClock:tse,FolderClockIcon:tse,FolderClosed:sse,FolderClosedIcon:sse,FolderCode:nse,FolderCodeIcon:nse,FolderCog:F5,FolderCog2:F5,FolderCog2Icon:F5,FolderCogIcon:F5,FolderDot:rse,FolderDotIcon:rse,FolderDown:ase,FolderDownIcon:ase,FolderEdit:z5,FolderEditIcon:z5,FolderGit:ose,FolderGit2:ise,FolderGit2Icon:ise,FolderGitIcon:ose,FolderHeart:lse,FolderHeartIcon:lse,FolderIcon:kse,FolderInput:cse,FolderInputIcon:cse,FolderKanban:dse,FolderKanbanIcon:dse,FolderKey:use,FolderKeyIcon:use,FolderLock:hse,FolderLockIcon:hse,FolderMinus:mse,FolderMinusIcon:mse,FolderOpen:gf,FolderOpenDot:pse,FolderOpenDotIcon:pse,FolderOpenIcon:gf,FolderOutput:fse,FolderOutputIcon:fse,FolderPen:z5,FolderPenIcon:z5,FolderPlus:xse,FolderPlusIcon:xse,FolderRoot:gse,FolderRootIcon:gse,FolderSearch:vse,FolderSearch2:yse,FolderSearch2Icon:yse,FolderSearchIcon:vse,FolderSymlink:bse,FolderSymlinkIcon:bse,FolderSync:_se,FolderSyncIcon:_se,FolderTree:wse,FolderTreeIcon:wse,FolderUp:jse,FolderUpIcon:jse,FolderX:Nse,FolderXIcon:Nse,Folders:Sse,FoldersIcon:Sse,Footprints:Cse,FootprintsIcon:Cse,ForkKnife:CE,ForkKnifeCrossed:SE,ForkKnifeCrossedIcon:SE,ForkKnifeIcon:CE,Forklift:Tse,ForkliftIcon:Tse,FormInput:cT,FormInputIcon:cT,Forward:Ese,ForwardIcon:Ese,Frame:Ase,FrameIcon:Ase,Framer:Mse,FramerIcon:Mse,Frown:Ise,FrownIcon:Ise,Fuel:Pse,FuelIcon:Pse,Fullscreen:Lse,FullscreenIcon:Lse,FunctionSquare:VT,FunctionSquareIcon:VT,GalleryHorizontal:Rse,GalleryHorizontalEnd:Dse,GalleryHorizontalEndIcon:Dse,GalleryHorizontalIcon:Rse,GalleryThumbnails:Ose,GalleryThumbnailsIcon:Ose,GalleryVertical:zse,GalleryVerticalEnd:Fse,GalleryVerticalEndIcon:Fse,GalleryVerticalIcon:zse,Gamepad:$se,Gamepad2:Bse,Gamepad2Icon:Bse,GamepadIcon:$se,GanttChart:Y3,GanttChartIcon:Y3,GanttChartSquare:L_,GanttChartSquareIcon:L_,Gauge:Use,GaugeCircle:u5,GaugeCircleIcon:u5,GaugeIcon:Use,Gavel:qse,GavelIcon:qse,Gem:Vse,GemIcon:Vse,Ghost:TA,GhostIcon:TA,Gift:Oi,GiftIcon:Oi,GitBranch:Gse,GitBranchIcon:Gse,GitBranchPlus:Hse,GitBranchPlusIcon:Hse,GitCommit:B5,GitCommitHorizontal:B5,GitCommitHorizontalIcon:B5,GitCommitIcon:B5,GitCommitVertical:Wse,GitCommitVerticalIcon:Wse,GitCompare:Yse,GitCompareArrows:Kse,GitCompareArrowsIcon:Kse,GitCompareIcon:Yse,GitFork:Zse,GitForkIcon:Zse,GitGraph:Qse,GitGraphIcon:Qse,GitMerge:Xse,GitMergeIcon:Xse,GitPullRequest:rne,GitPullRequestArrow:Jse,GitPullRequestArrowIcon:Jse,GitPullRequestClosed:ene,GitPullRequestClosedIcon:ene,GitPullRequestCreate:sne,GitPullRequestCreateArrow:tne,GitPullRequestCreateArrowIcon:tne,GitPullRequestCreateIcon:sne,GitPullRequestDraft:nne,GitPullRequestDraftIcon:nne,GitPullRequestIcon:rne,Github:ane,GithubIcon:ane,Gitlab:ine,GitlabIcon:ine,GlassWater:one,GlassWaterIcon:one,Glasses:lne,GlassesIcon:lne,Globe:lc,Globe2:A5,Globe2Icon:A5,GlobeIcon:lc,GlobeLock:cne,GlobeLockIcon:cne,Goal:dne,GoalIcon:dne,Grab:une,GrabIcon:une,GraduationCap:_d,GraduationCapIcon:_d,Grape:hne,GrapeIcon:hne,Grid:pv,Grid2X2:U5,Grid2X2Icon:U5,Grid2X2Plus:$5,Grid2X2PlusIcon:$5,Grid2x2:U5,Grid2x2Check:mne,Grid2x2CheckIcon:mne,Grid2x2Icon:U5,Grid2x2Plus:$5,Grid2x2PlusIcon:$5,Grid2x2X:pne,Grid2x2XIcon:pne,Grid3X3:pv,Grid3X3Icon:pv,Grid3x3:pv,Grid3x3Icon:pv,GridIcon:pv,Grip:xne,GripHorizontal:fne,GripHorizontalIcon:fne,GripIcon:xne,GripVertical:Fu,GripVerticalIcon:Fu,Group:gne,GroupIcon:gne,Guitar:yne,GuitarIcon:yne,Ham:vne,HamIcon:vne,Hammer:r9,HammerIcon:r9,Hand:a9,HandCoins:bne,HandCoinsIcon:bne,HandHeart:EA,HandHeartIcon:EA,HandHelping:tb,HandHelpingIcon:tb,HandIcon:a9,HandMetal:_ne,HandMetalIcon:_ne,HandPlatter:wne,HandPlatterIcon:wne,Handshake:pb,HandshakeIcon:pb,HardDrive:i9,HardDriveDownload:jne,HardDriveDownloadIcon:jne,HardDriveIcon:i9,HardDriveUpload:Nne,HardDriveUploadIcon:Nne,HardHat:kne,HardHatIcon:kne,Hash:XS,HashIcon:XS,Haze:Sne,HazeIcon:Sne,HdmiPort:Cne,HdmiPortIcon:Cne,Heading:Mne,Heading1:nL,Heading1Icon:nL,Heading2:rL,Heading2Icon:rL,Heading3:o9,Heading3Icon:o9,Heading4:Tne,Heading4Icon:Tne,Heading5:Ene,Heading5Icon:Ene,Heading6:Ane,Heading6Icon:Ane,HeadingIcon:Mne,HeadphoneOff:Ine,HeadphoneOffIcon:Ine,Headphones:Pne,HeadphonesIcon:Pne,Headset:Lne,HeadsetIcon:Lne,Heart:gi,HeartCrack:Dne,HeartCrackIcon:Dne,HeartHandshake:AA,HeartHandshakeIcon:AA,HeartIcon:gi,HeartOff:Rne,HeartOffIcon:Rne,HeartPulse:One,HeartPulseIcon:One,Heater:Fne,HeaterIcon:Fne,HelpCircle:K_,HelpCircleIcon:K_,HelpingHand:tb,HelpingHandIcon:tb,Hexagon:zne,HexagonIcon:zne,Highlighter:Bne,HighlighterIcon:Bne,History:MA,HistoryIcon:MA,Home:Or,HomeIcon:Or,Hop:Une,HopIcon:Une,HopOff:$ne,HopOffIcon:$ne,Hospital:qne,HospitalIcon:qne,Hotel:Vne,HotelIcon:Vne,Hourglass:Hne,HourglassIcon:Hne,House:Or,HouseIcon:Or,HousePlug:Gne,HousePlugIcon:Gne,HousePlus:Wne,HousePlusIcon:Wne,IceCream:V5,IceCream2:q5,IceCream2Icon:q5,IceCreamBowl:q5,IceCreamBowlIcon:q5,IceCreamCone:V5,IceCreamConeIcon:V5,IceCreamIcon:V5,Icon:krt,IdCard:Kne,IdCardIcon:Kne,Image:nl,ImageDown:Yne,ImageDownIcon:Yne,ImageIcon:nl,ImageMinus:Zne,ImageMinusIcon:Zne,ImageOff:Qne,ImageOffIcon:Qne,ImagePlay:Xne,ImagePlayIcon:Xne,ImagePlus:ry,ImagePlusIcon:ry,ImageUp:Jne,ImageUpIcon:Jne,ImageUpscale:ere,ImageUpscaleIcon:ere,Images:tre,ImagesIcon:tre,Import:sre,ImportIcon:sre,Inbox:Y2,InboxIcon:Y2,Indent:G5,IndentDecrease:H5,IndentDecreaseIcon:H5,IndentIcon:G5,IndentIncrease:G5,IndentIncreaseIcon:G5,IndianRupee:nre,IndianRupeeIcon:nre,Infinity:rre,InfinityIcon:rre,Info:yw,InfoIcon:yw,Inspect:ZT,InspectIcon:ZT,InspectionPanel:are,InspectionPanelIcon:are,Instagram:du,InstagramIcon:du,Italic:JS,ItalicIcon:JS,IterationCcw:ire,IterationCcwIcon:ire,IterationCw:ore,IterationCwIcon:ore,JapaneseYen:lre,JapaneseYenIcon:lre,Joystick:cre,JoystickIcon:cre,Kanban:Z2,KanbanIcon:Z2,KanbanSquare:HT,KanbanSquareDashed:FT,KanbanSquareDashedIcon:FT,KanbanSquareIcon:HT,Key:Vg,KeyIcon:Vg,KeyRound:IA,KeyRoundIcon:IA,KeySquare:dre,KeySquareIcon:dre,Keyboard:mre,KeyboardIcon:mre,KeyboardMusic:ure,KeyboardMusicIcon:ure,KeyboardOff:hre,KeyboardOffIcon:hre,Lamp:vre,LampCeiling:pre,LampCeilingIcon:pre,LampDesk:fre,LampDeskIcon:fre,LampFloor:xre,LampFloorIcon:xre,LampIcon:vre,LampWallDown:gre,LampWallDownIcon:gre,LampWallUp:yre,LampWallUpIcon:yre,LandPlot:bre,LandPlotIcon:bre,Landmark:_re,LandmarkIcon:_re,Languages:wre,LanguagesIcon:wre,Laptop:Nre,Laptop2:W5,Laptop2Icon:W5,LaptopIcon:Nre,LaptopMinimal:W5,LaptopMinimalCheck:jre,LaptopMinimalCheckIcon:jre,LaptopMinimalIcon:W5,Lasso:Sre,LassoIcon:Sre,LassoSelect:kre,LassoSelectIcon:kre,Laugh:Cre,LaughIcon:Cre,Layers:l9,Layers2:Tre,Layers2Icon:Tre,Layers3:Ere,Layers3Icon:Ere,LayersIcon:l9,Layout:T2,LayoutDashboard:e4,LayoutDashboardIcon:e4,LayoutGrid:yf,LayoutGridIcon:yf,LayoutIcon:T2,LayoutList:Are,LayoutListIcon:Are,LayoutPanelLeft:Mre,LayoutPanelLeftIcon:Mre,LayoutPanelTop:Ire,LayoutPanelTopIcon:Ire,LayoutTemplate:t4,LayoutTemplateIcon:t4,Leaf:Pre,LeafIcon:Pre,LeafyGreen:Lre,LeafyGreenIcon:Lre,Lectern:Dre,LecternIcon:Dre,LetterText:Rre,LetterTextIcon:Rre,Library:Hg,LibraryBig:Ore,LibraryBigIcon:Ore,LibraryIcon:Hg,LibrarySquare:GT,LibrarySquareIcon:GT,LifeBuoy:aL,LifeBuoyIcon:aL,Ligature:Fre,LigatureIcon:Fre,Lightbulb:vw,LightbulbIcon:vw,LightbulbOff:zre,LightbulbOffIcon:zre,LineChart:G3,LineChartIcon:G3,Link:Jo,Link2:El,Link2Icon:El,Link2Off:Bre,Link2OffIcon:Bre,LinkIcon:Jo,Linkedin:vf,LinkedinIcon:vf,List:Tp,ListCheck:$re,ListCheckIcon:$re,ListChecks:uu,ListChecksIcon:uu,ListCollapse:Ure,ListCollapseIcon:Ure,ListEnd:qre,ListEndIcon:qre,ListFilter:c9,ListFilterIcon:c9,ListIcon:Tp,ListMinus:Vre,ListMinusIcon:Vre,ListMusic:Hre,ListMusicIcon:Hre,ListOrdered:Ov,ListOrderedIcon:Ov,ListPlus:Gre,ListPlusIcon:Gre,ListRestart:Wre,ListRestartIcon:Wre,ListStart:Kre,ListStartIcon:Kre,ListTodo:Yre,ListTodoIcon:Yre,ListTree:Zre,ListTreeIcon:Zre,ListVideo:Qre,ListVideoIcon:Qre,ListX:Xre,ListXIcon:Xre,Loader:eae,Loader2:ts,Loader2Icon:ts,LoaderCircle:ts,LoaderCircleIcon:ts,LoaderIcon:eae,LoaderPinwheel:Jre,LoaderPinwheelIcon:Jre,Locate:iL,LocateFixed:tae,LocateFixedIcon:tae,LocateIcon:iL,LocateOff:sae,LocateOffIcon:sae,Lock:Kc,LockIcon:Kc,LockKeyhole:nae,LockKeyholeIcon:nae,LockKeyholeOpen:K5,LockKeyholeOpenIcon:K5,LockOpen:Y5,LockOpenIcon:Y5,LogIn:PA,LogInIcon:PA,LogOut:LA,LogOutIcon:LA,Logs:rae,LogsIcon:rae,Lollipop:aae,LollipopIcon:aae,LucideAArrowDown:SW,LucideAArrowUp:CW,LucideALargeSmall:TW,LucideAccessibility:EW,LucideActivity:nm,LucideActivitySquare:gT,LucideAirVent:AW,LucideAirplay:MW,LucideAlarmCheck:N3,LucideAlarmClock:PW,LucideAlarmClockCheck:N3,LucideAlarmClockMinus:k3,LucideAlarmClockOff:IW,LucideAlarmClockPlus:S3,LucideAlarmMinus:k3,LucideAlarmPlus:S3,LucideAlarmSmoke:LW,LucideAlbum:DW,LucideAlertCircle:Gi,LucideAlertOctagon:Y_,LucideAlertTriangle:$l,LucideAlignCenter:bA,LucideAlignCenterHorizontal:RW,LucideAlignCenterVertical:OW,LucideAlignEndHorizontal:FW,LucideAlignEndVertical:zW,LucideAlignHorizontalDistributeCenter:BW,LucideAlignHorizontalDistributeEnd:$W,LucideAlignHorizontalDistributeStart:UW,LucideAlignHorizontalJustifyCenter:qW,LucideAlignHorizontalJustifyEnd:VW,LucideAlignHorizontalJustifyStart:HW,LucideAlignHorizontalSpaceAround:GW,LucideAlignHorizontalSpaceBetween:WW,LucideAlignJustify:KW,LucideAlignLeft:_A,LucideAlignRight:wA,LucideAlignStartHorizontal:YW,LucideAlignStartVertical:ZW,LucideAlignVerticalDistributeCenter:QW,LucideAlignVerticalDistributeEnd:XW,LucideAlignVerticalDistributeStart:JW,LucideAlignVerticalJustifyCenter:eK,LucideAlignVerticalJustifyEnd:tK,LucideAlignVerticalJustifyStart:sK,LucideAlignVerticalSpaceAround:nK,LucideAlignVerticalSpaceBetween:rK,LucideAmbulance:aK,LucideAmpersand:iK,LucideAmpersands:oK,LucideAmphora:lK,LucideAnchor:cK,LucideAngry:dK,LucideAnnoyed:uK,LucideAntenna:hK,LucideAnvil:mK,LucideAperture:pK,LucideAppWindow:xK,LucideAppWindowMac:fK,LucideApple:gK,LucideArchive:rm,LucideArchiveRestore:ZP,LucideArchiveX:yK,LucideAreaChart:B3,LucideArmchair:vK,LucideArrowBigDown:_K,LucideArrowBigDownDash:bK,LucideArrowBigLeft:jK,LucideArrowBigLeftDash:wK,LucideArrowBigRight:kK,LucideArrowBigRightDash:NK,LucideArrowBigUp:CK,LucideArrowBigUpDash:SK,LucideArrowDown:am,LucideArrowDown01:TK,LucideArrowDown10:EK,LucideArrowDownAZ:C3,LucideArrowDownAz:C3,LucideArrowDownCircle:X3,LucideArrowDownFromLine:AK,LucideArrowDownLeft:MK,LucideArrowDownLeftFromCircle:e5,LucideArrowDownLeftFromSquare:wT,LucideArrowDownLeftSquare:yT,LucideArrowDownNarrowWide:IK,LucideArrowDownRight:V7,LucideArrowDownRightFromCircle:t5,LucideArrowDownRightFromSquare:jT,LucideArrowDownRightSquare:vT,LucideArrowDownSquare:bT,LucideArrowDownToDot:PK,LucideArrowDownToLine:LK,LucideArrowDownUp:DK,LucideArrowDownWideNarrow:T3,LucideArrowDownZA:E3,LucideArrowDownZa:E3,LucideArrowLeft:Hr,LucideArrowLeftCircle:J3,LucideArrowLeftFromLine:RK,LucideArrowLeftRight:OK,LucideArrowLeftSquare:_T,LucideArrowLeftToLine:FK,LucideArrowRight:Oa,LucideArrowRightCircle:r5,LucideArrowRightFromLine:zK,LucideArrowRightLeft:mw,LucideArrowRightSquare:ST,LucideArrowRightToLine:BK,LucideArrowUp:Ru,LucideArrowUp01:$K,LucideArrowUp10:UK,LucideArrowUpAZ:A3,LucideArrowUpAz:A3,LucideArrowUpCircle:a5,LucideArrowUpDown:em,LucideArrowUpFromDot:qK,LucideArrowUpFromLine:VK,LucideArrowUpLeft:HK,LucideArrowUpLeftFromCircle:s5,LucideArrowUpLeftFromSquare:NT,LucideArrowUpLeftSquare:CT,LucideArrowUpNarrowWide:M3,LucideArrowUpRight:QP,LucideArrowUpRightFromCircle:n5,LucideArrowUpRightFromSquare:kT,LucideArrowUpRightSquare:TT,LucideArrowUpSquare:ET,LucideArrowUpToLine:GK,LucideArrowUpWideNarrow:WK,LucideArrowUpZA:I3,LucideArrowUpZa:I3,LucideArrowsUpFromLine:KK,LucideAsterisk:YK,LucideAsteriskSquare:AT,LucideAtSign:ZK,LucideAtom:QK,LucideAudioLines:XK,LucideAudioWaveform:JK,LucideAward:bc,LucideAxe:eY,LucideAxis3D:P3,LucideAxis3d:P3,LucideBaby:tY,LucideBackpack:sY,LucideBadge:yY,LucideBadgeAlert:nY,LucideBadgeCent:rY,LucideBadgeCheck:L3,LucideBadgeDollarSign:aY,LucideBadgeEuro:iY,LucideBadgeHelp:oY,LucideBadgeIndianRupee:lY,LucideBadgeInfo:cY,LucideBadgeJapaneseYen:dY,LucideBadgeMinus:uY,LucideBadgePercent:hY,LucideBadgePlus:mY,LucideBadgePoundSterling:pY,LucideBadgeRussianRuble:fY,LucideBadgeSwissFranc:xY,LucideBadgeX:gY,LucideBaggageClaim:vY,LucideBan:XP,LucideBanana:bY,LucideBandage:_Y,LucideBanknote:wY,LucideBarChart:W3,LucideBarChart2:K3,LucideBarChart3:yo,LucideBarChart4:H3,LucideBarChartBig:V3,LucideBarChartHorizontal:U3,LucideBarChartHorizontalBig:$3,LucideBarcode:jY,LucideBaseline:NY,LucideBath:Cp,LucideBattery:AY,LucideBatteryCharging:kY,LucideBatteryFull:SY,LucideBatteryLow:CY,LucideBatteryMedium:TY,LucideBatteryWarning:EY,LucideBeaker:H7,LucideBean:IY,LucideBeanOff:MY,LucideBed:sy,LucideBedDouble:H2,LucideBedSingle:PY,LucideBeef:LY,LucideBeer:RY,LucideBeerOff:DY,LucideBell:im,LucideBellDot:OY,LucideBellElectric:FY,LucideBellMinus:zY,LucideBellOff:pw,LucideBellPlus:BY,LucideBellRing:WS,LucideBetweenHorizonalEnd:D3,LucideBetweenHorizonalStart:R3,LucideBetweenHorizontalEnd:D3,LucideBetweenHorizontalStart:R3,LucideBetweenVerticalEnd:$Y,LucideBetweenVerticalStart:UY,LucideBicepsFlexed:qY,LucideBike:VY,LucideBinary:HY,LucideBinoculars:GY,LucideBiohazard:WY,LucideBird:KY,LucideBitcoin:YY,LucideBlend:ZY,LucideBlinds:QY,LucideBlocks:XY,LucideBluetooth:sZ,LucideBluetoothConnected:JY,LucideBluetoothOff:eZ,LucideBluetoothSearching:tZ,LucideBold:KS,LucideBolt:nZ,LucideBomb:rZ,LucideBone:aZ,LucideBook:CZ,LucideBookA:iZ,LucideBookAudio:oZ,LucideBookCheck:lZ,LucideBookCopy:cZ,LucideBookDashed:O3,LucideBookDown:dZ,LucideBookHeadphones:uZ,LucideBookHeart:hZ,LucideBookImage:mZ,LucideBookKey:pZ,LucideBookLock:fZ,LucideBookMarked:xZ,LucideBookMinus:gZ,LucideBookOpen:Ou,LucideBookOpenCheck:yZ,LucideBookOpenText:vZ,LucideBookPlus:bZ,LucideBookTemplate:O3,LucideBookText:_Z,LucideBookType:wZ,LucideBookUp:NZ,LucideBookUp2:jZ,LucideBookUser:kZ,LucideBookX:SZ,LucideBookmark:Lv,LucideBookmarkCheck:TZ,LucideBookmarkMinus:EZ,LucideBookmarkPlus:JP,LucideBookmarkX:AZ,LucideBoomBox:MZ,LucideBot:YS,LucideBotMessageSquare:IZ,LucideBotOff:PZ,LucideBox:G7,LucideBoxSelect:BT,LucideBoxes:LZ,LucideBraces:F3,LucideBrackets:DZ,LucideBrain:W7,LucideBrainCircuit:RZ,LucideBrainCog:OZ,LucideBrickWall:FZ,LucideBriefcase:qm,LucideBriefcaseBusiness:zZ,LucideBriefcaseConveyorBelt:BZ,LucideBriefcaseMedical:$Z,LucideBringToFront:UZ,LucideBrush:qZ,LucideBug:GZ,LucideBugOff:VZ,LucideBugPlay:HZ,LucideBuilding:jA,LucideBuilding2:Va,LucideBus:KZ,LucideBusFront:WZ,LucideCable:ZZ,LucideCableCar:YZ,LucideCake:cu,LucideCakeSlice:QZ,LucideCalculator:fw,LucideCalendar:yr,LucideCalendar1:XZ,LucideCalendarArrowDown:JZ,LucideCalendarArrowUp:eQ,LucideCalendarCheck:ZS,LucideCalendarCheck2:tQ,LucideCalendarClock:om,LucideCalendarCog:sQ,LucideCalendarDays:Tl,LucideCalendarFold:nQ,LucideCalendarHeart:hb,LucideCalendarMinus:aQ,LucideCalendarMinus2:rQ,LucideCalendarOff:K7,LucideCalendarPlus:Rg,LucideCalendarPlus2:iQ,LucideCalendarRange:oQ,LucideCalendarSearch:lQ,LucideCalendarSync:cQ,LucideCalendarX:Y7,LucideCalendarX2:dQ,LucideCamera:mf,LucideCameraOff:uQ,LucideCandlestickChart:q3,LucideCandy:pQ,LucideCandyCane:hQ,LucideCandyOff:mQ,LucideCannabis:fQ,LucideCaptions:z3,LucideCaptionsOff:xQ,LucideCar:vQ,LucideCarFront:gQ,LucideCarTaxiFront:yQ,LucideCaravan:bQ,LucideCarrot:_Q,LucideCaseLower:wQ,LucideCaseSensitive:jQ,LucideCaseUpper:NQ,LucideCassetteTape:kQ,LucideCast:SQ,LucideCastle:CQ,LucideCat:TQ,LucideCctv:EQ,LucideChartArea:B3,LucideChartBar:U3,LucideChartBarBig:$3,LucideChartBarDecreasing:AQ,LucideChartBarIncreasing:MQ,LucideChartBarStacked:IQ,LucideChartCandlestick:q3,LucideChartColumn:yo,LucideChartColumnBig:V3,LucideChartColumnDecreasing:PQ,LucideChartColumnIncreasing:H3,LucideChartColumnStacked:LQ,LucideChartGantt:DQ,LucideChartLine:G3,LucideChartNetwork:RQ,LucideChartNoAxesColumn:K3,LucideChartNoAxesColumnDecreasing:OQ,LucideChartNoAxesColumnIncreasing:W3,LucideChartNoAxesCombined:FQ,LucideChartNoAxesGantt:Y3,LucideChartPie:Z3,LucideChartScatter:Q3,LucideChartSpline:zQ,LucideCheck:Ir,LucideCheckCheck:Z7,LucideCheckCircle:Ri,LucideCheckCircle2:xr,LucideCheckSquare:E2,LucideCheckSquare2:IT,LucideChefHat:BQ,LucideCherry:$Q,LucideChevronDown:io,LucideChevronDownCircle:i5,LucideChevronDownSquare:PT,LucideChevronFirst:UQ,LucideChevronLast:qQ,LucideChevronLeft:pl,LucideChevronLeftCircle:o5,LucideChevronLeftSquare:LT,LucideChevronRight:xa,LucideChevronRightCircle:l5,LucideChevronRightSquare:DT,LucideChevronUp:tx,LucideChevronUpCircle:c5,LucideChevronUpSquare:RT,LucideChevronsDown:HQ,LucideChevronsDownUp:VQ,LucideChevronsLeft:KQ,LucideChevronsLeftRight:WQ,LucideChevronsLeftRightEllipsis:GQ,LucideChevronsRight:ZQ,LucideChevronsRightLeft:YQ,LucideChevronsUp:QQ,LucideChevronsUpDown:qg,LucideChrome:NA,LucideChurch:XQ,LucideCigarette:eX,LucideCigaretteOff:JQ,LucideCircle:lm,LucideCircleAlert:Gi,LucideCircleArrowDown:X3,LucideCircleArrowLeft:J3,LucideCircleArrowOutDownLeft:e5,LucideCircleArrowOutDownRight:t5,LucideCircleArrowOutUpLeft:s5,LucideCircleArrowOutUpRight:n5,LucideCircleArrowRight:r5,LucideCircleArrowUp:a5,LucideCircleCheck:xr,LucideCircleCheckBig:Ri,LucideCircleChevronDown:i5,LucideCircleChevronLeft:o5,LucideCircleChevronRight:l5,LucideCircleChevronUp:c5,LucideCircleDashed:tX,LucideCircleDivide:d5,LucideCircleDollarSign:sX,LucideCircleDot:rX,LucideCircleDotDashed:nX,LucideCircleEllipsis:aX,LucideCircleEqual:iX,LucideCircleFadingArrowUp:oX,LucideCircleFadingPlus:lX,LucideCircleGauge:u5,LucideCircleHelp:K_,LucideCircleMinus:h5,LucideCircleOff:cX,LucideCircleParking:p5,LucideCircleParkingOff:m5,LucideCirclePause:f5,LucideCirclePercent:x5,LucideCirclePlay:Au,LucideCirclePlus:g5,LucideCirclePower:y5,LucideCircleSlash:dX,LucideCircleSlash2:v5,LucideCircleSlashed:v5,LucideCircleStop:b5,LucideCircleUser:w5,LucideCircleUserRound:_5,LucideCircleX:Hc,LucideCircuitBoard:uX,LucideCitrus:hX,LucideClapperboard:mX,LucideClipboard:bX,LucideClipboardCheck:G2,LucideClipboardCopy:pX,LucideClipboardEdit:N5,LucideClipboardList:Dv,LucideClipboardMinus:fX,LucideClipboardPaste:xX,LucideClipboardPen:N5,LucideClipboardPenLine:j5,LucideClipboardPlus:gX,LucideClipboardSignature:j5,LucideClipboardType:yX,LucideClipboardX:vX,LucideClock:gr,LucideClock1:_X,LucideClock10:wX,LucideClock11:jX,LucideClock12:NX,LucideClock2:kX,LucideClock3:Q7,LucideClock4:SX,LucideClock5:CX,LucideClock6:TX,LucideClock7:EX,LucideClock8:AX,LucideClock9:MX,LucideClockAlert:IX,LucideClockArrowDown:PX,LucideClockArrowUp:LX,LucideCloud:YX,LucideCloudAlert:DX,LucideCloudCog:RX,LucideCloudDownload:k5,LucideCloudDrizzle:OX,LucideCloudFog:FX,LucideCloudHail:zX,LucideCloudLightning:BX,LucideCloudMoon:UX,LucideCloudMoonRain:$X,LucideCloudOff:qX,LucideCloudRain:HX,LucideCloudRainWind:VX,LucideCloudSnow:GX,LucideCloudSun:KX,LucideCloudSunRain:WX,LucideCloudUpload:S5,LucideCloudy:ZX,LucideClover:R2,LucideClub:QX,LucideCode:kA,LucideCode2:C2,LucideCodeSquare:OT,LucideCodeXml:C2,LucideCodepen:XX,LucideCodesandbox:JX,LucideCoffee:ny,LucideCog:eJ,LucideCoins:X7,LucideColumns:C5,LucideColumns2:C5,LucideColumns3:Kk,LucideColumns4:tJ,LucideCombine:sJ,LucideCommand:nJ,LucideCompass:eL,LucideComponent:rJ,LucideComputer:aJ,LucideConciergeBell:iJ,LucideCone:oJ,LucideConstruction:lJ,LucideContact:SA,LucideContact2:T5,LucideContactRound:T5,LucideContainer:cJ,LucideContrast:dJ,LucideCookie:uJ,LucideCookingPot:hJ,LucideCopy:Xr,LucideCopyCheck:mJ,LucideCopyMinus:pJ,LucideCopyPlus:fJ,LucideCopySlash:xJ,LucideCopyX:gJ,LucideCopyleft:yJ,LucideCopyright:vJ,LucideCornerDownLeft:bJ,LucideCornerDownRight:_J,LucideCornerLeftDown:wJ,LucideCornerLeftUp:jJ,LucideCornerRightDown:NJ,LucideCornerRightUp:kJ,LucideCornerUpLeft:SJ,LucideCornerUpRight:CJ,LucideCpu:TJ,LucideCreativeCommons:EJ,LucideCreditCard:pf,LucideCroissant:AJ,LucideCrop:MJ,LucideCross:IJ,LucideCrosshair:PJ,LucideCrown:ff,LucideCuboid:LJ,LucideCupSoda:DJ,LucideCurlyBraces:F3,LucideCurrency:RJ,LucideCylinder:OJ,LucideDam:FJ,LucideDatabase:J7,LucideDatabaseBackup:zJ,LucideDatabaseZap:BJ,LucideDelete:$J,LucideDessert:UJ,LucideDiameter:qJ,LucideDiamond:GJ,LucideDiamondMinus:VJ,LucideDiamondPercent:E5,LucideDiamondPlus:HJ,LucideDice1:WJ,LucideDice2:KJ,LucideDice3:YJ,LucideDice4:ZJ,LucideDice5:QJ,LucideDice6:XJ,LucideDices:JJ,LucideDiff:eee,LucideDisc:ree,LucideDisc2:tee,LucideDisc3:see,LucideDiscAlbum:nee,LucideDivide:aee,LucideDivideCircle:d5,LucideDivideSquare:$T,LucideDna:oee,LucideDnaOff:iee,LucideDock:lee,LucideDog:cee,LucideDollarSign:Zl,LucideDonut:dee,LucideDoorClosed:uee,LucideDoorOpen:xw,LucideDot:hee,LucideDotSquare:UT,LucideDownload:Pa,LucideDownloadCloud:k5,LucideDraftingCompass:mee,LucideDrama:pee,LucideDribbble:fee,LucideDrill:xee,LucideDroplet:gee,LucideDroplets:mb,LucideDrum:yee,LucideDrumstick:vee,LucideDumbbell:bee,LucideEar:wee,LucideEarOff:_ee,LucideEarth:A5,LucideEarthLock:jee,LucideEclipse:Nee,LucideEdit:ku,LucideEdit2:wv,LucideEdit3:sb,LucideEgg:tL,LucideEggFried:kee,LucideEggOff:See,LucideEllipsis:Qf,LucideEllipsisVertical:Ig,LucideEqual:Eee,LucideEqualApproximately:Cee,LucideEqualNot:Tee,LucideEqualSquare:qT,LucideEraser:Aee,LucideEthernetPort:Mee,LucideEuro:Iee,LucideExpand:Pee,LucideExternalLink:tr,LucideEye:Er,LucideEyeClosed:Lee,LucideEyeOff:xf,LucideFacebook:Lh,LucideFactory:Dee,LucideFan:Ree,LucideFastForward:Oee,LucideFeather:Fee,LucideFence:zee,LucideFerrisWheel:Bee,LucideFigma:$ee,LucideFile:sL,LucideFileArchive:Uee,LucideFileAudio:Vee,LucideFileAudio2:qee,LucideFileAxis3D:M5,LucideFileAxis3d:M5,LucideFileBadge:Gee,LucideFileBadge2:Hee,LucideFileBarChart:I5,LucideFileBarChart2:P5,LucideFileBox:Wee,LucideFileChartColumn:P5,LucideFileChartColumnIncreasing:I5,LucideFileChartLine:L5,LucideFileChartPie:D5,LucideFileCheck:e9,LucideFileCheck2:Kee,LucideFileClock:Yee,LucideFileCode:Qee,LucideFileCode2:Zee,LucideFileCog:R5,LucideFileCog2:R5,LucideFileDiff:Xee,LucideFileDigit:Jee,LucideFileDown:CA,LucideFileEdit:O5,LucideFileHeart:ete,LucideFileImage:W2,LucideFileInput:tte,LucideFileJson:nte,LucideFileJson2:ste,LucideFileKey:ate,LucideFileKey2:rte,LucideFileLineChart:L5,LucideFileLock:ote,LucideFileLock2:ite,LucideFileMinus:cte,LucideFileMinus2:lte,LucideFileMusic:dte,LucideFileOutput:ute,LucideFilePen:O5,LucideFilePenLine:Yk,LucideFilePieChart:D5,LucideFilePlus:mte,LucideFilePlus2:hte,LucideFileQuestion:pte,LucideFileScan:fte,LucideFileSearch:gte,LucideFileSearch2:xte,LucideFileSignature:Yk,LucideFileSliders:yte,LucideFileSpreadsheet:gw,LucideFileStack:t9,LucideFileSymlink:vte,LucideFileTerminal:bte,LucideFileText:Nr,LucideFileType:wte,LucideFileType2:_te,LucideFileUp:jte,LucideFileUser:Nte,LucideFileVideo:s9,LucideFileVideo2:kte,LucideFileVolume:Cte,LucideFileVolume2:Ste,LucideFileWarning:Tte,LucideFileX:Ate,LucideFileX2:Ete,LucideFiles:Mte,LucideFilm:Ah,LucideFilter:Rv,LucideFilterX:Ite,LucideFingerprint:Pte,LucideFireExtinguisher:Lte,LucideFish:Ote,LucideFishOff:Dte,LucideFishSymbol:Rte,LucideFlag:K2,LucideFlagOff:Fte,LucideFlagTriangleLeft:zte,LucideFlagTriangleRight:Bte,LucideFlame:Dc,LucideFlameKindling:$te,LucideFlashlight:qte,LucideFlashlightOff:Ute,LucideFlaskConical:QS,LucideFlaskConicalOff:Vte,LucideFlaskRound:Hte,LucideFlipHorizontal:n9,LucideFlipHorizontal2:Gte,LucideFlipVertical:Kte,LucideFlipVertical2:Wte,LucideFlower:Yte,LucideFlower2:ob,LucideFocus:Zte,LucideFoldHorizontal:Qte,LucideFoldVertical:Xte,LucideFolder:kse,LucideFolderArchive:Jte,LucideFolderCheck:ese,LucideFolderClock:tse,LucideFolderClosed:sse,LucideFolderCode:nse,LucideFolderCog:F5,LucideFolderCog2:F5,LucideFolderDot:rse,LucideFolderDown:ase,LucideFolderEdit:z5,LucideFolderGit:ose,LucideFolderGit2:ise,LucideFolderHeart:lse,LucideFolderInput:cse,LucideFolderKanban:dse,LucideFolderKey:use,LucideFolderLock:hse,LucideFolderMinus:mse,LucideFolderOpen:gf,LucideFolderOpenDot:pse,LucideFolderOutput:fse,LucideFolderPen:z5,LucideFolderPlus:xse,LucideFolderRoot:gse,LucideFolderSearch:vse,LucideFolderSearch2:yse,LucideFolderSymlink:bse,LucideFolderSync:_se,LucideFolderTree:wse,LucideFolderUp:jse,LucideFolderX:Nse,LucideFolders:Sse,LucideFootprints:Cse,LucideForkKnife:CE,LucideForkKnifeCrossed:SE,LucideForklift:Tse,LucideFormInput:cT,LucideForward:Ese,LucideFrame:Ase,LucideFramer:Mse,LucideFrown:Ise,LucideFuel:Pse,LucideFullscreen:Lse,LucideFunctionSquare:VT,LucideGalleryHorizontal:Rse,LucideGalleryHorizontalEnd:Dse,LucideGalleryThumbnails:Ose,LucideGalleryVertical:zse,LucideGalleryVerticalEnd:Fse,LucideGamepad:$se,LucideGamepad2:Bse,LucideGanttChart:Y3,LucideGanttChartSquare:L_,LucideGauge:Use,LucideGaugeCircle:u5,LucideGavel:qse,LucideGem:Vse,LucideGhost:TA,LucideGift:Oi,LucideGitBranch:Gse,LucideGitBranchPlus:Hse,LucideGitCommit:B5,LucideGitCommitHorizontal:B5,LucideGitCommitVertical:Wse,LucideGitCompare:Yse,LucideGitCompareArrows:Kse,LucideGitFork:Zse,LucideGitGraph:Qse,LucideGitMerge:Xse,LucideGitPullRequest:rne,LucideGitPullRequestArrow:Jse,LucideGitPullRequestClosed:ene,LucideGitPullRequestCreate:sne,LucideGitPullRequestCreateArrow:tne,LucideGitPullRequestDraft:nne,LucideGithub:ane,LucideGitlab:ine,LucideGlassWater:one,LucideGlasses:lne,LucideGlobe:lc,LucideGlobe2:A5,LucideGlobeLock:cne,LucideGoal:dne,LucideGrab:une,LucideGraduationCap:_d,LucideGrape:hne,LucideGrid:pv,LucideGrid2X2:U5,LucideGrid2X2Plus:$5,LucideGrid2x2:U5,LucideGrid2x2Check:mne,LucideGrid2x2Plus:$5,LucideGrid2x2X:pne,LucideGrid3X3:pv,LucideGrid3x3:pv,LucideGrip:xne,LucideGripHorizontal:fne,LucideGripVertical:Fu,LucideGroup:gne,LucideGuitar:yne,LucideHam:vne,LucideHammer:r9,LucideHand:a9,LucideHandCoins:bne,LucideHandHeart:EA,LucideHandHelping:tb,LucideHandMetal:_ne,LucideHandPlatter:wne,LucideHandshake:pb,LucideHardDrive:i9,LucideHardDriveDownload:jne,LucideHardDriveUpload:Nne,LucideHardHat:kne,LucideHash:XS,LucideHaze:Sne,LucideHdmiPort:Cne,LucideHeading:Mne,LucideHeading1:nL,LucideHeading2:rL,LucideHeading3:o9,LucideHeading4:Tne,LucideHeading5:Ene,LucideHeading6:Ane,LucideHeadphoneOff:Ine,LucideHeadphones:Pne,LucideHeadset:Lne,LucideHeart:gi,LucideHeartCrack:Dne,LucideHeartHandshake:AA,LucideHeartOff:Rne,LucideHeartPulse:One,LucideHeater:Fne,LucideHelpCircle:K_,LucideHelpingHand:tb,LucideHexagon:zne,LucideHighlighter:Bne,LucideHistory:MA,LucideHome:Or,LucideHop:Une,LucideHopOff:$ne,LucideHospital:qne,LucideHotel:Vne,LucideHourglass:Hne,LucideHouse:Or,LucideHousePlug:Gne,LucideHousePlus:Wne,LucideIceCream:V5,LucideIceCream2:q5,LucideIceCreamBowl:q5,LucideIceCreamCone:V5,LucideIdCard:Kne,LucideImage:nl,LucideImageDown:Yne,LucideImageMinus:Zne,LucideImageOff:Qne,LucideImagePlay:Xne,LucideImagePlus:ry,LucideImageUp:Jne,LucideImageUpscale:ere,LucideImages:tre,LucideImport:sre,LucideInbox:Y2,LucideIndent:G5,LucideIndentDecrease:H5,LucideIndentIncrease:G5,LucideIndianRupee:nre,LucideInfinity:rre,LucideInfo:yw,LucideInspect:ZT,LucideInspectionPanel:are,LucideInstagram:du,LucideItalic:JS,LucideIterationCcw:ire,LucideIterationCw:ore,LucideJapaneseYen:lre,LucideJoystick:cre,LucideKanban:Z2,LucideKanbanSquare:HT,LucideKanbanSquareDashed:FT,LucideKey:Vg,LucideKeyRound:IA,LucideKeySquare:dre,LucideKeyboard:mre,LucideKeyboardMusic:ure,LucideKeyboardOff:hre,LucideLamp:vre,LucideLampCeiling:pre,LucideLampDesk:fre,LucideLampFloor:xre,LucideLampWallDown:gre,LucideLampWallUp:yre,LucideLandPlot:bre,LucideLandmark:_re,LucideLanguages:wre,LucideLaptop:Nre,LucideLaptop2:W5,LucideLaptopMinimal:W5,LucideLaptopMinimalCheck:jre,LucideLasso:Sre,LucideLassoSelect:kre,LucideLaugh:Cre,LucideLayers:l9,LucideLayers2:Tre,LucideLayers3:Ere,LucideLayout:T2,LucideLayoutDashboard:e4,LucideLayoutGrid:yf,LucideLayoutList:Are,LucideLayoutPanelLeft:Mre,LucideLayoutPanelTop:Ire,LucideLayoutTemplate:t4,LucideLeaf:Pre,LucideLeafyGreen:Lre,LucideLectern:Dre,LucideLetterText:Rre,LucideLibrary:Hg,LucideLibraryBig:Ore,LucideLibrarySquare:GT,LucideLifeBuoy:aL,LucideLigature:Fre,LucideLightbulb:vw,LucideLightbulbOff:zre,LucideLineChart:G3,LucideLink:Jo,LucideLink2:El,LucideLink2Off:Bre,LucideLinkedin:vf,LucideList:Tp,LucideListCheck:$re,LucideListChecks:uu,LucideListCollapse:Ure,LucideListEnd:qre,LucideListFilter:c9,LucideListMinus:Vre,LucideListMusic:Hre,LucideListOrdered:Ov,LucideListPlus:Gre,LucideListRestart:Wre,LucideListStart:Kre,LucideListTodo:Yre,LucideListTree:Zre,LucideListVideo:Qre,LucideListX:Xre,LucideLoader:eae,LucideLoader2:ts,LucideLoaderCircle:ts,LucideLoaderPinwheel:Jre,LucideLocate:iL,LucideLocateFixed:tae,LucideLocateOff:sae,LucideLock:Kc,LucideLockKeyhole:nae,LucideLockKeyholeOpen:K5,LucideLockOpen:Y5,LucideLogIn:PA,LucideLogOut:LA,LucideLogs:rae,LucideLollipop:aae,LucideLuggage:iae,LucideMSquare:WT,LucideMagnet:oae,LucideMail:Vs,LucideMailCheck:oL,LucideMailMinus:lae,LucideMailOpen:lL,LucideMailPlus:d9,LucideMailQuestion:cae,LucideMailSearch:dae,LucideMailWarning:uae,LucideMailX:cL,LucideMailbox:hae,LucideMails:mae,LucideMap:DA,LucideMapPin:ka,LucideMapPinCheck:fae,LucideMapPinCheckInside:pae,LucideMapPinHouse:xae,LucideMapPinMinus:yae,LucideMapPinMinusInside:gae,LucideMapPinOff:vae,LucideMapPinPlus:_ae,LucideMapPinPlusInside:bae,LucideMapPinX:jae,LucideMapPinXInside:wae,LucideMapPinned:Nae,LucideMartini:kae,LucideMaximize:RA,LucideMaximize2:u9,LucideMedal:Q2,LucideMegaphone:$d,LucideMegaphoneOff:Sae,LucideMeh:Cae,LucideMemoryStick:Tae,LucideMenu:s4,LucideMenuSquare:KT,LucideMerge:Eae,LucideMessageCircle:Ql,LucideMessageCircleCode:Aae,LucideMessageCircleDashed:Mae,LucideMessageCircleHeart:dL,LucideMessageCircleMore:Iae,LucideMessageCircleOff:Pae,LucideMessageCirclePlus:Lae,LucideMessageCircleQuestion:h9,LucideMessageCircleReply:Dae,LucideMessageCircleWarning:Rae,LucideMessageCircleX:Oae,LucideMessageSquare:Ei,LucideMessageSquareCode:Fae,LucideMessageSquareDashed:zae,LucideMessageSquareDiff:Bae,LucideMessageSquareDot:$ae,LucideMessageSquareHeart:uL,LucideMessageSquareLock:Uae,LucideMessageSquareMore:m9,LucideMessageSquareOff:qae,LucideMessageSquarePlus:nw,LucideMessageSquareQuote:bw,LucideMessageSquareReply:Vae,LucideMessageSquareShare:Hae,LucideMessageSquareText:Gae,LucideMessageSquareWarning:Wae,LucideMessageSquareX:Kae,LucideMessagesSquare:hL,LucideMic:Fv,LucideMic2:Z5,LucideMicOff:Yae,LucideMicVocal:Z5,LucideMicrochip:Zae,LucideMicroscope:Qae,LucideMicrowave:Xae,LucideMilestone:Jae,LucideMilk:tie,LucideMilkOff:eie,LucideMinimize:nie,LucideMinimize2:sie,LucideMinus:fb,LucideMinusCircle:h5,LucideMinusSquare:YT,LucideMonitor:xb,LucideMonitorCheck:rie,LucideMonitorCog:aie,LucideMonitorDot:iie,LucideMonitorDown:oie,LucideMonitorOff:lie,LucideMonitorPause:cie,LucideMonitorPlay:mL,LucideMonitorSmartphone:die,LucideMonitorSpeaker:uie,LucideMonitorStop:hie,LucideMonitorUp:OA,LucideMonitorX:mie,LucideMoon:fie,LucideMoonStar:pie,LucideMoreHorizontal:Qf,LucideMoreVertical:Ig,LucideMountain:gie,LucideMountainSnow:xie,LucideMouse:_ie,LucideMouseOff:yie,LucideMousePointer:Om,LucideMousePointer2:vie,LucideMousePointerBan:bie,LucideMousePointerClick:oc,LucideMousePointerSquareDashed:zT,LucideMove:Lie,LucideMove3D:Q5,LucideMove3d:Q5,LucideMoveDiagonal:jie,LucideMoveDiagonal2:wie,LucideMoveDown:Sie,LucideMoveDownLeft:Nie,LucideMoveDownRight:kie,LucideMoveHorizontal:Cie,LucideMoveLeft:Tie,LucideMoveRight:Eie,LucideMoveUp:Iie,LucideMoveUpLeft:Aie,LucideMoveUpRight:Mie,LucideMoveVertical:Pie,LucideMusic:pL,LucideMusic2:Die,LucideMusic3:Rie,LucideMusic4:Oie,LucideNavigation:p9,LucideNavigation2:zie,LucideNavigation2Off:Fie,LucideNavigationOff:Bie,LucideNetwork:$ie,LucideNewspaper:ay,LucideNfc:Uie,LucideNotebook:Gie,LucideNotebookPen:qie,LucideNotebookTabs:Vie,LucideNotebookText:Hie,LucideNotepadText:Kie,LucideNotepadTextDashed:Wie,LucideNut:Zie,LucideNutOff:Yie,LucideOctagon:Xie,LucideOctagonAlert:Y_,LucideOctagonMinus:Qie,LucideOctagonPause:X5,LucideOctagonX:J5,LucideOmega:Jie,LucideOption:eoe,LucideOrbit:toe,LucideOrigami:soe,LucideOutdent:H5,LucidePackage:Rc,LucidePackage2:noe,LucidePackageCheck:roe,LucidePackageMinus:aoe,LucidePackageOpen:ioe,LucidePackagePlus:f9,LucidePackageSearch:ooe,LucidePackageX:loe,LucidePaintBucket:coe,LucidePaintRoller:doe,LucidePaintbrush:uoe,LucidePaintbrush2:eT,LucidePaintbrushVertical:eT,LucidePalette:fl,LucidePalmtree:gE,LucidePanelBottom:poe,LucidePanelBottomClose:hoe,LucidePanelBottomDashed:tT,LucidePanelBottomInactive:tT,LucidePanelBottomOpen:moe,LucidePanelLeft:aT,LucidePanelLeftClose:sT,LucidePanelLeftDashed:nT,LucidePanelLeftInactive:nT,LucidePanelLeftOpen:rT,LucidePanelRight:goe,LucidePanelRightClose:foe,LucidePanelRightDashed:iT,LucidePanelRightInactive:iT,LucidePanelRightOpen:xoe,LucidePanelTop:boe,LucidePanelTopClose:yoe,LucidePanelTopDashed:oT,LucidePanelTopInactive:oT,LucidePanelTopOpen:voe,LucidePanelsLeftBottom:_oe,LucidePanelsLeftRight:Kk,LucidePanelsRightBottom:woe,LucidePanelsTopBottom:hT,LucidePanelsTopLeft:T2,LucidePaperclip:n4,LucideParentheses:joe,LucideParkingCircle:p5,LucideParkingCircleOff:m5,LucideParkingMeter:Noe,LucideParkingSquare:XT,LucideParkingSquareOff:QT,LucidePartyPopper:ch,LucidePause:bf,LucidePauseCircle:f5,LucidePauseOctagon:X5,LucidePawPrint:koe,LucidePcCase:Soe,LucidePen:wv,LucidePenBox:ku,LucidePenLine:sb,LucidePenOff:Coe,LucidePenSquare:ku,LucidePenTool:r4,LucidePencil:_a,LucidePencilLine:x9,LucidePencilOff:Toe,LucidePencilRuler:Eoe,LucidePentagon:Aoe,LucidePercent:a4,LucidePercentCircle:x5,LucidePercentDiamond:E5,LucidePercentSquare:JT,LucidePersonStanding:Moe,LucidePhilippinePeso:Ioe,LucidePhone:Ar,LucidePhoneCall:g9,LucidePhoneForwarded:Poe,LucidePhoneIncoming:Loe,LucidePhoneMissed:Doe,LucidePhoneOff:Roe,LucidePhoneOutgoing:Ooe,LucidePi:Foe,LucidePiSquare:eE,LucidePiano:zoe,LucidePickaxe:Boe,LucidePictureInPicture:Uoe,LucidePictureInPicture2:$oe,LucidePieChart:Z3,LucidePiggyBank:qoe,LucidePilcrow:Goe,LucidePilcrowLeft:Voe,LucidePilcrowRight:Hoe,LucidePilcrowSquare:tE,LucidePill:Koe,LucidePillBottle:Woe,LucidePin:i4,LucidePinOff:y9,LucidePipette:Yoe,LucidePizza:Zoe,LucidePlane:v9,LucidePlaneLanding:Qoe,LucidePlaneTakeoff:Xoe,LucidePlay:Al,LucidePlayCircle:Au,LucidePlaySquare:sE,LucidePlug:X2,LucidePlug2:Joe,LucidePlugZap:lT,LucidePlugZap2:lT,LucidePlus:Is,LucidePlusCircle:g5,LucidePlusSquare:nE,LucidePocket:tle,LucidePocketKnife:ele,LucidePodcast:sle,LucidePointer:rle,LucidePointerOff:nle,LucidePopcorn:ale,LucidePopsicle:ile,LucidePoundSterling:ole,LucidePower:b9,LucidePowerCircle:y5,LucidePowerOff:lle,LucidePowerSquare:rE,LucidePresentation:iy,LucidePrinter:_9,LucidePrinterCheck:cle,LucideProjector:dle,LucideProportions:ule,LucidePuzzle:hle,LucidePyramid:mle,LucideQrCode:oy,LucideQuote:gb,LucideRabbit:ple,LucideRadar:FA,LucideRadiation:fle,LucideRadical:xle,LucideRadio:_f,LucideRadioReceiver:gle,LucideRadioTower:yle,LucideRadius:vle,LucideRailSymbol:ble,LucideRainbow:_le,LucideRat:wle,LucideRatio:jle,LucideReceipt:Ile,LucideReceiptCent:Nle,LucideReceiptEuro:kle,LucideReceiptIndianRupee:Sle,LucideReceiptJapaneseYen:Cle,LucideReceiptPoundSterling:Tle,LucideReceiptRussianRuble:Ele,LucideReceiptSwissFranc:Ale,LucideReceiptText:Mle,LucideRectangleEllipsis:cT,LucideRectangleHorizontal:Ple,LucideRectangleVertical:Lle,LucideRecycle:Dle,LucideRedo:o4,LucideRedo2:Rle,LucideRedoDot:Ole,LucideRefreshCcw:fL,LucideRefreshCcwDot:Fle,LucideRefreshCw:Ti,LucideRefreshCwOff:zle,LucideRefrigerator:Ble,LucideRegex:$le,LucideRemoveFormatting:Ule,LucideRepeat:xL,LucideRepeat1:qle,LucideRepeat2:Vle,LucideReplace:Gle,LucideReplaceAll:Hle,LucideReply:w9,LucideReplyAll:Wle,LucideRewind:Kle,LucideRibbon:Yle,LucideRocket:sx,LucideRockingChair:Zle,LucideRollerCoaster:Qle,LucideRotate3D:dT,LucideRotate3d:dT,LucideRotateCcw:cm,LucideRotateCcwSquare:Xle,LucideRotateCw:zA,LucideRotateCwSquare:Jle,LucideRoute:j9,LucideRouteOff:ece,LucideRouter:tce,LucideRows:uT,LucideRows2:uT,LucideRows3:hT,LucideRows4:sce,LucideRss:nce,LucideRuler:J2,LucideRussianRuble:rce,LucideSailboat:ace,LucideSalad:ice,LucideSandwich:oce,LucideSatellite:cce,LucideSatelliteDish:lce,LucideSave:qo,LucideSaveAll:dce,LucideSaveOff:uce,LucideScale:N9,LucideScale3D:mT,LucideScale3d:mT,LucideScaling:hce,LucideScan:bce,LucideScanBarcode:mce,LucideScanEye:pce,LucideScanFace:fce,LucideScanLine:xce,LucideScanQrCode:gce,LucideScanSearch:yce,LucideScanText:vce,LucideScatterChart:Q3,LucideSchool:_ce,LucideSchool2:vE,LucideScissors:jce,LucideScissorsLineDashed:wce,LucideScissorsSquare:aE,LucideScissorsSquareDashedBottom:MT,LucideScreenShare:kce,LucideScreenShareOff:Nce,LucideScroll:Sce,LucideScrollText:k9,LucideSearch:vr,LucideSearchCheck:Cce,LucideSearchCode:Tce,LucideSearchSlash:Ece,LucideSearchX:S9,LucideSection:Ace,LucideSend:cr,LucideSendHorizonal:pT,LucideSendHorizontal:pT,LucideSendToBack:Mce,LucideSeparatorHorizontal:Ice,LucideSeparatorVertical:Pce,LucideServer:Oce,LucideServerCog:Lce,LucideServerCrash:Dce,LucideServerOff:Rce,LucideSettings:Xo,LucideSettings2:C9,LucideShapes:Fce,LucideShare:T9,LucideShare2:Hl,LucideSheet:zce,LucideShell:Bce,LucideShield:dh,LucideShieldAlert:gL,LucideShieldBan:$ce,LucideShieldCheck:sg,LucideShieldClose:fT,LucideShieldEllipsis:Uce,LucideShieldHalf:qce,LucideShieldMinus:Vce,LucideShieldOff:BA,LucideShieldPlus:Hce,LucideShieldQuestion:Gce,LucideShieldX:fT,LucideShip:Kce,LucideShipWheel:Wce,LucideShirt:Yce,LucideShoppingBag:_w,LucideShoppingBasket:Zce,LucideShoppingCart:Og,LucideShovel:Qce,LucideShowerHead:Xce,LucideShrink:Jce,LucideShrub:ede,LucideShuffle:$A,LucideSidebar:aT,LucideSidebarClose:sT,LucideSidebarOpen:rT,LucideSigma:tde,LucideSigmaSquare:iE,LucideSignal:ide,LucideSignalHigh:sde,LucideSignalLow:nde,LucideSignalMedium:rde,LucideSignalZero:ade,LucideSignature:ode,LucideSignpost:cde,LucideSignpostBig:lde,LucideSiren:dde,LucideSkipBack:ude,LucideSkipForward:hde,LucideSkull:mde,LucideSlack:pde,LucideSlash:fde,LucideSlashSquare:oE,LucideSlice:xde,LucideSliders:xT,LucideSlidersHorizontal:l4,LucideSlidersVertical:xT,LucideSmartphone:ng,LucideSmartphoneCharging:gde,LucideSmartphoneNfc:yde,LucideSmile:bde,LucideSmilePlus:vde,LucideSnail:_de,LucideSnowflake:Ev,LucideSofa:wde,LucideSortAsc:M3,LucideSortDesc:T3,LucideSoup:jde,LucideSpace:Nde,LucideSpade:kde,LucideSparkle:eN,LucideSparkles:un,LucideSpeaker:Sde,LucideSpeech:Cde,LucideSpellCheck:Ede,LucideSpellCheck2:Tde,LucideSpline:Ade,LucideSplit:Mde,LucideSplitSquareHorizontal:lE,LucideSplitSquareVertical:cE,LucideSprayCan:Ide,LucideSprout:UA,LucideSquare:ly,LucideSquareActivity:gT,LucideSquareArrowDown:bT,LucideSquareArrowDownLeft:yT,LucideSquareArrowDownRight:vT,LucideSquareArrowLeft:_T,LucideSquareArrowOutDownLeft:wT,LucideSquareArrowOutDownRight:jT,LucideSquareArrowOutUpLeft:NT,LucideSquareArrowOutUpRight:kT,LucideSquareArrowRight:ST,LucideSquareArrowUp:ET,LucideSquareArrowUpLeft:CT,LucideSquareArrowUpRight:TT,LucideSquareAsterisk:AT,LucideSquareBottomDashedScissors:MT,LucideSquareChartGantt:L_,LucideSquareCheck:IT,LucideSquareCheckBig:E2,LucideSquareChevronDown:PT,LucideSquareChevronLeft:LT,LucideSquareChevronRight:DT,LucideSquareChevronUp:RT,LucideSquareCode:OT,LucideSquareDashed:BT,LucideSquareDashedBottom:Lde,LucideSquareDashedBottomCode:Pde,LucideSquareDashedKanban:FT,LucideSquareDashedMousePointer:zT,LucideSquareDivide:$T,LucideSquareDot:UT,LucideSquareEqual:qT,LucideSquareFunction:VT,LucideSquareGanttChart:L_,LucideSquareKanban:HT,LucideSquareLibrary:GT,LucideSquareM:WT,LucideSquareMenu:KT,LucideSquareMinus:YT,LucideSquareMousePointer:ZT,LucideSquareParking:XT,LucideSquareParkingOff:QT,LucideSquarePen:ku,LucideSquarePercent:JT,LucideSquarePi:eE,LucideSquarePilcrow:tE,LucideSquarePlay:sE,LucideSquarePlus:nE,LucideSquarePower:rE,LucideSquareRadical:Dde,LucideSquareScissors:aE,LucideSquareSigma:iE,LucideSquareSlash:oE,LucideSquareSplitHorizontal:lE,LucideSquareSplitVertical:cE,LucideSquareSquare:Rde,LucideSquareStack:Ode,LucideSquareTerminal:dE,LucideSquareUser:hE,LucideSquareUserRound:uE,LucideSquareX:mE,LucideSquircle:Fde,LucideSquirrel:zde,LucideStamp:Bde,LucideStar:ca,LucideStarHalf:$de,LucideStarOff:Ude,LucideStars:un,LucideStepBack:qde,LucideStepForward:Vde,LucideStethoscope:Hde,LucideSticker:Gde,LucideStickyNote:E9,LucideStopCircle:b5,LucideStore:A9,LucideStretchHorizontal:Wde,LucideStretchVertical:Kde,LucideStrikethrough:M9,LucideSubscript:Yde,LucideSubtitles:z3,LucideSun:yb,LucideSunDim:Zde,LucideSunMedium:Qde,LucideSunMoon:Xde,LucideSunSnow:Jde,LucideSunrise:eue,LucideSunset:tue,LucideSuperscript:sue,LucideSwatchBook:nue,LucideSwissFranc:rue,LucideSwitchCamera:aue,LucideSword:iue,LucideSwords:oue,LucideSyringe:lue,LucideTable:vL,LucideTable2:yL,LucideTableCellsMerge:cue,LucideTableCellsSplit:due,LucideTableColumnsSplit:uue,LucideTableOfContents:hue,LucideTableProperties:mue,LucideTableRowsSplit:pue,LucideTablet:bL,LucideTabletSmartphone:fue,LucideTablets:xue,LucideTag:uh,LucideTags:I9,LucideTally1:gue,LucideTally2:yue,LucideTally3:vue,LucideTally4:bue,LucideTally5:_ue,LucideTangent:wue,LucideTarget:Oc,LucideTelescope:jue,LucideTent:kue,LucideTentTree:Nue,LucideTerminal:Sue,LucideTerminalSquare:dE,LucideTestTube:Cue,LucideTestTube2:pE,LucideTestTubeDiagonal:pE,LucideTestTubes:Tue,LucideText:Pue,LucideTextCursor:Aue,LucideTextCursorInput:Eue,LucideTextQuote:Mue,LucideTextSearch:Iue,LucideTextSelect:fE,LucideTextSelection:fE,LucideTheater:Lue,LucideThermometer:P9,LucideThermometerSnowflake:Due,LucideThermometerSun:Rue,LucideThumbsDown:L9,LucideThumbsUp:Vm,LucideTicket:D9,LucideTicketCheck:Oue,LucideTicketMinus:Fue,LucideTicketPercent:zue,LucideTicketPlus:Bue,LucideTicketSlash:$ue,LucideTicketX:Uue,LucideTickets:Vue,LucideTicketsPlane:que,LucideTimer:Wue,LucideTimerOff:Hue,LucideTimerReset:Gue,LucideToggleLeft:Kue,LucideToggleRight:Yue,LucideToilet:Zue,LucideTornado:Que,LucideTorus:Xue,LucideTouchpad:ehe,LucideTouchpadOff:Jue,LucideTowerControl:the,LucideToyBrick:she,LucideTractor:nhe,LucideTrafficCone:rhe,LucideTrain:xE,LucideTrainFront:ihe,LucideTrainFrontTunnel:ahe,LucideTrainTrack:ohe,LucideTramFront:xE,LucideTrash:lhe,LucideTrash2:_n,LucideTreeDeciduous:che,LucideTreePalm:gE,LucideTreePine:c4,LucideTrees:dhe,LucideTrello:uhe,LucideTrendingDown:vb,LucideTrendingUp:mo,LucideTrendingUpDown:hhe,LucideTriangle:phe,LucideTriangleAlert:$l,LucideTriangleRight:mhe,LucideTrophy:vo,LucideTruck:R9,LucideTurtle:fhe,LucideTv:ghe,LucideTv2:yE,LucideTvMinimal:yE,LucideTvMinimalPlay:xhe,LucideTwitch:yhe,LucideTwitter:vhe,LucideType:_he,LucideTypeOutline:bhe,LucideUmbrella:jhe,LucideUmbrellaOff:whe,LucideUnderline:_L,LucideUndo:d4,LucideUndo2:Nhe,LucideUndoDot:khe,LucideUnfoldHorizontal:She,LucideUnfoldVertical:Che,LucideUngroup:The,LucideUniversity:vE,LucideUnlink:qA,LucideUnlink2:Ehe,LucideUnlock:Y5,LucideUnlockKeyhole:K5,LucideUnplug:Ahe,LucideUpload:Na,LucideUploadCloud:S5,LucideUsb:Mhe,LucideUser:Xi,LucideUser2:kE,LucideUserCheck:bb,LucideUserCheck2:bE,LucideUserCircle:w5,LucideUserCircle2:_5,LucideUserCog:O9,LucideUserCog2:_E,LucideUserMinus:F9,LucideUserMinus2:wE,LucideUserPen:Ihe,LucideUserPlus:Fo,LucideUserPlus2:jE,LucideUserRound:kE,LucideUserRoundCheck:bE,LucideUserRoundCog:_E,LucideUserRoundMinus:wE,LucideUserRoundPen:Phe,LucideUserRoundPlus:jE,LucideUserRoundSearch:Lhe,LucideUserRoundX:NE,LucideUserSearch:Dhe,LucideUserSquare:hE,LucideUserSquare2:uE,LucideUserX:Rhe,LucideUserX2:NE,LucideUsers:Nn,LucideUsers2:G0,LucideUsersRound:G0,LucideUtensils:CE,LucideUtensilsCrossed:SE,LucideUtilityPole:Ohe,LucideVariable:wL,LucideVault:Fhe,LucideVegan:zhe,LucideVenetianMask:Bhe,LucideVerified:L3,LucideVibrate:Uhe,LucideVibrateOff:$he,LucideVideo:br,LucideVideoOff:qhe,LucideVideotape:Vhe,LucideView:Hhe,LucideVoicemail:Ghe,LucideVolleyball:Whe,LucideVolume:Zhe,LucideVolume1:Khe,LucideVolume2:z9,LucideVolumeOff:Yhe,LucideVolumeX:B9,LucideVote:Qhe,LucideWallet:jL,LucideWallet2:TE,LucideWalletCards:Xhe,LucideWalletMinimal:TE,LucideWallpaper:Jhe,LucideWand:eme,LucideWand2:Dm,LucideWandSparkles:Dm,LucideWarehouse:tme,LucideWashingMachine:sme,LucideWatch:nme,LucideWaves:rme,LucideWaypoints:ame,LucideWebcam:ime,LucideWebhook:lme,LucideWebhookOff:ome,LucideWeight:cme,LucideWheat:ume,LucideWheatOff:dme,LucideWholeWord:hme,LucideWifi:gme,LucideWifiHigh:mme,LucideWifiLow:pme,LucideWifiOff:fme,LucideWifiZero:xme,LucideWind:vme,LucideWindArrowDown:yme,LucideWine:$9,LucideWineOff:bme,LucideWorkflow:U9,LucideWorm:_me,LucideWrapText:wme,LucideWrench:_b,LucideX:Bn,LucideXCircle:Hc,LucideXOctagon:J5,LucideXSquare:mE,LucideYoutube:jme,LucideZap:hh,LucideZapOff:Nme,LucideZoomIn:u4,LucideZoomOut:NL,Luggage:iae,LuggageIcon:iae,MSquare:WT,MSquareIcon:WT,Magnet:oae,MagnetIcon:oae,Mail:Vs,MailCheck:oL,MailCheckIcon:oL,MailIcon:Vs,MailMinus:lae,MailMinusIcon:lae,MailOpen:lL,MailOpenIcon:lL,MailPlus:d9,MailPlusIcon:d9,MailQuestion:cae,MailQuestionIcon:cae,MailSearch:dae,MailSearchIcon:dae,MailWarning:uae,MailWarningIcon:uae,MailX:cL,MailXIcon:cL,Mailbox:hae,MailboxIcon:hae,Mails:mae,MailsIcon:mae,Map:DA,MapIcon:DA,MapPin:ka,MapPinCheck:fae,MapPinCheckIcon:fae,MapPinCheckInside:pae,MapPinCheckInsideIcon:pae,MapPinHouse:xae,MapPinHouseIcon:xae,MapPinIcon:ka,MapPinMinus:yae,MapPinMinusIcon:yae,MapPinMinusInside:gae,MapPinMinusInsideIcon:gae,MapPinOff:vae,MapPinOffIcon:vae,MapPinPlus:_ae,MapPinPlusIcon:_ae,MapPinPlusInside:bae,MapPinPlusInsideIcon:bae,MapPinX:jae,MapPinXIcon:jae,MapPinXInside:wae,MapPinXInsideIcon:wae,MapPinned:Nae,MapPinnedIcon:Nae,Martini:kae,MartiniIcon:kae,Maximize:RA,Maximize2:u9,Maximize2Icon:u9,MaximizeIcon:RA,Medal:Q2,MedalIcon:Q2,Megaphone:$d,MegaphoneIcon:$d,MegaphoneOff:Sae,MegaphoneOffIcon:Sae,Meh:Cae,MehIcon:Cae,MemoryStick:Tae,MemoryStickIcon:Tae,Menu:s4,MenuIcon:s4,MenuSquare:KT,MenuSquareIcon:KT,Merge:Eae,MergeIcon:Eae,MessageCircle:Ql,MessageCircleCode:Aae,MessageCircleCodeIcon:Aae,MessageCircleDashed:Mae,MessageCircleDashedIcon:Mae,MessageCircleHeart:dL,MessageCircleHeartIcon:dL,MessageCircleIcon:Ql,MessageCircleMore:Iae,MessageCircleMoreIcon:Iae,MessageCircleOff:Pae,MessageCircleOffIcon:Pae,MessageCirclePlus:Lae,MessageCirclePlusIcon:Lae,MessageCircleQuestion:h9,MessageCircleQuestionIcon:h9,MessageCircleReply:Dae,MessageCircleReplyIcon:Dae,MessageCircleWarning:Rae,MessageCircleWarningIcon:Rae,MessageCircleX:Oae,MessageCircleXIcon:Oae,MessageSquare:Ei,MessageSquareCode:Fae,MessageSquareCodeIcon:Fae,MessageSquareDashed:zae,MessageSquareDashedIcon:zae,MessageSquareDiff:Bae,MessageSquareDiffIcon:Bae,MessageSquareDot:$ae,MessageSquareDotIcon:$ae,MessageSquareHeart:uL,MessageSquareHeartIcon:uL,MessageSquareIcon:Ei,MessageSquareLock:Uae,MessageSquareLockIcon:Uae,MessageSquareMore:m9,MessageSquareMoreIcon:m9,MessageSquareOff:qae,MessageSquareOffIcon:qae,MessageSquarePlus:nw,MessageSquarePlusIcon:nw,MessageSquareQuote:bw,MessageSquareQuoteIcon:bw,MessageSquareReply:Vae,MessageSquareReplyIcon:Vae,MessageSquareShare:Hae,MessageSquareShareIcon:Hae,MessageSquareText:Gae,MessageSquareTextIcon:Gae,MessageSquareWarning:Wae,MessageSquareWarningIcon:Wae,MessageSquareX:Kae,MessageSquareXIcon:Kae,MessagesSquare:hL,MessagesSquareIcon:hL,Mic:Fv,Mic2:Z5,Mic2Icon:Z5,MicIcon:Fv,MicOff:Yae,MicOffIcon:Yae,MicVocal:Z5,MicVocalIcon:Z5,Microchip:Zae,MicrochipIcon:Zae,Microscope:Qae,MicroscopeIcon:Qae,Microwave:Xae,MicrowaveIcon:Xae,Milestone:Jae,MilestoneIcon:Jae,Milk:tie,MilkIcon:tie,MilkOff:eie,MilkOffIcon:eie,Minimize:nie,Minimize2:sie,Minimize2Icon:sie,MinimizeIcon:nie,Minus:fb,MinusCircle:h5,MinusCircleIcon:h5,MinusIcon:fb,MinusSquare:YT,MinusSquareIcon:YT,Monitor:xb,MonitorCheck:rie,MonitorCheckIcon:rie,MonitorCog:aie,MonitorCogIcon:aie,MonitorDot:iie,MonitorDotIcon:iie,MonitorDown:oie,MonitorDownIcon:oie,MonitorIcon:xb,MonitorOff:lie,MonitorOffIcon:lie,MonitorPause:cie,MonitorPauseIcon:cie,MonitorPlay:mL,MonitorPlayIcon:mL,MonitorSmartphone:die,MonitorSmartphoneIcon:die,MonitorSpeaker:uie,MonitorSpeakerIcon:uie,MonitorStop:hie,MonitorStopIcon:hie,MonitorUp:OA,MonitorUpIcon:OA,MonitorX:mie,MonitorXIcon:mie,Moon:fie,MoonIcon:fie,MoonStar:pie,MoonStarIcon:pie,MoreHorizontal:Qf,MoreHorizontalIcon:Qf,MoreVertical:Ig,MoreVerticalIcon:Ig,Mountain:gie,MountainIcon:gie,MountainSnow:xie,MountainSnowIcon:xie,Mouse:_ie,MouseIcon:_ie,MouseOff:yie,MouseOffIcon:yie,MousePointer:Om,MousePointer2:vie,MousePointer2Icon:vie,MousePointerBan:bie,MousePointerBanIcon:bie,MousePointerClick:oc,MousePointerClickIcon:oc,MousePointerIcon:Om,MousePointerSquareDashed:zT,MousePointerSquareDashedIcon:zT,Move:Lie,Move3D:Q5,Move3DIcon:Q5,Move3d:Q5,Move3dIcon:Q5,MoveDiagonal:jie,MoveDiagonal2:wie,MoveDiagonal2Icon:wie,MoveDiagonalIcon:jie,MoveDown:Sie,MoveDownIcon:Sie,MoveDownLeft:Nie,MoveDownLeftIcon:Nie,MoveDownRight:kie,MoveDownRightIcon:kie,MoveHorizontal:Cie,MoveHorizontalIcon:Cie,MoveIcon:Lie,MoveLeft:Tie,MoveLeftIcon:Tie,MoveRight:Eie,MoveRightIcon:Eie,MoveUp:Iie,MoveUpIcon:Iie,MoveUpLeft:Aie,MoveUpLeftIcon:Aie,MoveUpRight:Mie,MoveUpRightIcon:Mie,MoveVertical:Pie,MoveVerticalIcon:Pie,Music:pL,Music2:Die,Music2Icon:Die,Music3:Rie,Music3Icon:Rie,Music4:Oie,Music4Icon:Oie,MusicIcon:pL,Navigation:p9,Navigation2:zie,Navigation2Icon:zie,Navigation2Off:Fie,Navigation2OffIcon:Fie,NavigationIcon:p9,NavigationOff:Bie,NavigationOffIcon:Bie,Network:$ie,NetworkIcon:$ie,Newspaper:ay,NewspaperIcon:ay,Nfc:Uie,NfcIcon:Uie,Notebook:Gie,NotebookIcon:Gie,NotebookPen:qie,NotebookPenIcon:qie,NotebookTabs:Vie,NotebookTabsIcon:Vie,NotebookText:Hie,NotebookTextIcon:Hie,NotepadText:Kie,NotepadTextDashed:Wie,NotepadTextDashedIcon:Wie,NotepadTextIcon:Kie,Nut:Zie,NutIcon:Zie,NutOff:Yie,NutOffIcon:Yie,Octagon:Xie,OctagonAlert:Y_,OctagonAlertIcon:Y_,OctagonIcon:Xie,OctagonMinus:Qie,OctagonMinusIcon:Qie,OctagonPause:X5,OctagonPauseIcon:X5,OctagonX:J5,OctagonXIcon:J5,Omega:Jie,OmegaIcon:Jie,Option:eoe,OptionIcon:eoe,Orbit:toe,OrbitIcon:toe,Origami:soe,OrigamiIcon:soe,Outdent:H5,OutdentIcon:H5,Package:Rc,Package2:noe,Package2Icon:noe,PackageCheck:roe,PackageCheckIcon:roe,PackageIcon:Rc,PackageMinus:aoe,PackageMinusIcon:aoe,PackageOpen:ioe,PackageOpenIcon:ioe,PackagePlus:f9,PackagePlusIcon:f9,PackageSearch:ooe,PackageSearchIcon:ooe,PackageX:loe,PackageXIcon:loe,PaintBucket:coe,PaintBucketIcon:coe,PaintRoller:doe,PaintRollerIcon:doe,Paintbrush:uoe,Paintbrush2:eT,Paintbrush2Icon:eT,PaintbrushIcon:uoe,PaintbrushVertical:eT,PaintbrushVerticalIcon:eT,Palette:fl,PaletteIcon:fl,Palmtree:gE,PalmtreeIcon:gE,PanelBottom:poe,PanelBottomClose:hoe,PanelBottomCloseIcon:hoe,PanelBottomDashed:tT,PanelBottomDashedIcon:tT,PanelBottomIcon:poe,PanelBottomInactive:tT,PanelBottomInactiveIcon:tT,PanelBottomOpen:moe,PanelBottomOpenIcon:moe,PanelLeft:aT,PanelLeftClose:sT,PanelLeftCloseIcon:sT,PanelLeftDashed:nT,PanelLeftDashedIcon:nT,PanelLeftIcon:aT,PanelLeftInactive:nT,PanelLeftInactiveIcon:nT,PanelLeftOpen:rT,PanelLeftOpenIcon:rT,PanelRight:goe,PanelRightClose:foe,PanelRightCloseIcon:foe,PanelRightDashed:iT,PanelRightDashedIcon:iT,PanelRightIcon:goe,PanelRightInactive:iT,PanelRightInactiveIcon:iT,PanelRightOpen:xoe,PanelRightOpenIcon:xoe,PanelTop:boe,PanelTopClose:yoe,PanelTopCloseIcon:yoe,PanelTopDashed:oT,PanelTopDashedIcon:oT,PanelTopIcon:boe,PanelTopInactive:oT,PanelTopInactiveIcon:oT,PanelTopOpen:voe,PanelTopOpenIcon:voe,PanelsLeftBottom:_oe,PanelsLeftBottomIcon:_oe,PanelsLeftRight:Kk,PanelsLeftRightIcon:Kk,PanelsRightBottom:woe,PanelsRightBottomIcon:woe,PanelsTopBottom:hT,PanelsTopBottomIcon:hT,PanelsTopLeft:T2,PanelsTopLeftIcon:T2,Paperclip:n4,PaperclipIcon:n4,Parentheses:joe,ParenthesesIcon:joe,ParkingCircle:p5,ParkingCircleIcon:p5,ParkingCircleOff:m5,ParkingCircleOffIcon:m5,ParkingMeter:Noe,ParkingMeterIcon:Noe,ParkingSquare:XT,ParkingSquareIcon:XT,ParkingSquareOff:QT,ParkingSquareOffIcon:QT,PartyPopper:ch,PartyPopperIcon:ch,Pause:bf,PauseCircle:f5,PauseCircleIcon:f5,PauseIcon:bf,PauseOctagon:X5,PauseOctagonIcon:X5,PawPrint:koe,PawPrintIcon:koe,PcCase:Soe,PcCaseIcon:Soe,Pen:wv,PenBox:ku,PenBoxIcon:ku,PenIcon:wv,PenLine:sb,PenLineIcon:sb,PenOff:Coe,PenOffIcon:Coe,PenSquare:ku,PenSquareIcon:ku,PenTool:r4,PenToolIcon:r4,Pencil:_a,PencilIcon:_a,PencilLine:x9,PencilLineIcon:x9,PencilOff:Toe,PencilOffIcon:Toe,PencilRuler:Eoe,PencilRulerIcon:Eoe,Pentagon:Aoe,PentagonIcon:Aoe,Percent:a4,PercentCircle:x5,PercentCircleIcon:x5,PercentDiamond:E5,PercentDiamondIcon:E5,PercentIcon:a4,PercentSquare:JT,PercentSquareIcon:JT,PersonStanding:Moe,PersonStandingIcon:Moe,PhilippinePeso:Ioe,PhilippinePesoIcon:Ioe,Phone:Ar,PhoneCall:g9,PhoneCallIcon:g9,PhoneForwarded:Poe,PhoneForwardedIcon:Poe,PhoneIcon:Ar,PhoneIncoming:Loe,PhoneIncomingIcon:Loe,PhoneMissed:Doe,PhoneMissedIcon:Doe,PhoneOff:Roe,PhoneOffIcon:Roe,PhoneOutgoing:Ooe,PhoneOutgoingIcon:Ooe,Pi:Foe,PiIcon:Foe,PiSquare:eE,PiSquareIcon:eE,Piano:zoe,PianoIcon:zoe,Pickaxe:Boe,PickaxeIcon:Boe,PictureInPicture:Uoe,PictureInPicture2:$oe,PictureInPicture2Icon:$oe,PictureInPictureIcon:Uoe,PieChart:Z3,PieChartIcon:Z3,PiggyBank:qoe,PiggyBankIcon:qoe,Pilcrow:Goe,PilcrowIcon:Goe,PilcrowLeft:Voe,PilcrowLeftIcon:Voe,PilcrowRight:Hoe,PilcrowRightIcon:Hoe,PilcrowSquare:tE,PilcrowSquareIcon:tE,Pill:Koe,PillBottle:Woe,PillBottleIcon:Woe,PillIcon:Koe,Pin:i4,PinIcon:i4,PinOff:y9,PinOffIcon:y9,Pipette:Yoe,PipetteIcon:Yoe,Pizza:Zoe,PizzaIcon:Zoe,Plane:v9,PlaneIcon:v9,PlaneLanding:Qoe,PlaneLandingIcon:Qoe,PlaneTakeoff:Xoe,PlaneTakeoffIcon:Xoe,Play:Al,PlayCircle:Au,PlayCircleIcon:Au,PlayIcon:Al,PlaySquare:sE,PlaySquareIcon:sE,Plug:X2,Plug2:Joe,Plug2Icon:Joe,PlugIcon:X2,PlugZap:lT,PlugZap2:lT,PlugZap2Icon:lT,PlugZapIcon:lT,Plus:Is,PlusCircle:g5,PlusCircleIcon:g5,PlusIcon:Is,PlusSquare:nE,PlusSquareIcon:nE,Pocket:tle,PocketIcon:tle,PocketKnife:ele,PocketKnifeIcon:ele,Podcast:sle,PodcastIcon:sle,Pointer:rle,PointerIcon:rle,PointerOff:nle,PointerOffIcon:nle,Popcorn:ale,PopcornIcon:ale,Popsicle:ile,PopsicleIcon:ile,PoundSterling:ole,PoundSterlingIcon:ole,Power:b9,PowerCircle:y5,PowerCircleIcon:y5,PowerIcon:b9,PowerOff:lle,PowerOffIcon:lle,PowerSquare:rE,PowerSquareIcon:rE,Presentation:iy,PresentationIcon:iy,Printer:_9,PrinterCheck:cle,PrinterCheckIcon:cle,PrinterIcon:_9,Projector:dle,ProjectorIcon:dle,Proportions:ule,ProportionsIcon:ule,Puzzle:hle,PuzzleIcon:hle,Pyramid:mle,PyramidIcon:mle,QrCode:oy,QrCodeIcon:oy,Quote:gb,QuoteIcon:gb,Rabbit:ple,RabbitIcon:ple,Radar:FA,RadarIcon:FA,Radiation:fle,RadiationIcon:fle,Radical:xle,RadicalIcon:xle,Radio:_f,RadioIcon:_f,RadioReceiver:gle,RadioReceiverIcon:gle,RadioTower:yle,RadioTowerIcon:yle,Radius:vle,RadiusIcon:vle,RailSymbol:ble,RailSymbolIcon:ble,Rainbow:_le,RainbowIcon:_le,Rat:wle,RatIcon:wle,Ratio:jle,RatioIcon:jle,Receipt:Ile,ReceiptCent:Nle,ReceiptCentIcon:Nle,ReceiptEuro:kle,ReceiptEuroIcon:kle,ReceiptIcon:Ile,ReceiptIndianRupee:Sle,ReceiptIndianRupeeIcon:Sle,ReceiptJapaneseYen:Cle,ReceiptJapaneseYenIcon:Cle,ReceiptPoundSterling:Tle,ReceiptPoundSterlingIcon:Tle,ReceiptRussianRuble:Ele,ReceiptRussianRubleIcon:Ele,ReceiptSwissFranc:Ale,ReceiptSwissFrancIcon:Ale,ReceiptText:Mle,ReceiptTextIcon:Mle,RectangleEllipsis:cT,RectangleEllipsisIcon:cT,RectangleHorizontal:Ple,RectangleHorizontalIcon:Ple,RectangleVertical:Lle,RectangleVerticalIcon:Lle,Recycle:Dle,RecycleIcon:Dle,Redo:o4,Redo2:Rle,Redo2Icon:Rle,RedoDot:Ole,RedoDotIcon:Ole,RedoIcon:o4,RefreshCcw:fL,RefreshCcwDot:Fle,RefreshCcwDotIcon:Fle,RefreshCcwIcon:fL,RefreshCw:Ti,RefreshCwIcon:Ti,RefreshCwOff:zle,RefreshCwOffIcon:zle,Refrigerator:Ble,RefrigeratorIcon:Ble,Regex:$le,RegexIcon:$le,RemoveFormatting:Ule,RemoveFormattingIcon:Ule,Repeat:xL,Repeat1:qle,Repeat1Icon:qle,Repeat2:Vle,Repeat2Icon:Vle,RepeatIcon:xL,Replace:Gle,ReplaceAll:Hle,ReplaceAllIcon:Hle,ReplaceIcon:Gle,Reply:w9,ReplyAll:Wle,ReplyAllIcon:Wle,ReplyIcon:w9,Rewind:Kle,RewindIcon:Kle,Ribbon:Yle,RibbonIcon:Yle,Rocket:sx,RocketIcon:sx,RockingChair:Zle,RockingChairIcon:Zle,RollerCoaster:Qle,RollerCoasterIcon:Qle,Rotate3D:dT,Rotate3DIcon:dT,Rotate3d:dT,Rotate3dIcon:dT,RotateCcw:cm,RotateCcwIcon:cm,RotateCcwSquare:Xle,RotateCcwSquareIcon:Xle,RotateCw:zA,RotateCwIcon:zA,RotateCwSquare:Jle,RotateCwSquareIcon:Jle,Route:j9,RouteIcon:j9,RouteOff:ece,RouteOffIcon:ece,Router:tce,RouterIcon:tce,Rows:uT,Rows2:uT,Rows2Icon:uT,Rows3:hT,Rows3Icon:hT,Rows4:sce,Rows4Icon:sce,RowsIcon:uT,Rss:nce,RssIcon:nce,Ruler:J2,RulerIcon:J2,RussianRuble:rce,RussianRubleIcon:rce,Sailboat:ace,SailboatIcon:ace,Salad:ice,SaladIcon:ice,Sandwich:oce,SandwichIcon:oce,Satellite:cce,SatelliteDish:lce,SatelliteDishIcon:lce,SatelliteIcon:cce,Save:qo,SaveAll:dce,SaveAllIcon:dce,SaveIcon:qo,SaveOff:uce,SaveOffIcon:uce,Scale:N9,Scale3D:mT,Scale3DIcon:mT,Scale3d:mT,Scale3dIcon:mT,ScaleIcon:N9,Scaling:hce,ScalingIcon:hce,Scan:bce,ScanBarcode:mce,ScanBarcodeIcon:mce,ScanEye:pce,ScanEyeIcon:pce,ScanFace:fce,ScanFaceIcon:fce,ScanIcon:bce,ScanLine:xce,ScanLineIcon:xce,ScanQrCode:gce,ScanQrCodeIcon:gce,ScanSearch:yce,ScanSearchIcon:yce,ScanText:vce,ScanTextIcon:vce,ScatterChart:Q3,ScatterChartIcon:Q3,School:_ce,School2:vE,School2Icon:vE,SchoolIcon:_ce,Scissors:jce,ScissorsIcon:jce,ScissorsLineDashed:wce,ScissorsLineDashedIcon:wce,ScissorsSquare:aE,ScissorsSquareDashedBottom:MT,ScissorsSquareDashedBottomIcon:MT,ScissorsSquareIcon:aE,ScreenShare:kce,ScreenShareIcon:kce,ScreenShareOff:Nce,ScreenShareOffIcon:Nce,Scroll:Sce,ScrollIcon:Sce,ScrollText:k9,ScrollTextIcon:k9,Search:vr,SearchCheck:Cce,SearchCheckIcon:Cce,SearchCode:Tce,SearchCodeIcon:Tce,SearchIcon:vr,SearchSlash:Ece,SearchSlashIcon:Ece,SearchX:S9,SearchXIcon:S9,Section:Ace,SectionIcon:Ace,Send:cr,SendHorizonal:pT,SendHorizonalIcon:pT,SendHorizontal:pT,SendHorizontalIcon:pT,SendIcon:cr,SendToBack:Mce,SendToBackIcon:Mce,SeparatorHorizontal:Ice,SeparatorHorizontalIcon:Ice,SeparatorVertical:Pce,SeparatorVerticalIcon:Pce,Server:Oce,ServerCog:Lce,ServerCogIcon:Lce,ServerCrash:Dce,ServerCrashIcon:Dce,ServerIcon:Oce,ServerOff:Rce,ServerOffIcon:Rce,Settings:Xo,Settings2:C9,Settings2Icon:C9,SettingsIcon:Xo,Shapes:Fce,ShapesIcon:Fce,Share:T9,Share2:Hl,Share2Icon:Hl,ShareIcon:T9,Sheet:zce,SheetIcon:zce,Shell:Bce,ShellIcon:Bce,Shield:dh,ShieldAlert:gL,ShieldAlertIcon:gL,ShieldBan:$ce,ShieldBanIcon:$ce,ShieldCheck:sg,ShieldCheckIcon:sg,ShieldClose:fT,ShieldCloseIcon:fT,ShieldEllipsis:Uce,ShieldEllipsisIcon:Uce,ShieldHalf:qce,ShieldHalfIcon:qce,ShieldIcon:dh,ShieldMinus:Vce,ShieldMinusIcon:Vce,ShieldOff:BA,ShieldOffIcon:BA,ShieldPlus:Hce,ShieldPlusIcon:Hce,ShieldQuestion:Gce,ShieldQuestionIcon:Gce,ShieldX:fT,ShieldXIcon:fT,Ship:Kce,ShipIcon:Kce,ShipWheel:Wce,ShipWheelIcon:Wce,Shirt:Yce,ShirtIcon:Yce,ShoppingBag:_w,ShoppingBagIcon:_w,ShoppingBasket:Zce,ShoppingBasketIcon:Zce,ShoppingCart:Og,ShoppingCartIcon:Og,Shovel:Qce,ShovelIcon:Qce,ShowerHead:Xce,ShowerHeadIcon:Xce,Shrink:Jce,ShrinkIcon:Jce,Shrub:ede,ShrubIcon:ede,Shuffle:$A,ShuffleIcon:$A,Sidebar:aT,SidebarClose:sT,SidebarCloseIcon:sT,SidebarIcon:aT,SidebarOpen:rT,SidebarOpenIcon:rT,Sigma:tde,SigmaIcon:tde,SigmaSquare:iE,SigmaSquareIcon:iE,Signal:ide,SignalHigh:sde,SignalHighIcon:sde,SignalIcon:ide,SignalLow:nde,SignalLowIcon:nde,SignalMedium:rde,SignalMediumIcon:rde,SignalZero:ade,SignalZeroIcon:ade,Signature:ode,SignatureIcon:ode,Signpost:cde,SignpostBig:lde,SignpostBigIcon:lde,SignpostIcon:cde,Siren:dde,SirenIcon:dde,SkipBack:ude,SkipBackIcon:ude,SkipForward:hde,SkipForwardIcon:hde,Skull:mde,SkullIcon:mde,Slack:pde,SlackIcon:pde,Slash:fde,SlashIcon:fde,SlashSquare:oE,SlashSquareIcon:oE,Slice:xde,SliceIcon:xde,Sliders:xT,SlidersHorizontal:l4,SlidersHorizontalIcon:l4,SlidersIcon:xT,SlidersVertical:xT,SlidersVerticalIcon:xT,Smartphone:ng,SmartphoneCharging:gde,SmartphoneChargingIcon:gde,SmartphoneIcon:ng,SmartphoneNfc:yde,SmartphoneNfcIcon:yde,Smile:bde,SmileIcon:bde,SmilePlus:vde,SmilePlusIcon:vde,Snail:_de,SnailIcon:_de,Snowflake:Ev,SnowflakeIcon:Ev,Sofa:wde,SofaIcon:wde,SortAsc:M3,SortAscIcon:M3,SortDesc:T3,SortDescIcon:T3,Soup:jde,SoupIcon:jde,Space:Nde,SpaceIcon:Nde,Spade:kde,SpadeIcon:kde,Sparkle:eN,SparkleIcon:eN,Sparkles:un,SparklesIcon:un,Speaker:Sde,SpeakerIcon:Sde,Speech:Cde,SpeechIcon:Cde,SpellCheck:Ede,SpellCheck2:Tde,SpellCheck2Icon:Tde,SpellCheckIcon:Ede,Spline:Ade,SplineIcon:Ade,Split:Mde,SplitIcon:Mde,SplitSquareHorizontal:lE,SplitSquareHorizontalIcon:lE,SplitSquareVertical:cE,SplitSquareVerticalIcon:cE,SprayCan:Ide,SprayCanIcon:Ide,Sprout:UA,SproutIcon:UA,Square:ly,SquareActivity:gT,SquareActivityIcon:gT,SquareArrowDown:bT,SquareArrowDownIcon:bT,SquareArrowDownLeft:yT,SquareArrowDownLeftIcon:yT,SquareArrowDownRight:vT,SquareArrowDownRightIcon:vT,SquareArrowLeft:_T,SquareArrowLeftIcon:_T,SquareArrowOutDownLeft:wT,SquareArrowOutDownLeftIcon:wT,SquareArrowOutDownRight:jT,SquareArrowOutDownRightIcon:jT,SquareArrowOutUpLeft:NT,SquareArrowOutUpLeftIcon:NT,SquareArrowOutUpRight:kT,SquareArrowOutUpRightIcon:kT,SquareArrowRight:ST,SquareArrowRightIcon:ST,SquareArrowUp:ET,SquareArrowUpIcon:ET,SquareArrowUpLeft:CT,SquareArrowUpLeftIcon:CT,SquareArrowUpRight:TT,SquareArrowUpRightIcon:TT,SquareAsterisk:AT,SquareAsteriskIcon:AT,SquareBottomDashedScissors:MT,SquareBottomDashedScissorsIcon:MT,SquareChartGantt:L_,SquareChartGanttIcon:L_,SquareCheck:IT,SquareCheckBig:E2,SquareCheckBigIcon:E2,SquareCheckIcon:IT,SquareChevronDown:PT,SquareChevronDownIcon:PT,SquareChevronLeft:LT,SquareChevronLeftIcon:LT,SquareChevronRight:DT,SquareChevronRightIcon:DT,SquareChevronUp:RT,SquareChevronUpIcon:RT,SquareCode:OT,SquareCodeIcon:OT,SquareDashed:BT,SquareDashedBottom:Lde,SquareDashedBottomCode:Pde,SquareDashedBottomCodeIcon:Pde,SquareDashedBottomIcon:Lde,SquareDashedIcon:BT,SquareDashedKanban:FT,SquareDashedKanbanIcon:FT,SquareDashedMousePointer:zT,SquareDashedMousePointerIcon:zT,SquareDivide:$T,SquareDivideIcon:$T,SquareDot:UT,SquareDotIcon:UT,SquareEqual:qT,SquareEqualIcon:qT,SquareFunction:VT,SquareFunctionIcon:VT,SquareGanttChart:L_,SquareGanttChartIcon:L_,SquareIcon:ly,SquareKanban:HT,SquareKanbanIcon:HT,SquareLibrary:GT,SquareLibraryIcon:GT,SquareM:WT,SquareMIcon:WT,SquareMenu:KT,SquareMenuIcon:KT,SquareMinus:YT,SquareMinusIcon:YT,SquareMousePointer:ZT,SquareMousePointerIcon:ZT,SquareParking:XT,SquareParkingIcon:XT,SquareParkingOff:QT,SquareParkingOffIcon:QT,SquarePen:ku,SquarePenIcon:ku,SquarePercent:JT,SquarePercentIcon:JT,SquarePi:eE,SquarePiIcon:eE,SquarePilcrow:tE,SquarePilcrowIcon:tE,SquarePlay:sE,SquarePlayIcon:sE,SquarePlus:nE,SquarePlusIcon:nE,SquarePower:rE,SquarePowerIcon:rE,SquareRadical:Dde,SquareRadicalIcon:Dde,SquareScissors:aE,SquareScissorsIcon:aE,SquareSigma:iE,SquareSigmaIcon:iE,SquareSlash:oE,SquareSlashIcon:oE,SquareSplitHorizontal:lE,SquareSplitHorizontalIcon:lE,SquareSplitVertical:cE,SquareSplitVerticalIcon:cE,SquareSquare:Rde,SquareSquareIcon:Rde,SquareStack:Ode,SquareStackIcon:Ode,SquareTerminal:dE,SquareTerminalIcon:dE,SquareUser:hE,SquareUserIcon:hE,SquareUserRound:uE,SquareUserRoundIcon:uE,SquareX:mE,SquareXIcon:mE,Squircle:Fde,SquircleIcon:Fde,Squirrel:zde,SquirrelIcon:zde,Stamp:Bde,StampIcon:Bde,Star:ca,StarHalf:$de,StarHalfIcon:$de,StarIcon:ca,StarOff:Ude,StarOffIcon:Ude,Stars:un,StarsIcon:un,StepBack:qde,StepBackIcon:qde,StepForward:Vde,StepForwardIcon:Vde,Stethoscope:Hde,StethoscopeIcon:Hde,Sticker:Gde,StickerIcon:Gde,StickyNote:E9,StickyNoteIcon:E9,StopCircle:b5,StopCircleIcon:b5,Store:A9,StoreIcon:A9,StretchHorizontal:Wde,StretchHorizontalIcon:Wde,StretchVertical:Kde,StretchVerticalIcon:Kde,Strikethrough:M9,StrikethroughIcon:M9,Subscript:Yde,SubscriptIcon:Yde,Subtitles:z3,SubtitlesIcon:z3,Sun:yb,SunDim:Zde,SunDimIcon:Zde,SunIcon:yb,SunMedium:Qde,SunMediumIcon:Qde,SunMoon:Xde,SunMoonIcon:Xde,SunSnow:Jde,SunSnowIcon:Jde,Sunrise:eue,SunriseIcon:eue,Sunset:tue,SunsetIcon:tue,Superscript:sue,SuperscriptIcon:sue,SwatchBook:nue,SwatchBookIcon:nue,SwissFranc:rue,SwissFrancIcon:rue,SwitchCamera:aue,SwitchCameraIcon:aue,Sword:iue,SwordIcon:iue,Swords:oue,SwordsIcon:oue,Syringe:lue,SyringeIcon:lue,Table:vL,Table2:yL,Table2Icon:yL,TableCellsMerge:cue,TableCellsMergeIcon:cue,TableCellsSplit:due,TableCellsSplitIcon:due,TableColumnsSplit:uue,TableColumnsSplitIcon:uue,TableIcon:vL,TableOfContents:hue,TableOfContentsIcon:hue,TableProperties:mue,TablePropertiesIcon:mue,TableRowsSplit:pue,TableRowsSplitIcon:pue,Tablet:bL,TabletIcon:bL,TabletSmartphone:fue,TabletSmartphoneIcon:fue,Tablets:xue,TabletsIcon:xue,Tag:uh,TagIcon:uh,Tags:I9,TagsIcon:I9,Tally1:gue,Tally1Icon:gue,Tally2:yue,Tally2Icon:yue,Tally3:vue,Tally3Icon:vue,Tally4:bue,Tally4Icon:bue,Tally5:_ue,Tally5Icon:_ue,Tangent:wue,TangentIcon:wue,Target:Oc,TargetIcon:Oc,Telescope:jue,TelescopeIcon:jue,Tent:kue,TentIcon:kue,TentTree:Nue,TentTreeIcon:Nue,Terminal:Sue,TerminalIcon:Sue,TerminalSquare:dE,TerminalSquareIcon:dE,TestTube:Cue,TestTube2:pE,TestTube2Icon:pE,TestTubeDiagonal:pE,TestTubeDiagonalIcon:pE,TestTubeIcon:Cue,TestTubes:Tue,TestTubesIcon:Tue,Text:Pue,TextCursor:Aue,TextCursorIcon:Aue,TextCursorInput:Eue,TextCursorInputIcon:Eue,TextIcon:Pue,TextQuote:Mue,TextQuoteIcon:Mue,TextSearch:Iue,TextSearchIcon:Iue,TextSelect:fE,TextSelectIcon:fE,TextSelection:fE,TextSelectionIcon:fE,Theater:Lue,TheaterIcon:Lue,Thermometer:P9,ThermometerIcon:P9,ThermometerSnowflake:Due,ThermometerSnowflakeIcon:Due,ThermometerSun:Rue,ThermometerSunIcon:Rue,ThumbsDown:L9,ThumbsDownIcon:L9,ThumbsUp:Vm,ThumbsUpIcon:Vm,Ticket:D9,TicketCheck:Oue,TicketCheckIcon:Oue,TicketIcon:D9,TicketMinus:Fue,TicketMinusIcon:Fue,TicketPercent:zue,TicketPercentIcon:zue,TicketPlus:Bue,TicketPlusIcon:Bue,TicketSlash:$ue,TicketSlashIcon:$ue,TicketX:Uue,TicketXIcon:Uue,Tickets:Vue,TicketsIcon:Vue,TicketsPlane:que,TicketsPlaneIcon:que,Timer:Wue,TimerIcon:Wue,TimerOff:Hue,TimerOffIcon:Hue,TimerReset:Gue,TimerResetIcon:Gue,ToggleLeft:Kue,ToggleLeftIcon:Kue,ToggleRight:Yue,ToggleRightIcon:Yue,Toilet:Zue,ToiletIcon:Zue,Tornado:Que,TornadoIcon:Que,Torus:Xue,TorusIcon:Xue,Touchpad:ehe,TouchpadIcon:ehe,TouchpadOff:Jue,TouchpadOffIcon:Jue,TowerControl:the,TowerControlIcon:the,ToyBrick:she,ToyBrickIcon:she,Tractor:nhe,TractorIcon:nhe,TrafficCone:rhe,TrafficConeIcon:rhe,Train:xE,TrainFront:ihe,TrainFrontIcon:ihe,TrainFrontTunnel:ahe,TrainFrontTunnelIcon:ahe,TrainIcon:xE,TrainTrack:ohe,TrainTrackIcon:ohe,TramFront:xE,TramFrontIcon:xE,Trash:lhe,Trash2:_n,Trash2Icon:_n,TrashIcon:lhe,TreeDeciduous:che,TreeDeciduousIcon:che,TreePalm:gE,TreePalmIcon:gE,TreePine:c4,TreePineIcon:c4,Trees:dhe,TreesIcon:dhe,Trello:uhe,TrelloIcon:uhe,TrendingDown:vb,TrendingDownIcon:vb,TrendingUp:mo,TrendingUpDown:hhe,TrendingUpDownIcon:hhe,TrendingUpIcon:mo,Triangle:phe,TriangleAlert:$l,TriangleAlertIcon:$l,TriangleIcon:phe,TriangleRight:mhe,TriangleRightIcon:mhe,Trophy:vo,TrophyIcon:vo,Truck:R9,TruckIcon:R9,Turtle:fhe,TurtleIcon:fhe,Tv:ghe,Tv2:yE,Tv2Icon:yE,TvIcon:ghe,TvMinimal:yE,TvMinimalIcon:yE,TvMinimalPlay:xhe,TvMinimalPlayIcon:xhe,Twitch:yhe,TwitchIcon:yhe,Twitter:vhe,TwitterIcon:vhe,Type:_he,TypeIcon:_he,TypeOutline:bhe,TypeOutlineIcon:bhe,Umbrella:jhe,UmbrellaIcon:jhe,UmbrellaOff:whe,UmbrellaOffIcon:whe,Underline:_L,UnderlineIcon:_L,Undo:d4,Undo2:Nhe,Undo2Icon:Nhe,UndoDot:khe,UndoDotIcon:khe,UndoIcon:d4,UnfoldHorizontal:She,UnfoldHorizontalIcon:She,UnfoldVertical:Che,UnfoldVerticalIcon:Che,Ungroup:The,UngroupIcon:The,University:vE,UniversityIcon:vE,Unlink:qA,Unlink2:Ehe,Unlink2Icon:Ehe,UnlinkIcon:qA,Unlock:Y5,UnlockIcon:Y5,UnlockKeyhole:K5,UnlockKeyholeIcon:K5,Unplug:Ahe,UnplugIcon:Ahe,Upload:Na,UploadCloud:S5,UploadCloudIcon:S5,UploadIcon:Na,Usb:Mhe,UsbIcon:Mhe,User:Xi,User2:kE,User2Icon:kE,UserCheck:bb,UserCheck2:bE,UserCheck2Icon:bE,UserCheckIcon:bb,UserCircle:w5,UserCircle2:_5,UserCircle2Icon:_5,UserCircleIcon:w5,UserCog:O9,UserCog2:_E,UserCog2Icon:_E,UserCogIcon:O9,UserIcon:Xi,UserMinus:F9,UserMinus2:wE,UserMinus2Icon:wE,UserMinusIcon:F9,UserPen:Ihe,UserPenIcon:Ihe,UserPlus:Fo,UserPlus2:jE,UserPlus2Icon:jE,UserPlusIcon:Fo,UserRound:kE,UserRoundCheck:bE,UserRoundCheckIcon:bE,UserRoundCog:_E,UserRoundCogIcon:_E,UserRoundIcon:kE,UserRoundMinus:wE,UserRoundMinusIcon:wE,UserRoundPen:Phe,UserRoundPenIcon:Phe,UserRoundPlus:jE,UserRoundPlusIcon:jE,UserRoundSearch:Lhe,UserRoundSearchIcon:Lhe,UserRoundX:NE,UserRoundXIcon:NE,UserSearch:Dhe,UserSearchIcon:Dhe,UserSquare:hE,UserSquare2:uE,UserSquare2Icon:uE,UserSquareIcon:hE,UserX:Rhe,UserX2:NE,UserX2Icon:NE,UserXIcon:Rhe,Users:Nn,Users2:G0,Users2Icon:G0,UsersIcon:Nn,UsersRound:G0,UsersRoundIcon:G0,Utensils:CE,UtensilsCrossed:SE,UtensilsCrossedIcon:SE,UtensilsIcon:CE,UtilityPole:Ohe,UtilityPoleIcon:Ohe,Variable:wL,VariableIcon:wL,Vault:Fhe,VaultIcon:Fhe,Vegan:zhe,VeganIcon:zhe,VenetianMask:Bhe,VenetianMaskIcon:Bhe,Verified:L3,VerifiedIcon:L3,Vibrate:Uhe,VibrateIcon:Uhe,VibrateOff:$he,VibrateOffIcon:$he,Video:br,VideoIcon:br,VideoOff:qhe,VideoOffIcon:qhe,Videotape:Vhe,VideotapeIcon:Vhe,View:Hhe,ViewIcon:Hhe,Voicemail:Ghe,VoicemailIcon:Ghe,Volleyball:Whe,VolleyballIcon:Whe,Volume:Zhe,Volume1:Khe,Volume1Icon:Khe,Volume2:z9,Volume2Icon:z9,VolumeIcon:Zhe,VolumeOff:Yhe,VolumeOffIcon:Yhe,VolumeX:B9,VolumeXIcon:B9,Vote:Qhe,VoteIcon:Qhe,Wallet:jL,Wallet2:TE,Wallet2Icon:TE,WalletCards:Xhe,WalletCardsIcon:Xhe,WalletIcon:jL,WalletMinimal:TE,WalletMinimalIcon:TE,Wallpaper:Jhe,WallpaperIcon:Jhe,Wand:eme,Wand2:Dm,Wand2Icon:Dm,WandIcon:eme,WandSparkles:Dm,WandSparklesIcon:Dm,Warehouse:tme,WarehouseIcon:tme,WashingMachine:sme,WashingMachineIcon:sme,Watch:nme,WatchIcon:nme,Waves:rme,WavesIcon:rme,Waypoints:ame,WaypointsIcon:ame,Webcam:ime,WebcamIcon:ime,Webhook:lme,WebhookIcon:lme,WebhookOff:ome,WebhookOffIcon:ome,Weight:cme,WeightIcon:cme,Wheat:ume,WheatIcon:ume,WheatOff:dme,WheatOffIcon:dme,WholeWord:hme,WholeWordIcon:hme,Wifi:gme,WifiHigh:mme,WifiHighIcon:mme,WifiIcon:gme,WifiLow:pme,WifiLowIcon:pme,WifiOff:fme,WifiOffIcon:fme,WifiZero:xme,WifiZeroIcon:xme,Wind:vme,WindArrowDown:yme,WindArrowDownIcon:yme,WindIcon:vme,Wine:$9,WineIcon:$9,WineOff:bme,WineOffIcon:bme,Workflow:U9,WorkflowIcon:U9,Worm:_me,WormIcon:_me,WrapText:wme,WrapTextIcon:wme,Wrench:_b,WrenchIcon:_b,X:Bn,XCircle:Hc,XCircleIcon:Hc,XIcon:Bn,XOctagon:J5,XOctagonIcon:J5,XSquare:mE,XSquareIcon:mE,Youtube:jme,YoutubeIcon:jme,Zap:hh,ZapIcon:hh,ZapOff:Nme,ZapOffIcon:Nme,ZoomIn:u4,ZoomInIcon:u4,ZoomOut:NL,ZoomOutIcon:NL,createLucideIcon:re,icons:HMt},Symbol.toStringTag,{value:"Module"})),uAe="-",GMt=s=>{const t=KMt(s),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=s;return{getClassGroupId:l=>{const o=l.split(uAe);return o[0]===""&&o.length!==1&&o.shift(),Srt(o,t)||WMt(l)},getConflictingClassGroupIds:(l,o)=>{const c=n[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},Srt=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const n=s[0],r=t.nextPart.get(n),a=r?Srt(s.slice(1),r):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(uAe);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Y9e=/^\[(.+)\]$/,WMt=s=>{if(Y9e.test(s)){const t=Y9e.exec(s)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},KMt=s=>{const{theme:t,prefix:n}=s,r={nextPart:new Map,validators:[]};return ZMt(Object.entries(s.classGroups),n).forEach(([i,l])=>{OSe(l,r,i,t)}),r},OSe=(s,t,n,r)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:Z9e(t,a);i.classGroupId=n;return}if(typeof a=="function"){if(YMt(a)){OSe(a(r),t,n,r);return}t.validators.push({validator:a,classGroupId:n});return}Object.entries(a).forEach(([i,l])=>{OSe(l,Z9e(t,i),n,r)})})},Z9e=(s,t)=>{let n=s;return t.split(uAe).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},YMt=s=>s.isThemeGetter,ZMt=(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,QMt=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)}}},Crt="!",XMt=s=>{const{separator:t,experimentalParseClassName:n}=s,r=t.length===1,a=t[0],i=t.length,l=o=>{const c=[];let d=0,u=0,h;for(let v=0;vu?h-u:void 0;return{modifiers:c,hasImportantModifier:f,baseClassName:g,maybePostfixModifierPosition:_}};return n?o=>n({className:o,parseClassName:l}):l},JMt=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},e6t=s=>({cache:QMt(s.cacheSize),parseClassName:XMt(s),...GMt(s)}),t6t=/\s+/,s6t=(s,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(t6t);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:u,hasImportantModifier:h,baseClassName:p,maybePostfixModifierPosition:f}=n(d);let g=!!f,_=r(g?p.substring(0,f):p);if(!_){if(!g){o=d+(o.length>0?" "+o:o);continue}if(_=r(p),!_){o=d+(o.length>0?" "+o:o);continue}g=!1}const v=JMt(u).join(":"),j=h?v+Crt:v,b=j+_;if(i.includes(b))continue;i.push(b);const S=a(_,g);for(let A=0;A0?" "+o:o)}return o};function n6t(){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=e6t(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=s6t(c,n);return a(c,u),u}return function(){return i(n6t.apply(null,arguments))}}const Md=s=>{const t=n=>n[s]||[];return t.isThemeGetter=!0,t},Ert=/^\[(?:([a-z-]+):)?(.+)\]$/i,a6t=/^\d+\/\d+$/,i6t=new Set(["px","full","screen"]),o6t=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,l6t=/\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$/,c6t=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,d6t=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,u6t=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,s2=s=>kL(s)||i6t.has(s)||a6t.test(s),_k=s=>AD(s,"length",v6t),kL=s=>!!s&&!Number.isNaN(Number(s)),Owe=s=>AD(s,"number",kL),XO=s=>!!s&&Number.isInteger(Number(s)),h6t=s=>s.endsWith("%")&&kL(s.slice(0,-1)),$o=s=>Ert.test(s),wk=s=>o6t.test(s),m6t=new Set(["length","size","percentage"]),p6t=s=>AD(s,m6t,Art),f6t=s=>AD(s,"position",Art),x6t=new Set(["image","url"]),g6t=s=>AD(s,x6t,_6t),y6t=s=>AD(s,"",b6t),JO=()=>!0,AD=(s,t,n)=>{const r=Ert.exec(s);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},v6t=s=>l6t.test(s)&&!c6t.test(s),Art=()=>!1,b6t=s=>d6t.test(s),_6t=s=>u6t.test(s),w6t=()=>{const s=Md("colors"),t=Md("spacing"),n=Md("blur"),r=Md("brightness"),a=Md("borderColor"),i=Md("borderRadius"),l=Md("borderSpacing"),o=Md("borderWidth"),c=Md("contrast"),d=Md("grayscale"),u=Md("hueRotate"),h=Md("invert"),p=Md("gap"),f=Md("gradientColorStops"),g=Md("gradientColorStopPositions"),_=Md("inset"),v=Md("margin"),j=Md("opacity"),b=Md("padding"),S=Md("saturate"),A=Md("scale"),T=Md("sepia"),L=Md("skew"),D=Md("space"),M=Md("translate"),F=()=>["auto","contain","none"],z=()=>["auto","hidden","clip","visible","scroll"],V=()=>["auto",$o,t],W=()=>[$o,t],Y=()=>["",s2,_k],K=()=>["auto",kL,$o],J=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],ne=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],he=()=>["start","end","center","between","around","evenly","stretch"],ce=()=>["","0",$o],pe=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[kL,$o];return{cacheSize:500,separator:":",theme:{colors:[JO],spacing:[s2,_k],blur:["none","",wk,$o],brightness:le(),borderColor:[s],borderRadius:["none","","full",wk,$o],borderSpacing:W(),borderWidth:Y(),contrast:le(),grayscale:ce(),hueRotate:le(),invert:ce(),gap:W(),gradientColorStops:[s],gradientColorStopPositions:[h6t,_k],inset:V(),margin:V(),opacity:le(),padding:W(),saturate:le(),scale:le(),sepia:ce(),skew:le(),space:W(),translate:W()},classGroups:{aspect:[{aspect:["auto","square","video",$o]}],container:["container"],columns:[{columns:[wk]}],"break-after":[{"break-after":pe()}],"break-before":[{"break-before":pe()}],"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:[...J(),$o]}],overflow:[{overflow:z()}],"overflow-x":[{"overflow-x":z()}],"overflow-y":[{"overflow-y":z()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[_]}],"inset-x":[{"inset-x":[_]}],"inset-y":[{"inset-y":[_]}],start:[{start:[_]}],end:[{end:[_]}],top:[{top:[_]}],right:[{right:[_]}],bottom:[{bottom:[_]}],left:[{left:[_]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",XO,$o]}],basis:[{basis:V()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",$o]}],grow:[{grow:ce()}],shrink:[{shrink:ce()}],order:[{order:["first","last","none",XO,$o]}],"grid-cols":[{"grid-cols":[JO]}],"col-start-end":[{col:["auto",{span:["full",XO,$o]},$o]}],"col-start":[{"col-start":K()}],"col-end":[{"col-end":K()}],"grid-rows":[{"grid-rows":[JO]}],"row-start-end":[{row:["auto",{span:[XO,$o]},$o]}],"row-start":[{"row-start":K()}],"row-end":[{"row-end":K()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",$o]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",$o]}],gap:[{gap:[p]}],"gap-x":[{"gap-x":[p]}],"gap-y":[{"gap-y":[p]}],"justify-content":[{justify:["normal",...he()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...he(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...he(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[v]}],mx:[{mx:[v]}],my:[{my:[v]}],ms:[{ms:[v]}],me:[{me:[v]}],mt:[{mt:[v]}],mr:[{mr:[v]}],mb:[{mb:[v]}],ml:[{ml:[v]}],"space-x":[{"space-x":[D]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[D]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",$o,t]}],"min-w":[{"min-w":[$o,t,"min","max","fit"]}],"max-w":[{"max-w":[$o,t,"none","full","min","max","fit","prose",{screen:[wk]},wk]}],h:[{h:[$o,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[$o,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[$o,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[$o,t,"auto","min","max","fit"]}],"font-size":[{text:["base",wk,_k]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Owe]}],"font-family":[{font:[JO]}],"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",$o]}],"line-clamp":[{"line-clamp":["none",kL,Owe]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",s2,$o]}],"list-image":[{"list-image":["none",$o]}],"list-style-type":[{list:["none","disc","decimal",$o]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[j]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ne(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",s2,_k]}],"underline-offset":[{"underline-offset":["auto",s2,$o]}],"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:W()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$o]}],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",$o]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[j]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...J(),f6t]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",p6t]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},g6t]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[f]}],"gradient-via":[{via:[f]}],"gradient-to":[{to:[f]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[j]}],"border-style":[{border:[...ne(),"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":[j]}],"divide-style":[{divide:ne()}],"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:["",...ne()]}],"outline-offset":[{"outline-offset":[s2,$o]}],"outline-w":[{outline:[s2,_k]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:Y()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[j]}],"ring-offset-w":[{"ring-offset":[s2,_k]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",wk,y6t]}],"shadow-color":[{shadow:[JO]}],opacity:[{opacity:[j]}],"mix-blend":[{"mix-blend":[...ie(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",wk,$o]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[h]}],saturate:[{saturate:[S]}],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":[j]}],"backdrop-saturate":[{"backdrop-saturate":[S]}],"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",$o]}],duration:[{duration:le()}],ease:[{ease:["linear","in","out","in-out",$o]}],delay:[{delay:le()}],animate:[{animate:["none","spin","ping","pulse","bounce",$o]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[A]}],"scale-x":[{"scale-x":[A]}],"scale-y":[{"scale-y":[A]}],rotate:[{rotate:[XO,$o]}],"translate-x":[{"translate-x":[M]}],"translate-y":[{"translate-y":[M]}],"skew-x":[{"skew-x":[L]}],"skew-y":[{"skew-y":[L]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",$o]}],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",$o]}],"caret-color":[{caret:[s]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":W()}],"scroll-mx":[{"scroll-mx":W()}],"scroll-my":[{"scroll-my":W()}],"scroll-ms":[{"scroll-ms":W()}],"scroll-me":[{"scroll-me":W()}],"scroll-mt":[{"scroll-mt":W()}],"scroll-mr":[{"scroll-mr":W()}],"scroll-mb":[{"scroll-mb":W()}],"scroll-ml":[{"scroll-ml":W()}],"scroll-p":[{"scroll-p":W()}],"scroll-px":[{"scroll-px":W()}],"scroll-py":[{"scroll-py":W()}],"scroll-ps":[{"scroll-ps":W()}],"scroll-pe":[{"scroll-pe":W()}],"scroll-pt":[{"scroll-pt":W()}],"scroll-pr":[{"scroll-pr":W()}],"scroll-pb":[{"scroll-pb":W()}],"scroll-pl":[{"scroll-pl":W()}],"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",$o]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[s2,_k,Owe]}],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"]}}},j6t=r6t(w6t);function Et(...s){return j6t(So(s))}function yc(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 Q9e(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function Xz(s){return s?s.replace(/<[^>]*>/g,""):""}const N6t=UMt,Mrt=N.forwardRef(({className:s,...t},n)=>e.jsx(grt,{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}));Mrt.displayName=grt.displayName;const k6t=UM("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"}}),Irt=N.forwardRef(({className:s,variant:t,...n},r)=>e.jsx(yrt,{ref:r,className:Et(k6t({variant:t}),s),...n}));Irt.displayName=yrt.displayName;const S6t=N.forwardRef(({className:s,...t},n)=>e.jsx(_rt,{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}));S6t.displayName=_rt.displayName;const Prt=N.forwardRef(({className:s,...t},n)=>e.jsx(wrt,{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(Bn,{className:"h-4 w-4"})}));Prt.displayName=wrt.displayName;const Lrt=N.forwardRef(({className:s,...t},n)=>e.jsx(vrt,{ref:n,className:Et("text-sm font-semibold",s),...t}));Lrt.displayName=vrt.displayName;const Drt=N.forwardRef(({className:s,...t},n)=>e.jsx(brt,{ref:n,className:Et("text-sm opacity-90",s),...t}));Drt.displayName=brt.displayName;function C6t(){const{toasts:s}=Ba();return e.jsxs(N6t,{children:[s.map(function({id:t,title:n,description:r,action:a,...i}){return e.jsxs(Irt,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[n&&e.jsx(Lrt,{children:n}),r&&e.jsx(Drt,{children:r})]}),a,e.jsx(Prt,{})]},t)}),e.jsx(Mrt,{})]})}var X9e=["light","dark"],T6t="(prefers-color-scheme: dark)",E6t=N.createContext(void 0),A6t={setTheme:s=>{},themes:[]},M6t=()=>{var s;return(s=N.useContext(E6t))!=null?s:A6t};N.memo(({forcedTheme:s,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:a,defaultTheme:i,value:l,attrs:o,nonce:c})=>{let d=i==="system",u=n==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${o.map(g=>`'${g}'`).join(",")})`};`:`var d=document.documentElement,n='${n}',s='setAttribute';`,h=a?X9e.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",p=(g,_=!1,v=!0)=>{let j=l?l[g]:g,b=_?g+"|| ''":`'${j}'`,S="";return a&&v&&!_&&X9e.includes(g)&&(S+=`d.style.colorScheme = '${g}';`),n==="class"?_||j?S+=`c.add(${b})`:S+="null":j&&(S+=`d[s](n,${b})`),S},f=s?`!function(){${u}${p(s)}}()`:r?`!function(){try{${u}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${T6t}',m=window.matchMedia(t);if(m.media!==t||m.matches){${p("dark")}}else{${p("light")}}}else if(e){${l?`var x=${JSON.stringify(l)};`:""}${p(l?"x[e]":"e",!0)}}${d?"":"else{"+p(i,!1,!1)+"}"}${h}}catch(e){}}()`:`!function(){try{${u}var e=localStorage.getItem('${t}');if(e){${l?`var x=${JSON.stringify(l)};`:""}${p(l?"x[e]":"e",!0)}}else{${p(i,!1,!1)};}${h}}catch(t){}}();`;return N.createElement("script",{nonce:c,dangerouslySetInnerHTML:{__html:f}})});var I6t=s=>{switch(s){case"success":return D6t;case"info":return O6t;case"warning":return R6t;case"error":return F6t;default:return null}},P6t=Array(12).fill(0),L6t=({visible:s,className:t})=>St.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},St.createElement("div",{className:"sonner-spinner"},P6t.map((n,r)=>St.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),D6t=St.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},St.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"})),R6t=St.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},St.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"})),O6t=St.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},St.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"})),F6t=St.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},St.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"})),z6t=St.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"},St.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),St.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),B6t=()=>{let[s,t]=St.useState(document.hidden);return St.useEffect(()=>{let n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),s},FSe=1,$6t=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:FSe++,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],St.isValidElement(d))i=!1,this.create({id:r,type:"default",message:d});else if(q6t(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)||FSe++;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}},Ag=new $6t,U6t=(s,t)=>{let n=(t==null?void 0:t.id)||FSe++;return Ag.addToast({title:s,...t,id:n}),n},q6t=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",V6t=U6t,H6t=()=>Ag.toasts,G6t=()=>Ag.getActiveToasts(),ae=Object.assign(V6t,{success:Ag.success,info:Ag.info,warning:Ag.warning,error:Ag.error,custom:Ag.custom,message:Ag.message,promise:Ag.promise,dismiss:Ag.dismiss,loading:Ag.loading},{getHistory:H6t,getToasts:G6t});function W6t(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))}W6t(`: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 $V(s){return s.label!==void 0}var K6t=3,Y6t="32px",Z6t="16px",J9e=4e3,Q6t=356,X6t=14,J6t=20,eIt=200;function O1(...s){return s.filter(Boolean).join(" ")}function tIt(s){let[t,n]=s.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}var sIt=s=>{var t,n,r,a,i,l,o,c,d,u,h;let{invert:p,toast:f,unstyled:g,interacting:_,setHeights:v,visibleToasts:j,heights:b,index:S,toasts:A,expanded:T,removeToast:L,defaultRichColors:D,closeButton:M,style:F,cancelButtonStyle:z,actionButtonStyle:V,className:W="",descriptionClassName:Y="",duration:K,position:J,gap:ne,loadingIcon:ie,expandByDefault:he,classNames:ce,icons:pe,closeButtonAriaLabel:le="Close toast",pauseWhenPageIsHidden:ve}=s,[ge,Te]=St.useState(null),[Me,Ce]=St.useState(null),[Ae,De]=St.useState(!1),[Ie,Fe]=St.useState(!1),[qe,be]=St.useState(!1),[Ze,Ne]=St.useState(!1),[it,je]=St.useState(!1),[Ge,Be]=St.useState(0),[Ye,We]=St.useState(0),rt=St.useRef(f.duration||K||J9e),tt=St.useRef(null),at=St.useRef(null),He=S===0,dt=S+1<=j,bt=f.type,vt=f.dismissible!==!1,Bt=f.className||"",Zt=f.descriptionClassName||"",Fs=St.useMemo(()=>b.findIndex(gn=>gn.toastId===f.id)||0,[b,f.id]),Rs=St.useMemo(()=>{var gn;return(gn=f.closeButton)!=null?gn:M},[f.closeButton,M]),ms=St.useMemo(()=>f.duration||K||J9e,[f.duration,K]),Pt=St.useRef(0),Jt=St.useRef(0),ft=St.useRef(0),Vt=St.useRef(null),[Ms,Xt]=J.split("-"),Js=St.useMemo(()=>b.reduce((gn,In,Zn)=>Zn>=Fs?gn:gn+In.height,0),[b,Fs]),Cs=B6t(),As=f.invert||p,rn=bt==="loading";Jt.current=St.useMemo(()=>Fs*ne+Js,[Fs,Js]),St.useEffect(()=>{rt.current=ms},[ms]),St.useEffect(()=>{De(!0)},[]),St.useEffect(()=>{let gn=at.current;if(gn){let In=gn.getBoundingClientRect().height;return We(In),v(Zn=>[{toastId:f.id,height:In,position:f.position},...Zn]),()=>v(Zn=>Zn.filter(ea=>ea.toastId!==f.id))}},[v,f.id]),St.useLayoutEffect(()=>{if(!Ae)return;let gn=at.current,In=gn.style.height;gn.style.height="auto";let Zn=gn.getBoundingClientRect().height;gn.style.height=In,We(Zn),v(ea=>ea.find(vi=>vi.toastId===f.id)?ea.map(vi=>vi.toastId===f.id?{...vi,height:Zn}:vi):[{toastId:f.id,height:Zn,position:f.position},...ea])},[Ae,f.title,f.description,v,f.id]);let tn=St.useCallback(()=>{Fe(!0),Be(Jt.current),v(gn=>gn.filter(In=>In.toastId!==f.id)),setTimeout(()=>{L(f)},eIt)},[f,L,v,Jt]);St.useEffect(()=>{if(f.promise&&bt==="loading"||f.duration===1/0||f.type==="loading")return;let gn;return T||_||ve&&Cs?(()=>{if(ft.current{var In;(In=f.onAutoClose)==null||In.call(f,f),tn()},rt.current)),()=>clearTimeout(gn)},[T,_,f,bt,ve,Cs,tn]),St.useEffect(()=>{f.delete&&tn()},[tn,f.delete]);function er(){var gn,In,Zn;return pe!=null&&pe.loading?St.createElement("div",{className:O1(ce==null?void 0:ce.loader,(gn=f==null?void 0:f.classNames)==null?void 0:gn.loader,"sonner-loader"),"data-visible":bt==="loading"},pe.loading):ie?St.createElement("div",{className:O1(ce==null?void 0:ce.loader,(In=f==null?void 0:f.classNames)==null?void 0:In.loader,"sonner-loader"),"data-visible":bt==="loading"},ie):St.createElement(L6t,{className:O1(ce==null?void 0:ce.loader,(Zn=f==null?void 0:f.classNames)==null?void 0:Zn.loader),visible:bt==="loading"})}return St.createElement("li",{tabIndex:0,ref:at,className:O1(W,Bt,ce==null?void 0:ce.toast,(t=f==null?void 0:f.classNames)==null?void 0:t.toast,ce==null?void 0:ce.default,ce==null?void 0:ce[bt],(n=f==null?void 0:f.classNames)==null?void 0:n[bt]),"data-sonner-toast":"","data-rich-colors":(r=f.richColors)!=null?r:D,"data-styled":!(f.jsx||f.unstyled||g),"data-mounted":Ae,"data-promise":!!f.promise,"data-swiped":it,"data-removed":Ie,"data-visible":dt,"data-y-position":Ms,"data-x-position":Xt,"data-index":S,"data-front":He,"data-swiping":qe,"data-dismissible":vt,"data-type":bt,"data-invert":As,"data-swipe-out":Ze,"data-swipe-direction":Me,"data-expanded":!!(T||he&&Ae),style:{"--index":S,"--toasts-before":S,"--z-index":A.length-S,"--offset":`${Ie?Ge:Jt.current}px`,"--initial-height":he?"auto":`${Ye}px`,...F,...f.style},onDragEnd:()=>{be(!1),Te(null),Vt.current=null},onPointerDown:gn=>{rn||!vt||(tt.current=new Date,Be(Jt.current),gn.target.setPointerCapture(gn.pointerId),gn.target.tagName!=="BUTTON"&&(be(!0),Vt.current={x:gn.clientX,y:gn.clientY}))},onPointerUp:()=>{var gn,In,Zn,ea;if(Ze||!vt)return;Vt.current=null;let vi=Number(((gn=at.current)==null?void 0:gn.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Ls=Number(((In=at.current)==null?void 0:In.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),fi=new Date().getTime()-((Zn=tt.current)==null?void 0:Zn.getTime()),Lr=ge==="x"?vi:Ls,Jn=Math.abs(Lr)/fi;if(Math.abs(Lr)>=J6t||Jn>.11){Be(Jt.current),(ea=f.onDismiss)==null||ea.call(f,f),Ce(ge==="x"?vi>0?"right":"left":Ls>0?"down":"up"),tn(),Ne(!0),je(!1);return}be(!1),Te(null)},onPointerMove:gn=>{var In,Zn,ea,vi;if(!Vt.current||!vt||((In=window.getSelection())==null?void 0:In.toString().length)>0)return;let Ls=gn.clientY-Vt.current.y,fi=gn.clientX-Vt.current.x,Lr=(Zn=s.swipeDirections)!=null?Zn:tIt(J);!ge&&(Math.abs(fi)>1||Math.abs(Ls)>1)&&Te(Math.abs(fi)>Math.abs(Ls)?"x":"y");let Jn={x:0,y:0};ge==="y"?(Lr.includes("top")||Lr.includes("bottom"))&&(Lr.includes("top")&&Ls<0||Lr.includes("bottom")&&Ls>0)&&(Jn.y=Ls):ge==="x"&&(Lr.includes("left")||Lr.includes("right"))&&(Lr.includes("left")&&fi<0||Lr.includes("right")&&fi>0)&&(Jn.x=fi),(Math.abs(Jn.x)>0||Math.abs(Jn.y)>0)&&je(!0),(ea=at.current)==null||ea.style.setProperty("--swipe-amount-x",`${Jn.x}px`),(vi=at.current)==null||vi.style.setProperty("--swipe-amount-y",`${Jn.y}px`)}},Rs&&!f.jsx?St.createElement("button",{"aria-label":le,"data-disabled":rn,"data-close-button":!0,onClick:rn||!vt?()=>{}:()=>{var gn;tn(),(gn=f.onDismiss)==null||gn.call(f,f)},className:O1(ce==null?void 0:ce.closeButton,(a=f==null?void 0:f.classNames)==null?void 0:a.closeButton)},(i=pe==null?void 0:pe.close)!=null?i:z6t):null,f.jsx||N.isValidElement(f.title)?f.jsx?f.jsx:typeof f.title=="function"?f.title():f.title:St.createElement(St.Fragment,null,bt||f.icon||f.promise?St.createElement("div",{"data-icon":"",className:O1(ce==null?void 0:ce.icon,(l=f==null?void 0:f.classNames)==null?void 0:l.icon)},f.promise||f.type==="loading"&&!f.icon?f.icon||er():null,f.type!=="loading"?f.icon||(pe==null?void 0:pe[bt])||I6t(bt):null):null,St.createElement("div",{"data-content":"",className:O1(ce==null?void 0:ce.content,(o=f==null?void 0:f.classNames)==null?void 0:o.content)},St.createElement("div",{"data-title":"",className:O1(ce==null?void 0:ce.title,(c=f==null?void 0:f.classNames)==null?void 0:c.title)},typeof f.title=="function"?f.title():f.title),f.description?St.createElement("div",{"data-description":"",className:O1(Y,Zt,ce==null?void 0:ce.description,(d=f==null?void 0:f.classNames)==null?void 0:d.description)},typeof f.description=="function"?f.description():f.description):null),N.isValidElement(f.cancel)?f.cancel:f.cancel&&$V(f.cancel)?St.createElement("button",{"data-button":!0,"data-cancel":!0,style:f.cancelButtonStyle||z,onClick:gn=>{var In,Zn;$V(f.cancel)&&vt&&((Zn=(In=f.cancel).onClick)==null||Zn.call(In,gn),tn())},className:O1(ce==null?void 0:ce.cancelButton,(u=f==null?void 0:f.classNames)==null?void 0:u.cancelButton)},f.cancel.label):null,N.isValidElement(f.action)?f.action:f.action&&$V(f.action)?St.createElement("button",{"data-button":!0,"data-action":!0,style:f.actionButtonStyle||V,onClick:gn=>{var In,Zn;$V(f.action)&&((Zn=(In=f.action).onClick)==null||Zn.call(In,gn),!gn.defaultPrevented&&tn())},className:O1(ce==null?void 0:ce.actionButton,(h=f==null?void 0:f.classNames)==null?void 0:h.actionButton)},f.action.label):null))};function eze(){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 nIt(s,t){let n={};return[s,t].forEach((r,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?Z6t:Y6t;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 rIt=N.forwardRef(function(s,t){let{invert:n,position:r="bottom-right",hotkey:a=["altKey","KeyT"],expand:i,closeButton:l,className:o,offset:c,mobileOffset:d,theme:u="light",richColors:h,duration:p,style:f,visibleToasts:g=K6t,toastOptions:_,dir:v=eze(),gap:j=X6t,loadingIcon:b,icons:S,containerAriaLabel:A="Notifications",pauseWhenPageIsHidden:T}=s,[L,D]=St.useState([]),M=St.useMemo(()=>Array.from(new Set([r].concat(L.filter(ve=>ve.position).map(ve=>ve.position)))),[L,r]),[F,z]=St.useState([]),[V,W]=St.useState(!1),[Y,K]=St.useState(!1),[J,ne]=St.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),ie=St.useRef(null),he=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),ce=St.useRef(null),pe=St.useRef(!1),le=St.useCallback(ve=>{D(ge=>{var Te;return(Te=ge.find(Me=>Me.id===ve.id))!=null&&Te.delete||Ag.dismiss(ve.id),ge.filter(({id:Me})=>Me!==ve.id)})},[]);return St.useEffect(()=>Ag.subscribe(ve=>{if(ve.dismiss){D(ge=>ge.map(Te=>Te.id===ve.id?{...Te,delete:!0}:Te));return}setTimeout(()=>{aAe.flushSync(()=>{D(ge=>{let Te=ge.findIndex(Me=>Me.id===ve.id);return Te!==-1?[...ge.slice(0,Te),{...ge[Te],...ve},...ge.slice(Te+1)]:[ve,...ge]})})})}),[]),St.useEffect(()=>{if(u!=="system"){ne(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?ne("dark"):ne("light")),typeof window>"u")return;let ve=window.matchMedia("(prefers-color-scheme: dark)");try{ve.addEventListener("change",({matches:ge})=>{ne(ge?"dark":"light")})}catch{ve.addListener(({matches:Te})=>{try{ne(Te?"dark":"light")}catch(Me){console.error(Me)}})}},[u]),St.useEffect(()=>{L.length<=1&&W(!1)},[L]),St.useEffect(()=>{let ve=ge=>{var Te,Me;a.every(Ce=>ge[Ce]||ge.code===Ce)&&(W(!0),(Te=ie.current)==null||Te.focus()),ge.code==="Escape"&&(document.activeElement===ie.current||(Me=ie.current)!=null&&Me.contains(document.activeElement))&&W(!1)};return document.addEventListener("keydown",ve),()=>document.removeEventListener("keydown",ve)},[a]),St.useEffect(()=>{if(ie.current)return()=>{ce.current&&(ce.current.focus({preventScroll:!0}),ce.current=null,pe.current=!1)}},[ie.current]),St.createElement("section",{ref:t,"aria-label":`${A} ${he}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},M.map((ve,ge)=>{var Te;let[Me,Ce]=ve.split("-");return L.length?St.createElement("ol",{key:ve,dir:v==="auto"?eze():v,tabIndex:-1,ref:ie,className:o,"data-sonner-toaster":!0,"data-theme":J,"data-y-position":Me,"data-lifted":V&&L.length>1&&!i,"data-x-position":Ce,style:{"--front-toast-height":`${((Te=F[0])==null?void 0:Te.height)||0}px`,"--width":`${Q6t}px`,"--gap":`${j}px`,...f,...nIt(c,d)},onBlur:Ae=>{pe.current&&!Ae.currentTarget.contains(Ae.relatedTarget)&&(pe.current=!1,ce.current&&(ce.current.focus({preventScroll:!0}),ce.current=null))},onFocus:Ae=>{Ae.target instanceof HTMLElement&&Ae.target.dataset.dismissible==="false"||pe.current||(pe.current=!0,ce.current=Ae.relatedTarget)},onMouseEnter:()=>W(!0),onMouseMove:()=>W(!0),onMouseLeave:()=>{Y||W(!1)},onDragEnd:()=>W(!1),onPointerDown:Ae=>{Ae.target instanceof HTMLElement&&Ae.target.dataset.dismissible==="false"||K(!0)},onPointerUp:()=>K(!1)},L.filter(Ae=>!Ae.position&&ge===0||Ae.position===ve).map((Ae,De)=>{var Ie,Fe;return St.createElement(sIt,{key:Ae.id,icons:S,index:De,toast:Ae,defaultRichColors:h,duration:(Ie=_==null?void 0:_.duration)!=null?Ie:p,className:_==null?void 0:_.className,descriptionClassName:_==null?void 0:_.descriptionClassName,invert:n,visibleToasts:g,closeButton:(Fe=_==null?void 0:_.closeButton)!=null?Fe:l,interacting:Y,position:ve,style:_==null?void 0:_.style,unstyled:_==null?void 0:_.unstyled,classNames:_==null?void 0:_.classNames,cancelButtonStyle:_==null?void 0:_.cancelButtonStyle,actionButtonStyle:_==null?void 0:_.actionButtonStyle,removeToast:le,toasts:L.filter(qe=>qe.position==Ae.position),heights:F.filter(qe=>qe.position==Ae.position),setHeights:z,expandByDefault:i,gap:j,loadingIcon:b,expanded:V,pauseWhenPageIsHidden:T,swipeDirections:s.swipeDirections})})):null}))});const aIt=({...s})=>{const{theme:t="system"}=M6t();return e.jsx(rIt,{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 iIt=pEe[" useId ".trim().toString()]||(()=>{}),oIt=0;function dm(s){const[t,n]=N.useState(iIt());return mh(()=>{s||n(r=>r??String(oIt++))},[s]),s||(t?`radix-${t}`:"")}const lIt=["top","right","bottom","left"],C4=Math.min,W0=Math.max,Vpe=Math.round,UV=Math.floor,T4=s=>({x:s,y:s}),cIt={left:"right",right:"left",bottom:"top",top:"bottom"},dIt={start:"end",end:"start"};function zSe(s,t,n){return W0(s,C4(t,n))}function hN(s,t){return typeof s=="function"?s(t):s}function mN(s){return s.split("-")[0]}function MD(s){return s.split("-")[1]}function hAe(s){return s==="x"?"y":"x"}function mAe(s){return s==="y"?"height":"width"}function E4(s){return["top","bottom"].includes(mN(s))?"y":"x"}function pAe(s){return hAe(E4(s))}function uIt(s,t,n){n===void 0&&(n=!1);const r=MD(s),a=pAe(s),i=mAe(a);let l=a==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=Hpe(l)),[l,Hpe(l)]}function hIt(s){const t=Hpe(s);return[BSe(s),t,BSe(t)]}function BSe(s){return s.replace(/start|end/g,t=>dIt[t])}function mIt(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 pIt(s,t,n,r){const a=MD(s);let i=mIt(mN(s),n==="start",r);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map(BSe)))),i}function Hpe(s){return s.replace(/left|right|bottom|top/g,t=>cIt[t])}function fIt(s){return{top:0,right:0,bottom:0,left:0,...s}}function Rrt(s){return typeof s!="number"?fIt(s):{top:s,right:s,bottom:s,left:s}}function Gpe(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 tze(s,t,n){let{reference:r,floating:a}=s;const i=E4(t),l=pAe(t),o=mAe(l),c=mN(t),d=i==="y",u=r.x+r.width/2-a.width/2,h=r.y+r.height/2-a.height/2,p=r[o]/2-a[o]/2;let f;switch(c){case"top":f={x:u,y:r.y-a.height};break;case"bottom":f={x:u,y:r.y+r.height};break;case"right":f={x:r.x+r.width,y:h};break;case"left":f={x:r.x-a.width,y:h};break;default:f={x:r.x,y:r.y}}switch(MD(t)){case"start":f[l]-=p*(n&&d?-1:1);break;case"end":f[l]+=p*(n&&d?-1:1);break}return f}const xIt=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}=tze(d,r,c),p=r,f={},g=0;for(let _=0;_({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}=hN(s,t)||{};if(d==null)return{};const h=Rrt(u),p={x:n,y:r},f=pAe(a),g=mAe(f),_=await l.getDimensions(d),v=f==="y",j=v?"top":"left",b=v?"bottom":"right",S=v?"clientHeight":"clientWidth",A=i.reference[g]+i.reference[f]-p[f]-i.floating[g],T=p[f]-i.reference[f],L=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let D=L?L[S]:0;(!D||!await(l.isElement==null?void 0:l.isElement(L)))&&(D=o.floating[S]||i.floating[g]);const M=A/2-T/2,F=D/2-_[g]/2-1,z=C4(h[j],F),V=C4(h[b],F),W=z,Y=D-_[g]-V,K=D/2-_[g]/2+M,J=zSe(W,K,Y),ne=!c.arrow&&MD(a)!=null&&K!==J&&i.reference[g]/2-(KK<=0)){var V,W;const K=(((V=i.flip)==null?void 0:V.index)||0)+1,J=D[K];if(J)return{data:{index:K,overflows:z},reset:{placement:J}};let ne=(W=z.filter(ie=>ie.overflows[0]<=0).sort((ie,he)=>ie.overflows[1]-he.overflows[1])[0])==null?void 0:W.placement;if(!ne)switch(f){case"bestFit":{var Y;const ie=(Y=z.filter(he=>{if(L){const ce=E4(he.placement);return ce===b||ce==="y"}return!0}).map(he=>[he.placement,he.overflows.filter(ce=>ce>0).reduce((ce,pe)=>ce+pe,0)]).sort((he,ce)=>he[1]-ce[1])[0])==null?void 0:Y[0];ie&&(ne=ie);break}case"initialPlacement":ne=o;break}if(a!==ne)return{reset:{placement:ne}}}return{}}}};function sze(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function nze(s){return lIt.some(t=>s[t]>=0)}const vIt=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...a}=hN(s,t);switch(r){case"referenceHidden":{const i=await Jz(t,{...a,elementContext:"reference"}),l=sze(i,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:nze(l)}}}case"escaped":{const i=await Jz(t,{...a,altBoundary:!0}),l=sze(i,n.floating);return{data:{escapedOffsets:l,escaped:nze(l)}}}default:return{}}}}};async function bIt(s,t){const{placement:n,platform:r,elements:a}=s,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),l=mN(n),o=MD(n),c=E4(n)==="y",d=["left","top"].includes(l)?-1:1,u=i&&c?-1:1,h=hN(t,s);let{mainAxis:p,crossAxis:f,alignmentAxis:g}=typeof h=="number"?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return o&&typeof g=="number"&&(f=o==="end"?g*-1:g),c?{x:f*u,y:p*d}:{x:p*d,y:f*u}}const _It=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 bIt(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}}}}},wIt=function(s){return s===void 0&&(s={}),{name:"shift",options:s,async fn(t){const{x:n,y:r,placement:a}=t,{mainAxis:i=!0,crossAxis:l=!1,limiter:o={fn:v=>{let{x:j,y:b}=v;return{x:j,y:b}}},...c}=hN(s,t),d={x:n,y:r},u=await Jz(t,c),h=E4(mN(a)),p=hAe(h);let f=d[p],g=d[h];if(i){const v=p==="y"?"top":"left",j=p==="y"?"bottom":"right",b=f+u[v],S=f-u[j];f=zSe(b,f,S)}if(l){const v=h==="y"?"top":"left",j=h==="y"?"bottom":"right",b=g+u[v],S=g-u[j];g=zSe(b,g,S)}const _=o.fn({...t,[p]:f,[h]:g});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[p]:i,[h]:l}}}}}},jIt=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}=hN(s,t),u={x:n,y:r},h=E4(a),p=hAe(h);let f=u[p],g=u[h];const _=hN(o,t),v=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(c){const S=p==="y"?"height":"width",A=i.reference[p]-i.floating[S]+v.mainAxis,T=i.reference[p]+i.reference[S]-v.mainAxis;fT&&(f=T)}if(d){var j,b;const S=p==="y"?"width":"height",A=["top","left"].includes(mN(a)),T=i.reference[h]-i.floating[S]+(A&&((j=l.offset)==null?void 0:j[h])||0)+(A?0:v.crossAxis),L=i.reference[h]+i.reference[S]+(A?0:((b=l.offset)==null?void 0:b[h])||0)-(A?v.crossAxis:0);gL&&(g=L)}return{[p]:f,[h]:g}}}},NIt=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}=hN(s,t),u=await Jz(t,d),h=mN(a),p=MD(a),f=E4(a)==="y",{width:g,height:_}=i.floating;let v,j;h==="top"||h==="bottom"?(v=h,j=p===(await(l.isRTL==null?void 0:l.isRTL(o.floating))?"start":"end")?"left":"right"):(j=h,v=p==="end"?"top":"bottom");const b=_-u.top-u.bottom,S=g-u.left-u.right,A=C4(_-u[v],b),T=C4(g-u[j],S),L=!t.middlewareData.shift;let D=A,M=T;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(M=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(D=b),L&&!p){const z=W0(u.left,0),V=W0(u.right,0),W=W0(u.top,0),Y=W0(u.bottom,0);f?M=g-2*(z!==0||V!==0?z+V:W0(u.left,u.right)):D=_-2*(W!==0||Y!==0?W+Y:W0(u.top,u.bottom))}await c({...t,availableWidth:M,availableHeight:D});const F=await l.getDimensions(o.floating);return g!==F.width||_!==F.height?{reset:{rects:!0}}:{}}}};function E0e(){return typeof window<"u"}function ID(s){return Ort(s)?(s.nodeName||"").toLowerCase():"#document"}function cy(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function Hw(s){var t;return(t=(Ort(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function Ort(s){return E0e()?s instanceof Node||s instanceof cy(s).Node:!1}function Cb(s){return E0e()?s instanceof Element||s instanceof cy(s).Element:!1}function Aw(s){return E0e()?s instanceof HTMLElement||s instanceof cy(s).HTMLElement:!1}function rze(s){return!E0e()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof cy(s).ShadowRoot}function z$(s){const{overflow:t,overflowX:n,overflowY:r,display:a}=Tb(s);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(a)}function kIt(s){return["table","td","th"].includes(ID(s))}function A0e(s){return[":popover-open",":modal"].some(t=>{try{return s.matches(t)}catch{return!1}})}function fAe(s){const t=xAe(),n=Cb(s)?Tb(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 SIt(s){let t=A4(s);for(;Aw(t)&&!f8(t);){if(fAe(t))return t;if(A0e(t))return null;t=A4(t)}return null}function xAe(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function f8(s){return["html","body","#document"].includes(ID(s))}function Tb(s){return cy(s).getComputedStyle(s)}function M0e(s){return Cb(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function A4(s){if(ID(s)==="html")return s;const t=s.assignedSlot||s.parentNode||rze(s)&&s.host||Hw(s);return rze(t)?t.host:t}function Frt(s){const t=A4(s);return f8(t)?s.ownerDocument?s.ownerDocument.body:s.body:Aw(t)&&z$(t)?t:Frt(t)}function eB(s,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const a=Frt(s),i=a===((r=s.ownerDocument)==null?void 0:r.body),l=cy(a);if(i){const o=$Se(l);return t.concat(l,l.visualViewport||[],z$(a)?a:[],o&&n?eB(o):[])}return t.concat(a,eB(a,[],n))}function $Se(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function zrt(s){const t=Tb(s);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=Aw(s),i=a?s.offsetWidth:n,l=a?s.offsetHeight:r,o=Vpe(n)!==i||Vpe(r)!==l;return o&&(n=i,r=l),{width:n,height:r,$:o}}function gAe(s){return Cb(s)?s:s.contextElement}function SL(s){const t=gAe(s);if(!Aw(t))return T4(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=zrt(t);let l=(i?Vpe(n.width):n.width)/r,o=(i?Vpe(n.height):n.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const CIt=T4(0);function Brt(s){const t=cy(s);return!xAe()||!t.visualViewport?CIt:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function TIt(s,t,n){return t===void 0&&(t=!1),!n||t&&n!==cy(s)?!1:t}function hM(s,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=s.getBoundingClientRect(),i=gAe(s);let l=T4(1);t&&(r?Cb(r)&&(l=SL(r)):l=SL(s));const o=TIt(i,n,r)?Brt(i):T4(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 p=cy(i),f=r&&Cb(r)?cy(r):r;let g=p,_=$Se(g);for(;_&&r&&f!==g;){const v=SL(_),j=_.getBoundingClientRect(),b=Tb(_),S=j.left+(_.clientLeft+parseFloat(b.paddingLeft))*v.x,A=j.top+(_.clientTop+parseFloat(b.paddingTop))*v.y;c*=v.x,d*=v.y,u*=v.x,h*=v.y,c+=S,d+=A,g=cy(_),_=$Se(g)}}return Gpe({width:u,height:h,x:c,y:d})}function EIt(s){let{elements:t,rect:n,offsetParent:r,strategy:a}=s;const i=a==="fixed",l=Hw(r),o=t?A0e(t.floating):!1;if(r===l||o&&i)return n;let c={scrollLeft:0,scrollTop:0},d=T4(1);const u=T4(0),h=Aw(r);if((h||!h&&!i)&&((ID(r)!=="body"||z$(l))&&(c=M0e(r)),Aw(r))){const p=hM(r);d=SL(r),u.x=p.x+r.clientLeft,u.y=p.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 AIt(s){return Array.from(s.getClientRects())}function USe(s,t){const n=M0e(s).scrollLeft;return t?t.left+n:hM(Hw(s)).left+n}function MIt(s){const t=Hw(s),n=M0e(s),r=s.ownerDocument.body,a=W0(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=W0(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let l=-n.scrollLeft+USe(s);const o=-n.scrollTop;return Tb(r).direction==="rtl"&&(l+=W0(t.clientWidth,r.clientWidth)-a),{width:a,height:i,x:l,y:o}}function IIt(s,t){const n=cy(s),r=Hw(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=xAe();(!d||d&&t==="fixed")&&(o=a.offsetLeft,c=a.offsetTop)}return{width:i,height:l,x:o,y:c}}function PIt(s,t){const n=hM(s,!0,t==="fixed"),r=n.top+s.clientTop,a=n.left+s.clientLeft,i=Aw(s)?SL(s):T4(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 aze(s,t,n){let r;if(t==="viewport")r=IIt(s,n);else if(t==="document")r=MIt(Hw(s));else if(Cb(t))r=PIt(t,n);else{const a=Brt(s);r={...t,x:t.x-a.x,y:t.y-a.y}}return Gpe(r)}function $rt(s,t){const n=A4(s);return n===t||!Cb(n)||f8(n)?!1:Tb(n).position==="fixed"||$rt(n,t)}function LIt(s,t){const n=t.get(s);if(n)return n;let r=eB(s,[],!1).filter(o=>Cb(o)&&ID(o)!=="body"),a=null;const i=Tb(s).position==="fixed";let l=i?A4(s):s;for(;Cb(l)&&!f8(l);){const o=Tb(l),c=fAe(l);!c&&o.position==="fixed"&&(a=null),(i?!c&&!a:!c&&o.position==="static"&&!!a&&["absolute","fixed"].includes(a.position)||z$(l)&&!c&&$rt(s,l))?r=r.filter(u=>u!==l):a=o,l=A4(l)}return t.set(s,r),r}function DIt(s){let{element:t,boundary:n,rootBoundary:r,strategy:a}=s;const l=[...n==="clippingAncestors"?A0e(t)?[]:LIt(t,this._c):[].concat(n),r],o=l[0],c=l.reduce((d,u)=>{const h=aze(t,u,a);return d.top=W0(h.top,d.top),d.right=C4(h.right,d.right),d.bottom=C4(h.bottom,d.bottom),d.left=W0(h.left,d.left),d},aze(t,o,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function RIt(s){const{width:t,height:n}=zrt(s);return{width:t,height:n}}function OIt(s,t,n){const r=Aw(t),a=Hw(t),i=n==="fixed",l=hM(s,!0,i,t);let o={scrollLeft:0,scrollTop:0};const c=T4(0);if(r||!r&&!i)if((ID(t)!=="body"||z$(a))&&(o=M0e(t)),r){const f=hM(t,!0,i,t);c.x=f.x+t.clientLeft,c.y=f.y+t.clientTop}else a&&(c.x=USe(a));let d=0,u=0;if(a&&!r&&!i){const f=a.getBoundingClientRect();u=f.top+o.scrollTop,d=f.left+o.scrollLeft-USe(a,f)}const h=l.left+o.scrollLeft-c.x-d,p=l.top+o.scrollTop-c.y-u;return{x:h,y:p,width:l.width,height:l.height}}function Fwe(s){return Tb(s).position==="static"}function ize(s,t){if(!Aw(s)||Tb(s).position==="fixed")return null;if(t)return t(s);let n=s.offsetParent;return Hw(s)===n&&(n=n.ownerDocument.body),n}function Urt(s,t){const n=cy(s);if(A0e(s))return n;if(!Aw(s)){let a=A4(s);for(;a&&!f8(a);){if(Cb(a)&&!Fwe(a))return a;a=A4(a)}return n}let r=ize(s,t);for(;r&&kIt(r)&&Fwe(r);)r=ize(r,t);return r&&f8(r)&&Fwe(r)&&!fAe(r)?n:r||SIt(s)||n}const FIt=async function(s){const t=this.getOffsetParent||Urt,n=this.getDimensions,r=await n(s.floating);return{reference:OIt(s.reference,await t(s.floating),s.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function zIt(s){return Tb(s).direction==="rtl"}const BIt={convertOffsetParentRelativeRectToViewportRelativeRect:EIt,getDocumentElement:Hw,getClippingRect:DIt,getOffsetParent:Urt,getElementRects:FIt,getClientRects:AIt,getDimensions:RIt,getScale:SL,isElement:Cb,isRTL:zIt};function $It(s,t){let n=null,r;const a=Hw(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:p}=s.getBoundingClientRect();if(o||t(),!h||!p)return;const f=UV(u),g=UV(a.clientWidth-(d+h)),_=UV(a.clientHeight-(u+p)),v=UV(d),b={rootMargin:-f+"px "+-g+"px "+-_+"px "+-v+"px",threshold:W0(0,C4(1,c))||1};let S=!0;function A(T){const L=T[0].intersectionRatio;if(L!==c){if(!S)return l();L?l(!1,L):r=setTimeout(()=>{l(!1,1e-7)},1e3)}S=!1}try{n=new IntersectionObserver(A,{...b,root:a.ownerDocument})}catch{n=new IntersectionObserver(A,b)}n.observe(s)}return l(!0),i}function UIt(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=gAe(s),u=a||i?[...d?eB(d):[],...eB(t)]:[];u.forEach(j=>{a&&j.addEventListener("scroll",n,{passive:!0}),i&&j.addEventListener("resize",n)});const h=d&&o?$It(d,n):null;let p=-1,f=null;l&&(f=new ResizeObserver(j=>{let[b]=j;b&&b.target===d&&f&&(f.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var S;(S=f)==null||S.observe(t)})),n()}),d&&!c&&f.observe(d),f.observe(t));let g,_=c?hM(s):null;c&&v();function v(){const j=hM(s);_&&(j.x!==_.x||j.y!==_.y||j.width!==_.width||j.height!==_.height)&&n(),_=j,g=requestAnimationFrame(v)}return n(),()=>{var j;u.forEach(b=>{a&&b.removeEventListener("scroll",n),i&&b.removeEventListener("resize",n)}),h==null||h(),(j=f)==null||j.disconnect(),f=null,c&&cancelAnimationFrame(g)}}const qIt=_It,VIt=wIt,HIt=yIt,GIt=NIt,WIt=vIt,oze=gIt,KIt=jIt,YIt=(s,t,n)=>{const r=new Map,a={platform:BIt,...n},i={...a.platform,_c:r};return xIt(s,t,{...a,platform:i})};var kme=typeof document<"u"?N.useLayoutEffect:N.useEffect;function Wpe(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(!Wpe(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)&&!Wpe(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function qrt(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function lze(s,t){const n=qrt(s);return Math.round(t*n)/n}function zwe(s){const t=N.useRef(s);return kme(()=>{t.current=s}),t}function ZIt(s){s===void 0&&(s={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:a,elements:{reference:i,floating:l}={},transform:o=!0,whileElementsMounted:c,open:d}=s,[u,h]=N.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[p,f]=N.useState(r);Wpe(p,r)||f(r);const[g,_]=N.useState(null),[v,j]=N.useState(null),b=N.useCallback(he=>{he!==L.current&&(L.current=he,_(he))},[]),S=N.useCallback(he=>{he!==D.current&&(D.current=he,j(he))},[]),A=i||g,T=l||v,L=N.useRef(null),D=N.useRef(null),M=N.useRef(u),F=c!=null,z=zwe(c),V=zwe(a),W=zwe(d),Y=N.useCallback(()=>{if(!L.current||!D.current)return;const he={placement:t,strategy:n,middleware:p};V.current&&(he.platform=V.current),YIt(L.current,D.current,he).then(ce=>{const pe={...ce,isPositioned:W.current!==!1};K.current&&!Wpe(M.current,pe)&&(M.current=pe,Hx.flushSync(()=>{h(pe)}))})},[p,t,n,V,W]);kme(()=>{d===!1&&M.current.isPositioned&&(M.current.isPositioned=!1,h(he=>({...he,isPositioned:!1})))},[d]);const K=N.useRef(!1);kme(()=>(K.current=!0,()=>{K.current=!1}),[]),kme(()=>{if(A&&(L.current=A),T&&(D.current=T),A&&T){if(z.current)return z.current(A,T,Y);Y()}},[A,T,Y,z,F]);const J=N.useMemo(()=>({reference:L,floating:D,setReference:b,setFloating:S}),[b,S]),ne=N.useMemo(()=>({reference:A,floating:T}),[A,T]),ie=N.useMemo(()=>{const he={position:n,left:0,top:0};if(!ne.floating)return he;const ce=lze(ne.floating,u.x),pe=lze(ne.floating,u.y);return o?{...he,transform:"translate("+ce+"px, "+pe+"px)",...qrt(ne.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ce,top:pe}},[n,o,ne.floating,u.x,u.y]);return N.useMemo(()=>({...u,update:Y,refs:J,elements:ne,floatingStyles:ie}),[u,Y,J,ne,ie])}const QIt=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?oze({element:r.current,padding:a}).fn(n):{}:r?oze({element:r,padding:a}).fn(n):{}}}},XIt=(s,t)=>({...qIt(s),options:[s,t]}),JIt=(s,t)=>({...VIt(s),options:[s,t]}),ePt=(s,t)=>({...KIt(s),options:[s,t]}),tPt=(s,t)=>({...HIt(s),options:[s,t]}),sPt=(s,t)=>({...GIt(s),options:[s,t]}),nPt=(s,t)=>({...WIt(s),options:[s,t]}),rPt=(s,t)=>({...QIt(s),options:[s,t]});var aPt="Arrow",Vrt=N.forwardRef((s,t)=>{const{children:n,width:r=10,height:a=5,...i}=s;return e.jsx(Jr.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"})})});Vrt.displayName=aPt;var iPt=Vrt;function B$(s){const[t,n]=N.useState(void 0);return mh(()=>{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 yAe="Popper",[Hrt,Gw]=pu(yAe),[oPt,Grt]=Hrt(yAe),Wrt=s=>{const{__scopePopper:t,children:n}=s,[r,a]=N.useState(null);return e.jsx(oPt,{scope:t,anchor:r,onAnchorChange:a,children:n})};Wrt.displayName=yAe;var Krt="PopperAnchor",Yrt=N.forwardRef((s,t)=>{const{__scopePopper:n,virtualRef:r,...a}=s,i=Grt(Krt,n),l=N.useRef(null),o=Si(t,l);return N.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||l.current)}),r?null:e.jsx(Jr.div,{...a,ref:o})});Yrt.displayName=Krt;var vAe="PopperContent",[lPt,cPt]=Hrt(vAe),Zrt=N.forwardRef((s,t)=>{var Ae,De,Ie,Fe,qe,be;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:p=!1,updatePositionStrategy:f="optimized",onPlaced:g,..._}=s,v=Grt(vAe,n),[j,b]=N.useState(null),S=Si(t,Ze=>b(Ze)),[A,T]=N.useState(null),L=B$(A),D=(L==null?void 0:L.width)??0,M=(L==null?void 0:L.height)??0,F=r+(i!=="center"?"-"+i:""),z=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},V=Array.isArray(d)?d:[d],W=V.length>0,Y={padding:z,boundary:V.filter(uPt),altBoundary:W},{refs:K,floatingStyles:J,placement:ne,isPositioned:ie,middlewareData:he}=ZIt({strategy:"fixed",placement:F,whileElementsMounted:(...Ze)=>UIt(...Ze,{animationFrame:f==="always"}),elements:{reference:v.anchor},middleware:[XIt({mainAxis:a+M,alignmentAxis:l}),c&&JIt({mainAxis:!0,crossAxis:!1,limiter:h==="partial"?ePt():void 0,...Y}),c&&tPt({...Y}),sPt({...Y,apply:({elements:Ze,rects:Ne,availableWidth:it,availableHeight:je})=>{const{width:Ge,height:Be}=Ne.reference,Ye=Ze.floating.style;Ye.setProperty("--radix-popper-available-width",`${it}px`),Ye.setProperty("--radix-popper-available-height",`${je}px`),Ye.setProperty("--radix-popper-anchor-width",`${Ge}px`),Ye.setProperty("--radix-popper-anchor-height",`${Be}px`)}}),A&&rPt({element:A,padding:o}),hPt({arrowWidth:D,arrowHeight:M}),p&&nPt({strategy:"referenceHidden",...Y})]}),[ce,pe]=Jrt(ne),le=lh(g);mh(()=>{ie&&(le==null||le())},[ie,le]);const ve=(Ae=he.arrow)==null?void 0:Ae.x,ge=(De=he.arrow)==null?void 0:De.y,Te=((Ie=he.arrow)==null?void 0:Ie.centerOffset)!==0,[Me,Ce]=N.useState();return mh(()=>{j&&Ce(window.getComputedStyle(j).zIndex)},[j]),e.jsx("div",{ref:K.setFloating,"data-radix-popper-content-wrapper":"",style:{...J,transform:ie?J.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Me,"--radix-popper-transform-origin":[(Fe=he.transformOrigin)==null?void 0:Fe.x,(qe=he.transformOrigin)==null?void 0:qe.y].join(" "),...((be=he.hide)==null?void 0:be.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:s.dir,children:e.jsx(lPt,{scope:n,placedSide:ce,onArrowChange:T,arrowX:ve,arrowY:ge,shouldHideArrow:Te,children:e.jsx(Jr.div,{"data-side":ce,"data-align":pe,..._,ref:S,style:{..._.style,animation:ie?void 0:"none"}})})})});Zrt.displayName=vAe;var Qrt="PopperArrow",dPt={top:"bottom",right:"left",bottom:"top",left:"right"},Xrt=N.forwardRef(function(t,n){const{__scopePopper:r,...a}=t,i=cPt(Qrt,r),l=dPt[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(iPt,{...a,ref:n,style:{...a.style,display:"block"}})})});Xrt.displayName=Qrt;function uPt(s){return s!==null}var hPt=s=>({name:"transformOrigin",options:s,fn(t){var v,j,b;const{placement:n,rects:r,middlewareData:a}=t,l=((v=a.arrow)==null?void 0:v.centerOffset)!==0,o=l?0:s.arrowWidth,c=l?0:s.arrowHeight,[d,u]=Jrt(n),h={start:"0%",center:"50%",end:"100%"}[u],p=(((j=a.arrow)==null?void 0:j.x)??0)+o/2,f=(((b=a.arrow)==null?void 0:b.y)??0)+c/2;let g="",_="";return d==="bottom"?(g=l?h:`${p}px`,_=`${-c}px`):d==="top"?(g=l?h:`${p}px`,_=`${r.floating.height+c}px`):d==="right"?(g=`${-c}px`,_=l?h:`${f}px`):d==="left"&&(g=`${r.floating.width+c}px`,_=l?h:`${f}px`),{data:{x:g,y:_}}}});function Jrt(s){const[t,n="center"]=s.split("-");return[t,n]}var $$=Wrt,PD=Yrt,U$=Zrt,q$=Xrt,[I0e,lxn]=pu("Tooltip",[Gw]),P0e=Gw(),eat="TooltipProvider",mPt=700,qSe="tooltip.open",[pPt,bAe]=I0e(eat),tat=s=>{const{__scopeTooltip:t,delayDuration:n=mPt,skipDelayDuration:r=300,disableHoverableContent:a=!1,children:i}=s,l=N.useRef(!0),o=N.useRef(!1),c=N.useRef(0);return N.useEffect(()=>{const d=c.current;return()=>window.clearTimeout(d)},[]),e.jsx(pPt,{scope:t,isOpenDelayedRef:l,delayDuration:n,onOpen:N.useCallback(()=>{window.clearTimeout(c.current),l.current=!1},[]),onClose:N.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>l.current=!0,r)},[r]),isPointerInTransitRef:o,onPointerInTransitChange:N.useCallback(d=>{o.current=d},[]),disableHoverableContent:a,children:i})};tat.displayName=eat;var tB="Tooltip",[fPt,L0e]=I0e(tB),sat=s=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=bAe(tB,s.__scopeTooltip),d=P0e(t),[u,h]=N.useState(null),p=dm(),f=N.useRef(0),g=l??c.disableHoverableContent,_=o??c.delayDuration,v=N.useRef(!1),[j,b]=hm({prop:r,defaultProp:a??!1,onChange:D=>{D?(c.onOpen(),document.dispatchEvent(new CustomEvent(qSe))):c.onClose(),i==null||i(D)},caller:tB}),S=N.useMemo(()=>j?v.current?"delayed-open":"instant-open":"closed",[j]),A=N.useCallback(()=>{window.clearTimeout(f.current),f.current=0,v.current=!1,b(!0)},[b]),T=N.useCallback(()=>{window.clearTimeout(f.current),f.current=0,b(!1)},[b]),L=N.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>{v.current=!0,b(!0),f.current=0},_)},[_,b]);return N.useEffect(()=>()=>{f.current&&(window.clearTimeout(f.current),f.current=0)},[]),e.jsx($$,{...d,children:e.jsx(fPt,{scope:t,contentId:p,open:j,stateAttribute:S,trigger:u,onTriggerChange:h,onTriggerEnter:N.useCallback(()=>{c.isOpenDelayedRef.current?L():A()},[c.isOpenDelayedRef,L,A]),onTriggerLeave:N.useCallback(()=>{g?T():(window.clearTimeout(f.current),f.current=0)},[T,g]),onOpen:A,onClose:T,disableHoverableContent:g,children:n})})};sat.displayName=tB;var VSe="TooltipTrigger",nat=N.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=L0e(VSe,n),i=bAe(VSe,n),l=P0e(n),o=N.useRef(null),c=Si(t,o,a.onTriggerChange),d=N.useRef(!1),u=N.useRef(!1),h=N.useCallback(()=>d.current=!1,[]);return N.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),e.jsx(PD,{asChild:!0,...l,children:e.jsx(Jr.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...r,ref:c,onPointerMove:_r(s.onPointerMove,p=>{p.pointerType!=="touch"&&!u.current&&!i.isPointerInTransitRef.current&&(a.onTriggerEnter(),u.current=!0)}),onPointerLeave:_r(s.onPointerLeave,()=>{a.onTriggerLeave(),u.current=!1}),onPointerDown:_r(s.onPointerDown,()=>{a.open&&a.onClose(),d.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:_r(s.onFocus,()=>{d.current||a.onOpen()}),onBlur:_r(s.onBlur,a.onClose),onClick:_r(s.onClick,a.onClose)})})});nat.displayName=VSe;var xPt="TooltipPortal",[cxn,gPt]=I0e(xPt,{forceMount:void 0}),x8="TooltipContent",rat=N.forwardRef((s,t)=>{const n=gPt(x8,s.__scopeTooltip),{forceMount:r=n.forceMount,side:a="top",...i}=s,l=L0e(x8,s.__scopeTooltip);return e.jsx(Rh,{present:r||l.open,children:l.disableHoverableContent?e.jsx(aat,{side:a,...i,ref:t}):e.jsx(yPt,{side:a,...i,ref:t})})}),yPt=N.forwardRef((s,t)=>{const n=L0e(x8,s.__scopeTooltip),r=bAe(x8,s.__scopeTooltip),a=N.useRef(null),i=Si(t,a),[l,o]=N.useState(null),{trigger:c,onClose:d}=n,u=a.current,{onPointerInTransitChange:h}=r,p=N.useCallback(()=>{o(null),h(!1)},[h]),f=N.useCallback((g,_)=>{const v=g.currentTarget,j={x:g.clientX,y:g.clientY},b=jPt(j,v.getBoundingClientRect()),S=NPt(j,b),A=kPt(_.getBoundingClientRect()),T=CPt([...S,...A]);o(T),h(!0)},[h]);return N.useEffect(()=>()=>p(),[p]),N.useEffect(()=>{if(c&&u){const g=v=>f(v,u),_=v=>f(v,c);return c.addEventListener("pointerleave",g),u.addEventListener("pointerleave",_),()=>{c.removeEventListener("pointerleave",g),u.removeEventListener("pointerleave",_)}}},[c,u,f,p]),N.useEffect(()=>{if(l){const g=_=>{const v=_.target,j={x:_.clientX,y:_.clientY},b=(c==null?void 0:c.contains(v))||(u==null?void 0:u.contains(v)),S=!SPt(j,l);b?p():S&&(p(),d())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[c,u,l,d,p]),e.jsx(aat,{...s,ref:i})}),[vPt,bPt]=I0e(tB,{isInside:!1}),_Pt=Jnt("TooltipContent"),aat=N.forwardRef((s,t)=>{const{__scopeTooltip:n,children:r,"aria-label":a,onEscapeKeyDown:i,onPointerDownOutside:l,...o}=s,c=L0e(x8,n),d=P0e(n),{onClose:u}=c;return N.useEffect(()=>(document.addEventListener(qSe,u),()=>document.removeEventListener(qSe,u)),[u]),N.useEffect(()=>{if(c.trigger){const h=p=>{const f=p.target;f!=null&&f.contains(c.trigger)&&u()};return window.addEventListener("scroll",h,{capture:!0}),()=>window.removeEventListener("scroll",h,{capture:!0})}},[c.trigger,u]),e.jsx(H4,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:h=>h.preventDefault(),onDismiss:u,children:e.jsxs(U$,{"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(_Pt,{children:r}),e.jsx(vPt,{scope:n,isInside:!0,children:e.jsx(NMt,{id:c.contentId,role:"tooltip",children:a||r})})]})})});rat.displayName=x8;var iat="TooltipArrow",wPt=N.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=P0e(n);return bPt(iat,n).isInside?null:e.jsx(q$,{...a,...r,ref:t})});wPt.displayName=iat;function jPt(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 NPt(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 kPt(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 SPt(s,t){const{x:n,y:r}=s;let a=!1;for(let i=0,l=t.length-1;ir!=p>r&&n<(h-d)*(r-u)/(p-u)+d&&(a=!a)}return a}function CPt(s){const t=s.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),TPt(t)}function TPt(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 EPt=tat,APt=sat,MPt=nat,oat=rat;const Ww=EPt,Ec=APt,Ac=MPt,vc=N.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(oat,{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}));vc.displayName=oat.displayName;var LD=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(){}},mM=typeof window>"u"||"Deno"in globalThis;function qx(){}function IPt(s,t){return typeof s=="function"?s(t):s}function HSe(s){return typeof s=="number"&&s>=0&&s!==1/0}function lat(s,t){return Math.max(s+(t||0)-Date.now(),0)}function h4(s,t){return typeof s=="function"?s(t):s}function gv(s,t){return typeof s=="function"?s(t):s}function cze(s,t){const{type:n="all",exact:r,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(r){if(t.queryHash!==_Ae(l,t.options))return!1}else if(!sB(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 dze(s,t){const{exact:n,status:r,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(n){if(pM(t.options.mutationKey)!==pM(i))return!1}else if(!sB(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function _Ae(s,t){return((t==null?void 0:t.queryKeyHashFn)||pM)(s)}function pM(s){return JSON.stringify(s,(t,n)=>GSe(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function sB(s,t){return s===t?!0:typeof s!=typeof t?!1:s&&t&&typeof s=="object"&&typeof t=="object"?Object.keys(t).every(n=>sB(s[n],t[n])):!1}function cat(s,t){if(s===t)return s;const n=uze(s)&&uze(t);if(n||GSe(s)&&GSe(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 WSe(s,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(s,t):n.structuralSharing!==!1?cat(s,t):t}function LPt(s,t,n=0){const r=[...s,t];return n&&r.length>n?r.slice(1):r}function DPt(s,t,n=0){const r=[t,...s];return n&&r.length>n?r.slice(0,-1):r}var wAe=Symbol();function dat(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===wAe?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function uat(s,t){return typeof s=="function"?s(...t):!!s}var lA,yS,ZL,Ttt,RPt=(Ttt=class extends LD{constructor(){super();Ui(this,lA);Ui(this,yS);Ui(this,ZL);qa(this,ZL,t=>{if(!mM&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){Zs(this,yS)||this.setEventListener(Zs(this,ZL))}onUnsubscribe(){var t;this.hasListeners()||((t=Zs(this,yS))==null||t.call(this),qa(this,yS,void 0))}setEventListener(t){var n;qa(this,ZL,t),(n=Zs(this,yS))==null||n.call(this),qa(this,yS,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){Zs(this,lA)!==t&&(qa(this,lA,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof Zs(this,lA)=="boolean"?Zs(this,lA):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},lA=new WeakMap,yS=new WeakMap,ZL=new WeakMap,Ttt),jAe=new RPt,QL,vS,XL,Ett,OPt=(Ett=class extends LD{constructor(){super();Ui(this,QL,!0);Ui(this,vS);Ui(this,XL);qa(this,XL,t=>{if(!mM&&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(){Zs(this,vS)||this.setEventListener(Zs(this,XL))}onUnsubscribe(){var t;this.hasListeners()||((t=Zs(this,vS))==null||t.call(this),qa(this,vS,void 0))}setEventListener(t){var n;qa(this,XL,t),(n=Zs(this,vS))==null||n.call(this),qa(this,vS,t(this.setOnline.bind(this)))}setOnline(t){Zs(this,QL)!==t&&(qa(this,QL,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return Zs(this,QL)}},QL=new WeakMap,vS=new WeakMap,XL=new WeakMap,Ett),Ype=new OPt;function KSe(){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 FPt(s){return Math.min(1e3*2**s,3e4)}function hat(s){return(s??"online")==="online"?Ype.isOnline():!0}var mat=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function Bwe(s){return s instanceof mat}function pat(s){let t=!1,n=0,r=!1,a;const i=KSe(),l=_=>{var v;r||(p(new mat(_)),(v=s.abort)==null||v.call(s))},o=()=>{t=!0},c=()=>{t=!1},d=()=>jAe.isFocused()&&(s.networkMode==="always"||Ype.isOnline())&&s.canRun(),u=()=>hat(s.networkMode)&&s.canRun(),h=_=>{var v;r||(r=!0,(v=s.onSuccess)==null||v.call(s,_),a==null||a(),i.resolve(_))},p=_=>{var v;r||(r=!0,(v=s.onError)==null||v.call(s,_),a==null||a(),i.reject(_))},f=()=>new Promise(_=>{var v;a=j=>{(r||d())&&_(j)},(v=s.onPause)==null||v.call(s)}).then(()=>{var _;a=void 0,r||(_=s.onContinue)==null||_.call(s)}),g=()=>{if(r)return;let _;const v=n===0?s.initialPromise:void 0;try{_=v??s.fn()}catch(j){_=Promise.reject(j)}Promise.resolve(_).then(h).catch(j=>{var L;if(r)return;const b=s.retry??(mM?0:3),S=s.retryDelay??FPt,A=typeof S=="function"?S(n,j):S,T=b===!0||typeof b=="number"&&nd()?void 0:f()).then(()=>{t?p(j):g()})})};return{promise:i,cancel:l,continue:()=>(a==null||a(),i),cancelRetry:o,continueRetry:c,canStart:u,start:()=>(u()?g():f().then(g),i)}}var zPt=s=>setTimeout(s,0);function BPt(){let s=[],t=0,n=o=>{o()},r=o=>{o()},a=zPt;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 Rm=BPt(),cA,Att,fat=(Att=class{constructor(){Ui(this,cA)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),HSe(this.gcTime)&&qa(this,cA,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(mM?1/0:5*60*1e3))}clearGcTimeout(){Zs(this,cA)&&(clearTimeout(Zs(this,cA)),qa(this,cA,void 0))}},cA=new WeakMap,Att),JL,dA,xv,uA,Gf,E$,hA,G1,f2,Mtt,$Pt=(Mtt=class extends fat{constructor(t){super();Ui(this,G1);Ui(this,JL);Ui(this,dA);Ui(this,xv);Ui(this,uA);Ui(this,Gf);Ui(this,E$);Ui(this,hA);qa(this,hA,!1),qa(this,E$,t.defaultOptions),this.setOptions(t.options),this.observers=[],qa(this,uA,t.client),qa(this,xv,Zs(this,uA).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,qa(this,JL,UPt(this.options)),this.state=t.state??Zs(this,JL),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=Zs(this,Gf))==null?void 0:t.promise}setOptions(t){this.options={...Zs(this,E$),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Zs(this,xv).remove(this)}setData(t,n){const r=WSe(this.state.data,t,this.options);return Yo(this,G1,f2).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){Yo(this,G1,f2).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,a;const n=(r=Zs(this,Gf))==null?void 0:r.promise;return(a=Zs(this,Gf))==null||a.cancel(t),n?n.then(qx).catch(qx):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(Zs(this,JL))}isActive(){return this.observers.some(t=>gv(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===wAe||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>h4(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:!lat(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=Zs(this,Gf))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=Zs(this,Gf))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),Zs(this,xv).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(Zs(this,Gf)&&(Zs(this,hA)?Zs(this,Gf).cancel({revert:!0}):Zs(this,Gf).cancelRetry()),this.scheduleGc()),Zs(this,xv).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Yo(this,G1,f2).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(Zs(this,Gf))return Zs(this,Gf).continueRetry(),Zs(this,Gf).promise}if(t&&this.setOptions(t),!this.options.queryFn){const p=this.observers.find(f=>f.options.queryFn);p&&this.setOptions(p.options)}const r=new AbortController,a=p=>{Object.defineProperty(p,"signal",{enumerable:!0,get:()=>(qa(this,hA,!0),r.signal)})},i=()=>{const p=dat(this.options,n),g=(()=>{const _={client:Zs(this,uA),queryKey:this.queryKey,meta:this.meta};return a(_),_})();return qa(this,hA,!1),this.options.persister?this.options.persister(p,g,this):p(g)},o=(()=>{const p={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:Zs(this,uA),state:this.state,fetchFn:i};return a(p),p})();(d=this.options.behavior)==null||d.onFetch(o,this),qa(this,dA,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&Yo(this,G1,f2).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta});const c=p=>{var f,g,_,v;Bwe(p)&&p.silent||Yo(this,G1,f2).call(this,{type:"error",error:p}),Bwe(p)||((g=(f=Zs(this,xv).config).onError)==null||g.call(f,p,this),(v=(_=Zs(this,xv).config).onSettled)==null||v.call(_,this.state.data,p,this)),this.scheduleGc()};return qa(this,Gf,pat({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,abort:r.abort.bind(r),onSuccess:p=>{var f,g,_,v;if(p===void 0){c(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(p)}catch(j){c(j);return}(g=(f=Zs(this,xv).config).onSuccess)==null||g.call(f,p,this),(v=(_=Zs(this,xv).config).onSettled)==null||v.call(_,p,this.state.error,this),this.scheduleGc()},onError:c,onFail:(p,f)=>{Yo(this,G1,f2).call(this,{type:"failed",failureCount:p,error:f})},onPause:()=>{Yo(this,G1,f2).call(this,{type:"pause"})},onContinue:()=>{Yo(this,G1,f2).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),Zs(this,Gf).start()}},JL=new WeakMap,dA=new WeakMap,xv=new WeakMap,uA=new WeakMap,Gf=new WeakMap,E$=new WeakMap,hA=new WeakMap,G1=new WeakSet,f2=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,...xat(r.data,this.options),fetchMeta:t.meta??null};case"success":return qa(this,dA,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 Bwe(a)&&a.revert&&Zs(this,dA)?{...Zs(this,dA),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),Rm.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),Zs(this,xv).notify({query:this,type:"updated",action:t})})},Mtt);function xat(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:hat(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function UPt(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 H_,Itt,qPt=(Itt=class extends LD{constructor(t={}){super();Ui(this,H_);this.config=t,qa(this,H_,new Map)}build(t,n,r){const a=n.queryKey,i=n.queryHash??_Ae(a,n);let l=this.get(i);return l||(l=new $Pt({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){Zs(this,H_).has(t.queryHash)||(Zs(this,H_).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=Zs(this,H_).get(t.queryHash);n&&(t.destroy(),n===t&&Zs(this,H_).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Rm.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return Zs(this,H_).get(t)}getAll(){return[...Zs(this,H_).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>cze(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>cze(t,r)):n}notify(t){Rm.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){Rm.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){Rm.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},H_=new WeakMap,Itt),G_,Bx,mA,W_,Rk,Ptt,VPt=(Ptt=class extends fat{constructor(t){super();Ui(this,W_);Ui(this,G_);Ui(this,Bx);Ui(this,mA);this.mutationId=t.mutationId,qa(this,Bx,t.mutationCache),qa(this,G_,[]),this.state=t.state||gat(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){Zs(this,G_).includes(t)||(Zs(this,G_).push(t),this.clearGcTimeout(),Zs(this,Bx).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){qa(this,G_,Zs(this,G_).filter(n=>n!==t)),this.scheduleGc(),Zs(this,Bx).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){Zs(this,G_).length||(this.state.status==="pending"?this.scheduleGc():Zs(this,Bx).remove(this))}continue(){var t;return((t=Zs(this,mA))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,l,o,c,d,u,h,p,f,g,_,v,j,b,S,A,T,L,D,M;const n=()=>{Yo(this,W_,Rk).call(this,{type:"continue"})};qa(this,mA,pat({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(F,z)=>{Yo(this,W_,Rk).call(this,{type:"failed",failureCount:F,error:z})},onPause:()=>{Yo(this,W_,Rk).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Zs(this,Bx).canRun(this)}));const r=this.state.status==="pending",a=!Zs(this,mA).canStart();try{if(r)n();else{Yo(this,W_,Rk).call(this,{type:"pending",variables:t,isPaused:a}),await((l=(i=Zs(this,Bx).config).onMutate)==null?void 0:l.call(i,t,this));const z=await((c=(o=this.options).onMutate)==null?void 0:c.call(o,t));z!==this.state.context&&Yo(this,W_,Rk).call(this,{type:"pending",context:z,variables:t,isPaused:a})}const F=await Zs(this,mA).start();return await((u=(d=Zs(this,Bx).config).onSuccess)==null?void 0:u.call(d,F,t,this.state.context,this)),await((p=(h=this.options).onSuccess)==null?void 0:p.call(h,F,t,this.state.context)),await((g=(f=Zs(this,Bx).config).onSettled)==null?void 0:g.call(f,F,null,this.state.variables,this.state.context,this)),await((v=(_=this.options).onSettled)==null?void 0:v.call(_,F,null,t,this.state.context)),Yo(this,W_,Rk).call(this,{type:"success",data:F}),F}catch(F){try{throw await((b=(j=Zs(this,Bx).config).onError)==null?void 0:b.call(j,F,t,this.state.context,this)),await((A=(S=this.options).onError)==null?void 0:A.call(S,F,t,this.state.context)),await((L=(T=Zs(this,Bx).config).onSettled)==null?void 0:L.call(T,void 0,F,this.state.variables,this.state.context,this)),await((M=(D=this.options).onSettled)==null?void 0:M.call(D,void 0,F,t,this.state.context)),F}finally{Yo(this,W_,Rk).call(this,{type:"error",error:F})}}finally{Zs(this,Bx).runNext(this)}}},G_=new WeakMap,Bx=new WeakMap,mA=new WeakMap,W_=new WeakSet,Rk=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),Rm.batch(()=>{Zs(this,G_).forEach(r=>{r.onMutationUpdate(t)}),Zs(this,Bx).notify({mutation:this,type:"updated",action:t})})},Ptt);function gat(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var A2,W1,A$,Ltt,HPt=(Ltt=class extends LD{constructor(t={}){super();Ui(this,A2);Ui(this,W1);Ui(this,A$);this.config=t,qa(this,A2,new Set),qa(this,W1,new Map),qa(this,A$,0)}build(t,n,r){const a=new VPt({mutationCache:this,mutationId:++_V(this,A$)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){Zs(this,A2).add(t);const n=qV(t);if(typeof n=="string"){const r=Zs(this,W1).get(n);r?r.push(t):Zs(this,W1).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(Zs(this,A2).delete(t)){const n=qV(t);if(typeof n=="string"){const r=Zs(this,W1).get(n);if(r)if(r.length>1){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}else r[0]===t&&Zs(this,W1).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=qV(t);if(typeof n=="string"){const r=Zs(this,W1).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=qV(t);if(typeof n=="string"){const a=(r=Zs(this,W1).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(){Rm.batch(()=>{Zs(this,A2).forEach(t=>{this.notify({type:"removed",mutation:t})}),Zs(this,A2).clear(),Zs(this,W1).clear()})}getAll(){return Array.from(Zs(this,A2))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>dze(n,r))}findAll(t={}){return this.getAll().filter(n=>dze(t,n))}notify(t){Rm.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return Rm.batch(()=>Promise.all(t.map(n=>n.continue().catch(qx))))}},A2=new WeakMap,W1=new WeakMap,A$=new WeakMap,Ltt);function qV(s){var t;return(t=s.options.scope)==null?void 0:t.id}function Zpe(s){return{onFetch:(t,n)=>{var u,h,p,f,g;const r=t.options,a=(p=(h=(u=t.fetchOptions)==null?void 0:u.meta)==null?void 0:h.fetchMore)==null?void 0:p.direction,i=((f=t.state.data)==null?void 0:f.pages)||[],l=((g=t.state.data)==null?void 0:g.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let _=!1;const v=S=>{Object.defineProperty(S,"signal",{enumerable:!0,get:()=>(t.signal.aborted?_=!0:t.signal.addEventListener("abort",()=>{_=!0}),t.signal)})},j=dat(t.options,t.fetchOptions),b=async(S,A,T)=>{if(_)return Promise.reject();if(A==null&&S.pages.length)return Promise.resolve(S);const D=(()=>{const V={client:t.client,queryKey:t.queryKey,pageParam:A,direction:T?"backward":"forward",meta:t.options.meta};return v(V),V})(),M=await j(D),{maxPages:F}=t.options,z=T?DPt:LPt;return{pages:z(S.pages,M,F),pageParams:z(S.pageParams,A,F)}};if(a&&i.length){const S=a==="backward",A=S?yat:YSe,T={pages:i,pageParams:l},L=A(r,T);o=await b(T,L,S)}else{const S=s??i.length;do{const A=c===0?l[0]??r.initialPageParam:YSe(r,o);if(c>0&&A==null)break;o=await b(o,A),c++}while(c{var _,v;return(v=(_=t.options).persister)==null?void 0:v.call(_,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=d}}}function YSe(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 yat(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 GPt(s,t){return t?YSe(s,t)!=null:!1}function WPt(s,t){return!t||!s.getPreviousPageParam?!1:yat(s,t)!=null}var sh,bS,_S,e8,t8,wS,s8,n8,Dtt,KPt=(Dtt=class{constructor(s={}){Ui(this,sh);Ui(this,bS);Ui(this,_S);Ui(this,e8);Ui(this,t8);Ui(this,wS);Ui(this,s8);Ui(this,n8);qa(this,sh,s.queryCache||new qPt),qa(this,bS,s.mutationCache||new HPt),qa(this,_S,s.defaultOptions||{}),qa(this,e8,new Map),qa(this,t8,new Map),qa(this,wS,0)}mount(){_V(this,wS)._++,Zs(this,wS)===1&&(qa(this,s8,jAe.subscribe(async s=>{s&&(await this.resumePausedMutations(),Zs(this,sh).onFocus())})),qa(this,n8,Ype.subscribe(async s=>{s&&(await this.resumePausedMutations(),Zs(this,sh).onOnline())})))}unmount(){var s,t;_V(this,wS)._--,Zs(this,wS)===0&&((s=Zs(this,s8))==null||s.call(this),qa(this,s8,void 0),(t=Zs(this,n8))==null||t.call(this),qa(this,n8,void 0))}isFetching(s){return Zs(this,sh).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return Zs(this,bS).findAll({...s,status:"pending"}).length}getQueryData(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=Zs(this,sh).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),n=Zs(this,sh).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(s):(s.revalidateIfStale&&n.isStaleByTime(h4(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(s){return Zs(this,sh).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=Zs(this,sh).get(r.queryHash),i=a==null?void 0:a.state.data,l=IPt(t,i);if(l!==void 0)return Zs(this,sh).build(this,r).setData(l,{...n,manual:!0})}setQueriesData(s,t,n){return Rm.batch(()=>Zs(this,sh).findAll(s).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=Zs(this,sh).get(t.queryHash))==null?void 0:n.state}removeQueries(s){const t=Zs(this,sh);Rm.batch(()=>{t.findAll(s).forEach(n=>{t.remove(n)})})}resetQueries(s,t){const n=Zs(this,sh);return Rm.batch(()=>(n.findAll(s).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...s},t)))}cancelQueries(s,t={}){const n={revert:!0,...t},r=Rm.batch(()=>Zs(this,sh).findAll(s).map(a=>a.cancel(n)));return Promise.all(r).then(qx).catch(qx)}invalidateQueries(s,t={}){return Rm.batch(()=>(Zs(this,sh).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=Rm.batch(()=>Zs(this,sh).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch(qx)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(qx)}fetchQuery(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const n=Zs(this,sh).build(this,t);return n.isStaleByTime(h4(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(qx).catch(qx)}fetchInfiniteQuery(s){return s.behavior=Zpe(s.pages),this.fetchQuery(s)}prefetchInfiniteQuery(s){return this.fetchInfiniteQuery(s).then(qx).catch(qx)}ensureInfiniteQueryData(s){return s.behavior=Zpe(s.pages),this.ensureQueryData(s)}resumePausedMutations(){return Ype.isOnline()?Zs(this,bS).resumePausedMutations():Promise.resolve()}getQueryCache(){return Zs(this,sh)}getMutationCache(){return Zs(this,bS)}getDefaultOptions(){return Zs(this,_S)}setDefaultOptions(s){qa(this,_S,s)}setQueryDefaults(s,t){Zs(this,e8).set(pM(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...Zs(this,e8).values()],n={};return t.forEach(r=>{sB(s,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(s,t){Zs(this,t8).set(pM(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...Zs(this,t8).values()],n={};return t.forEach(r=>{sB(s,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(s){if(s._defaulted)return s;const t={...Zs(this,_S).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=_Ae(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===wAe&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...Zs(this,_S).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){Zs(this,sh).clear(),Zs(this,bS).clear()}},sh=new WeakMap,bS=new WeakMap,_S=new WeakMap,e8=new WeakMap,t8=new WeakMap,wS=new WeakMap,s8=new WeakMap,n8=new WeakMap,Dtt),Cg,kl,M$,$x,pA,r8,jS,NS,I$,a8,i8,fA,xA,kS,o8,_c,l7,ZSe,QSe,XSe,JSe,e4e,t4e,s4e,bat,Rtt,vat=(Rtt=class extends LD{constructor(t,n){super();Ui(this,_c);Ui(this,Cg);Ui(this,kl);Ui(this,M$);Ui(this,$x);Ui(this,pA);Ui(this,r8);Ui(this,jS);Ui(this,NS);Ui(this,I$);Ui(this,a8);Ui(this,i8);Ui(this,fA);Ui(this,xA);Ui(this,kS);Ui(this,o8,new Set);this.options=n,qa(this,Cg,t),qa(this,NS,null),qa(this,jS,KSe()),this.options.experimental_prefetchInRender||Zs(this,jS).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&&(Zs(this,kl).addObserver(this),mze(Zs(this,kl),this.options)?Yo(this,_c,l7).call(this):this.updateResult(),Yo(this,_c,JSe).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return n4e(Zs(this,kl),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return n4e(Zs(this,kl),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Yo(this,_c,e4e).call(this),Yo(this,_c,t4e).call(this),Zs(this,kl).removeObserver(this)}setOptions(t){const n=this.options,r=Zs(this,kl);if(this.options=Zs(this,Cg).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof gv(this.options.enabled,Zs(this,kl))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Yo(this,_c,s4e).call(this),Zs(this,kl).setOptions(this.options),n._defaulted&&!Kpe(this.options,n)&&Zs(this,Cg).getQueryCache().notify({type:"observerOptionsUpdated",query:Zs(this,kl),observer:this});const a=this.hasListeners();a&&pze(Zs(this,kl),r,this.options,n)&&Yo(this,_c,l7).call(this),this.updateResult(),a&&(Zs(this,kl)!==r||gv(this.options.enabled,Zs(this,kl))!==gv(n.enabled,Zs(this,kl))||h4(this.options.staleTime,Zs(this,kl))!==h4(n.staleTime,Zs(this,kl)))&&Yo(this,_c,ZSe).call(this);const i=Yo(this,_c,QSe).call(this);a&&(Zs(this,kl)!==r||gv(this.options.enabled,Zs(this,kl))!==gv(n.enabled,Zs(this,kl))||i!==Zs(this,kS))&&Yo(this,_c,XSe).call(this,i)}getOptimisticResult(t){const n=Zs(this,Cg).getQueryCache().build(Zs(this,Cg),t),r=this.createResult(n,t);return ZPt(this,r)&&(qa(this,$x,r),qa(this,r8,this.options),qa(this,pA,Zs(this,kl).state)),r}getCurrentResult(){return Zs(this,$x)}trackResult(t,n){return new Proxy(t,{get:(r,a)=>(this.trackProp(a),n==null||n(a),Reflect.get(r,a))})}trackProp(t){Zs(this,o8).add(t)}getCurrentQuery(){return Zs(this,kl)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=Zs(this,Cg).defaultQueryOptions(t),r=Zs(this,Cg).getQueryCache().build(Zs(this,Cg),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Yo(this,_c,l7).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),Zs(this,$x)))}createResult(t,n){var F;const r=Zs(this,kl),a=this.options,i=Zs(this,$x),l=Zs(this,pA),o=Zs(this,r8),d=t!==r?t.state:Zs(this,M$),{state:u}=t;let h={...u},p=!1,f;if(n._optimisticResults){const z=this.hasListeners(),V=!z&&mze(t,n),W=z&&pze(t,r,n,a);(V||W)&&(h={...h,...xat(u.data,t.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:g,errorUpdatedAt:_,status:v}=h;f=h.data;let j=!1;if(n.placeholderData!==void 0&&f===void 0&&v==="pending"){let z;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(z=i.data,j=!0):z=typeof n.placeholderData=="function"?n.placeholderData((F=Zs(this,i8))==null?void 0:F.state.data,Zs(this,i8)):n.placeholderData,z!==void 0&&(v="success",f=WSe(i==null?void 0:i.data,z,n),p=!0)}if(n.select&&f!==void 0&&!j)if(i&&f===(l==null?void 0:l.data)&&n.select===Zs(this,I$))f=Zs(this,a8);else try{qa(this,I$,n.select),f=n.select(f),f=WSe(i==null?void 0:i.data,f,n),qa(this,a8,f),qa(this,NS,null)}catch(z){qa(this,NS,z)}Zs(this,NS)&&(g=Zs(this,NS),f=Zs(this,a8),_=Date.now(),v="error");const b=h.fetchStatus==="fetching",S=v==="pending",A=v==="error",T=S&&b,L=f!==void 0,M={status:v,fetchStatus:h.fetchStatus,isPending:S,isSuccess:v==="success",isError:A,isInitialLoading:T,isLoading:T,data:f,dataUpdatedAt:h.dataUpdatedAt,error:g,errorUpdatedAt:_,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:b,isRefetching:b&&!S,isLoadingError:A&&!L,isPaused:h.fetchStatus==="paused",isPlaceholderData:p,isRefetchError:A&&L,isStale:NAe(t,n),refetch:this.refetch,promise:Zs(this,jS),isEnabled:gv(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const z=Y=>{M.status==="error"?Y.reject(M.error):M.data!==void 0&&Y.resolve(M.data)},V=()=>{const Y=qa(this,jS,M.promise=KSe());z(Y)},W=Zs(this,jS);switch(W.status){case"pending":t.queryHash===r.queryHash&&z(W);break;case"fulfilled":(M.status==="error"||M.data!==W.value)&&V();break;case"rejected":(M.status!=="error"||M.error!==W.reason)&&V();break}}return M}updateResult(){const t=Zs(this,$x),n=this.createResult(Zs(this,kl),this.options);if(qa(this,pA,Zs(this,kl).state),qa(this,r8,this.options),Zs(this,pA).data!==void 0&&qa(this,i8,Zs(this,kl)),Kpe(n,t))return;qa(this,$x,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!Zs(this,o8).size)return!0;const l=new Set(i??Zs(this,o8));return this.options.throwOnError&&l.add("error"),Object.keys(Zs(this,$x)).some(o=>{const c=o;return Zs(this,$x)[c]!==t[c]&&l.has(c)})};Yo(this,_c,bat).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Yo(this,_c,JSe).call(this)}},Cg=new WeakMap,kl=new WeakMap,M$=new WeakMap,$x=new WeakMap,pA=new WeakMap,r8=new WeakMap,jS=new WeakMap,NS=new WeakMap,I$=new WeakMap,a8=new WeakMap,i8=new WeakMap,fA=new WeakMap,xA=new WeakMap,kS=new WeakMap,o8=new WeakMap,_c=new WeakSet,l7=function(t){Yo(this,_c,s4e).call(this);let n=Zs(this,kl).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(qx)),n},ZSe=function(){Yo(this,_c,e4e).call(this);const t=h4(this.options.staleTime,Zs(this,kl));if(mM||Zs(this,$x).isStale||!HSe(t))return;const r=lat(Zs(this,$x).dataUpdatedAt,t)+1;qa(this,fA,setTimeout(()=>{Zs(this,$x).isStale||this.updateResult()},r))},QSe=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(Zs(this,kl)):this.options.refetchInterval)??!1},XSe=function(t){Yo(this,_c,t4e).call(this),qa(this,kS,t),!(mM||gv(this.options.enabled,Zs(this,kl))===!1||!HSe(Zs(this,kS))||Zs(this,kS)===0)&&qa(this,xA,setInterval(()=>{(this.options.refetchIntervalInBackground||jAe.isFocused())&&Yo(this,_c,l7).call(this)},Zs(this,kS)))},JSe=function(){Yo(this,_c,ZSe).call(this),Yo(this,_c,XSe).call(this,Yo(this,_c,QSe).call(this))},e4e=function(){Zs(this,fA)&&(clearTimeout(Zs(this,fA)),qa(this,fA,void 0))},t4e=function(){Zs(this,xA)&&(clearInterval(Zs(this,xA)),qa(this,xA,void 0))},s4e=function(){const t=Zs(this,Cg).getQueryCache().build(Zs(this,Cg),this.options);if(t===Zs(this,kl))return;const n=Zs(this,kl);qa(this,kl,t),qa(this,M$,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},bat=function(t){Rm.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(Zs(this,$x))}),Zs(this,Cg).getQueryCache().notify({query:Zs(this,kl),type:"observerResultsUpdated"})})},Rtt);function YPt(s,t){return gv(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&t.retryOnMount===!1)}function mze(s,t){return YPt(s,t)||s.state.data!==void 0&&n4e(s,t,t.refetchOnMount)}function n4e(s,t,n){if(gv(t.enabled,s)!==!1&&h4(t.staleTime,s)!=="static"){const r=typeof n=="function"?n(s):n;return r==="always"||r!==!1&&NAe(s,t)}return!1}function pze(s,t,n,r){return(s!==t||gv(r.enabled,s)===!1)&&(!n.suspense||s.state.status!=="error")&&NAe(s,n)}function NAe(s,t){return gv(t.enabled,s)!==!1&&s.isStaleByTime(h4(t.staleTime,s))}function ZPt(s,t){return!Kpe(s.getCurrentResult(),t)}var QPt=class extends vat{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:Zpe()})}getOptimisticResult(s){return s.behavior=Zpe(),super.getOptimisticResult(s)}fetchNextPage(s){return this.fetch({...s,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(s){return this.fetch({...s,meta:{fetchMore:{direction:"backward"}}})}createResult(s,t){var g,_;const{state:n}=s,r=super.createResult(s,t),{isFetching:a,isRefetching:i,isError:l,isRefetchError:o}=r,c=(_=(g=n.fetchMeta)==null?void 0:g.fetchMore)==null?void 0:_.direction,d=l&&c==="forward",u=a&&c==="forward",h=l&&c==="backward",p=a&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:GPt(t,n.data),hasPreviousPage:WPt(t,n.data),isFetchNextPageError:d,isFetchingNextPage:u,isFetchPreviousPageError:h,isFetchingPreviousPage:p,isRefetchError:o&&!d&&!h,isRefetching:i&&!u&&!p}}},SS,CS,Tg,M2,iN,Sme,r4e,Ott,XPt=(Ott=class extends LD{constructor(n,r){super();Ui(this,iN);Ui(this,SS);Ui(this,CS);Ui(this,Tg);Ui(this,M2);qa(this,SS,n),this.setOptions(r),this.bindMethods(),Yo(this,iN,Sme).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=Zs(this,SS).defaultMutationOptions(n),Kpe(this.options,r)||Zs(this,SS).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Zs(this,Tg),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&pM(r.mutationKey)!==pM(this.options.mutationKey)?this.reset():((a=Zs(this,Tg))==null?void 0:a.state.status)==="pending"&&Zs(this,Tg).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=Zs(this,Tg))==null||n.removeObserver(this)}onMutationUpdate(n){Yo(this,iN,Sme).call(this),Yo(this,iN,r4e).call(this,n)}getCurrentResult(){return Zs(this,CS)}reset(){var n;(n=Zs(this,Tg))==null||n.removeObserver(this),qa(this,Tg,void 0),Yo(this,iN,Sme).call(this),Yo(this,iN,r4e).call(this)}mutate(n,r){var a;return qa(this,M2,r),(a=Zs(this,Tg))==null||a.removeObserver(this),qa(this,Tg,Zs(this,SS).getMutationCache().build(Zs(this,SS),this.options)),Zs(this,Tg).addObserver(this),Zs(this,Tg).execute(n)}},SS=new WeakMap,CS=new WeakMap,Tg=new WeakMap,M2=new WeakMap,iN=new WeakSet,Sme=function(){var r;const n=((r=Zs(this,Tg))==null?void 0:r.state)??gat();qa(this,CS,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},r4e=function(n){Rm.batch(()=>{var r,a,i,l,o,c,d,u;if(Zs(this,M2)&&this.hasListeners()){const h=Zs(this,CS).variables,p=Zs(this,CS).context;(n==null?void 0:n.type)==="success"?((a=(r=Zs(this,M2)).onSuccess)==null||a.call(r,n.data,h,p),(l=(i=Zs(this,M2)).onSettled)==null||l.call(i,n.data,null,h,p)):(n==null?void 0:n.type)==="error"&&((c=(o=Zs(this,M2)).onError)==null||c.call(o,n.error,h,p),(u=(d=Zs(this,M2)).onSettled)==null||u.call(d,void 0,n.error,h,p))}this.listeners.forEach(h=>{h(Zs(this,CS))})})},Ott),_at=N.createContext(void 0),Ht=s=>{const t=N.useContext(_at);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},JPt=({client:s,children:t})=>(N.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(_at.Provider,{value:s,children:t})),wat=N.createContext(!1),eLt=()=>N.useContext(wat);wat.Provider;function tLt(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}var sLt=N.createContext(tLt()),nLt=()=>N.useContext(sLt),rLt=(s,t)=>{(s.suspense||s.throwOnError||s.experimental_prefetchInRender)&&(t.isReset()||(s.retryOnMount=!1))},aLt=s=>{N.useEffect(()=>{s.clearReset()},[s])},iLt=({result:s,errorResetBoundary:t,throwOnError:n,query:r,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&r&&(a&&s.data===void 0||uat(n,[s.error,r])),oLt=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))}},lLt=(s,t)=>s.isLoading&&s.isFetching&&!t,cLt=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,fze=(s,t,n)=>t.fetchOptimistic(s).catch(()=>{n.clearReset()});function jat(s,t,n){var h,p,f,g,_;const r=eLt(),a=nLt(),i=Ht(),l=i.defaultQueryOptions(s);(p=(h=i.getDefaultOptions().queries)==null?void 0:h._experimental_beforeQuery)==null||p.call(h,l),l._optimisticResults=r?"isRestoring":"optimistic",oLt(l),rLt(l,a),aLt(a);const o=!i.getQueryCache().get(l.queryHash),[c]=N.useState(()=>new t(i,l)),d=c.getOptimisticResult(l),u=!r&&s.subscribed!==!1;if(N.useSyncExternalStore(N.useCallback(v=>{const j=u?c.subscribe(Rm.batchCalls(v)):qx;return c.updateResult(),j},[c,u]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),N.useEffect(()=>{c.setOptions(l)},[l,c]),cLt(l,d))throw fze(l,c,a);if(iLt({result:d,errorResetBoundary:a,throwOnError:l.throwOnError,query:i.getQueryCache().get(l.queryHash),suspense:l.suspense}))throw d.error;if((g=(f=i.getDefaultOptions().queries)==null?void 0:f._experimental_afterQuery)==null||g.call(f,l,d),l.experimental_prefetchInRender&&!mM&&lLt(d,r)){const v=o?fze(l,c,a):(_=i.getQueryCache().get(l.queryHash))==null?void 0:_.promise;v==null||v.catch(qx).finally(()=>{c.updateResult()})}return l.notifyOnChangeProps?d:c.trackResult(d)}function ct(s,t){return jat(s,vat)}function gt(s,t){const n=Ht(),[r]=N.useState(()=>new XPt(n,s));N.useEffect(()=>{r.setOptions(s)},[r,s]);const a=N.useSyncExternalStore(N.useCallback(l=>r.subscribe(Rm.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=N.useCallback((l,o)=>{r.mutate(l,o).catch(qx)},[r]);if(a.error&&uat(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function dLt(s,t){return jat(s,QPt)}/** * @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 nB(){return nB=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function Nat(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function hLt(){return Math.random().toString(36).substr(2,8)}function gze(s,t){return{usr:s.state,key:s.key,idx:t}}function a4e(s,t,n,r){return n===void 0&&(n=null),nB({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?DD(t):t,{state:n,key:t&&t.key||r||hLt()})}function Qpe(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 DD(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 mLt(s,t,n,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,o=AS.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(nB({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function h(){o=AS.Pop;let v=u(),j=v==null?null:v-d;d=v,c&&c({action:o,location:_.location,delta:j})}function p(v,j){o=AS.Push;let b=a4e(_.location,v,j);d=u()+1;let S=gze(b,d),A=_.createHref(b);try{l.pushState(S,"",A)}catch(T){if(T instanceof DOMException&&T.name==="DataCloneError")throw T;a.location.assign(A)}i&&c&&c({action:o,location:_.location,delta:1})}function f(v,j){o=AS.Replace;let b=a4e(_.location,v,j);d=u();let S=gze(b,d),A=_.createHref(b);l.replaceState(S,"",A),i&&c&&c({action:o,location:_.location,delta:0})}function g(v){let j=a.location.origin!=="null"?a.location.origin:a.location.href,b=typeof v=="string"?v:Qpe(v);return b=b.replace(/ $/,"%20"),zu(j,"No window.location.(origin|href) available to create URL for href: "+b),new URL(b,j)}let _={get action(){return o},get location(){return s(a,l)},listen(v){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(xze,h),c=v,()=>{a.removeEventListener(xze,h),c=null}},createHref(v){return t(a,v)},createURL:g,encodeLocation(v){let j=g(v);return{pathname:j.pathname,search:j.search,hash:j.hash}},push:p,replace:f,go(v){return l.go(v)}};return _}var yze;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(yze||(yze={}));function pLt(s,t,n){return n===void 0&&(n="/"),fLt(s,t,n,!1)}function fLt(s,t,n,r){let a=typeof t=="string"?DD(t):t,i=g8(a.pathname||"/",n);if(i==null)return null;let l=kat(s);xLt(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("/")&&(zu(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=m4([r,c.relativePath]),u=n.concat(c);i.children&&i.children.length>0&&(zu(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),kat(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:jLt(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 Sat(i.path))a(i,l,c)}),t}function Sat(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=Sat(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 xLt(s){s.sort((t,n)=>t.score!==n.score?n.score-t.score:NLt(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const gLt=/^:[\w-]+$/,yLt=3,vLt=2,bLt=1,_Lt=10,wLt=-2,vze=s=>s==="*";function jLt(s,t){let n=s.split("/"),r=n.length;return n.some(vze)&&(r+=wLt),t&&(r+=vLt),n.filter(a=>!vze(a)).reduce((a,i)=>a+(gLt.test(i)?yLt:i===""?bLt:_Lt),r)}function NLt(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 kLt(s,t,n){let{routesMeta:r}=s,a={},i="/",l=[];for(let o=0;o{let{paramName:p,isOptional:f}=u;if(p==="*"){let _=o[h]||"";l=i.slice(0,i.length-_.length).replace(/(.)\/+$/,"$1")}const g=o[h];return f&&!g?d[p]=void 0:d[p]=(g||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:s}}function SLt(s,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Nat(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 CLt(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Nat(!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 g8(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 TLt(s,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:a=""}=typeof s=="string"?DD(s):s;return{pathname:n?n.startsWith("/")?n:ELt(n,t):t,search:ILt(r),hash:PLt(a)}}function ELt(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 $we(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 ALt(s){return s.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function kAe(s,t){let n=ALt(s);return t?n.map((r,a)=>a===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function SAe(s,t,n,r){r===void 0&&(r=!1);let a;typeof s=="string"?a=DD(s):(a=nB({},s),zu(!a.pathname||!a.pathname.includes("?"),$we("?","pathname","search",a)),zu(!a.pathname||!a.pathname.includes("#"),$we("#","pathname","hash",a)),zu(!a.search||!a.search.includes("#"),$we("#","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 p=l.split("/");for(;p[0]==="..";)p.shift(),h-=1;a.pathname=p.join("/")}o=h>=0?t[h]:"/"}let c=TLt(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const m4=s=>s.join("/").replace(/\/\/+/g,"/"),MLt=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),ILt=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,PLt=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function LLt(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const Cat=["post","put","patch","delete"];new Set(Cat);const DLt=["get",...Cat];new Set(DLt);/** * 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 rB(){return rB=Object.assign?Object.assign.bind():function(s){for(var t=1;t{o.current=!0}),N.useCallback(function(d,u){if(u===void 0&&(u={}),!o.current)return;if(typeof d=="number"){r.go(d);return}let h=SAe(d,JSON.parse(l),i,u.relative==="path");s==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:m4([t,h.pathname])),(u.replace?r.replace:r.push)(h,u.state,u)},[t,r,l,i,s])}const FLt=N.createContext(null);function zLt(s){let t=N.useContext(Kw).outlet;return t&&N.createElement(FLt.Provider,{value:s},t)}function bi(){let{matches:s}=N.useContext(Kw),t=s[s.length-1];return t?t.params:{}}function O0e(s,t){let{relative:n}=t===void 0?{}:t,{future:r}=N.useContext(jN),{matches:a}=N.useContext(Kw),{pathname:i}=Jl(),l=JSON.stringify(kAe(a,r.v7_relativeSplatPath));return N.useMemo(()=>SAe(s,JSON.parse(l),i,n==="path"),[s,l,i,n])}function BLt(s,t){return $Lt(s,t)}function $Lt(s,t,n,r){RD()||zu(!1);let{navigator:a}=N.useContext(jN),{matches:i}=N.useContext(Kw),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=Jl(),u;if(t){var h;let v=typeof t=="string"?DD(t):t;c==="/"||(h=v.pathname)!=null&&h.startsWith(c)||zu(!1),u=v}else u=d;let p=u.pathname||"/",f=p;if(c!=="/"){let v=c.replace(/^\//,"").split("/");f="/"+p.replace(/^\//,"").split("/").slice(v.length).join("/")}let g=pLt(s,{pathname:f}),_=GLt(g&&g.map(v=>Object.assign({},v,{params:Object.assign({},o,v.params),pathname:m4([c,a.encodeLocation?a.encodeLocation(v.pathname).pathname:v.pathname]),pathnameBase:v.pathnameBase==="/"?c:m4([c,a.encodeLocation?a.encodeLocation(v.pathnameBase).pathname:v.pathnameBase])})),i,n,r);return t&&_?N.createElement(R0e.Provider,{value:{location:rB({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:AS.Pop}},_):_}function ULt(){let s=ZLt(),t=LLt(s)?s.status+" "+s.statusText:s instanceof Error?s.message:JSON.stringify(s),n=s instanceof Error?s.stack:null,a={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return N.createElement(N.Fragment,null,N.createElement("h2",null,"Unexpected Application Error!"),N.createElement("h3",{style:{fontStyle:"italic"}},t),n?N.createElement("pre",{style:a},n):null,null)}const qLt=N.createElement(ULt,null);class VLt extends N.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?N.createElement(Kw.Provider,{value:this.props.routeContext},N.createElement(Eat.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function HLt(s){let{routeContext:t,match:n,children:r}=s,a=N.useContext(D0e);return a&&a.static&&a.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=n.route.id),N.createElement(Kw.Provider,{value:t},r)}function GLt(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||zu(!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,p)=>{let f,g=!1,_=null,v=null;n&&(f=o&&h.route.id?o[h.route.id]:void 0,_=h.route.errorElement||qLt,c&&(d<0&&p===0?(g=!0,v=null):d===p&&(g=!0,v=h.route.hydrateFallbackElement||null)));let j=t.concat(l.slice(0,p+1)),b=()=>{let S;return f?S=_:g?S=v:h.route.Component?S=N.createElement(h.route.Component,null):h.route.element?S=h.route.element:S=u,N.createElement(HLt,{match:h,routeContext:{outlet:u,matches:j,isDataRoute:n!=null},children:S})};return n&&(h.route.ErrorBoundary||h.route.errorElement||p===0)?N.createElement(VLt,{location:n.location,revalidation:n.revalidation,component:_,error:f,children:b(),routeContext:{outlet:null,matches:j,isDataRoute:!0}}):b()},null)}var Mat=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}(Mat||{}),Jpe=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}(Jpe||{});function WLt(s){let t=N.useContext(D0e);return t||zu(!1),t}function KLt(s){let t=N.useContext(Tat);return t||zu(!1),t}function YLt(s){let t=N.useContext(Kw);return t||zu(!1),t}function Iat(s){let t=YLt(),n=t.matches[t.matches.length-1];return n.route.id||zu(!1),n.route.id}function ZLt(){var s;let t=N.useContext(Eat),n=KLt(Jpe.UseRouteError),r=Iat(Jpe.UseRouteError);return t!==void 0?t:(s=n.errors)==null?void 0:s[r]}function QLt(){let{router:s}=WLt(Mat.UseNavigateStable),t=Iat(Jpe.UseNavigateStable),n=N.useRef(!1);return Aat(()=>{n.current=!0}),N.useCallback(function(a,i){i===void 0&&(i={}),n.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,rB({fromRouteId:t},i)))},[s,t])}function XLt(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function p4(s){let{to:t,replace:n,state:r,relative:a}=s;RD()||zu(!1);let{future:i,static:l}=N.useContext(jN),{matches:o}=N.useContext(Kw),{pathname:c}=Jl(),d=Mn(),u=SAe(t,kAe(o,i.v7_relativeSplatPath),c,a==="path"),h=JSON.stringify(u);return N.useEffect(()=>d(JSON.parse(h),{replace:n,state:r,relative:a}),[d,h,a,n,r]),null}function Pat(s){return zLt(s.context)}function as(s){zu(!1)}function JLt(s){let{basename:t="/",children:n=null,location:r,navigationType:a=AS.Pop,navigator:i,static:l=!1,future:o}=s;RD()&&zu(!1);let c=t.replace(/^\/*/,"/"),d=N.useMemo(()=>({basename:c,navigator:i,static:l,future:rB({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof r=="string"&&(r=DD(r));let{pathname:u="/",search:h="",hash:p="",state:f=null,key:g="default"}=r,_=N.useMemo(()=>{let v=g8(u,c);return v==null?null:{location:{pathname:v,search:h,hash:p,state:f,key:g},navigationType:a}},[c,u,h,p,f,g,a]);return _==null?null:N.createElement(jN.Provider,{value:d},N.createElement(R0e.Provider,{children:n,value:_}))}function efe(s){let{children:t,location:n}=s;return BLt(i4e(t),n)}new Promise(()=>{});function i4e(s,t){t===void 0&&(t=[]);let n=[];return N.Children.forEach(s,(r,a)=>{if(!N.isValidElement(r))return;let i=[...t,a];if(r.type===N.Fragment){n.push.apply(n,i4e(r.props.children,i));return}r.type!==as&&zu(!1),!r.props.index||!r.props.children||zu(!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=i4e(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 tfe(){return tfe=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&(n[a]=s[a]);return n}function e8t(s){return!!(s.metaKey||s.altKey||s.ctrlKey||s.shiftKey)}function t8t(s,t){return s.button===0&&(!t||t==="_self")&&!e8t(s)}function o4e(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 s8t(s,t){let n=o4e(s);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(i=>{n.append(a,i)})}),n}const n8t=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],r8t=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],a8t="6";try{window.__reactRouterVersion=a8t}catch{}const i8t=N.createContext({isTransitioning:!1}),o8t="startTransition",bze=pEe[o8t];function l8t(s){let{basename:t,children:n,future:r,window:a}=s,i=N.useRef();i.current==null&&(i.current=uLt({window:a,v5Compat:!0}));let l=i.current,[o,c]=N.useState({action:l.action,location:l.location}),{v7_startTransition:d}=r||{},u=N.useCallback(h=>{d&&bze?bze(()=>c(h)):c(h)},[c,d]);return N.useLayoutEffect(()=>l.listen(u),[l,u]),N.useEffect(()=>XLt(r),[r]),N.createElement(JLt,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:l,future:r})}const c8t=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",d8t=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Ln=N.forwardRef(function(t,n){let{onClick:r,relative:a,reloadDocument:i,replace:l,state:o,target:c,to:d,preventScrollReset:u,viewTransition:h}=t,p=Lat(t,n8t),{basename:f}=N.useContext(jN),g,_=!1;if(typeof d=="string"&&d8t.test(d)&&(g=d,c8t))try{let S=new URL(window.location.href),A=d.startsWith("//")?new URL(S.protocol+d):new URL(d),T=g8(A.pathname,f);A.origin===S.origin&&T!=null?d=T+A.search+A.hash:_=!0}catch{}let v=RLt(d,{relative:a}),j=h8t(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:h});function b(S){r&&r(S),S.defaultPrevented||j(S)}return N.createElement("a",tfe({},p,{href:g||v,onClick:_||i?r:b,ref:n,target:c}))}),eF=N.forwardRef(function(t,n){let{"aria-current":r="page",caseSensitive:a=!1,className:i="",end:l=!1,style:o,to:c,viewTransition:d,children:u}=t,h=Lat(t,r8t),p=O0e(c,{relative:h.relative}),f=Jl(),g=N.useContext(Tat),{navigator:_,basename:v}=N.useContext(jN),j=g!=null&&m8t(p)&&d===!0,b=_.encodeLocation?_.encodeLocation(p).pathname:p.pathname,S=f.pathname,A=g&&g.navigation&&g.navigation.location?g.navigation.location.pathname:null;a||(S=S.toLowerCase(),A=A?A.toLowerCase():null,b=b.toLowerCase()),A&&v&&(A=g8(A,v)||A);const T=b!=="/"&&b.endsWith("/")?b.length-1:b.length;let L=S===b||!l&&S.startsWith(b)&&S.charAt(T)==="/",D=A!=null&&(A===b||!l&&A.startsWith(b)&&A.charAt(b.length)==="/"),M={isActive:L,isPending:D,isTransitioning:j},F=L?r:void 0,z;typeof i=="function"?z=i(M):z=[i,L?"active":null,D?"pending":null,j?"transitioning":null].filter(Boolean).join(" ");let V=typeof o=="function"?o(M):o;return N.createElement(Ln,tfe({},h,{"aria-current":F,className:z,ref:n,style:V,to:c,viewTransition:d}),typeof u=="function"?u(M):u)});var l4e;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(l4e||(l4e={}));var _ze;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(_ze||(_ze={}));function u8t(s){let t=N.useContext(D0e);return t||zu(!1),t}function h8t(s,t){let{target:n,replace:r,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=Mn(),d=Jl(),u=O0e(s,{relative:l});return N.useCallback(h=>{if(t8t(h,n)){h.preventDefault();let p=r!==void 0?r:Qpe(d)===Qpe(u);c(s,{replace:p,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,u,r,a,n,s,i,l,o])}function gl(s){let t=N.useRef(o4e(s)),n=N.useRef(!1),r=Jl(),a=N.useMemo(()=>s8t(r.search,n.current?null:t.current),[r.search]),i=Mn(),l=N.useCallback((o,c)=>{const d=o4e(typeof o=="function"?o(a):o);n.current=!0,i("?"+d,c)},[i,a]);return[a,l]}function m8t(s,t){t===void 0&&(t={});let n=N.useContext(i8t);n==null&&zu(!1);let{basename:r}=u8t(l4e.useViewTransitionState),a=O0e(s,{relative:t.relative});if(!n.isTransitioning)return!1;let i=g8(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=g8(n.nextLocation.pathname,r)||n.nextLocation.pathname;return Xpe(a.pathname,l)!=null||Xpe(a.pathname,i)!=null}var p8t=typeof Element<"u",f8t=typeof Map=="function",x8t=typeof Set=="function",g8t=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function Cme(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(!Cme(s[r],t[r]))return!1;return!0}var i;if(f8t&&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(!Cme(r.value[1],t.get(r.value[0])))return!1;return!0}if(x8t&&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(g8t&&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(p8t&&s instanceof Element)return!1;for(r=n;r--!==0;)if(!((a[r]==="_owner"||a[r]==="__v"||a[r]==="__o")&&s.$$typeof)&&!Cme(s[a[r]],t[a[r]]))return!1;return!0}return s!==s&&t!==t}var y8t=function(t,n){try{return Cme(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 v8t=wl(y8t);var b8t=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}},_8t=b8t;const wze=wl(_8t);var w8t=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))(Dat||{}),Uwe={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"]}},jze=Object.values(Dat),CAe={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},N8t=Object.entries(CAe).reduce((s,[t,n])=>(s[n]=t,s),{}),lb="data-rh",CL={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},TL=(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},k8t=s=>{let t=TL(s,"title");const n=TL(s,CL.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),n&&t)return n.replace(/%s/g,()=>t);const r=TL(s,CL.DEFAULT_TITLE);return t||r||void 0},S8t=s=>TL(s,CL.ON_CHANGE_CLIENT_STATE)||(()=>{}),qwe=(s,t)=>t.filter(n=>typeof n[s]<"u").map(n=>n[s]).reduce((n,r)=>({...n,...r}),{}),C8t=(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),tF=(s,t,n)=>{const r={};return n.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&T8t(`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 p=0;pa.push(c));const o=Object.keys(l);for(let c=0;c{if(Array.isArray(s)&&s.length){for(let n=0;n({baseTag:C8t(["href"],s),bodyAttributes:qwe("bodyAttributes",s),defer:TL(s,CL.DEFER),encode:TL(s,CL.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:qwe("htmlAttributes",s),linkTags:tF("link",["rel","href"],s),metaTags:tF("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:tF("noscript",["innerHTML"],s),onChangeClientState:S8t(s),scriptTags:tF("script",["src","innerHTML"],s),styleTags:tF("style",["cssText"],s),title:k8t(s),titleAttributes:qwe("titleAttributes",s),prioritizeSeoTags:E8t(s,CL.PRIORITIZE_SEO_TAGS)}),Rat=s=>Array.isArray(s)?s.join(""):s,M8t=(s,t)=>{const n=Object.keys(s);for(let r=0;rArray.isArray(s)?s.reduce((n,r)=>(M8t(r,t)?n.priority.push(r):n.default.push(r),n),{priority:[],default:[]}):{default:s,priority:[]},Nze=(s,t)=>({...s,[t]:void 0}),I8t=["noscript","script","style"],c4e=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),Oat=s=>Object.keys(s).reduce((t,n)=>{const r=typeof s[n]<"u"?`${n}="${s[n]}"`:`${n}`;return t?`${t} ${r}`:r},""),P8t=(s,t,n,r)=>{const a=Oat(n),i=Rat(t);return a?`<${s} ${lb}="true" ${a}>${c4e(i,r)}`:`<${s} ${lb}="true">${c4e(i,r)}`},L8t=(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}="${c4e(i[u],n)}"`;return d?`${d} ${h}`:h},""),o=i.innerHTML||i.cssText||"",c=I8t.indexOf(s)===-1;return`${r}<${s} ${lb}="true" ${l}${c?"/>":`>${o}`}`},""),Fat=(s,t={})=>Object.keys(s).reduce((n,r)=>{const a=CAe[r];return n[a||r]=s[r],n},t),D8t=(s,t,n)=>{const r={key:t,[lb]:!0},a=Fat(n,r);return[St.createElement("title",a,t)]},Tme=(s,t)=>t.map((n,r)=>{const a={key:r,[lb]:!0};return Object.keys(n).forEach(i=>{const o=CAe[i]||i;if(o==="innerHTML"||o==="cssText"){const c=n.innerHTML||n.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=n[i]}),St.createElement(s,a)}),fv=(s,t,n=!0)=>{switch(s){case"title":return{toComponent:()=>D8t(s,t.title,t.titleAttributes),toString:()=>P8t(s,t.title,t.titleAttributes,n)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>Fat(t),toString:()=>Oat(t)};default:return{toComponent:()=>Tme(s,t),toString:()=>L8t(s,t,n)}}},R8t=({metaTags:s,linkTags:t,scriptTags:n,encode:r})=>{const a=Vwe(s,Uwe.meta),i=Vwe(t,Uwe.link),l=Vwe(n,Uwe.script);return{priorityMethods:{toComponent:()=>[...Tme("meta",a.priority),...Tme("link",i.priority),...Tme("script",l.priority)],toString:()=>`${fv("meta",a.priority,r)} ${fv("link",i.priority,r)} ${fv("script",l.priority,r)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},O8t=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:p}=s,f={toComponent:()=>{},toString:()=>""};return d&&({priorityMethods:f,linkTags:u,metaTags:h,scriptTags:p}=R8t(s)),{priority:f,base:fv("base",t,r),bodyAttributes:fv("bodyAttributes",n,r),htmlAttributes:fv("htmlAttributes",a,r),link:fv("link",u,r),meta:fv("meta",h,r),noscript:fv("noscript",i,r),script:fv("script",p,r),style:fv("style",l,r),title:fv("title",{title:o,titleAttributes:c},r)}},d4e=O8t,VV=[],zat=!!(typeof window<"u"&&window.document&&window.document.createElement),u4e=class{constructor(s,t){Ma(this,"instances",[]);Ma(this,"canUseDOM",zat);Ma(this,"context");Ma(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?VV:this.instances,add:s=>{(this.canUseDOM?VV:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?VV:this.instances).indexOf(s);(this.canUseDOM?VV:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=d4e({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},F8t={},Bat=St.createContext(F8t),gA,$at=(gA=class extends N.Component{constructor(n){super(n);Ma(this,"helmetData");this.helmetData=new u4e(this.props.context||{},gA.canUseDOM)}render(){return St.createElement(Bat.Provider,{value:this.helmetData.value},this.props.children)}},Ma(gA,"canUseDOM",zat),gA),uI=(s,t)=>{const n=document.head||document.querySelector("head"),r=n.querySelectorAll(`${s}[${lb}]`),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(lb,"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}},h4e=(s,t)=>{const n=document.getElementsByTagName(s)[0];if(!n)return;const r=n.getAttribute(lb),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(lb):n.getAttribute(lb)!==l.join(",")&&n.setAttribute(lb,l.join(","))},z8t=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=Rat(s)),h4e("title",t)},kze=(s,t)=>{const{baseTag:n,bodyAttributes:r,htmlAttributes:a,linkTags:i,metaTags:l,noscriptTags:o,onChangeClientState:c,scriptTags:d,styleTags:u,title:h,titleAttributes:p}=s;h4e("body",r),h4e("html",a),z8t(h,p);const f={baseTag:uI("base",n),linkTags:uI("link",i),metaTags:uI("meta",l),noscriptTags:uI("noscript",o),scriptTags:uI("script",d),styleTags:uI("style",u)},g={},_={};Object.keys(f).forEach(v=>{const{newTags:j,oldTags:b}=f[v];j.length&&(g[v]=j),b.length&&(_[v]=f[v].oldTags)}),t&&t(),c(s,g,_)},sF=null,B8t=s=>{sF&&cancelAnimationFrame(sF),s.defer?sF=requestAnimationFrame(()=>{kze(s,()=>{sF=null})}):(kze(s),sF=null)},$8t=B8t,Sze=class extends N.Component{constructor(){super(...arguments);Ma(this,"rendered",!1)}shouldComponentUpdate(t){return!j8t(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=A8t(t.get().map(i=>{const l={...i.props};return delete l.context,l}));$at.canUseDOM?$8t(a):d4e&&(r=d4e(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}},Bke,Go=(Bke=class extends N.Component{shouldComponentUpdate(s){return!v8t(Nze(this.props,"helmetData"),Nze(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 wze(jze.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 ${jze.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),wze(!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 St.Children.forEach(s,r=>{if(!r||!r.props)return;const{children:a,...i}=r.props,l=Object.keys(i).reduce((c,d)=>(c[N8t[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 u4e)){const a=r;r=new u4e(a.context,!0),delete n.helmetData}return r?St.createElement(Sze,{...n,context:r.value}):St.createElement(Bat.Consumer,null,a=>St.createElement(Sze,{...n,context:a}))}},Ma(Bke,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),Bke);const U8t=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>yi(async()=>{const{default:r}=await Promise.resolve().then(()=>OD);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class TAe extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class q8t extends TAe{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class V8t extends TAe{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class H8t extends TAe{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var m4e;(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"})(m4e||(m4e={}));var G8t=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 W8t{constructor(t,{headers:n={},customFetch:r,region:a=m4e.Any}={}){this.url=t,this.headers=n,this.region=a,this.fetch=U8t(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return G8t(this,void 0,void 0,function*(){try{const{headers:a,method:i,body:l}=n;let o={},{region:c}=n;c||(c=this.region),c&&c!=="any"&&(o["x-region"]=c);let d;l&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)&&(typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer?(o["Content-Type"]="application/octet-stream",d=l):typeof l=="string"?(o["Content-Type"]="text/plain",d=l):typeof FormData<"u"&&l instanceof FormData?d=l:(o["Content-Type"]="application/json",d=JSON.stringify(l)));const u=yield this.fetch(`${this.url}/${t}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},o),this.headers),a),body:d}).catch(g=>{throw new q8t(g)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new V8t(u);if(!u.ok)throw new H8t(u);let p=((r=u.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),f;return p==="application/json"?f=yield u.json():p==="application/octet-stream"?f=yield u.blob():p==="text/event-stream"?f=u:p==="multipart/form-data"?f=yield u.formData():f=yield u.text(),{data:f,error:null}}catch(a){return{data:null,error:a}}})}}var Pg={},EAe={},F0e={},V$={},z0e={},B0e={},K8t=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")},y8=K8t();const Y8t=y8.fetch,Uat=y8.fetch.bind(y8),qat=y8.Headers,Z8t=y8.Request,Q8t=y8.Response,OD=Object.freeze(Object.defineProperty({__proto__:null,Headers:qat,Request:Z8t,Response:Q8t,default:Uat,fetch:Y8t},Symbol.toStringTag,{value:"Module"})),X8t=kTt(OD);var $0e={};Object.defineProperty($0e,"__esModule",{value:!0});let J8t=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};$0e.default=J8t;var Vat=Eh&&Eh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(B0e,"__esModule",{value:!0});const eDt=Vat(X8t),tDt=Vat($0e);let sDt=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=eDt.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,p=i.status,f=i.statusText;if(i.ok){if(this.method!=="HEAD"){const j=await i.text();j===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=j:u=JSON.parse(j))}const _=(l=this.headers.Prefer)===null||l===void 0?void 0:l.match(/count=(exact|planned|estimated)/),v=(o=i.headers.get("content-range"))===null||o===void 0?void 0:o.split("/");_&&v&&v.length>1&&(h=parseInt(v[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(d={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,h=null,p=406,f="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{const _=await i.text();try{d=JSON.parse(_),Array.isArray(d)&&i.status===404&&(u=[],d=null,p=200,f="OK")}catch{i.status===404&&_===""?(p=204,f="No Content"):d={message:_}}if(d&&this.isMaybeSingle&&(!((c=d==null?void 0:d.details)===null||c===void 0)&&c.includes("0 rows"))&&(d=null,p=200,f="OK"),d&&this.shouldThrowOnError)throw new tDt.default(d)}return{error:d,data:u,count:h,status:p,statusText:f}});return this.shouldThrowOnError||(a=a.catch(i=>{var l,o,c;return{error:{message:`${(l=i==null?void 0:i.name)!==null&&l!==void 0?l:"FetchError"}: ${i==null?void 0:i.message}`,details:`${(o=i==null?void 0:i.stack)!==null&&o!==void 0?o:""}`,hint:"",code:`${(c=i==null?void 0:i.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),a.then(t,n)}returns(){return this}overrideTypes(){return this}};B0e.default=sDt;var nDt=Eh&&Eh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(z0e,"__esModule",{value:!0});const rDt=nDt(B0e);let aDt=class extends rDt.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}};z0e.default=aDt;var iDt=Eh&&Eh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(V$,"__esModule",{value:!0});const oDt=iDt(z0e);let lDt=class extends oDt.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}};V$.default=lDt;var cDt=Eh&&Eh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(F0e,"__esModule",{value:!0});const nF=cDt(V$);let dDt=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 nF.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 nF.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 nF.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 nF.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 nF.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};F0e.default=dDt;var U0e={},q0e={};Object.defineProperty(q0e,"__esModule",{value:!0});q0e.version=void 0;q0e.version="0.0.0-automated";Object.defineProperty(U0e,"__esModule",{value:!0});U0e.DEFAULT_HEADERS=void 0;const uDt=q0e;U0e.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${uDt.version}`};var Hat=Eh&&Eh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(EAe,"__esModule",{value:!0});const hDt=Hat(F0e),mDt=Hat(V$),pDt=U0e;let fDt=class Gat{constructor(t,{headers:n={},schema:r,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},pDt.DEFAULT_HEADERS),n),this.schemaName=r,this.fetch=a}from(t){const n=new URL(`${this.url}/${t}`);return new hDt.default(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new Gat(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 mDt.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};EAe.default=fDt;var FD=Eh&&Eh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Pg,"__esModule",{value:!0});Pg.PostgrestError=Pg.PostgrestBuilder=Pg.PostgrestTransformBuilder=Pg.PostgrestFilterBuilder=Pg.PostgrestQueryBuilder=Pg.PostgrestClient=void 0;const Wat=FD(EAe);Pg.PostgrestClient=Wat.default;const Kat=FD(F0e);Pg.PostgrestQueryBuilder=Kat.default;const Yat=FD(V$);Pg.PostgrestFilterBuilder=Yat.default;const Zat=FD(z0e);Pg.PostgrestTransformBuilder=Zat.default;const Qat=FD(B0e);Pg.PostgrestBuilder=Qat.default;const Xat=FD($0e);Pg.PostgrestError=Xat.default;var xDt=Pg.default={PostgrestClient:Wat.default,PostgrestQueryBuilder:Kat.default,PostgrestFilterBuilder:Yat.default,PostgrestTransformBuilder:Zat.default,PostgrestBuilder:Qat.default,PostgrestError:Xat.default};const{PostgrestClient:gDt,PostgrestQueryBuilder:xxn,PostgrestFilterBuilder:gxn,PostgrestTransformBuilder:yxn,PostgrestBuilder:vxn,PostgrestError:bxn}=xDt;let p4e;typeof window>"u"?p4e=require("ws"):p4e=window.WebSocket;const yDt=p4e,vDt="2.11.10",bDt={"X-Client-Info":`realtime-js/${vDt}`},_Dt="1.0.0",Jat=1e4,wDt=1e3;var EL;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(EL||(EL={}));var zx;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(zx||(zx={}));var Y1;(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"})(Y1||(Y1={}));var f4e;(function(s){s.websocket="websocket"})(f4e||(f4e={}));var zE;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(zE||(zE={}));class jDt{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 eit{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 fd;(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"})(fd||(fd={}));const Cze=(s,t,n={})=>{var r;const a=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((i,l)=>(i[l]=NDt(l,s,t,a),i),{})},NDt=(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)?tit(i,l):x4e(l)},tit=(s,t)=>{if(s.charAt(0)==="_"){const n=s.slice(1,s.length);return TDt(t,n)}switch(s){case fd.bool:return kDt(t);case fd.float4:case fd.float8:case fd.int2:case fd.int4:case fd.int8:case fd.numeric:case fd.oid:return SDt(t);case fd.json:case fd.jsonb:return CDt(t);case fd.timestamp:return EDt(t);case fd.abstime:case fd.date:case fd.daterange:case fd.int4range:case fd.int8range:case fd.money:case fd.reltime:case fd.text:case fd.time:case fd.timestamptz:case fd.timetz:case fd.tsrange:case fd.tstzrange:return x4e(t);default:return x4e(t)}},x4e=s=>s,kDt=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},SDt=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},CDt=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},TDt=(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=>tit(t,o))}return s},EDt=s=>typeof s=="string"?s.replace(" ","T"):s,sit=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class Hwe{constructor(t,n,r={},a=Jat){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 Tze;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Tze||(Tze={}));class q9{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=q9.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=q9.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=q9.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 p=u.map(v=>v.presence_ref),f=h.map(v=>v.presence_ref),g=u.filter(v=>f.indexOf(v.presence_ref)<0),_=h.filter(v=>p.indexOf(v.presence_ref)<0);g.length>0&&(o[d]=g),_.length>0&&(c[d]=_)}else o[d]=u}),this.syncDiff(i,{joins:o,leaves:c},r,a)}static syncDiff(t,n,r,a){const{joins:i,leaves:l}={joins:this.transformState(n.joins),leaves:this.transformState(n.leaves)};return r||(r=()=>{}),a||(a=()=>{}),this.map(i,(o,c)=>{var d;const u=(d=t[o])!==null&&d!==void 0?d:[];if(t[o]=this.cloneDeep(c),u.length>0){const h=t[o].map(f=>f.presence_ref),p=u.filter(f=>h.indexOf(f.presence_ref)<0);t[o].unshift(...p)}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 Eze;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Eze||(Eze={}));var Aze;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(Aze||(Aze={}));var _2;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(_2||(_2={}));class AAe{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=zx.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 Hwe(this,Y1.join,this.params,this.timeout),this.rejoinTimer=new eit(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=zx.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=zx.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=zx.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=zx.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Y1.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new q9(this),this.broadcastEndpointURL=sit(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(_2.CHANNEL_ERROR,u)),this._onClose(()=>t==null?void 0:t(_2.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(_2.SUBSCRIBED);return}else{const p=this.bindings.postgres_changes,f=(h=p==null?void 0:p.length)!==null&&h!==void 0?h:0,g=[];for(let _=0;_{this.state=zx.errored,t==null||t(_2.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(_2.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=zx.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Y1.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(r=>{const a=new Hwe(this,Y1.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 Hwe(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}=Y1;if(r&&[o,c,d,u].indexOf(l)>=0&&r!==this._joinRef())return;let p=this._onMessage(l,n,r);if(n&&!p)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(l)?(a=this.bindings.postgres_changes)===null||a===void 0||a.filter(f=>{var g,_,v;return((g=f.filter)===null||g===void 0?void 0:g.event)==="*"||((v=(_=f.filter)===null||_===void 0?void 0:_.event)===null||v===void 0?void 0:v.toLocaleLowerCase())===l}).map(f=>f.callback(p,r)):(i=this.bindings[l])===null||i===void 0||i.filter(f=>{var g,_,v,j,b,S;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in f){const A=f.id,T=(g=f.filter)===null||g===void 0?void 0:g.event;return A&&((_=n.ids)===null||_===void 0?void 0:_.includes(A))&&(T==="*"||(T==null?void 0:T.toLocaleLowerCase())===((v=n.data)===null||v===void 0?void 0:v.type.toLocaleLowerCase()))}else{const A=(b=(j=f==null?void 0:f.filter)===null||j===void 0?void 0:j.event)===null||b===void 0?void 0:b.toLocaleLowerCase();return A==="*"||A===((S=n==null?void 0:n.event)===null||S===void 0?void 0:S.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===l}).map(f=>{if(typeof p=="object"&&"ids"in p){const g=p.data,{schema:_,table:v,commit_timestamp:j,type:b,errors:S}=g;p=Object.assign(Object.assign({},{schema:_,table:v,commit_timestamp:j,eventType:b,new:{},old:{},errors:S}),this._getPayloadRecords(g))}f.callback(p,r)})}_isClosed(){return this.state===zx.closed}_isJoined(){return this.state===zx.joined}_isJoining(){return this.state===zx.joining}_isLeaving(){return this.state===zx.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&&AAe.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(Y1.close,{},t)}_onError(t){this._on(Y1.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=zx.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=Cze(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=Cze(t.columns,t.old_record)),n}}const Mze=()=>{},ADt=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class MDt{constructor(t,n){var r;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=bDt,this.params={},this.timeout=Jat,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Mze,this.ref=0,this.logger=Mze,this.conn=null,this.sendBuffer=[],this.serializer=new jDt,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let l;return i?l=i:typeof fetch>"u"?l=(...o)=>yi(async()=>{const{default:c}=await Promise.resolve().then(()=>OD);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${f4e.websocket}`,this.httpEndpoint=sit(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 eit(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=yDt),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 IDt(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:_Dt}))}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 EL.connecting:return zE.Connecting;case EL.open:return zE.Open;case EL.closing:return zE.Closing;default:return zE.Closed}}isConnected(){return this.connectionState()===zE.Open}channel(t,n={config:{}}){const r=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===r);if(a)return a;{const i=new AAe(`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(Y1.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(wDt,"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(Y1.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([ADt],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}}class IDt{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=EL.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class MAe extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function yp(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class PDt extends MAe{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class g4e extends MAe{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var LDt=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 nit=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>yi(async()=>{const{default:r}=await Promise.resolve().then(()=>OD);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},DDt=()=>LDt(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield yi(()=>Promise.resolve().then(()=>OD),void 0)).Response:Response}),y4e=s=>{if(Array.isArray(s))return s.map(n=>y4e(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]=y4e(r)}),t};var qM=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 Gwe=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),RDt=(s,t,n)=>qM(void 0,void 0,void 0,function*(){const r=yield DDt();s instanceof r&&!(n!=null&&n.noResolveJson)?s.json().then(a=>{t(new PDt(Gwe(a),s.status||500))}).catch(a=>{t(new g4e(Gwe(a),a))}):t(new g4e(Gwe(s),s))}),ODt=(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 H$(s,t,n,r,a,i){return qM(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(n,ODt(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=>RDt(c,o,r))})})}function sfe(s,t,n,r){return qM(this,void 0,void 0,function*(){return H$(s,"GET",t,n,r)})}function Zk(s,t,n,r,a){return qM(this,void 0,void 0,function*(){return H$(s,"POST",t,r,a,n)})}function FDt(s,t,n,r,a){return qM(this,void 0,void 0,function*(){return H$(s,"PUT",t,r,a,n)})}function zDt(s,t,n,r){return qM(this,void 0,void 0,function*(){return H$(s,"HEAD",t,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}function rit(s,t,n,r,a){return qM(this,void 0,void 0,function*(){return H$(s,"DELETE",t,r,a,n)})}var jg=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 BDt={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ize={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class $Dt{constructor(t,n={},r,a){this.url=t,this.headers=n,this.bucketId=r,this.fetch=nit(a)}uploadOrUpdate(t,n,r,a){return jg(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},Ize),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}:{})),p=yield h.json();return h.ok?{data:{path:d,id:p.Id,fullPath:p.Key},error:null}:{data:null,error:p}}catch(i){if(yp(i))return{data:null,error:i};throw i}})}upload(t,n,r){return jg(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,a){return jg(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:Ize.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}),p=yield h.json();return h.ok?{data:{path:i,fullPath:p.Key},error:null}:{data:null,error:p}}catch(c){if(yp(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,n){return jg(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 Zk(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 MAe("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(r){if(yp(r))return{data:null,error:r};throw r}})}update(t,n,r){return jg(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n,r){return jg(this,void 0,void 0,function*(){try{return{data:yield Zk(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(yp(a))return{data:null,error:a};throw a}})}copy(t,n,r){return jg(this,void 0,void 0,function*(){try{return{data:{path:(yield Zk(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(yp(a))return{data:null,error:a};throw a}})}createSignedUrl(t,n,r){return jg(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield Zk(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(yp(a))return{data:null,error:a};throw a}})}createSignedUrls(t,n,r){return jg(this,void 0,void 0,function*(){try{const a=yield Zk(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(yp(a))return{data:null,error:a};throw a}})}download(t,n){return jg(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 sfe(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(yp(o))return{data:null,error:o};throw o}})}info(t){return jg(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{const r=yield sfe(this.fetch,`${this.url}/object/info/${n}`,{headers:this.headers});return{data:y4e(r),error:null}}catch(r){if(yp(r))return{data:null,error:r};throw r}})}exists(t){return jg(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{return yield zDt(this.fetch,`${this.url}/object/${n}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(yp(r)&&r instanceof g4e){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 jg(this,void 0,void 0,function*(){try{return{data:yield rit(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(yp(n))return{data:null,error:n};throw n}})}list(t,n,r){return jg(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},BDt),n),{prefix:t||""});return{data:yield Zk(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},r),error:null}}catch(a){if(yp(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 UDt="2.7.1",qDt={"X-Client-Info":`storage-js/${UDt}`};var hI=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 VDt{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},qDt),n),this.fetch=nit(r)}listBuckets(){return hI(this,void 0,void 0,function*(){try{return{data:yield sfe(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(yp(t))return{data:null,error:t};throw t}})}getBucket(t){return hI(this,void 0,void 0,function*(){try{return{data:yield sfe(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(yp(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return hI(this,void 0,void 0,function*(){try{return{data:yield Zk(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(yp(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return hI(this,void 0,void 0,function*(){try{return{data:yield FDt(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(yp(r))return{data:null,error:r};throw r}})}emptyBucket(t){return hI(this,void 0,void 0,function*(){try{return{data:yield Zk(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(yp(n))return{data:null,error:n};throw n}})}deleteBucket(t){return hI(this,void 0,void 0,function*(){try{return{data:yield rit(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(yp(n))return{data:null,error:n};throw n}})}}class HDt extends VDt{constructor(t,n={},r){super(t,n,r)}from(t){return new $Dt(this.url,this.headers,t,this.fetch)}}const GDt="2.49.10";let c7="";typeof Deno<"u"?c7="deno":typeof document<"u"?c7="web":typeof navigator<"u"&&navigator.product==="ReactNative"?c7="react-native":c7="node";const WDt={"X-Client-Info":`supabase-js-${c7}/${GDt}`},KDt={headers:WDt},YDt={schema:"public"},ZDt={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},QDt={};var XDt=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 JDt=s=>{let t;return s?t=s:typeof fetch>"u"?t=Uat:t=fetch,(...n)=>t(...n)},eRt=()=>typeof Headers>"u"?qat:Headers,tRt=(s,t,n)=>{const r=JDt(n),a=eRt();return(i,l)=>XDt(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 sRt=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 nRt(s){return s.endsWith("/")?s:s+"/"}function rRt(s,t){var n,r;const{db:a,auth:i,realtime:l,global:o}=s,{db:c,auth:d,realtime:u,global:h}=t,p={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:()=>sRt(this,void 0,void 0,function*(){return""})};return s.accessToken?p.accessToken=s.accessToken:delete p.accessToken,p}const ait="2.69.1",nP=30*1e3,v4e=3,Wwe=v4e*nP,aRt="http://localhost:9999",iRt="supabase.auth.token",oRt={"X-Client-Info":`gotrue-js/${ait}`},b4e="X-Supabase-Api-Version",iit={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},lRt=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,cRt=6e5;class IAe extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function Uo(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class dRt extends IAe{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function uRt(s){return Uo(s)&&s.name==="AuthApiError"}class oit extends IAe{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class G4 extends IAe{constructor(t,n,r,a){super(t,r,a),this.name=n,this.status=r}}class Ok extends G4{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function hRt(s){return Uo(s)&&s.name==="AuthSessionMissingError"}class Kwe extends G4{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class HV extends G4{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class GV extends G4{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 mRt(s){return Uo(s)&&s.name==="AuthImplicitGrantRedirectError"}class Pze extends G4{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 _4e extends G4{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function Ywe(s){return Uo(s)&&s.name==="AuthRetryableFetchError"}class Lze extends G4{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class V9 extends G4{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const Dze="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Rze=` \r=`.split(""),pRt=(()=>{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 Oze(s){const t=[],n=l=>{t.push(String.fromCodePoint(l))},r={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{gRt(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 xRt(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}fRt(r,t)}}function gRt(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 yRt(s){const t=[],n={queue:0,queuedBits:0},r=a=>{t.push(a)};for(let a=0;at.push(n)),new Uint8Array(t)}function bRt(s){return Math.round(Date.now()/1e3)+s}function _Rt(){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 D_=()=>typeof window<"u"&&typeof document<"u",l3={tested:!1,writable:!1},H9=()=>{if(!D_())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(l3.tested)return l3.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),l3.tested=!0,l3.writable=!0}catch{l3.tested=!0,l3.writable=!1}return l3.writable};function wRt(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 cit=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>yi(async()=>{const{default:r}=await Promise.resolve().then(()=>OD);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},jRt=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",dit=async(s,t,n)=>{await s.setItem(t,JSON.stringify(n))},WV=async(s,t)=>{const n=await s.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},KV=async(s,t)=>{await s.removeItem(t)};class V0e{constructor(){this.promise=new V0e.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}V0e.promiseConstructor=Promise;function Zwe(s){const t=s.split(".");if(t.length!==3)throw new V9("Invalid JWT structure");for(let r=0;r{setTimeout(()=>t(null),s)})}function kRt(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 SRt(s){return("0"+s.toString(16)).substr(-2)}function CRt(){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,SRt).join("")}async function TRt(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 ERt(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 TRt(s);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function mI(s,t,n=!1){const r=CRt();let a=r;n&&(a+="/PASSWORD_RECOVERY"),await dit(s,`${t}-code-verifier`,a);const i=await ERt(r);return[i,r===i?"plain":"s256"]}const ARt=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function MRt(s){const t=s.headers.get(b4e);if(!t||!t.match(ARt))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function IRt(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 PRt(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 LRt=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),DRt=[502,503,504];async function Fze(s){var t;if(!jRt(s))throw new _4e(EE(s),0);if(DRt.includes(s.status))throw new _4e(EE(s),s.status);let n;try{n=await s.json()}catch(i){throw new oit(EE(i),i)}let r;const a=MRt(s);if(a&&a.getTime()>=iit["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 Lze(EE(n),s.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new Ok}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 Lze(EE(n),s.status,n.weak_password.reasons);throw new dRt(EE(n),s.status||500,r)}const RRt=(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 _l(s,t,n,r){var a;const i=Object.assign({},r==null?void 0:r.headers);i[b4e]||(i[b4e]=iit["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 ORt(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 ORt(s,t,n,r,a,i){const l=RRt(t,r,a,i);let o;try{o=await s(n,Object.assign({},l))}catch(c){throw console.error(c),new _4e(EE(c),0)}if(o.ok||await Fze(o),r!=null&&r.noResolveJson)return o;try{return await o.json()}catch(c){await Fze(c)}}function Fk(s){var t;let n=null;$Rt(s)&&(n=Object.assign({},s),s.expires_at||(n.expires_at=bRt(s.expires_in)));const r=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:n,user:r},error:null}}function zze(s){const t=Fk(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 uS(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function FRt(s){return{data:s,error:null}}function zRt(s){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i}=s,l=LRt(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 BRt(s){return s}function $Rt(s){return s.access_token&&s.refresh_token&&s.expires_in}var URt=function(s,t){var n={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(s);a0&&(f.forEach(g=>{const _=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),v=JSON.parse(g.split(";")[1].split("=")[1]);d[`${v}Page`]=_}),d.total=parseInt(p)),{data:Object.assign(Object.assign({},h),d),error:null}}catch(d){if(Uo(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await _l(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:uS})}catch(n){if(Uo(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await _l(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:uS})}catch(r){if(Uo(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await _l(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:uS})}catch(r){if(Uo(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await _l(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(Uo(n))return{data:null,error:n};throw n}}async _deleteFactor(t){try{return{data:await _l(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(Uo(n))return{data:null,error:n};throw n}}}const VRt={getItem:s=>H9()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{H9()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{H9()&&globalThis.localStorage.removeItem(s)}};function Bze(s={}){return{getItem:t=>s[t]||null,setItem:(t,n)=>{s[t]=n},removeItem:t=>{delete s[t]}}}function HRt(){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 pI={debug:!!(globalThis&&H9()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class uit extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class GRt extends uit{}async function WRt(s,t,n){pI.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),pI.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){pI.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await n()}finally{pI.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(t===0)throw pI.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new GRt(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(pI.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()}}))}HRt();const KRt={url:aRt,storageKey:iRt,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:oRt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function $ze(s,t,n){return await n()}class aB{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=aB.nextInstanceID,aB.nextInstanceID+=1,this.instanceID>0&&D_()&&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({},KRt),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 qRt({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=cit(a.fetch),this.lock=a.lock||$ze,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:D_()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=WRt:this.lock=$ze,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:H9()?this.storage=VRt:(this.memoryStorage={},this.storage=Bze(this.memoryStorage)):(this.memoryStorage={},this.storage=Bze(this.memoryStorage)),D_()&&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} (${ait}) ${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=wRt(window.location.href);let r="none";if(this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce"),D_()&&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),mRt(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 Uo(n)?{error:n}:{error:new oit("Unexpected error during initialization",n)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,a;try{const i=await _l(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:Fk}),{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(Uo(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:p}=t;let f=null,g=null;this.flowType==="pkce"&&([f,g]=await mI(this.storage,this.storageKey)),i=await _l(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p==null?void 0:p.emailRedirectTo,body:{email:u,password:h,data:(n=p==null?void 0:p.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken},code_challenge:f,code_challenge_method:g},xform:Fk})}else if("phone"in t){const{phone:u,password:h,options:p}=t;i=await _l(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:h,data:(r=p==null?void 0:p.data)!==null&&r!==void 0?r:{},channel:(a=p==null?void 0:p.channel)!==null&&a!==void 0?a:"sms",gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken}},xform:Fk})}else throw new HV("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(Uo(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 _l(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:zze})}else if("phone"in t){const{phone:i,password:l,options:o}=t;n=await _l(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:zze})}else throw new HV("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 Kwe}:(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(Uo(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 WV(this.storage,`${this.storageKey}-code-verifier`),[r,a]=(n??"").split("/");try{const{data:i,error:l}=await _l(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:Fk});if(await KV(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Kwe}:(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(Uo(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 _l(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:Fk}),{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 Kwe}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(n){if(Uo(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 mI(this.storage,this.storageKey));const{error:h}=await _l(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 _l(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 HV("You must provide either an email or phone number.")}catch(o){if(Uo(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 _l(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:Fk});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(Uo(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 mI(this.storage,this.storageKey)),await _l(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:FRt})}catch(i){if(Uo(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 Ok;const{error:a}=await _l(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:a}})}catch(t){if(Uo(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 _l(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 _l(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 HV("You must provide either an email or phone number and a type")}catch(n){if(Uo(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 WV(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 _l(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:uS}):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 Ok}:await _l(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:uS})})}catch(n){if(Uo(n))return hRt(n)&&(await this._removeSession(),await KV(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 Ok;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await mI(this.storage,this.storageKey));const{data:d,error:u}=await _l(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:uS});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(Uo(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 Ok;const n=Date.now()/1e3;let r=n,a=!0,i=null;const{payload:l}=Zwe(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(Uo(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 Ok;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(Uo(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(t,n){try{if(!D_())throw new GV("No browser detected.");if(t.error||t.error_description||t.error_code)throw new GV(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 Pze("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new GV("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 Pze("No code detected.");const{data:b,error:S}=await this._exchangeCodeForSession(t.code);if(S)throw S;const A=new URL(window.location.href);return A.searchParams.delete("code"),window.history.replaceState(window.history.state,"",A.toString()),{data:{session:b.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:a,access_token:i,refresh_token:l,expires_in:o,expires_at:c,token_type:d}=t;if(!i||!o||!l||!d)throw new GV("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(o);let p=u+h;c&&(p=parseInt(c));const f=p-u;f*1e3<=nP&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${h}s`);const g=p-h;u-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,p,u):u-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,p,u);const{data:_,error:v}=await this._getUser(i);if(v)throw v;const j={provider_token:r,provider_refresh_token:a,access_token:i,expires_in:h,expires_at:p,refresh_token:l,token_type:d,user:_.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:j,redirectType:t.type},error:null}}catch(r){if(Uo(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 WV(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&&!(uRt(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await KV(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const n=_Rt(),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 mI(this.storage,this.storageKey,!0));try{return await _l(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(Uo(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(Uo(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:p}=i;if(p)throw p;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(l=t.options)===null||l===void 0?void 0:l.redirectTo,scopes:(o=t.options)===null||o===void 0?void 0:o.scopes,queryParams:(c=t.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await _l(this.fetch,"GET",f,{headers:this.headers,jwt:(u=(d=h.session)===null||d===void 0?void 0:d.access_token)!==null&&u!==void 0?u:void 0})});if(a)throw a;return D_()&&!(!((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(Uo(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 _l(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(Uo(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 kRt(async a=>(a>0&&await NRt(200*Math.pow(2,a-1)),this._debug(n,"refreshing attempt",a),await _l(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:Fk})),(a,i)=>{const l=200*Math.pow(2,a);return i&&Ywe(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(),nP);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)/nP);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${nP}ms, refresh threshold is ${v4e} ticks`),a<=v4e&&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 uit)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!D_()||!(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 mI(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 _l(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(Uo(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 _l(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(Uo(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 _l(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(Uo(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 _l(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(Uo(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}=Zwe(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+cRt>Date.now()))return r;const{data:a,error:i}=await _l(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 V9("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),r=a.keys.find(l=>l.kid===t),!r)throw new V9("No matching signing key found in JWKS");return r}async getClaims(t,n={keys:[]}){try{let r=t;if(!r){const{data:f,error:g}=await this.getSession();if(g||!f.session)return{data:null,error:g};r=f.session.access_token}const{header:a,payload:i,signature:l,raw:{header:o,payload:c}}=Zwe(r);if(IRt(i.exp),!a.kid||a.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:f}=await this.getUser(r);if(f)throw f;return{data:{claims:i,header:a,signature:l},error:null}}const d=PRt(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,vRt(`${o}.${c}`)))throw new V9("Invalid JWT signature");return{data:{claims:i,header:a,signature:l},error:null}}catch(r){if(Uo(r))return{data:null,error:r};throw r}}}aB.nextInstanceID=0;const YRt=aB;class ZRt extends YRt{constructor(t){super(t)}}var QRt=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 XRt{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=nRt(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:YDt,realtime:QDt,auth:Object.assign(Object.assign({},ZDt),{storageKey:d}),global:KDt},h=rRt(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:(p,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((l=h.auth)!==null&&l!==void 0?l:{},this.headers,h.global.fetch),this.fetch=tRt(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 gDt(new URL("rest/v1",c).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new W8t(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new HDt(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 QRt(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 ZRt({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 MDt(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 JRt=(s,t,n)=>new XRt(s,t,n),eOt="https://relzejiswnotikjgvjhz.supabase.co",tOt="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",q=JRt(eOt,tOt,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}}),sOt=Object.freeze(Object.defineProperty({__proto__:null,supabase:q},Symbol.toStringTag,{value:"Module"})),hit=N.createContext(void 0),nOt=({children:s})=>{const[t,n]=N.useState(null),[r,a]=N.useState(null),[i,l]=N.useState(!0),[o,c]=N.useState(!0),[d,u]=N.useState(!1),[h,p]=N.useState(!1),[f,g]=N.useState(!1),[_,v]=N.useState(null),[j,b]=N.useState([]),[S,A]=N.useState(null),T=N.useRef(null),L=N.useRef(!1),D=N.useRef(!1),M=Mn(),F=()=>{u(!1),p(!1),g(!1),v(null),b([]),A(null),T.current=null,L.current=!1},z=async K=>{if(!(L.current&&T.current===K)&&!D.current){D.current=!0,c(!0);try{console.log("Checking roles via RPC for user:",K);const[{data:J,error:ne},{data:ie,error:he},{data:ce,error:pe}]=await Promise.all([q.rpc("has_role",{_user_id:K,_role:"admin"}),q.rpc("has_role",{_user_id:K,_role:"brokerage_manager"}),q.rpc("has_role",{_user_id:K,_role:"coach"})]);if(ne||he)console.error("Role RPC errors:",{isAdminError:ne,isBrokerError:he,isCoachError:pe}),u(!1),p(!1),g(!1);else{const ge=!!J,Te=!!ie,Me=!!ce;console.log("RPC roles result:",{adminValue:ge,brokerValue:Te,coachValue:Me}),u(ge),p(Te),g(Me)}const{data:le,error:ve}=await q.from("profiles").select("brokerage_id").eq("id",K).single();if(v(!ve&&le?le.brokerage_id:null),ie){console.log("Fetching managed brokerages for user:",K);const{data:ge,error:Te}=await q.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",K);if(console.log("Managed brokerage assignments result:",{assignments:ge,assignmentsError:Te}),Te||!ge){console.error("Error fetching managed brokerage assignments:",Te),b([]);return}const Me=Array.from(new Set(ge.map(Ie=>Ie.brokerage_id).filter(Boolean)));if(Me.length===0){b([]);return}const{data:Ce,error:Ae}=await q.from("brokerages").select("id, name").in("id",Me);if(console.log("Managed brokerages details result:",{brokeragesData:Ce,brokeragesError:Ae}),Ae||!Ce){console.error("Error fetching managed brokerages details:",Ae),b([]);return}const De=Ce.map(Ie=>({id:Ie.id,name:Ie.name})).sort((Ie,Fe)=>Me.indexOf(Ie.id)-Me.indexOf(Fe.id));console.log("Parsed managed brokerages:",De),b(De),De.length>0&&A(Ie=>Ie??De[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),b([]);T.current=K,L.current=!0}catch(J){console.error("Unexpected error in checkRoles:",J),F()}finally{D.current=!1,c(!1)}}};N.useEffect(()=>{let K=!0,J=!1;const ne=()=>{!K||J||(J=!0,l(!1))},{data:{subscription:ie}}=q.auth.onAuthStateChange((pe,le)=>{console.log("Auth event:",pe),K&&(a(le),n((le==null?void 0:le.user)??null),ne(),pe==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{M("/profile?reset=true")},100)),le!=null&&le.user?(!L.current||T.current!==le.user.id)&&setTimeout(()=>{z(le.user.id)},0):(F(),c(!1)))}),he=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),ne()},4e3);return(async()=>{try{const{data:{session:pe}}=await q.auth.getSession();if(!K)return;a(pe),n((pe==null?void 0:pe.user)??null),pe!=null&&pe.user?await z(pe.user.id):F()}catch(pe){console.error("Error restoring auth session:",pe),K&&(a(null),n(null),F())}finally{ne()}})(),()=>{K=!1,window.clearTimeout(he),ie.unsubscribe()}},[]);const V=async(K,J)=>{const{error:ne}=await q.auth.signInWithPassword({email:K,password:J});if(ne)throw ae.error(ne.message),ne;ae.success("Welcome back!")},W=async(K,J,ne)=>{var le;const ie=`${window.location.origin}/dashboard`,he=localStorage.getItem("levelup_referral_code")||null,{data:ce,error:pe}=await q.auth.signUp({email:K,password:J,options:{emailRedirectTo:ie,data:{name:ne,referred_by_code:he}}});if(pe)throw ae.error(pe.message),pe;if(he&&((le=ce.user)!=null&&le.id))try{await q.from("profiles").update({referred_by_code:he}).eq("id",ce.user.id),localStorage.removeItem("levelup_referral_code")}catch(ve){console.warn("Failed to attach referral code to profile",ve)}ae.success("Account created! Welcome to LevelUp."),M("/dashboard")},Y=async()=>{try{const{data:{session:K}}=await q.auth.getSession();if(K){const{error:J}=await q.auth.signOut();J?J.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",J.message):(console.error("Sign out error:",J),ae.error(J.message)):ae.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");n(null),a(null),u(!1),p(!1),v(null),b([]),A(null),M("/auth")}catch(K){console.error("Unexpected sign out error:",K),M("/auth")}};return e.jsx(hit.Provider,{value:{user:t,session:r,loading:i,rolesLoading:o,signIn:V,signUp:W,signOut:Y,isAdmin:d,isBrokerageManager:h,isCoach:f,brokerageId:_,managedBrokerages:j,selectedBrokerageId:S,setSelectedBrokerageId:A},children:s})},ys=()=>{const s=N.useContext(hit);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},mit=N.createContext({onlineUsers:[],totalOnline:0}),rOt=async s=>{try{const{data:t}=await q.storage.from("avatars").list(`${s}`);if(t&&t.length>0){const{data:n}=q.storage.from("avatars").getPublicUrl(`${s}/${t[0].name}`);return n.publicUrl}}catch{}},aOt=({children:s})=>{const{user:t,brokerageId:n,isAdmin:r}=ys(),[a,i]=N.useState([]),[l,o]=N.useState(null);N.useEffect(()=>{if(!t)return;let d=!1;q.auth.getSession().then(({data:h})=>{var f;const p=(f=h.session)==null?void 0:f.access_token;if(p)try{q.realtime.setAuth(p)}catch{}});const u=q.channel("app-presence-v2",{config:{presence:{key:t.id},broadcast:{self:!0}}});return u.on("presence",{event:"sync"},()=>{const h=u.presenceState(),p=[];Object.entries(h).forEach(([f,g])=>{if(g&&g.length>0){const _=g[0];p.push({id:f,name:_.name||"Unknown",avatarUrl:_.avatarUrl,brokerageId:_.brokerageId,onlineSince:_.onlineSince})}}),console.log("[Presence] sync, users:",p.length,p),i(p)}).on("presence",{event:"join"},({key:h,newPresences:p})=>{console.log("[Presence] join",h,p)}).on("presence",{event:"leave"},({key:h})=>{console.log("[Presence] leave",h)}).subscribe(async(h,p)=>{var f;if(console.log("[Presence] subscribe status:",h,p),h==="SUBSCRIBED"&&!d){const{data:g}=await q.from("profiles").select("name, brokerage_id").eq("id",t.id).maybeSingle(),_=await rOt(t.id),v=await u.track({name:(g==null?void 0:g.name)||((f=t.email)==null?void 0:f.split("@")[0])||"User",avatarUrl:_,brokerageId:g==null?void 0:g.brokerage_id,onlineSince:new Date().toISOString()});console.log("[Presence] track result:",v)}}),o(u),()=>{d=!0;try{u.untrack()}catch{}q.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(mit.Provider,{value:{onlineUsers:c,totalOnline:a.length},children:s})},pit=()=>N.useContext(mit),fit=N.createContext(void 0),c3="levelup_admin_session",jk="levelup_impersonation",Qwe="levelup_impersonation_return",iOt=({children:s})=>{const[t,n]=N.useState(!1),[r,a]=N.useState(null),[i,l]=N.useState(!1);N.useEffect(()=>{const d=sessionStorage.getItem(jk);if(d)try{const u=JSON.parse(d);n(!0),a(u)}catch{sessionStorage.removeItem(jk)}},[]);const o=async(d,u)=>{l(!0);try{const{data:{session:h}}=await q.auth.getSession();if(!h)return ae.error("No active session found"),!1;const p={access_token:h.access_token,refresh_token:h.refresh_token};sessionStorage.setItem(c3,JSON.stringify(p)),u&&sessionStorage.setItem(Qwe,u);const f=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/impersonate-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h.access_token}`},body:JSON.stringify({targetUserId:d})}),g=await f.json();if(!f.ok)throw new Error(g.error||"Failed to impersonate user");const _={id:g.targetUser.id,name:g.targetUser.name,email:g.targetUser.email};if(sessionStorage.setItem(jk,JSON.stringify(_)),g.method==="session"){const{error:v}=await q.auth.setSession({access_token:g.access_token,refresh_token:g.refresh_token});if(v)throw console.error("Set session error:",v),sessionStorage.removeItem(c3),sessionStorage.removeItem(jk),new Error("Failed to establish impersonation session")}else{const v=g.type||"recovery",{error:j}=await q.auth.verifyOtp({token_hash:g.token_hash,type:v});if(j)throw console.error("Verify OTP error:",j),sessionStorage.removeItem(c3),sessionStorage.removeItem(jk),new Error("Failed to establish impersonation session")}return n(!0),a(_),ae.success(`Now viewing as ${_.name}`),window.location.href="/dashboard",!0}catch(h){return console.error("Impersonation error:",h),ae.error(h.message||"Failed to impersonate user"),sessionStorage.removeItem(c3),sessionStorage.removeItem(jk),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(c3);if(!d){await q.auth.signOut(),window.location.href="/auth";return}const u=JSON.parse(d);await q.auth.signOut();const{error:h}=await q.auth.setSession({access_token:u.access_token,refresh_token:u.refresh_token});if(sessionStorage.removeItem(c3),sessionStorage.removeItem(jk),h){console.error("Failed to restore admin session:",h),ae.error("Admin session expired, please sign in again"),window.location.href="/auth";return}n(!1),a(null),ae.success("Returned to your account");const p=sessionStorage.getItem(Qwe)||"/admin/members";sessionStorage.removeItem(Qwe),window.location.href=p}catch(d){console.error("Stop impersonation error:",d),ae.error("Failed to restore admin session"),sessionStorage.removeItem(c3),sessionStorage.removeItem(jk),window.location.href="/auth"}finally{l(!1)}};return e.jsx(fit.Provider,{value:{isImpersonating:t,impersonatedUser:r,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},H0e=()=>{const s=N.useContext(fit);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},v8=UM("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-full text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-full px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),B=N.forwardRef(({className:s,variant:t,size:n,asChild:r=!1,...a},i)=>{const l=r?iAe:"button";return e.jsx(l,{className:Et(v8({variant:t,size:n,className:s})),ref:i,...a})});B.displayName="Button";const oOt=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:n,isLoading:r}=H0e();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($l,{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(ts,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Bn,{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"})]})})]})})},xit=N.createContext(void 0),fI="levelup_acting_as",YV="levelup_acting_as_self",lOt=({children:s})=>{const{user:t}=ys(),[n,r]=N.useState(!1),[a,i]=N.useState([]),[l,o]=N.useState(null),[c,d]=N.useState({}),[u,h]=N.useState(!0),[p,f]=N.useState(()=>sessionStorage.getItem(YV)==="true");N.useEffect(()=>{if(!(t!=null&&t.id)){r(!1),i([]),o(null),d({}),h(!1);return}(async()=>{h(!0);try{const{data:S}=await q.rpc("has_role",{_user_id:t.id,_role:"assistant"});if(!S){r(!1),i([]),o(null),d({}),h(!1);return}r(!0);const{data:A,error:T}=await q.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",t.id);if(T||!A||A.length===0){i([]),h(!1);return}const L=A.map(F=>F.agent_id),{data:D}=await q.from("profiles").select("id, name, email, avatar_url").in("id",L),M=(D||[]).map(F=>({id:F.id,name:F.name||F.email||"Unknown",email:F.email||"",avatar_url:F.avatar_url}));if(i(M),sessionStorage.getItem(YV)==="true")f(!0),o(null),d({});else{const F=sessionStorage.getItem(fI);if(F){const z=M.find(V=>V.id===F);if(z){o(z);const V=A.find(W=>W.agent_id===F);d((V==null?void 0:V.permissions)||{})}else if(M.length>0){o(M[0]);const V=A.find(W=>W.agent_id===M[0].id);d((V==null?void 0:V.permissions)||{}),sessionStorage.setItem(fI,M[0].id)}}else if(M.length>0){o(M[0]);const z=A.find(V=>V.agent_id===M[0].id);d((z==null?void 0:z.permissions)||{}),sessionStorage.setItem(fI,M[0].id)}}}catch(S){console.error("Error loading assistant data:",S)}finally{h(!1)}})()},[t==null?void 0:t.id]);const g=b=>{o(b),f(!1),sessionStorage.removeItem(YV),b?(sessionStorage.setItem(fI,b.id),q.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(t==null?void 0:t.id)||"").eq("agent_id",b.id).single().then(({data:S})=>{d((S==null?void 0:S.permissions)||{})})):(sessionStorage.removeItem(fI),d({}))},_=()=>{f(!0),o(null),d({}),sessionStorage.setItem(YV,"true"),sessionStorage.removeItem(fI)},v=b=>!n||p?!0:c[b]===!0,j=n&&l&&!p?l.id:(t==null?void 0:t.id)||null;return e.jsx(xit.Provider,{value:{isAssistant:n,assignedAgents:a,actingAsAgent:l,setActingAsAgent:g,effectiveUserId:j,permissions:c,hasPermission:v,isLoading:u,isActingAsSelf:p,setActingAsSelf:_},children:s})},PAe=()=>{const s=N.useContext(xit);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},ma=()=>{const{effectiveUserId:s}=PAe();return s};var git={exports:{}},yit={};/** * @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 b8=N;function cOt(s,t){return s===t&&(s!==0||1/s===1/t)||s!==s&&t!==t}var dOt=typeof Object.is=="function"?Object.is:cOt,uOt=b8.useState,hOt=b8.useEffect,mOt=b8.useLayoutEffect,pOt=b8.useDebugValue;function fOt(s,t){var n=t(),r=uOt({inst:{value:n,getSnapshot:t}}),a=r[0].inst,i=r[1];return mOt(function(){a.value=n,a.getSnapshot=t,Xwe(a)&&i({inst:a})},[s,n,t]),hOt(function(){return Xwe(a)&&i({inst:a}),s(function(){Xwe(a)&&i({inst:a})})},[s]),pOt(n),n}function Xwe(s){var t=s.getSnapshot;s=s.value;try{var n=t();return!dOt(s,n)}catch{return!0}}function xOt(s,t){return t()}var gOt=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?xOt:fOt;yit.useSyncExternalStore=b8.useSyncExternalStore!==void 0?b8.useSyncExternalStore:gOt;git.exports=yit;var yOt=git.exports;function vOt(){return yOt.useSyncExternalStore(bOt,()=>!0,()=>!1)}function bOt(){return()=>{}}var LAe="Avatar",[_Ot,_xn]=pu(LAe),[wOt,vit]=_Ot(LAe),bit=N.forwardRef((s,t)=>{const{__scopeAvatar:n,...r}=s,[a,i]=N.useState("idle");return e.jsx(wOt,{scope:n,imageLoadingStatus:a,onImageLoadingStatusChange:i,children:e.jsx(Jr.span,{...r,ref:t})})});bit.displayName=LAe;var _it="AvatarImage",wit=N.forwardRef((s,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:a=()=>{},...i}=s,l=vit(_it,n),o=jOt(r,i),c=lh(d=>{a(d),l.onImageLoadingStatusChange(d)});return mh(()=>{o!=="idle"&&c(o)},[o,c]),o==="loaded"?e.jsx(Jr.img,{...i,ref:t,src:r}):null});wit.displayName=_it;var jit="AvatarFallback",Nit=N.forwardRef((s,t)=>{const{__scopeAvatar:n,delayMs:r,...a}=s,i=vit(jit,n),[l,o]=N.useState(r===void 0);return N.useEffect(()=>{if(r!==void 0){const c=window.setTimeout(()=>o(!0),r);return()=>window.clearTimeout(c)}},[r]),l&&i.imageLoadingStatus!=="loaded"?e.jsx(Jr.span,{...a,ref:t}):null});Nit.displayName=jit;function Uze(s,t){return s?t?(s.src!==t&&(s.src=t),s.complete&&s.naturalWidth>0?"loaded":"loading"):"error":"idle"}function jOt(s,{referrerPolicy:t,crossOrigin:n}){const r=vOt(),a=N.useRef(null),i=r?(a.current||(a.current=new window.Image),a.current):null,[l,o]=N.useState(()=>Uze(i,s));return mh(()=>{o(Uze(i,s))},[i,s]),mh(()=>{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 kit=bit,Sit=wit,Cit=Nit;const ra=N.forwardRef(({className:s,...t},n)=>e.jsx(kit,{ref:n,className:Et("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));ra.displayName=kit.displayName;const ni=N.forwardRef(({className:s,...t},n)=>e.jsx(Sit,{ref:n,className:Et("aspect-square h-full w-full",s),...t}));ni.displayName=Sit.displayName;const aa=N.forwardRef(({className:s,...t},n)=>e.jsx(Cit,{ref:n,className:Et("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));aa.displayName=Cit.displayName;const NOt=UM("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 ze({className:s,variant:t,...n}){return e.jsx("div",{className:Et(NOt({variant:t}),s),...n})}var kOt=N.createContext(void 0);function NN(s){const t=N.useContext(kOt);return s||t||"ltr"}var Jwe=0;function G0e(){N.useEffect(()=>{const s=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",s[0]??qze()),document.body.insertAdjacentElement("beforeend",s[1]??qze()),Jwe++,()=>{Jwe===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Jwe--}},[])}function qze(){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 eje="focusScope.autoFocusOnMount",tje="focusScope.autoFocusOnUnmount",Vze={bubbles:!1,cancelable:!0},SOt="FocusScope",G$=N.forwardRef((s,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...l}=s,[o,c]=N.useState(null),d=lh(a),u=lh(i),h=N.useRef(null),p=Si(t,_=>c(_)),f=N.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;N.useEffect(()=>{if(r){let _=function(S){if(f.paused||!o)return;const A=S.target;o.contains(A)?h.current=A:zk(h.current,{select:!0})},v=function(S){if(f.paused||!o)return;const A=S.relatedTarget;A!==null&&(o.contains(A)||zk(h.current,{select:!0}))},j=function(S){if(document.activeElement===document.body)for(const T of S)T.removedNodes.length>0&&zk(o)};document.addEventListener("focusin",_),document.addEventListener("focusout",v);const b=new MutationObserver(j);return o&&b.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",_),document.removeEventListener("focusout",v),b.disconnect()}}},[r,o,f.paused]),N.useEffect(()=>{if(o){Gze.add(f);const _=document.activeElement;if(!o.contains(_)){const j=new CustomEvent(eje,Vze);o.addEventListener(eje,d),o.dispatchEvent(j),j.defaultPrevented||(COt(IOt(Tit(o)),{select:!0}),document.activeElement===_&&zk(o))}return()=>{o.removeEventListener(eje,d),setTimeout(()=>{const j=new CustomEvent(tje,Vze);o.addEventListener(tje,u),o.dispatchEvent(j),j.defaultPrevented||zk(_??document.body,{select:!0}),o.removeEventListener(tje,u),Gze.remove(f)},0)}}},[o,d,u,f]);const g=N.useCallback(_=>{if(!n&&!r||f.paused)return;const v=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,j=document.activeElement;if(v&&j){const b=_.currentTarget,[S,A]=TOt(b);S&&A?!_.shiftKey&&j===A?(_.preventDefault(),n&&zk(S,{select:!0})):_.shiftKey&&j===S&&(_.preventDefault(),n&&zk(A,{select:!0})):j===b&&_.preventDefault()}},[n,r,f.paused]);return e.jsx(Jr.div,{tabIndex:-1,...l,ref:p,onKeyDown:g})});G$.displayName=SOt;function COt(s,{select:t=!1}={}){const n=document.activeElement;for(const r of s)if(zk(r,{select:t}),document.activeElement!==n)return}function TOt(s){const t=Tit(s),n=Hze(t,s),r=Hze(t.reverse(),s);return[n,r]}function Tit(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 Hze(s,t){for(const n of s)if(!EOt(n,{upTo:t}))return n}function EOt(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 AOt(s){return s instanceof HTMLInputElement&&"select"in s}function zk(s,{select:t=!1}={}){if(s&&s.focus){const n=document.activeElement;s.focus({preventScroll:!0}),s!==n&&AOt(s)&&t&&s.select()}}var Gze=MOt();function MOt(){let s=[];return{add(t){const n=s[0];t!==n&&(n==null||n.pause()),s=Wze(s,t),s.unshift(t)},remove(t){var n;s=Wze(s,t),(n=s[0])==null||n.resume()}}}function Wze(s,t){const n=[...s],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function IOt(s){return s.filter(t=>t.tagName!=="A")}var sje="rovingFocusGroup.onEntryFocus",POt={bubbles:!1,cancelable:!0},W$="RovingFocusGroup",[w4e,Eit,LOt]=TD(W$),[DOt,W4]=pu(W$,[LOt]),[ROt,OOt]=DOt(W$),Ait=N.forwardRef((s,t)=>e.jsx(w4e.Provider,{scope:s.__scopeRovingFocusGroup,children:e.jsx(w4e.Slot,{scope:s.__scopeRovingFocusGroup,children:e.jsx(FOt,{...s,ref:t})})}));Ait.displayName=W$;var FOt=N.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:a=!1,dir:i,currentTabStopId:l,defaultCurrentTabStopId:o,onCurrentTabStopIdChange:c,onEntryFocus:d,preventScrollOnEntryFocus:u=!1,...h}=s,p=N.useRef(null),f=Si(t,p),g=NN(i),[_,v]=hm({prop:l,defaultProp:o??null,onChange:c,caller:W$}),[j,b]=N.useState(!1),S=lh(d),A=Eit(n),T=N.useRef(!1),[L,D]=N.useState(0);return N.useEffect(()=>{const M=p.current;if(M)return M.addEventListener(sje,S),()=>M.removeEventListener(sje,S)},[S]),e.jsx(ROt,{scope:n,orientation:r,dir:g,loop:a,currentTabStopId:_,onItemFocus:N.useCallback(M=>v(M),[v]),onItemShiftTab:N.useCallback(()=>b(!0),[]),onFocusableItemAdd:N.useCallback(()=>D(M=>M+1),[]),onFocusableItemRemove:N.useCallback(()=>D(M=>M-1),[]),children:e.jsx(Jr.div,{tabIndex:j||L===0?-1:0,"data-orientation":r,...h,ref:f,style:{outline:"none",...s.style},onMouseDown:_r(s.onMouseDown,()=>{T.current=!0}),onFocus:_r(s.onFocus,M=>{const F=!T.current;if(M.target===M.currentTarget&&F&&!j){const z=new CustomEvent(sje,POt);if(M.currentTarget.dispatchEvent(z),!z.defaultPrevented){const V=A().filter(ne=>ne.focusable),W=V.find(ne=>ne.active),Y=V.find(ne=>ne.id===_),J=[W,Y,...V].filter(Boolean).map(ne=>ne.ref.current);Pit(J,u)}}T.current=!1}),onBlur:_r(s.onBlur,()=>b(!1))})})}),Mit="RovingFocusGroupItem",Iit=N.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:a=!1,tabStopId:i,children:l,...o}=s,c=dm(),d=i||c,u=OOt(Mit,n),h=u.currentTabStopId===d,p=Eit(n),{onFocusableItemAdd:f,onFocusableItemRemove:g,currentTabStopId:_}=u;return N.useEffect(()=>{if(r)return f(),()=>g()},[r,f,g]),e.jsx(w4e.ItemSlot,{scope:n,id:d,focusable:r,active:a,children:e.jsx(Jr.span,{tabIndex:h?0:-1,"data-orientation":u.orientation,...o,ref:t,onMouseDown:_r(s.onMouseDown,v=>{r?u.onItemFocus(d):v.preventDefault()}),onFocus:_r(s.onFocus,()=>u.onItemFocus(d)),onKeyDown:_r(s.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){u.onItemShiftTab();return}if(v.target!==v.currentTarget)return;const j=$Ot(v,u.orientation,u.dir);if(j!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let S=p().filter(A=>A.focusable).map(A=>A.ref.current);if(j==="last")S.reverse();else if(j==="prev"||j==="next"){j==="prev"&&S.reverse();const A=S.indexOf(v.currentTarget);S=u.loop?UOt(S,A+1):S.slice(A+1)}setTimeout(()=>Pit(S))}}),children:typeof l=="function"?l({isCurrentTabStop:h,hasTabStop:_!=null}):l})})});Iit.displayName=Mit;var zOt={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function BOt(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}function $Ot(s,t,n){const r=BOt(s.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return zOt[r]}function Pit(s,t=!1){const n=document.activeElement;for(const r of s)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function UOt(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var W0e=Ait,K0e=Iit,qOt=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},xI=new WeakMap,ZV=new WeakMap,QV={},nje=0,Lit=function(s){return s&&(s.host||Lit(s.parentNode))},VOt=function(s,t){return t.map(function(n){if(s.contains(n))return n;var r=Lit(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})},HOt=function(s,t,n,r){var a=VOt(t,Array.isArray(s)?s:[s]);QV[n]||(QV[n]=new WeakMap);var i=QV[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(p){if(o.has(p))u(p);else try{var f=p.getAttribute(r),g=f!==null&&f!=="false",_=(xI.get(p)||0)+1,v=(i.get(p)||0)+1;xI.set(p,_),i.set(p,v),l.push(p),_===1&&g&&ZV.set(p,!0),v===1&&p.setAttribute(n,"true"),g||p.setAttribute(r,"true")}catch(j){console.error("aria-hidden: cannot operate on ",p,j)}})};return u(t),o.clear(),nje++,function(){l.forEach(function(h){var p=xI.get(h)-1,f=i.get(h)-1;xI.set(h,p),i.set(h,f),p||(ZV.has(h)||h.removeAttribute(r),ZV.delete(h)),f||h.removeAttribute(n)}),nje--,nje||(xI=new WeakMap,xI=new WeakMap,ZV=new WeakMap,QV={})}},Y0e=function(s,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(s)?s:[s]),a=qOt(s);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live]"))),HOt(r,a,n,"aria-hidden")):function(){return null}},J_=function(){return J_=Object.assign||function(t){for(var n,r=1,a=arguments.length;r"u")return lFt;var t=cFt(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])}},uFt=Fit(),AL="data-scroll-locked",hFt=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(WOt,` { overflow: hidden `).concat(r,`; padding-right: `).concat(o,"px ").concat(r,`; } body[`).concat(AL,`] { 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(Eme,` { right: `).concat(o,"px ").concat(r,`; } .`).concat(Ame,` { margin-right: `).concat(o,"px ").concat(r,`; } .`).concat(Eme," .").concat(Eme,` { right: 0 `).concat(r,`; } .`).concat(Ame," .").concat(Ame,` { margin-right: 0 `).concat(r,`; } body[`).concat(AL,`] { `).concat(KOt,": ").concat(o,`px; } `)},Yze=function(){var s=parseInt(document.body.getAttribute(AL)||"0",10);return isFinite(s)?s:0},mFt=function(){N.useEffect(function(){return document.body.setAttribute(AL,(Yze()+1).toString()),function(){var s=Yze()-1;s<=0?document.body.removeAttribute(AL):document.body.setAttribute(AL,s.toString())}},[])},pFt=function(s){var t=s.noRelative,n=s.noImportant,r=s.gapMode,a=r===void 0?"margin":r;mFt();var i=N.useMemo(function(){return dFt(a)},[a]);return N.createElement(uFt,{styles:hFt(i,!t,a,n?"":"!important")})},j4e=!1;if(typeof window<"u")try{var XV=Object.defineProperty({},"passive",{get:function(){return j4e=!0,!0}});window.addEventListener("test",XV,XV),window.removeEventListener("test",XV,XV)}catch{j4e=!1}var gI=j4e?{passive:!1}:!1,fFt=function(s){return s.tagName==="TEXTAREA"},zit=function(s,t){if(!(s instanceof Element))return!1;var n=window.getComputedStyle(s);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!fFt(s)&&n[t]==="visible")},xFt=function(s){return zit(s,"overflowY")},gFt=function(s){return zit(s,"overflowX")},Zze=function(s,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=Bit(s,r);if(a){var i=$it(s,r),l=i[1],o=i[2];if(l>o)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},yFt=function(s){var t=s.scrollTop,n=s.scrollHeight,r=s.clientHeight;return[t,n,r]},vFt=function(s){var t=s.scrollLeft,n=s.scrollWidth,r=s.clientWidth;return[t,n,r]},Bit=function(s,t){return s==="v"?xFt(t):gFt(t)},$it=function(s,t){return s==="v"?yFt(t):vFt(t)},bFt=function(s,t){return s==="h"&&t==="rtl"?-1:1},_Ft=function(s,t,n,r,a){var i=bFt(s,window.getComputedStyle(t).direction),l=i*r,o=n.target,c=t.contains(o),d=!1,u=l>0,h=0,p=0;do{if(!o)break;var f=$it(s,o),g=f[0],_=f[1],v=f[2],j=_-v-i*g;(g||j)&&Bit(s,o)&&(h+=j,p+=g);var b=o.parentNode;o=b&&b.nodeType===Node.DOCUMENT_FRAGMENT_NODE?b.host:b}while(!c&&o!==document.body||c&&(t.contains(o)||t===o));return(u&&(Math.abs(h)<1||!a)||!u&&(Math.abs(p)<1||!a))&&(d=!0),d},JV=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},Qze=function(s){return[s.deltaX,s.deltaY]},Xze=function(s){return s&&"current"in s?s.current:s},wFt=function(s,t){return s[0]===t[0]&&s[1]===t[1]},jFt=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},NFt=0,yI=[];function kFt(s){var t=N.useRef([]),n=N.useRef([0,0]),r=N.useRef(),a=N.useState(NFt++)[0],i=N.useState(Fit)[0],l=N.useRef(s);N.useEffect(function(){l.current=s},[s]),N.useEffect(function(){if(s.inert){document.body.classList.add("block-interactivity-".concat(a));var _=GOt([s.lockRef.current],(s.shards||[]).map(Xze),!0).filter(Boolean);return _.forEach(function(v){return v.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),_.forEach(function(v){return v.classList.remove("allow-interactivity-".concat(a))})}}},[s.inert,s.lockRef.current,s.shards]);var o=N.useCallback(function(_,v){if("touches"in _&&_.touches.length===2||_.type==="wheel"&&_.ctrlKey)return!l.current.allowPinchZoom;var j=JV(_),b=n.current,S="deltaX"in _?_.deltaX:b[0]-j[0],A="deltaY"in _?_.deltaY:b[1]-j[1],T,L=_.target,D=Math.abs(S)>Math.abs(A)?"h":"v";if("touches"in _&&D==="h"&&L.type==="range")return!1;var M=Zze(D,L);if(!M)return!0;if(M?T=D:(T=D==="v"?"h":"v",M=Zze(D,L)),!M)return!1;if(!r.current&&"changedTouches"in _&&(S||A)&&(r.current=T),!T)return!0;var F=r.current||T;return _Ft(F,v,_,F==="h"?S:A,!0)},[]),c=N.useCallback(function(_){var v=_;if(!(!yI.length||yI[yI.length-1]!==i)){var j="deltaY"in v?Qze(v):JV(v),b=t.current.filter(function(T){return T.name===v.type&&(T.target===v.target||v.target===T.shadowParent)&&wFt(T.delta,j)})[0];if(b&&b.should){v.cancelable&&v.preventDefault();return}if(!b){var S=(l.current.shards||[]).map(Xze).filter(Boolean).filter(function(T){return T.contains(v.target)}),A=S.length>0?o(v,S[0]):!l.current.noIsolation;A&&v.cancelable&&v.preventDefault()}}},[]),d=N.useCallback(function(_,v,j,b){var S={name:_,delta:v,target:j,should:b,shadowParent:SFt(j)};t.current.push(S),setTimeout(function(){t.current=t.current.filter(function(A){return A!==S})},1)},[]),u=N.useCallback(function(_){n.current=JV(_),r.current=void 0},[]),h=N.useCallback(function(_){d(_.type,Qze(_),_.target,o(_,s.lockRef.current))},[]),p=N.useCallback(function(_){d(_.type,JV(_),_.target,o(_,s.lockRef.current))},[]);N.useEffect(function(){return yI.push(i),s.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:p}),document.addEventListener("wheel",c,gI),document.addEventListener("touchmove",c,gI),document.addEventListener("touchstart",u,gI),function(){yI=yI.filter(function(_){return _!==i}),document.removeEventListener("wheel",c,gI),document.removeEventListener("touchmove",c,gI),document.removeEventListener("touchstart",u,gI)}},[]);var f=s.removeScrollBar,g=s.inert;return N.createElement(N.Fragment,null,g?N.createElement(i,{styles:jFt(a)}):null,f?N.createElement(pFt,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function SFt(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const CFt=tFt(Oit,kFt);var K$=N.forwardRef(function(s,t){return N.createElement(Z0e,J_({},s,{ref:t,sideCar:CFt}))});K$.classNames=Z0e.classNames;var N4e=["Enter"," "],TFt=["ArrowDown","PageUp","Home"],Uit=["ArrowUp","PageDown","End"],EFt=[...TFt,...Uit],AFt={ltr:[...N4e,"ArrowRight"],rtl:[...N4e,"ArrowLeft"]},MFt={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Y$="Menu",[iB,IFt,PFt]=TD(Y$),[VM,qit]=pu(Y$,[PFt,Gw,W4]),Q0e=Gw(),Vit=W4(),[LFt,HM]=VM(Y$),[DFt,Z$]=VM(Y$),Hit=s=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:i,modal:l=!0}=s,o=Q0e(t),[c,d]=N.useState(null),u=N.useRef(!1),h=lh(i),p=NN(a);return N.useEffect(()=>{const f=()=>{u.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},g=()=>u.current=!1;return document.addEventListener("keydown",f,{capture:!0}),()=>{document.removeEventListener("keydown",f,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),e.jsx($$,{...o,children:e.jsx(LFt,{scope:t,open:n,onOpenChange:h,content:c,onContentChange:d,children:e.jsx(DFt,{scope:t,onClose:N.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:u,dir:p,modal:l,children:r})})})};Hit.displayName=Y$;var RFt="MenuAnchor",DAe=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=Q0e(n);return e.jsx(PD,{...a,...r,ref:t})});DAe.displayName=RFt;var RAe="MenuPortal",[OFt,Git]=VM(RAe,{forceMount:void 0}),Wit=s=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=s,i=HM(RAe,t);return e.jsx(OFt,{scope:t,forceMount:n,children:e.jsx(Rh,{present:n||i.open,children:e.jsx(ED,{asChild:!0,container:a,children:r})})})};Wit.displayName=RAe;var zv="MenuContent",[FFt,OAe]=VM(zv),Kit=N.forwardRef((s,t)=>{const n=Git(zv,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=HM(zv,s.__scopeMenu),l=Z$(zv,s.__scopeMenu);return e.jsx(iB.Provider,{scope:s.__scopeMenu,children:e.jsx(Rh,{present:r||i.open,children:e.jsx(iB.Slot,{scope:s.__scopeMenu,children:l.modal?e.jsx(zFt,{...a,ref:t}):e.jsx(BFt,{...a,ref:t})})})})}),zFt=N.forwardRef((s,t)=>{const n=HM(zv,s.__scopeMenu),r=N.useRef(null),a=Si(t,r);return N.useEffect(()=>{const i=r.current;if(i)return Y0e(i)},[]),e.jsx(FAe,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:_r(s.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),BFt=N.forwardRef((s,t)=>{const n=HM(zv,s.__scopeMenu);return e.jsx(FAe,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),$Ft=S4("MenuContent.ScrollLock"),FAe=N.forwardRef((s,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:l,disableOutsidePointerEvents:o,onEntryFocus:c,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:p,onDismiss:f,disableOutsideScroll:g,..._}=s,v=HM(zv,n),j=Z$(zv,n),b=Q0e(n),S=Vit(n),A=IFt(n),[T,L]=N.useState(null),D=N.useRef(null),M=Si(t,D,v.onContentChange),F=N.useRef(0),z=N.useRef(""),V=N.useRef(0),W=N.useRef(null),Y=N.useRef("right"),K=N.useRef(0),J=g?K$:N.Fragment,ne=g?{as:$Ft,allowPinchZoom:!0}:void 0,ie=ce=>{var Ae,De;const pe=z.current+ce,le=A().filter(Ie=>!Ie.disabled),ve=document.activeElement,ge=(Ae=le.find(Ie=>Ie.ref.current===ve))==null?void 0:Ae.textValue,Te=le.map(Ie=>Ie.textValue),Me=JFt(Te,pe,ge),Ce=(De=le.find(Ie=>Ie.textValue===Me))==null?void 0:De.ref.current;(function Ie(Fe){z.current=Fe,window.clearTimeout(F.current),Fe!==""&&(F.current=window.setTimeout(()=>Ie(""),1e3))})(pe),Ce&&setTimeout(()=>Ce.focus())};N.useEffect(()=>()=>window.clearTimeout(F.current),[]),G0e();const he=N.useCallback(ce=>{var le,ve;return Y.current===((le=W.current)==null?void 0:le.side)&&t7t(ce,(ve=W.current)==null?void 0:ve.area)},[]);return e.jsx(FFt,{scope:n,searchRef:z,onItemEnter:N.useCallback(ce=>{he(ce)&&ce.preventDefault()},[he]),onItemLeave:N.useCallback(ce=>{var pe;he(ce)||((pe=D.current)==null||pe.focus(),L(null))},[he]),onTriggerLeave:N.useCallback(ce=>{he(ce)&&ce.preventDefault()},[he]),pointerGraceTimerRef:V,onPointerGraceIntentChange:N.useCallback(ce=>{W.current=ce},[]),children:e.jsx(J,{...ne,children:e.jsx(G$,{asChild:!0,trapped:a,onMountAutoFocus:_r(i,ce=>{var pe;ce.preventDefault(),(pe=D.current)==null||pe.focus({preventScroll:!0})}),onUnmountAutoFocus:l,children:e.jsx(H4,{asChild:!0,disableOutsidePointerEvents:o,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:p,onDismiss:f,children:e.jsx(W0e,{asChild:!0,...S,dir:j.dir,orientation:"vertical",loop:r,currentTabStopId:T,onCurrentTabStopIdChange:L,onEntryFocus:_r(c,ce=>{j.isUsingKeyboardRef.current||ce.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(U$,{role:"menu","aria-orientation":"vertical","data-state":dot(v.open),"data-radix-menu-content":"",dir:j.dir,...b,..._,ref:M,style:{outline:"none",..._.style},onKeyDown:_r(_.onKeyDown,ce=>{const le=ce.target.closest("[data-radix-menu-content]")===ce.currentTarget,ve=ce.ctrlKey||ce.altKey||ce.metaKey,ge=ce.key.length===1;le&&(ce.key==="Tab"&&ce.preventDefault(),!ve&&ge&&ie(ce.key));const Te=D.current;if(ce.target!==Te||!EFt.includes(ce.key))return;ce.preventDefault();const Ce=A().filter(Ae=>!Ae.disabled).map(Ae=>Ae.ref.current);Uit.includes(ce.key)&&Ce.reverse(),QFt(Ce)}),onBlur:_r(s.onBlur,ce=>{ce.currentTarget.contains(ce.target)||(window.clearTimeout(F.current),z.current="")}),onPointerMove:_r(s.onPointerMove,oB(ce=>{const pe=ce.target,le=K.current!==ce.clientX;if(ce.currentTarget.contains(pe)&&le){const ve=ce.clientX>K.current?"right":"left";Y.current=ve,K.current=ce.clientX}}))})})})})})})});Kit.displayName=zv;var UFt="MenuGroup",zAe=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(Jr.div,{role:"group",...r,ref:t})});zAe.displayName=UFt;var qFt="MenuLabel",Yit=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(Jr.div,{...r,ref:t})});Yit.displayName=qFt;var nfe="MenuItem",Jze="menu.itemSelect",X0e=N.forwardRef((s,t)=>{const{disabled:n=!1,onSelect:r,...a}=s,i=N.useRef(null),l=Z$(nfe,s.__scopeMenu),o=OAe(nfe,s.__scopeMenu),c=Si(t,i),d=N.useRef(!1),u=()=>{const h=i.current;if(!n&&h){const p=new CustomEvent(Jze,{bubbles:!0,cancelable:!0});h.addEventListener(Jze,f=>r==null?void 0:r(f),{once:!0}),oAe(h,p),p.defaultPrevented?d.current=!1:l.onClose()}};return e.jsx(Zit,{...a,ref:c,disabled:n,onClick:_r(s.onClick,u),onPointerDown:h=>{var p;(p=s.onPointerDown)==null||p.call(s,h),d.current=!0},onPointerUp:_r(s.onPointerUp,h=>{var p;d.current||(p=h.currentTarget)==null||p.click()}),onKeyDown:_r(s.onKeyDown,h=>{const p=o.searchRef.current!=="";n||p&&h.key===" "||N4e.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});X0e.displayName=nfe;var Zit=N.forwardRef((s,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:a,...i}=s,l=OAe(nfe,n),o=Vit(n),c=N.useRef(null),d=Si(t,c),[u,h]=N.useState(!1),[p,f]=N.useState("");return N.useEffect(()=>{const g=c.current;g&&f((g.textContent??"").trim())},[i.children]),e.jsx(iB.ItemSlot,{scope:n,disabled:r,textValue:a??p,children:e.jsx(K0e,{asChild:!0,...o,focusable:!r,children:e.jsx(Jr.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:d,onPointerMove:_r(s.onPointerMove,oB(g=>{r?l.onItemLeave(g):(l.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:_r(s.onPointerLeave,oB(g=>l.onItemLeave(g))),onFocus:_r(s.onFocus,()=>h(!0)),onBlur:_r(s.onBlur,()=>h(!1))})})})}),VFt="MenuCheckboxItem",Qit=N.forwardRef((s,t)=>{const{checked:n=!1,onCheckedChange:r,...a}=s;return e.jsx(sot,{scope:s.__scopeMenu,checked:n,children:e.jsx(X0e,{role:"menuitemcheckbox","aria-checked":rfe(n)?"mixed":n,...a,ref:t,"data-state":$Ae(n),onSelect:_r(a.onSelect,()=>r==null?void 0:r(rfe(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Qit.displayName=VFt;var Xit="MenuRadioGroup",[HFt,GFt]=VM(Xit,{value:void 0,onValueChange:()=>{}}),Jit=N.forwardRef((s,t)=>{const{value:n,onValueChange:r,...a}=s,i=lh(r);return e.jsx(HFt,{scope:s.__scopeMenu,value:n,onValueChange:i,children:e.jsx(zAe,{...a,ref:t})})});Jit.displayName=Xit;var eot="MenuRadioItem",tot=N.forwardRef((s,t)=>{const{value:n,...r}=s,a=GFt(eot,s.__scopeMenu),i=n===a.value;return e.jsx(sot,{scope:s.__scopeMenu,checked:i,children:e.jsx(X0e,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":$Ae(i),onSelect:_r(r.onSelect,()=>{var l;return(l=a.onValueChange)==null?void 0:l.call(a,n)},{checkForDefaultPrevented:!1})})})});tot.displayName=eot;var BAe="MenuItemIndicator",[sot,WFt]=VM(BAe,{checked:!1}),not=N.forwardRef((s,t)=>{const{__scopeMenu:n,forceMount:r,...a}=s,i=WFt(BAe,n);return e.jsx(Rh,{present:r||rfe(i.checked)||i.checked===!0,children:e.jsx(Jr.span,{...a,ref:t,"data-state":$Ae(i.checked)})})});not.displayName=BAe;var KFt="MenuSeparator",rot=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(Jr.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});rot.displayName=KFt;var YFt="MenuArrow",aot=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=Q0e(n);return e.jsx(q$,{...a,...r,ref:t})});aot.displayName=YFt;var ZFt="MenuSub",[wxn,iot]=VM(ZFt),d7="MenuSubTrigger",oot=N.forwardRef((s,t)=>{const n=HM(d7,s.__scopeMenu),r=Z$(d7,s.__scopeMenu),a=iot(d7,s.__scopeMenu),i=OAe(d7,s.__scopeMenu),l=N.useRef(null),{pointerGraceTimerRef:o,onPointerGraceIntentChange:c}=i,d={__scopeMenu:s.__scopeMenu},u=N.useCallback(()=>{l.current&&window.clearTimeout(l.current),l.current=null},[]);return N.useEffect(()=>u,[u]),N.useEffect(()=>{const h=o.current;return()=>{window.clearTimeout(h),c(null)}},[o,c]),e.jsx(DAe,{asChild:!0,...d,children:e.jsx(Zit,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":a.contentId,"data-state":dot(n.open),...s,ref:uN(t,a.onTriggerChange),onClick:h=>{var p;(p=s.onClick)==null||p.call(s,h),!(s.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:_r(s.onPointerMove,oB(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:_r(s.onPointerLeave,oB(h=>{var f,g;u();const p=(f=n.content)==null?void 0:f.getBoundingClientRect();if(p){const _=(g=n.content)==null?void 0:g.dataset.side,v=_==="right",j=v?-5:5,b=p[v?"left":"right"],S=p[v?"right":"left"];i.onPointerGraceIntentChange({area:[{x:h.clientX+j,y:h.clientY},{x:b,y:p.top},{x:S,y:p.top},{x:S,y:p.bottom},{x:b,y:p.bottom}],side:_}),window.clearTimeout(o.current),o.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(h),h.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:_r(s.onKeyDown,h=>{var f;const p=i.searchRef.current!=="";s.disabled||p&&h.key===" "||AFt[r.dir].includes(h.key)&&(n.onOpenChange(!0),(f=n.content)==null||f.focus(),h.preventDefault())})})})});oot.displayName=d7;var lot="MenuSubContent",cot=N.forwardRef((s,t)=>{const n=Git(zv,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=HM(zv,s.__scopeMenu),l=Z$(zv,s.__scopeMenu),o=iot(lot,s.__scopeMenu),c=N.useRef(null),d=Si(t,c);return e.jsx(iB.Provider,{scope:s.__scopeMenu,children:e.jsx(Rh,{present:r||i.open,children:e.jsx(iB.Slot,{scope:s.__scopeMenu,children:e.jsx(FAe,{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:_r(s.onFocusOutside,u=>{u.target!==o.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:_r(s.onEscapeKeyDown,u=>{l.onClose(),u.preventDefault()}),onKeyDown:_r(s.onKeyDown,u=>{var f;const h=u.currentTarget.contains(u.target),p=MFt[l.dir].includes(u.key);h&&p&&(i.onOpenChange(!1),(f=o.trigger)==null||f.focus(),u.preventDefault())})})})})})});cot.displayName=lot;function dot(s){return s?"open":"closed"}function rfe(s){return s==="indeterminate"}function $Ae(s){return rfe(s)?"indeterminate":s?"checked":"unchecked"}function QFt(s){const t=document.activeElement;for(const n of s)if(n===t||(n.focus(),document.activeElement!==t))return}function XFt(s,t){return s.map((n,r)=>s[(t+r)%s.length])}function JFt(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=XFt(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 e7t(s,t){const{x:n,y:r}=s;let a=!1;for(let i=0,l=t.length-1;ir!=p>r&&n<(h-d)*(r-u)/(p-u)+d&&(a=!a)}return a}function t7t(s,t){if(!t)return!1;const n={x:s.clientX,y:s.clientY};return e7t(n,t)}function oB(s){return t=>t.pointerType==="mouse"?s(t):void 0}var s7t=Hit,n7t=DAe,r7t=Wit,a7t=Kit,i7t=zAe,o7t=Yit,l7t=X0e,c7t=Qit,d7t=Jit,u7t=tot,h7t=not,m7t=rot,p7t=aot,f7t=oot,x7t=cot,J0e="DropdownMenu",[g7t,jxn]=pu(J0e,[qit]),lg=qit(),[y7t,uot]=g7t(J0e),hot=s=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=lg(t),d=N.useRef(null),[u,h]=hm({prop:a,defaultProp:i??!1,onChange:l,caller:J0e});return e.jsx(y7t,{scope:t,triggerId:dm(),triggerRef:d,contentId:dm(),open:u,onOpenChange:h,onOpenToggle:N.useCallback(()=>h(p=>!p),[h]),modal:o,children:e.jsx(s7t,{...c,open:u,onOpenChange:h,dir:r,modal:o,children:n})})};hot.displayName=J0e;var mot="DropdownMenuTrigger",pot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...a}=s,i=uot(mot,n),l=lg(n);return e.jsx(n7t,{asChild:!0,...l,children:e.jsx(Jr.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:uN(t,i.triggerRef),onPointerDown:_r(s.onPointerDown,o=>{!r&&o.button===0&&o.ctrlKey===!1&&(i.onOpenToggle(),i.open||o.preventDefault())}),onKeyDown:_r(s.onKeyDown,o=>{r||(["Enter"," "].includes(o.key)&&i.onOpenToggle(),o.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(o.key)&&o.preventDefault())})})})});pot.displayName=mot;var v7t="DropdownMenuPortal",fot=s=>{const{__scopeDropdownMenu:t,...n}=s,r=lg(t);return e.jsx(r7t,{...r,...n})};fot.displayName=v7t;var xot="DropdownMenuContent",got=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=uot(xot,n),i=lg(n),l=N.useRef(!1);return e.jsx(a7t,{id:a.contentId,"aria-labelledby":a.triggerId,...i,...r,ref:t,onCloseAutoFocus:_r(s.onCloseAutoFocus,o=>{var c;l.current||(c=a.triggerRef.current)==null||c.focus(),l.current=!1,o.preventDefault()}),onInteractOutside:_r(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)"}})});got.displayName=xot;var b7t="DropdownMenuGroup",_7t=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=lg(n);return e.jsx(i7t,{...a,...r,ref:t})});_7t.displayName=b7t;var w7t="DropdownMenuLabel",yot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=lg(n);return e.jsx(o7t,{...a,...r,ref:t})});yot.displayName=w7t;var j7t="DropdownMenuItem",vot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=lg(n);return e.jsx(l7t,{...a,...r,ref:t})});vot.displayName=j7t;var N7t="DropdownMenuCheckboxItem",bot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=lg(n);return e.jsx(c7t,{...a,...r,ref:t})});bot.displayName=N7t;var k7t="DropdownMenuRadioGroup",S7t=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=lg(n);return e.jsx(d7t,{...a,...r,ref:t})});S7t.displayName=k7t;var C7t="DropdownMenuRadioItem",_ot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=lg(n);return e.jsx(u7t,{...a,...r,ref:t})});_ot.displayName=C7t;var T7t="DropdownMenuItemIndicator",wot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=lg(n);return e.jsx(h7t,{...a,...r,ref:t})});wot.displayName=T7t;var E7t="DropdownMenuSeparator",jot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=lg(n);return e.jsx(m7t,{...a,...r,ref:t})});jot.displayName=E7t;var A7t="DropdownMenuArrow",M7t=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=lg(n);return e.jsx(p7t,{...a,...r,ref:t})});M7t.displayName=A7t;var I7t="DropdownMenuSubTrigger",Not=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=lg(n);return e.jsx(f7t,{...a,...r,ref:t})});Not.displayName=I7t;var P7t="DropdownMenuSubContent",kot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=lg(n);return e.jsx(x7t,{...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)"}})});kot.displayName=P7t;var L7t=hot,D7t=pot,R7t=fot,Sot=got,Cot=yot,Tot=vot,Eot=bot,Aot=_ot,Mot=wot,Iot=jot,Pot=Not,Lot=kot;const wc=L7t,jc=D7t,O7t=N.forwardRef(({className:s,inset:t,children:n,...r},a)=>e.jsxs(Pot,{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(xa,{className:"ml-auto h-4 w-4"})]}));O7t.displayName=Pot.displayName;const F7t=N.forwardRef(({className:s,...t},n)=>e.jsx(Lot,{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}));F7t.displayName=Lot.displayName;const cc=N.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(R7t,{children:e.jsx(Sot,{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})}));cc.displayName=Sot.displayName;const Qr=N.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(Tot,{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}));Qr.displayName=Tot.displayName;const z7t=N.forwardRef(({className:s,children:t,checked:n,...r},a)=>e.jsxs(Eot,{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(Mot,{children:e.jsx(Ir,{className:"h-4 w-4"})})}),t]}));z7t.displayName=Eot.displayName;const B7t=N.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(Aot,{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(Mot,{children:e.jsx(lm,{className:"h-2 w-2 fill-current"})})}),t]}));B7t.displayName=Aot.displayName;const M4=N.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(Cot,{ref:r,className:Et("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...n}));M4.displayName=Cot.displayName;const Zg=N.forwardRef(({className:s,...t},n)=>e.jsx(Iot,{ref:n,className:Et("-mx-1 my-1 h-px bg-muted",s),...t}));Zg.displayName=Iot.displayName;const $7t=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:n,setActingAsAgent:r,isActingAsSelf:a,setActingAsSelf:i}=PAe();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(Xi,{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(Nn,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),e.jsxs(wc,{children:[e.jsx(jc,{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(Xi,{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(ni,{src:t.avatar_url||void 0}),e.jsx(aa,{className:"text-[10px] bg-primary-foreground/30",children:l(t.name)})]}),e.jsx("strong",{children:t.name})]}):e.jsx("strong",{children:"Select..."}),e.jsx(io,{className:"h-3 w-3"})]})}),e.jsxs(cc,{align:"start",className:"z-[2147483647]",children:[e.jsxs(Qr,{onClick:i,className:"gap-2",children:[e.jsx(Xi,{className:"h-4 w-4"}),e.jsx("span",{children:"My Account"}),a&&e.jsx(ze,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),e.jsx(Zg,{}),n.map(o=>e.jsxs(Qr,{onClick:()=>r(o),className:"gap-2",children:[e.jsxs(ra,{className:"h-6 w-6",children:[e.jsx(ni,{src:o.avatar_url||void 0}),e.jsx(aa,{className:"text-[10px]",children:l(o.name)})]}),e.jsx("span",{children:o.name}),!a&&o.id===(t==null?void 0:t.id)&&e.jsx(ze,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},o.id))]})]})]}),e.jsx(ze,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:a?"Personal Mode":"Assistant Mode"})]})})},nn=({children:s,requireAdmin:t=!1,requireBrokerageManager:n=!1})=>{const{user:r,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=ys(),c=Jl();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(p4,{to:"/auth",replace:!0})}return t&&!l?e.jsx(p4,{to:"/dashboard",replace:!0}):n&&!o&&!l?e.jsx(p4,{to:"/dashboard",replace:!0}):e.jsx(e.Fragment,{children:s})};var UAe={};(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 pe=new OffscreenCanvas(1,1),le=pe.getContext("2d");le.fillRect(0,0,1,1);var ve=pe.transferToImageBitmap();le.createPattern(ve,"no-repeat")}catch{return!1}return!0}();function c(){}function d(pe){var le=n.exports.Promise,ve=le!==void 0?le:t.Promise;return typeof ve=="function"?new ve(pe):(pe(c,c),null)}var u=function(pe,le){return{transform:function(ve){if(pe)return ve;if(le.has(ve))return le.get(ve);var ge=new OffscreenCanvas(ve.width,ve.height),Te=ge.getContext("2d");return Te.drawImage(ve,0,0),le.set(ve,ge),ge},clear:function(){le.clear()}}}(o,new Map),h=function(){var pe=Math.floor(16.666666666666668),le,ve,ge={},Te=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(le=function(Me){var Ce=Math.random();return ge[Ce]=requestAnimationFrame(function Ae(De){Te===De||Te+pe-1{const{data:t,error:n}=await q.from("celebration_queue").select("*").eq("user_id",s.id).is("seen_at",null).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!(s!=null&&s.id),refetchOnWindowFocus:!0,staleTime:0})}function q7t(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}function V7t(){const s=Ht(),{user:t}=ys();return gt({mutationFn:async n=>{const{error:r}=await q.from("celebration_queue").insert({user_id:n.user_id,celebration_type:n.celebration_type,title:n.title,message:n.message||null,points_amount:n.points_amount||null,created_by:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}var eye="Dialog",[Dot,Rot]=pu(eye),[H7t,Ib]=Dot(eye),Oot=s=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!0}=s,o=N.useRef(null),c=N.useRef(null),[d,u]=hm({prop:r,defaultProp:a??!1,onChange:i,caller:eye});return e.jsx(H7t,{scope:t,triggerRef:o,contentRef:c,contentId:dm(),titleId:dm(),descriptionId:dm(),open:d,onOpenChange:u,onOpenToggle:N.useCallback(()=>u(h=>!h),[u]),modal:l,children:n})};Oot.displayName=eye;var Fot="DialogTrigger",zot=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=Ib(Fot,n),i=Si(t,a.triggerRef);return e.jsx(Jr.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":HAe(a.open),...r,ref:i,onClick:_r(s.onClick,a.onOpenToggle)})});zot.displayName=Fot;var qAe="DialogPortal",[G7t,Bot]=Dot(qAe,{forceMount:void 0}),$ot=s=>{const{__scopeDialog:t,forceMount:n,children:r,container:a}=s,i=Ib(qAe,t);return e.jsx(G7t,{scope:t,forceMount:n,children:N.Children.map(r,l=>e.jsx(Rh,{present:n||i.open,children:e.jsx(ED,{asChild:!0,container:a,children:l})}))})};$ot.displayName=qAe;var afe="DialogOverlay",Uot=N.forwardRef((s,t)=>{const n=Bot(afe,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=Ib(afe,s.__scopeDialog);return i.modal?e.jsx(Rh,{present:r||i.open,children:e.jsx(K7t,{...a,ref:t})}):null});Uot.displayName=afe;var W7t=S4("DialogOverlay.RemoveScroll"),K7t=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=Ib(afe,n);return e.jsx(K$,{as:W7t,allowPinchZoom:!0,shards:[a.contentRef],children:e.jsx(Jr.div,{"data-state":HAe(a.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),fM="DialogContent",qot=N.forwardRef((s,t)=>{const n=Bot(fM,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=Ib(fM,s.__scopeDialog);return e.jsx(Rh,{present:r||i.open,children:i.modal?e.jsx(Y7t,{...a,ref:t}):e.jsx(Z7t,{...a,ref:t})})});qot.displayName=fM;var Y7t=N.forwardRef((s,t)=>{const n=Ib(fM,s.__scopeDialog),r=N.useRef(null),a=Si(t,n.contentRef,r);return N.useEffect(()=>{const i=r.current;if(i)return Y0e(i)},[]),e.jsx(Vot,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:_r(s.onCloseAutoFocus,i=>{var l;i.preventDefault(),(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:_r(s.onPointerDownOutside,i=>{const l=i.detail.originalEvent,o=l.button===0&&l.ctrlKey===!0;(l.button===2||o)&&i.preventDefault()}),onFocusOutside:_r(s.onFocusOutside,i=>i.preventDefault())})}),Z7t=N.forwardRef((s,t)=>{const n=Ib(fM,s.__scopeDialog),r=N.useRef(!1),a=N.useRef(!1);return e.jsx(Vot,{...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()}})}),Vot=N.forwardRef((s,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,...l}=s,o=Ib(fM,n),c=N.useRef(null),d=Si(t,c);return G0e(),e.jsxs(e.Fragment,{children:[e.jsx(G$,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(H4,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":HAe(o.open),...l,ref:d,onDismiss:()=>o.onOpenChange(!1)})}),e.jsxs(e.Fragment,{children:[e.jsx(X7t,{titleId:o.titleId}),e.jsx(e9t,{contentRef:c,descriptionId:o.descriptionId})]})]})}),VAe="DialogTitle",Hot=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=Ib(VAe,n);return e.jsx(Jr.h2,{id:a.titleId,...r,ref:t})});Hot.displayName=VAe;var Got="DialogDescription",Wot=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=Ib(Got,n);return e.jsx(Jr.p,{id:a.descriptionId,...r,ref:t})});Wot.displayName=Got;var Kot="DialogClose",Yot=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=Ib(Kot,n);return e.jsx(Jr.button,{type:"button",...r,ref:t,onClick:_r(s.onClick,()=>a.onOpenChange(!1))})});Yot.displayName=Kot;function HAe(s){return s?"open":"closed"}var Zot="DialogTitleWarning",[Q7t,Qot]=eMt(Zot,{contentName:fM,titleName:VAe,docsSlug:"dialog"}),X7t=({titleId:s})=>{const t=Qot(Zot),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users. If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component. For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return N.useEffect(()=>{s&&(document.getElementById(s)||console.error(n))},[n,s]),null},J7t="DialogDescriptionWarning",e9t=({contentRef:s,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Qot(J7t).contentName}}.`;return N.useEffect(()=>{var i;const a=(i=s.current)==null?void 0:i.getAttribute("aria-describedby");t&&a&&(document.getElementById(t)||console.warn(r))},[r,s,t]),null},tye=Oot,GAe=zot,sye=$ot,zD=Uot,BD=qot,Q$=Hot,X$=Wot,J$=Yot;const bs=tye,Ai=GAe,t9t=sye,Nxn=J$,Xot=N.forwardRef(({className:s,...t},n)=>e.jsx(zD,{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}));Xot.displayName=zD.displayName;const vs=N.forwardRef(({className:s,children:t,overlayClassName:n,...r},a)=>e.jsxs(t9t,{children:[e.jsx(Xot,{className:n}),e.jsxs(BD,{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(J$,{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(Bn,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));vs.displayName=BD.displayName;const ws=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col space-y-1.5 text-center sm:text-left",s),...t});ws.displayName="DialogHeader";const Xn=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Xn.displayName="DialogFooter";const _s=N.forwardRef(({className:s,...t},n)=>e.jsx(Q$,{ref:n,className:Et("text-lg font-semibold leading-none tracking-tight",s),...t}));_s.displayName=Q$.displayName;const Qn=N.forwardRef(({className:s,...t},n)=>e.jsx(X$,{ref:n,className:Et("text-sm text-muted-foreground",s),...t}));Qn.displayName=X$.displayName;const s9t={points_earned:vo,listing_created:Or,deal_closed:Zl,custom:ca},tBe={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"},sBe=()=>{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 n9t(){const{user:s}=ys(),t=Ht(),{data:n}=U7t(),r=q7t(),[a,i]=N.useState(null),[l,o]=N.useState(!1),c=N.useCallback(()=>{const f=Date.now()+3e3,g={startVelocity:30,spread:360,ticks:60,zIndex:9999},_=(j,b)=>Math.random()*(b-j)+j,v=setInterval(()=>{const j=f-Date.now();if(j<=0){clearInterval(v);return}const b=50*(j/3e3);eBe({...g,particleCount:b,origin:{x:_(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),eBe({...g,particleCount:b,origin:{x:_(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);N.useEffect(()=>{sBe()||n&&n.length>0&&!a&&(i(n[0]),o(!0),setTimeout(c,100))},[n,a,c]);const d=async()=>{if(a){const p=a.id;o(!1),i(null),t.setQueryData(["celebrations","pending",s==null?void 0:s.id],f=>(f==null?void 0:f.filter(g=>g.id!==p))??[]),await r.mutateAsync(p)}};if(sBe()||!a)return null;const u=s9t[a.celebration_type]||ca,h=tBe[a.celebration_type]||tBe.custom;return e.jsx(bs,{open:l,onOpenChange:p=>!p&&d(),children:e.jsxs(vs,{className:"sm:max-w-md text-center border-0 overflow-hidden",children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${h} opacity-10`}),e.jsxs("div",{className:"relative z-10 py-6",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx("div",{className:`w-20 h-20 rounded-full bg-gradient-to-br ${h} flex items-center justify-center animate-bounce`,children:e.jsx(u,{className:"w-10 h-10 text-white"})})}),e.jsxs("div",{className:"flex justify-center gap-1 mb-4",children:[e.jsx(un,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),e.jsx(un,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),e.jsx(un,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-150"})]}),e.jsxs("h2",{className:"text-2xl font-bold mb-2 bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent",children:["🎉 ",a.title]}),a.points_amount&&a.points_amount>0&&e.jsxs("div",{className:"text-4xl font-bold text-primary mb-2",children:["+",a.points_amount," points!"]}),a.message&&e.jsx("p",{className:"text-muted-foreground mb-6",children:a.message}),e.jsx(B,{onClick:d,className:"w-full",size:"lg",children:"Awesome! 🙌"}),n&&n.length>1&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:["+",n.length-1," more celebration",n.length>2?"s":""," waiting"]})]})]})})}function Ws({className:s,...t}){return e.jsx("div",{className:Et("animate-pulse rounded-md bg-muted",s),...t})}const ye=N.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 r9t="Label",Jot=N.forwardRef((s,t)=>e.jsx(Jr.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())}}));Jot.displayName=r9t;var elt=Jot;const a9t=UM("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),se=N.forwardRef(({className:s,...t},n)=>e.jsx(elt,{ref:n,className:Et(a9t(),s),...t}));se.displayName=elt.displayName;const Es=N.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}));Es.displayName="Textarea";var nye="Tabs",[i9t,kxn]=pu(nye,[W4]),tlt=W4(),[o9t,WAe]=i9t(nye),slt=N.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,onValueChange:a,defaultValue:i,orientation:l="horizontal",dir:o,activationMode:c="automatic",...d}=s,u=NN(o),[h,p]=hm({prop:r,onChange:a,defaultProp:i??"",caller:nye});return e.jsx(o9t,{scope:n,baseId:dm(),value:h,onValueChange:p,orientation:l,dir:u,activationMode:c,children:e.jsx(Jr.div,{dir:u,"data-orientation":l,...d,ref:t})})});slt.displayName=nye;var nlt="TabsList",rlt=N.forwardRef((s,t)=>{const{__scopeTabs:n,loop:r=!0,...a}=s,i=WAe(nlt,n),l=tlt(n);return e.jsx(W0e,{asChild:!0,...l,orientation:i.orientation,dir:i.dir,loop:r,children:e.jsx(Jr.div,{role:"tablist","aria-orientation":i.orientation,...a,ref:t})})});rlt.displayName=nlt;var alt="TabsTrigger",ilt=N.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,disabled:a=!1,...i}=s,l=WAe(alt,n),o=tlt(n),c=clt(l.baseId,r),d=dlt(l.baseId,r),u=r===l.value;return e.jsx(K0e,{asChild:!0,...o,focusable:!a,active:u,children:e.jsx(Jr.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:_r(s.onMouseDown,h=>{!a&&h.button===0&&h.ctrlKey===!1?l.onValueChange(r):h.preventDefault()}),onKeyDown:_r(s.onKeyDown,h=>{[" ","Enter"].includes(h.key)&&l.onValueChange(r)}),onFocus:_r(s.onFocus,()=>{const h=l.activationMode!=="manual";!u&&!a&&h&&l.onValueChange(r)})})})});ilt.displayName=alt;var olt="TabsContent",llt=N.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,forceMount:a,children:i,...l}=s,o=WAe(olt,n),c=clt(o.baseId,r),d=dlt(o.baseId,r),u=r===o.value,h=N.useRef(u);return N.useEffect(()=>{const p=requestAnimationFrame(()=>h.current=!1);return()=>cancelAnimationFrame(p)},[]),e.jsx(Rh,{present:a||u,children:({present:p})=>e.jsx(Jr.div,{"data-state":u?"active":"inactive","data-orientation":o.orientation,role:"tabpanel","aria-labelledby":c,hidden:!p,id:d,tabIndex:0,...l,ref:t,style:{...s.style,animationDuration:h.current?"0s":void 0},children:p&&i})})});llt.displayName=olt;function clt(s,t){return`${s}-trigger-${t}`}function dlt(s,t){return`${s}-content-${t}`}var l9t=slt,ult=rlt,hlt=ilt,mlt=llt;const Br=l9t,Fr=N.forwardRef(({className:s,...t},n)=>e.jsx(ult,{ref:n,className:Et("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));Fr.displayName=ult.displayName;const Kt=N.forwardRef(({className:s,...t},n)=>e.jsx(hlt,{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}));Kt.displayName=hlt.displayName;const is=N.forwardRef(({className:s,...t},n)=>e.jsx(mlt,{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}));is.displayName=mlt.displayName;const lB="#0d0d0d",ife="#1a1a1a",lf="#c9a84c",eU="#f0d78c",Mw={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function rye(s){const t={...s,source_page:typeof window<"u"?window.location.pathname:null,user_agent:typeof navigator<"u"?navigator.userAgent:null,referrer:typeof document<"u"?document.referrer:null},{data:n,error:r}=await q.functions.invoke("public-site-lead",{body:t});if(r)throw r;try{localStorage.setItem(Mw.captured,JSON.stringify({email:s.email,ts:Date.now()}))}catch{}return n}function KAe(){try{return!!localStorage.getItem(Mw.captured)}catch{return!1}}function c9t(){try{const s=localStorage.getItem(Mw.captured);return s?JSON.parse(s).email??null:null}catch{return null}}function YAe({open:s,onClose:t,children:n}){return N.useEffect(()=>{if(!s)return;const r=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=r}},[s]),s?Hx.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, ${ife} 0%, ${lB} 100%)`,border:`1px solid ${lf}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${lf}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(Bn,{className:"h-4 w-4"})}),n]})}),document.body):null}function ZAe(){const[s,t]=N.useState({first_name:"",email:"",phone:"",area:""}),[n,r]=N.useState(!1),[a,i]=N.useState("");return{values:s,setValues:t,loading:n,setLoading:r,honeypot:a,setHoneypot:i}}function QAe({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(Xi,{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(Vs,{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(Ar,{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(ka,{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 XAe({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, ${eU} 0%, ${lf} 100%)`,color:lB,boxShadow:`0 8px 24px ${lf}55`},children:s})}function nBe({open:s,onClose:t,initialCriteria:n}){const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=ZAe(),[d,u]=N.useState(!1),h=async p=>{if(p.preventDefault(),!!r.email){l(!0);try{await rye({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(Mw.stickyDismissed,"1")}catch{}setTimeout(t,2200)}catch{ae.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(YAe,{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(im,{className:"h-4 w-4",style:{color:lf}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:eU},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:`${lf}22`,border:`1px solid ${lf}55`},children:e.jsx(un,{className:"h-5 w-5",style:{color:lf}})}),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(QAe,{values:r,setValues:a,honeypot:o,setHoneypot:c}),e.jsx(XAe,{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 d9t(){const[s,t]=N.useState(!0),[n,r]=N.useState(!1);N.useEffect(()=>{try{const i=!!localStorage.getItem(Mw.stickyDismissed)||KAe();t(i)}catch{t(!1)}},[]);const a=()=>{t(!0);try{localStorage.setItem(Mw.stickyDismissed,"1")}catch{}};return s?e.jsx(nBe,{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, ${ife} 0%, ${lB} 100%)`,borderTop:`1px solid ${lf}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:`${lf}22`,border:`1px solid ${lf}55`},children:e.jsx(im,{className:"h-4 w-4",style:{color:lf}})}),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, ${eU} 0%, ${lf} 100%)`,color:lB},children:"Get Alerts"}),e.jsx("button",{onClick:a,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:e.jsx(Bn,{className:"h-4 w-4"})})]})}),e.jsx(nBe,{open:n,onClose:()=>r(!1)})]})}function u9t(){const[s,t]=N.useState(!1),n=N.useRef(!1);N.useEffect(()=>{try{if(sessionStorage.getItem(Mw.exitShown)||KAe())return}catch{}const p=setTimeout(()=>{n.current=!0},8e3),f=g=>{if(n.current&&!(g.clientY>0)){t(!0);try{sessionStorage.setItem(Mw.exitShown,"1")}catch{}window.removeEventListener("mouseleave",f),document.removeEventListener("mouseleave",f)}};return document.addEventListener("mouseleave",f),()=>{clearTimeout(p),document.removeEventListener("mouseleave",f)}},[]);const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=ZAe(),[d,u]=N.useState(!1),h=async p=>{if(p.preventDefault(),!!r.email){l(!0);try{await rye({lead_type:"exit_intent",email:r.email.trim().toLowerCase(),first_name:r.first_name.trim()||void 0,phone:r.phone.trim()||void 0,criteria:r.area.trim()?{area:r.area.trim()}:void 0}),u(!0),setTimeout(()=>t(!1),2200)}catch{ae.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(YAe,{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, ${lB} 0%, ${ife} 60%, ${lf} 130%)`},children:e.jsx("div",{className:"absolute top-4 left-6",children:e.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:eU},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:ife,border:`1px solid ${lf}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:e.jsx(un,{className:"h-6 w-6",style:{color:lf}})}),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(QAe,{values:r,setValues:a,honeypot:o,setHoneypot:c,showPhone:!1}),e.jsx(XAe,{type:"submit",disabled:i||!r.email,children:i?"Sending…":"Send My List"})]})]})]})})}function h9t(){const[s,t]=N.useState([]);N.useEffect(()=>{try{const o=localStorage.getItem(Mw.savedListings);o&&t(JSON.parse(o))}catch{}},[]);const n=o=>{t(o);try{localStorage.setItem(Mw.savedListings,JSON.stringify(o))}catch{}},r=N.useCallback(o=>s.includes(o),[s]),a=o=>{s.includes(o)||n([...s,o])},i=o=>n(s.filter(c=>c!==o));return{ids:s,has:r,add:a,remove:i,toggle:o=>s.includes(o)?i(o):a(o)}}function m9t({listingId:s,listingAddress:t,className:n}){const{has:r,add:a,remove:i}=h9t(),l=r(s),[o,c]=N.useState(!1),d=()=>{if(l){i(s);return}if(KAe()){a(s),ae.success("Saved to your favorites"),rye({lead_type:"saved_listing",email:c9t()||"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(gi,{className:`h-5 w-5 ${l?"fill-current":""}`})}),e.jsx(p9t,{open:o,onClose:()=>c(!1),listingId:s,listingAddress:t,onSaved:()=>a(s)})]})}function p9t({open:s,onClose:t,listingId:n,listingAddress:r,onSaved:a}){const{values:i,setValues:l,loading:o,setLoading:c,honeypot:d,setHoneypot:u}=ZAe(),h=async p=>{if(p.preventDefault(),!!i.email){c(!0);try{await rye({lead_type:"saved_listing",email:i.email.trim().toLowerCase(),first_name:i.first_name.trim()||void 0,phone:i.phone.trim()||void 0,listing_id:n,listing_address:r}),a(),ae.success("Saved to your favorites"),t()}catch{ae.error("Something went wrong. Please try again.")}finally{c(!1)}}};return e.jsx(YAe,{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(gi,{className:"h-4 w-4",style:{color:lf}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:eU},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(QAe,{values:i,setValues:l,honeypot:d,setHoneypot:u}),e.jsx(XAe,{type:"submit",disabled:o||!i.email,children:o?"Saving…":"Save Home"})]})]})})}function cB(s,[t,n]){return Math.min(n,Math.max(t,s))}function tU(s){const t=N.useRef({value:s,previous:s});return N.useMemo(()=>(t.current.value!==s&&(t.current.previous=t.current.value,t.current.value=s),t.current.previous),[s])}var plt=["PageUp","PageDown"],flt=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],xlt={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},$D="Slider",[k4e,f9t,x9t]=TD($D),[glt,Sxn]=pu($D,[x9t]),[g9t,aye]=glt($D),ylt=N.forwardRef((s,t)=>{const{name:n,min:r=0,max:a=100,step:i=1,orientation:l="horizontal",disabled:o=!1,minStepsBetweenThumbs:c=0,defaultValue:d=[r],value:u,onValueChange:h=()=>{},onValueCommit:p=()=>{},inverted:f=!1,form:g,..._}=s,v=N.useRef(new Set),j=N.useRef(0),S=l==="horizontal"?y9t:v9t,[A=[],T]=hm({prop:u,defaultProp:d,onChange:V=>{var Y;(Y=[...v.current][j.current])==null||Y.focus(),h(V)}}),L=N.useRef(A);function D(V){const W=N9t(A,V);z(V,W)}function M(V){z(V,j.current)}function F(){const V=L.current[j.current];A[j.current]!==V&&p(A)}function z(V,W,{commit:Y}={commit:!1}){const K=T9t(i),J=E9t(Math.round((V-r)/i)*i+r,K),ne=cB(J,[r,a]);T((ie=[])=>{const he=w9t(ie,ne,W);if(C9t(he,c*i)){j.current=he.indexOf(ne);const ce=String(he)!==String(ie);return ce&&Y&&p(he),ce?he:ie}else return ie})}return e.jsx(g9t,{scope:s.__scopeSlider,name:n,disabled:o,min:r,max:a,valueIndexToChangeRef:j,thumbs:v.current,values:A,orientation:l,form:g,children:e.jsx(k4e.Provider,{scope:s.__scopeSlider,children:e.jsx(k4e.Slot,{scope:s.__scopeSlider,children:e.jsx(S,{"aria-disabled":o,"data-disabled":o?"":void 0,..._,ref:t,onPointerDown:_r(_.onPointerDown,()=>{o||(L.current=A)}),min:r,max:a,inverted:f,onSlideStart:o?void 0:D,onSlideMove:o?void 0:M,onSlideEnd:o?void 0:F,onHomeKeyDown:()=>!o&&z(r,0,{commit:!0}),onEndKeyDown:()=>!o&&z(a,A.length-1,{commit:!0}),onStepKeyDown:({event:V,direction:W})=>{if(!o){const J=plt.includes(V.key)||V.shiftKey&&flt.includes(V.key)?10:1,ne=j.current,ie=A[ne],he=i*J*W;z(ie+he,ne,{commit:!0})}}})})})})});ylt.displayName=$D;var[vlt,blt]=glt($D,{startEdge:"left",endEdge:"right",size:"width",direction:1}),y9t=N.forwardRef((s,t)=>{const{min:n,max:r,dir:a,inverted:i,onSlideStart:l,onSlideMove:o,onSlideEnd:c,onStepKeyDown:d,...u}=s,[h,p]=N.useState(null),f=Si(t,S=>p(S)),g=N.useRef(void 0),_=NN(a),v=_==="ltr",j=v&&!i||!v&&i;function b(S){const A=g.current||h.getBoundingClientRect(),T=[0,A.width],D=JAe(T,j?[n,r]:[r,n]);return g.current=A,D(S-A.left)}return e.jsx(vlt,{scope:s.__scopeSlider,startEdge:j?"left":"right",endEdge:j?"right":"left",direction:j?1:-1,size:"width",children:e.jsx(_lt,{dir:_,"data-orientation":"horizontal",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:S=>{const A=b(S.clientX);l==null||l(A)},onSlideMove:S=>{const A=b(S.clientX);o==null||o(A)},onSlideEnd:()=>{g.current=void 0,c==null||c()},onStepKeyDown:S=>{const T=xlt[j?"from-left":"from-right"].includes(S.key);d==null||d({event:S,direction:T?-1:1})}})})}),v9t=N.forwardRef((s,t)=>{const{min:n,max:r,inverted:a,onSlideStart:i,onSlideMove:l,onSlideEnd:o,onStepKeyDown:c,...d}=s,u=N.useRef(null),h=Si(t,u),p=N.useRef(void 0),f=!a;function g(_){const v=p.current||u.current.getBoundingClientRect(),j=[0,v.height],S=JAe(j,f?[r,n]:[n,r]);return p.current=v,S(_-v.top)}return e.jsx(vlt,{scope:s.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:e.jsx(_lt,{"data-orientation":"vertical",...d,ref:h,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:_=>{const v=g(_.clientY);i==null||i(v)},onSlideMove:_=>{const v=g(_.clientY);l==null||l(v)},onSlideEnd:()=>{p.current=void 0,o==null||o()},onStepKeyDown:_=>{const j=xlt[f?"from-bottom":"from-top"].includes(_.key);c==null||c({event:_,direction:j?-1:1})}})})}),_lt=N.forwardRef((s,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:a,onSlideEnd:i,onHomeKeyDown:l,onEndKeyDown:o,onStepKeyDown:c,...d}=s,u=aye($D,n);return e.jsx(Jr.span,{...d,ref:t,onKeyDown:_r(s.onKeyDown,h=>{h.key==="Home"?(l(h),h.preventDefault()):h.key==="End"?(o(h),h.preventDefault()):plt.concat(flt).includes(h.key)&&(c(h),h.preventDefault())}),onPointerDown:_r(s.onPointerDown,h=>{const p=h.target;p.setPointerCapture(h.pointerId),h.preventDefault(),u.thumbs.has(p)?p.focus():r(h)}),onPointerMove:_r(s.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&a(h)}),onPointerUp:_r(s.onPointerUp,h=>{const p=h.target;p.hasPointerCapture(h.pointerId)&&(p.releasePointerCapture(h.pointerId),i(h))})})}),wlt="SliderTrack",jlt=N.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=aye(wlt,n);return e.jsx(Jr.span,{"data-disabled":a.disabled?"":void 0,"data-orientation":a.orientation,...r,ref:t})});jlt.displayName=wlt;var S4e="SliderRange",Nlt=N.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=aye(S4e,n),i=blt(S4e,n),l=N.useRef(null),o=Si(t,l),c=a.values.length,d=a.values.map(p=>Clt(p,a.min,a.max)),u=c>1?Math.min(...d):0,h=100-Math.max(...d);return e.jsx(Jr.span,{"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,...r,ref:o,style:{...s.style,[i.startEdge]:u+"%",[i.endEdge]:h+"%"}})});Nlt.displayName=S4e;var C4e="SliderThumb",klt=N.forwardRef((s,t)=>{const n=f9t(s.__scopeSlider),[r,a]=N.useState(null),i=Si(t,o=>a(o)),l=N.useMemo(()=>r?n().findIndex(o=>o.ref.current===r):-1,[n,r]);return e.jsx(b9t,{...s,ref:i,index:l})}),b9t=N.forwardRef((s,t)=>{const{__scopeSlider:n,index:r,name:a,...i}=s,l=aye(C4e,n),o=blt(C4e,n),[c,d]=N.useState(null),u=Si(t,b=>d(b)),h=c?l.form||!!c.closest("form"):!0,p=B$(c),f=l.values[r],g=f===void 0?0:Clt(f,l.min,l.max),_=j9t(r,l.values.length),v=p==null?void 0:p[o.size],j=v?k9t(v,g,o.direction):0;return N.useEffect(()=>{if(c)return l.thumbs.add(c),()=>{l.thumbs.delete(c)}},[c,l.thumbs]),e.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[o.startEdge]:`calc(${g}% + ${j}px)`},children:[e.jsx(k4e.ItemSlot,{scope:s.__scopeSlider,children:e.jsx(Jr.span,{role:"slider","aria-label":s["aria-label"]||_,"aria-valuemin":l.min,"aria-valuenow":f,"aria-valuemax":l.max,"aria-orientation":l.orientation,"data-orientation":l.orientation,"data-disabled":l.disabled?"":void 0,tabIndex:l.disabled?void 0:0,...i,ref:u,style:f===void 0?{display:"none"}:s.style,onFocus:_r(s.onFocus,()=>{l.valueIndexToChangeRef.current=r})})}),h&&e.jsx(Slt,{name:a??(l.name?l.name+(l.values.length>1?"[]":""):void 0),form:l.form,value:f},r)]})});klt.displayName=C4e;var _9t="RadioBubbleInput",Slt=N.forwardRef(({__scopeSlider:s,value:t,...n},r)=>{const a=N.useRef(null),i=Si(a,r),l=tU(t);return N.useEffect(()=>{const o=a.current;if(!o)return;const c=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(c,"value").set;if(l!==t&&u){const h=new Event("input",{bubbles:!0});u.call(o,t),o.dispatchEvent(h)}},[l,t]),e.jsx(Jr.input,{style:{display:"none"},...n,ref:i,defaultValue:t})});Slt.displayName=_9t;function w9t(s=[],t,n){const r=[...s];return r[n]=t,r.sort((a,i)=>a-i)}function Clt(s,t,n){const i=100/(n-t)*(s-t);return cB(i,[0,100])}function j9t(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}function N9t(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 k9t(s,t,n){const r=s/2,i=JAe([0,50],[0,r]);return(r-i(t)*n)*n}function S9t(s){return s.slice(0,-1).map((t,n)=>s[n+1]-t)}function C9t(s,t){if(t>0){const n=S9t(s);return Math.min(...n)>=t}return!0}function JAe(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 T9t(s){return(String(s).split(".")[1]||"").length}function E9t(s,t){const n=Math.pow(10,t);return Math.round(s*n)/n}var Tlt=ylt,A9t=jlt,M9t=Nlt,I9t=klt;const Bm=N.forwardRef(({className:s,...t},n)=>e.jsxs(Tlt,{ref:n,className:Et("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx(A9t,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(M9t,{className:"absolute h-full bg-primary"})}),e.jsx(I9t,{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"})]}));Bm.displayName=Tlt.displayName;var P9t=[" ","Enter","ArrowUp","ArrowDown"],L9t=[" ","Enter"],xM="Select",[iye,oye,D9t]=TD(xM),[UD,Cxn]=pu(xM,[D9t,Gw]),lye=Gw(),[R9t,K4]=UD(xM),[O9t,F9t]=UD(xM),Elt=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:p,required:f,form:g}=s,_=lye(t),[v,j]=N.useState(null),[b,S]=N.useState(null),[A,T]=N.useState(!1),L=NN(d),[D,M]=hm({prop:r,defaultProp:a??!1,onChange:i,caller:xM}),[F,z]=hm({prop:l,defaultProp:o,onChange:c,caller:xM}),V=N.useRef(null),W=v?g||!!v.closest("form"):!0,[Y,K]=N.useState(new Set),J=Array.from(Y).map(ne=>ne.props.value).join(";");return e.jsx($$,{..._,children:e.jsxs(R9t,{required:f,scope:t,trigger:v,onTriggerChange:j,valueNode:b,onValueNodeChange:S,valueNodeHasChildren:A,onValueNodeHasChildrenChange:T,contentId:dm(),value:F,onValueChange:z,open:D,onOpenChange:M,dir:L,triggerPointerDownPosRef:V,disabled:p,children:[e.jsx(iye.Provider,{scope:t,children:e.jsx(O9t,{scope:s.__scopeSelect,onNativeOptionAdd:N.useCallback(ne=>{K(ie=>new Set(ie).add(ne))},[]),onNativeOptionRemove:N.useCallback(ne=>{K(ie=>{const he=new Set(ie);return he.delete(ne),he})},[]),children:n})}),W?e.jsxs(Jlt,{"aria-hidden":!0,required:f,tabIndex:-1,name:u,autoComplete:h,value:F,onChange:ne=>z(ne.target.value),disabled:p,form:g,children:[F===void 0?e.jsx("option",{value:""}):null,Array.from(Y)]},J):null]})})};Elt.displayName=xM;var Alt="SelectTrigger",Mlt=N.forwardRef((s,t)=>{const{__scopeSelect:n,disabled:r=!1,...a}=s,i=lye(n),l=K4(Alt,n),o=l.disabled||r,c=Si(t,l.onTriggerChange),d=oye(n),u=N.useRef("touch"),[h,p,f]=tct(_=>{const v=d().filter(S=>!S.disabled),j=v.find(S=>S.value===l.value),b=sct(v,_,j);b!==void 0&&l.onValueChange(b.value)}),g=_=>{o||(l.onOpenChange(!0),f()),_&&(l.triggerPointerDownPosRef.current={x:Math.round(_.pageX),y:Math.round(_.pageY)})};return e.jsx(PD,{asChild:!0,...i,children:e.jsx(Jr.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":ect(l.value)?"":void 0,...a,ref:c,onClick:_r(a.onClick,_=>{_.currentTarget.focus(),u.current!=="mouse"&&g(_)}),onPointerDown:_r(a.onPointerDown,_=>{u.current=_.pointerType;const v=_.target;v.hasPointerCapture(_.pointerId)&&v.releasePointerCapture(_.pointerId),_.button===0&&_.ctrlKey===!1&&_.pointerType==="mouse"&&(g(_),_.preventDefault())}),onKeyDown:_r(a.onKeyDown,_=>{const v=h.current!=="";!(_.ctrlKey||_.altKey||_.metaKey)&&_.key.length===1&&p(_.key),!(v&&_.key===" ")&&P9t.includes(_.key)&&(g(),_.preventDefault())})})})});Mlt.displayName=Alt;var Ilt="SelectValue",Plt=N.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,children:i,placeholder:l="",...o}=s,c=K4(Ilt,n),{onValueNodeHasChildrenChange:d}=c,u=i!==void 0,h=Si(t,c.onValueNodeChange);return mh(()=>{d(u)},[d,u]),e.jsx(Jr.span,{...o,ref:h,style:{pointerEvents:"none"},children:ect(c.value)?e.jsx(e.Fragment,{children:l}):i})});Plt.displayName=Ilt;var z9t="SelectIcon",Llt=N.forwardRef((s,t)=>{const{__scopeSelect:n,children:r,...a}=s;return e.jsx(Jr.span,{"aria-hidden":!0,...a,ref:t,children:r||"▼"})});Llt.displayName=z9t;var B9t="SelectPortal",Dlt=s=>e.jsx(ED,{asChild:!0,...s});Dlt.displayName=B9t;var gM="SelectContent",Rlt=N.forwardRef((s,t)=>{const n=K4(gM,s.__scopeSelect),[r,a]=N.useState();if(mh(()=>{a(new DocumentFragment)},[]),!n.open){const i=r;return i?Hx.createPortal(e.jsx(Olt,{scope:s.__scopeSelect,children:e.jsx(iye.Slot,{scope:s.__scopeSelect,children:e.jsx("div",{children:s.children})})}),i):null}return e.jsx(Flt,{...s,ref:t})});Rlt.displayName=gM;var U1=10,[Olt,Y4]=UD(gM),$9t="SelectContentImpl",U9t=S4("SelectContent.RemoveScroll"),Flt=N.forwardRef((s,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:a,onEscapeKeyDown:i,onPointerDownOutside:l,side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:p,collisionPadding:f,sticky:g,hideWhenDetached:_,avoidCollisions:v,...j}=s,b=K4(gM,n),[S,A]=N.useState(null),[T,L]=N.useState(null),D=Si(t,Ae=>A(Ae)),[M,F]=N.useState(null),[z,V]=N.useState(null),W=oye(n),[Y,K]=N.useState(!1),J=N.useRef(!1);N.useEffect(()=>{if(S)return Y0e(S)},[S]),G0e();const ne=N.useCallback(Ae=>{const[De,...Ie]=W().map(be=>be.ref.current),[Fe]=Ie.slice(-1),qe=document.activeElement;for(const be of Ae)if(be===qe||(be==null||be.scrollIntoView({block:"nearest"}),be===De&&T&&(T.scrollTop=0),be===Fe&&T&&(T.scrollTop=T.scrollHeight),be==null||be.focus(),document.activeElement!==qe))return},[W,T]),ie=N.useCallback(()=>ne([M,S]),[ne,M,S]);N.useEffect(()=>{Y&&ie()},[Y,ie]);const{onOpenChange:he,triggerPointerDownPosRef:ce}=b;N.useEffect(()=>{if(S){let Ae={x:0,y:0};const De=Fe=>{var qe,be;Ae={x:Math.abs(Math.round(Fe.pageX)-(((qe=ce.current)==null?void 0:qe.x)??0)),y:Math.abs(Math.round(Fe.pageY)-(((be=ce.current)==null?void 0:be.y)??0))}},Ie=Fe=>{Ae.x<=10&&Ae.y<=10?Fe.preventDefault():S.contains(Fe.target)||he(!1),document.removeEventListener("pointermove",De),ce.current=null};return ce.current!==null&&(document.addEventListener("pointermove",De),document.addEventListener("pointerup",Ie,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",De),document.removeEventListener("pointerup",Ie,{capture:!0})}}},[S,he,ce]),N.useEffect(()=>{const Ae=()=>he(!1);return window.addEventListener("blur",Ae),window.addEventListener("resize",Ae),()=>{window.removeEventListener("blur",Ae),window.removeEventListener("resize",Ae)}},[he]);const[pe,le]=tct(Ae=>{const De=W().filter(qe=>!qe.disabled),Ie=De.find(qe=>qe.ref.current===document.activeElement),Fe=sct(De,Ae,Ie);Fe&&setTimeout(()=>Fe.ref.current.focus())}),ve=N.useCallback((Ae,De,Ie)=>{const Fe=!J.current&&!Ie;(b.value!==void 0&&b.value===De||Fe)&&(F(Ae),Fe&&(J.current=!0))},[b.value]),ge=N.useCallback(()=>S==null?void 0:S.focus(),[S]),Te=N.useCallback((Ae,De,Ie)=>{const Fe=!J.current&&!Ie;(b.value!==void 0&&b.value===De||Fe)&&V(Ae)},[b.value]),Me=r==="popper"?T4e:zlt,Ce=Me===T4e?{side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:p,collisionPadding:f,sticky:g,hideWhenDetached:_,avoidCollisions:v}:{};return e.jsx(Olt,{scope:n,content:S,viewport:T,onViewportChange:L,itemRefCallback:ve,selectedItem:M,onItemLeave:ge,itemTextRefCallback:Te,focusSelectedItem:ie,selectedItemText:z,position:r,isPositioned:Y,searchRef:pe,children:e.jsx(K$,{as:U9t,allowPinchZoom:!0,children:e.jsx(G$,{asChild:!0,trapped:b.open,onMountAutoFocus:Ae=>{Ae.preventDefault()},onUnmountAutoFocus:_r(a,Ae=>{var De;(De=b.trigger)==null||De.focus({preventScroll:!0}),Ae.preventDefault()}),children:e.jsx(H4,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:Ae=>Ae.preventDefault(),onDismiss:()=>b.onOpenChange(!1),children:e.jsx(Me,{role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:Ae=>Ae.preventDefault(),...j,...Ce,onPlaced:()=>K(!0),ref:D,style:{display:"flex",flexDirection:"column",outline:"none",...j.style},onKeyDown:_r(j.onKeyDown,Ae=>{const De=Ae.ctrlKey||Ae.altKey||Ae.metaKey;if(Ae.key==="Tab"&&Ae.preventDefault(),!De&&Ae.key.length===1&&le(Ae.key),["ArrowUp","ArrowDown","Home","End"].includes(Ae.key)){let Fe=W().filter(qe=>!qe.disabled).map(qe=>qe.ref.current);if(["ArrowUp","End"].includes(Ae.key)&&(Fe=Fe.slice().reverse()),["ArrowUp","ArrowDown"].includes(Ae.key)){const qe=Ae.target,be=Fe.indexOf(qe);Fe=Fe.slice(be+1)}setTimeout(()=>ne(Fe)),Ae.preventDefault()}})})})})})})});Flt.displayName=$9t;var q9t="SelectItemAlignedPosition",zlt=N.forwardRef((s,t)=>{const{__scopeSelect:n,onPlaced:r,...a}=s,i=K4(gM,n),l=Y4(gM,n),[o,c]=N.useState(null),[d,u]=N.useState(null),h=Si(t,D=>u(D)),p=oye(n),f=N.useRef(!1),g=N.useRef(!0),{viewport:_,selectedItem:v,selectedItemText:j,focusSelectedItem:b}=l,S=N.useCallback(()=>{if(i.trigger&&i.valueNode&&o&&d&&_&&v&&j){const D=i.trigger.getBoundingClientRect(),M=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),z=j.getBoundingClientRect();if(i.dir!=="rtl"){const qe=z.left-M.left,be=F.left-qe,Ze=D.left-be,Ne=D.width+Ze,it=Math.max(Ne,M.width),je=window.innerWidth-U1,Ge=cB(be,[U1,Math.max(U1,je-it)]);o.style.minWidth=Ne+"px",o.style.left=Ge+"px"}else{const qe=M.right-z.right,be=window.innerWidth-F.right-qe,Ze=window.innerWidth-D.right-be,Ne=D.width+Ze,it=Math.max(Ne,M.width),je=window.innerWidth-U1,Ge=cB(be,[U1,Math.max(U1,je-it)]);o.style.minWidth=Ne+"px",o.style.right=Ge+"px"}const V=p(),W=window.innerHeight-U1*2,Y=_.scrollHeight,K=window.getComputedStyle(d),J=parseInt(K.borderTopWidth,10),ne=parseInt(K.paddingTop,10),ie=parseInt(K.borderBottomWidth,10),he=parseInt(K.paddingBottom,10),ce=J+ne+Y+he+ie,pe=Math.min(v.offsetHeight*5,ce),le=window.getComputedStyle(_),ve=parseInt(le.paddingTop,10),ge=parseInt(le.paddingBottom,10),Te=D.top+D.height/2-U1,Me=W-Te,Ce=v.offsetHeight/2,Ae=v.offsetTop+Ce,De=J+ne+Ae,Ie=ce-De;if(De<=Te){const qe=V.length>0&&v===V[V.length-1].ref.current;o.style.bottom="0px";const be=d.clientHeight-_.offsetTop-_.offsetHeight,Ze=Math.max(Me,Ce+(qe?ge:0)+be+ie),Ne=De+Ze;o.style.height=Ne+"px"}else{const qe=V.length>0&&v===V[0].ref.current;o.style.top="0px";const Ze=Math.max(Te,J+_.offsetTop+(qe?ve:0)+Ce)+Ie;o.style.height=Ze+"px",_.scrollTop=De-Te+_.offsetTop}o.style.margin=`${U1}px 0`,o.style.minHeight=pe+"px",o.style.maxHeight=W+"px",r==null||r(),requestAnimationFrame(()=>f.current=!0)}},[p,i.trigger,i.valueNode,o,d,_,v,j,i.dir,r]);mh(()=>S(),[S]);const[A,T]=N.useState();mh(()=>{d&&T(window.getComputedStyle(d).zIndex)},[d]);const L=N.useCallback(D=>{D&&g.current===!0&&(S(),b==null||b(),g.current=!1)},[S,b]);return e.jsx(H9t,{scope:n,contentWrapper:o,shouldExpandOnScrollRef:f,onScrollButtonChange:L,children:e.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:A},children:e.jsx(Jr.div,{...a,ref:h,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});zlt.displayName=q9t;var V9t="SelectPopperPosition",T4e=N.forwardRef((s,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:a=U1,...i}=s,l=lye(n);return e.jsx(U$,{...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)"}})});T4e.displayName=V9t;var[H9t,eMe]=UD(gM,{}),E4e="SelectViewport",Blt=N.forwardRef((s,t)=>{const{__scopeSelect:n,nonce:r,...a}=s,i=Y4(E4e,n),l=eMe(E4e,n),o=Si(t,i.onViewportChange),c=N.useRef(0);return e.jsxs(e.Fragment,{children:[e.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),e.jsx(iye.Slot,{scope:n,children:e.jsx(Jr.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:o,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:_r(a.onScroll,d=>{const u=d.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:p}=l;if(p!=null&&p.current&&h){const f=Math.abs(c.current-u.scrollTop);if(f>0){const g=window.innerHeight-U1*2,_=parseFloat(h.style.minHeight),v=parseFloat(h.style.height),j=Math.max(_,v);if(j0?A:0,h.style.justifyContent="flex-end")}}}c.current=u.scrollTop})})})]})});Blt.displayName=E4e;var $lt="SelectGroup",[G9t,W9t]=UD($lt),K9t=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=dm();return e.jsx(G9t,{scope:n,id:a,children:e.jsx(Jr.div,{role:"group","aria-labelledby":a,...r,ref:t})})});K9t.displayName=$lt;var Ult="SelectLabel",qlt=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=W9t(Ult,n);return e.jsx(Jr.div,{id:a.id,...r,ref:t})});qlt.displayName=Ult;var ofe="SelectItem",[Y9t,Vlt]=UD(ofe),Hlt=N.forwardRef((s,t)=>{const{__scopeSelect:n,value:r,disabled:a=!1,textValue:i,...l}=s,o=K4(ofe,n),c=Y4(ofe,n),d=o.value===r,[u,h]=N.useState(i??""),[p,f]=N.useState(!1),g=Si(t,b=>{var S;return(S=c.itemRefCallback)==null?void 0:S.call(c,b,r,a)}),_=dm(),v=N.useRef("touch"),j=()=>{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(Y9t,{scope:n,value:r,disabled:a,textId:_,isSelected:d,onItemTextChange:N.useCallback(b=>{h(S=>S||((b==null?void 0:b.textContent)??"").trim())},[]),children:e.jsx(iye.ItemSlot,{scope:n,value:r,disabled:a,textValue:u,children:e.jsx(Jr.div,{role:"option","aria-labelledby":_,"data-highlighted":p?"":void 0,"aria-selected":d&&p,"data-state":d?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...l,ref:g,onFocus:_r(l.onFocus,()=>f(!0)),onBlur:_r(l.onBlur,()=>f(!1)),onClick:_r(l.onClick,()=>{v.current!=="mouse"&&j()}),onPointerUp:_r(l.onPointerUp,()=>{v.current==="mouse"&&j()}),onPointerDown:_r(l.onPointerDown,b=>{v.current=b.pointerType}),onPointerMove:_r(l.onPointerMove,b=>{var S;v.current=b.pointerType,a?(S=c.onItemLeave)==null||S.call(c):v.current==="mouse"&&b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:_r(l.onPointerLeave,b=>{var S;b.currentTarget===document.activeElement&&((S=c.onItemLeave)==null||S.call(c))}),onKeyDown:_r(l.onKeyDown,b=>{var A;((A=c.searchRef)==null?void 0:A.current)!==""&&b.key===" "||(L9t.includes(b.key)&&j(),b.key===" "&&b.preventDefault())})})})})});Hlt.displayName=ofe;var u7="SelectItemText",Glt=N.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,...i}=s,l=K4(u7,n),o=Y4(u7,n),c=Vlt(u7,n),d=F9t(u7,n),[u,h]=N.useState(null),p=Si(t,j=>h(j),c.onItemTextChange,j=>{var b;return(b=o.itemTextRefCallback)==null?void 0:b.call(o,j,c.value,c.disabled)}),f=u==null?void 0:u.textContent,g=N.useMemo(()=>e.jsx("option",{value:c.value,disabled:c.disabled,children:f},c.value),[c.disabled,c.value,f]),{onNativeOptionAdd:_,onNativeOptionRemove:v}=d;return mh(()=>(_(g),()=>v(g)),[_,v,g]),e.jsxs(e.Fragment,{children:[e.jsx(Jr.span,{id:c.textId,...i,ref:p}),c.isSelected&&l.valueNode&&!l.valueNodeHasChildren?Hx.createPortal(i.children,l.valueNode):null]})});Glt.displayName=u7;var Wlt="SelectItemIndicator",Klt=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return Vlt(Wlt,n).isSelected?e.jsx(Jr.span,{"aria-hidden":!0,...r,ref:t}):null});Klt.displayName=Wlt;var A4e="SelectScrollUpButton",Ylt=N.forwardRef((s,t)=>{const n=Y4(A4e,s.__scopeSelect),r=eMe(A4e,s.__scopeSelect),[a,i]=N.useState(!1),l=Si(t,r.onScrollButtonChange);return mh(()=>{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(Qlt,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop-c.offsetHeight)}}):null});Ylt.displayName=A4e;var M4e="SelectScrollDownButton",Zlt=N.forwardRef((s,t)=>{const n=Y4(M4e,s.__scopeSelect),r=eMe(M4e,s.__scopeSelect),[a,i]=N.useState(!1),l=Si(t,r.onScrollButtonChange);return mh(()=>{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(Qlt,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop+c.offsetHeight)}}):null});Zlt.displayName=M4e;var Qlt=N.forwardRef((s,t)=>{const{__scopeSelect:n,onAutoScroll:r,...a}=s,i=Y4("SelectScrollButton",n),l=N.useRef(null),o=oye(n),c=N.useCallback(()=>{l.current!==null&&(window.clearInterval(l.current),l.current=null)},[]);return N.useEffect(()=>()=>c(),[c]),mh(()=>{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(Jr.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:_r(a.onPointerDown,()=>{l.current===null&&(l.current=window.setInterval(r,50))}),onPointerMove:_r(a.onPointerMove,()=>{var d;(d=i.onItemLeave)==null||d.call(i),l.current===null&&(l.current=window.setInterval(r,50))}),onPointerLeave:_r(a.onPointerLeave,()=>{c()})})}),Z9t="SelectSeparator",Xlt=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return e.jsx(Jr.div,{"aria-hidden":!0,...r,ref:t})});Xlt.displayName=Z9t;var I4e="SelectArrow",Q9t=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=lye(n),i=K4(I4e,n),l=Y4(I4e,n);return i.open&&l.position==="popper"?e.jsx(q$,{...a,...r,ref:t}):null});Q9t.displayName=I4e;var X9t="SelectBubbleInput",Jlt=N.forwardRef(({__scopeSelect:s,value:t,...n},r)=>{const a=N.useRef(null),i=Si(r,a),l=tU(t);return N.useEffect(()=>{const o=a.current;if(!o)return;const c=window.HTMLSelectElement.prototype,u=Object.getOwnPropertyDescriptor(c,"value").set;if(l!==t&&u){const h=new Event("change",{bubbles:!0});u.call(o,t),o.dispatchEvent(h)}},[l,t]),e.jsx(Jr.select,{...n,style:{...nrt,...n.style},ref:i,defaultValue:t})});Jlt.displayName=X9t;function ect(s){return s===""||s===void 0}function tct(s){const t=lh(s),n=N.useRef(""),r=N.useRef(0),a=N.useCallback(l=>{const o=n.current+l;t(o),function c(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>c(""),1e3))}(o)},[t]),i=N.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return N.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,a,i]}function sct(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=J9t(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 J9t(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var ezt=Elt,nct=Mlt,tzt=Plt,szt=Llt,nzt=Dlt,rct=Rlt,rzt=Blt,act=qlt,ict=Hlt,azt=Glt,izt=Klt,oct=Ylt,lct=Zlt,cct=Xlt;const ds=ezt,us=tzt,ls=N.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(nct,{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(szt,{asChild:!0,children:e.jsx(io,{className:"h-4 w-4 opacity-50"})})]}));ls.displayName=nct.displayName;const dct=N.forwardRef(({className:s,...t},n)=>e.jsx(oct,{ref:n,className:Et("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(tx,{className:"h-4 w-4"})}));dct.displayName=oct.displayName;const uct=N.forwardRef(({className:s,...t},n)=>e.jsx(lct,{ref:n,className:Et("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(io,{className:"h-4 w-4"})}));uct.displayName=lct.displayName;const cs=N.forwardRef(({className:s,children:t,position:n="popper",...r},a)=>e.jsx(nzt,{children:e.jsxs(rct,{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(dct,{}),e.jsx(rzt,{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(uct,{})]})}));cs.displayName=rct.displayName;const ozt=N.forwardRef(({className:s,...t},n)=>e.jsx(act,{ref:n,className:Et("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));ozt.displayName=act.displayName;const Qe=N.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(ict,{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(izt,{children:e.jsx(Ir,{className:"h-4 w-4"})})}),e.jsx(azt,{children:t})]}));Qe.displayName=ict.displayName;const lzt=N.forwardRef(({className:s,...t},n)=>e.jsx(cct,{ref:n,className:Et("-mx-1 my-1 h-px bg-muted",s),...t}));lzt.displayName=cct.displayName;const czt=s=>ct({queryKey:["public-listings",s],queryFn:async()=>{let t=q.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, 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}}),dzt=()=>ct({queryKey:["public-listings-search-index"],staleTime:5*60*1e3,queryFn:async()=>{const{data:s,error:t}=await q.from("listings").select("city, state, neighborhood, property_address").eq("is_approved",!0).eq("is_public",!0);if(t)throw t;const n=new Map,r=new Map,a=new Map;return(s||[]).forEach(i=>{if(i.city){const l=`${i.city}|${i.state||""}`.toLowerCase(),o=i.state?`${i.city}, ${i.state}`:i.city,c=n.get(l);c?c.count++:n.set(l,{label:o,city:i.city,state:i.state,count:1})}if(i.neighborhood){const l=`${i.neighborhood}|${i.city||""}`.toLowerCase(),o=i.city?`${i.neighborhood} — ${i.city}`:i.neighborhood,c=r.get(l);c?c.count++:r.set(l,{label:o,city:i.city||"",neighborhood:i.neighborhood,count:1})}if(i.property_address){const l=String(i.property_address).match(/\b(\d{5})(?:-\d{4})?\b/);if(l){const o=l[1],c=a.get(o);c?c.count++:a.set(o,{label:o,zip:o,count:1})}}}),{cities:Array.from(n.values()).sort((i,l)=>l.count-i.count),neighborhoods:Array.from(r.values()).sort((i,l)=>l.count-i.count),zips:Array.from(a.values()).sort((i,l)=>l.count-i.count)}}}),uzt=s=>ct({queryKey:["public-listing",s],queryFn:async()=>{const t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);let n=q.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, agent_notes, agent_notes_public, mls_link, video_link, video_id, latitude, longitude, page_config, page_theme, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary, sort_order), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds, bunny_video_id) `).eq("is_approved",!0).eq("is_public",!0);t?n=n.eq("id",s):n=n.eq("slug",s);const{data:r,error:a}=await n.single();if(a)throw a;return r},enabled:!!s}),hzt=()=>gt({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 p=null,f=null;if(l){const{data:j}=await q.from("listing_shares").select("id, sharing_agent_id").eq("share_token",l).eq("listing_id",s).maybeSingle();j&&(p=j.id,f=j.sharing_agent_id)}const{data:g,error:_}=await q.from("listing_leads").insert({listing_id:s,agent_id:f||t,first_name:n,last_name:r,email:a,phone:i,share_id:p,referred_by_agent_id:f,lead_type:o,preferred_date:c||null,preferred_time:d||null,showing_mode:u||null,message:h||null}).select().single();if(_)throw _;const{error:v}=await q.functions.invoke("process-listing-lead",{body:{leadId:g.id}});return v&&console.error("Error processing lead:",v),g}}),mzt=()=>gt({mutationFn:async s=>{const{error:t}=await q.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}}),rBe="/assets/levelup-logo-color-BeKd2k_g.png",pzt={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"},fzt={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"},aBe={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},eH=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),rF=s=>new Intl.NumberFormat("en-US").format(s);function hct({slugOverride:s}={}){var Bt,Zt,Fs,Rs,ms;const t=bi(),n=s||t.slugOrId,[r]=gl(),{data:a,isLoading:i}=uzt(n||""),l=hzt(),o=mzt(),c=r.get("ref"),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(""),[_,v]=N.useState(""),[j,b]=N.useState(""),[S,A]=N.useState(""),[T,L]=N.useState(""),[D,M]=N.useState("in_person"),[F,z]=N.useState("info"),[V,W]=N.useState(!1),[Y,K]=N.useState(!1),[J,ne]=N.useState(null),[ie,he]=N.useState(!1);N.useState(!1);const[ce,pe]=N.useState(!1),[le,ve]=N.useState(20),[ge,Te]=N.useState(6.5),[Me,Ce]=N.useState(30),Ae=N.useRef(null),[De,Ie]=N.useState(!1);N.useEffect(()=>{const Pt=()=>Ie(window.scrollY>300);return window.addEventListener("scroll",Pt,{passive:!0}),()=>window.removeEventListener("scroll",Pt)},[]),N.useEffect(()=>{c&&o.mutate(c)},[c]),N.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[n]);const Fe=(a==null?void 0:a.photos)||[],qe=Fe.find(Pt=>Pt.is_primary)||Fe[0],be=N.useMemo(()=>{if(!(a!=null&&a.price))return 0;const Pt=a.price*(1-le/100),Jt=ge/100/12,ft=Me*12;return Jt===0?Pt/ft:Pt*Jt/(1-Math.pow(1+Jt,-ft))},[a==null?void 0:a.price,le,ge,Me]),Ze=async()=>{const Pt=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:Pt})}catch{}else await navigator.clipboard.writeText(Pt),ae.success("Link copied to clipboard")},Ne=async Pt=>{if(Pt.preventDefault(),!d.trim()||!f.trim()||!a)return;const Jt=F==="showing";if(Jt&&!S){ae.error("Please pick a preferred date for your showing");return}W(!0);try{await l.mutateAsync({listingId:a.id,agentId:a.agent_id,firstName:d.trim(),lastName:h.trim(),email:f.trim(),phone:_.trim(),shareToken:c,leadType:Jt?"showing_request":"info_request",preferredDate:Jt?S:null,preferredTime:Jt&&T||null,showingMode:Jt?D:null,message:j.trim()||null}),K(!0),ae.success(Jt?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(ft){console.error("Lead submission error:",ft),ae.error(`Failed to submit: ${ft.message||"Please try again"}`)}finally{W(!1)}},it=()=>{J!==null&&ne(J===0?Fe.length-1:J-1)},je=()=>{J!==null&&ne(J===Fe.length-1?0:J+1)};if(i)return e.jsx("div",{className:"min-h-screen bg-neutral-950",children:e.jsx(Ws,{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(Ln,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:rBe,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[e.jsx(Or,{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(Ln,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const Ge=a.property_address?`${a.property_address} — ${a.city}, ${a.state}`:`${a.city}, ${a.state} Home for Sale`,Be=((Zt=(Bt=a.agent)==null?void 0:Bt.brokerage)==null?void 0:Zt.name)||((Fs=a.agent)==null?void 0:Fs.brokerage_name),Ye=a.latitude&&a.longitude?`https://maps.google.com/maps?q=${a.latitude},${a.longitude}&z=15&output=embed`:a.property_address?`https://maps.google.com/maps?q=${encodeURIComponent(`${a.property_address}, ${a.city}, ${a.state}`)}&z=15&output=embed`:null,We=a.description||"",rt=We.length>420,tt=ce||!rt?We:We.slice(0,420).trimEnd()+"…",at=a.page_config||{},He=Pt=>{var Jt;return(((Jt=at.sections)==null?void 0:Jt[Pt])??!0)!==!1},dt=Array.isArray(at.addons)?at.addons:[],bt=at.custom_note||"",vt=at.accent_color||null;return e.jsxs(e.Fragment,{children:[e.jsxs(Go,{children:[e.jsxs("title",{children:[Ge," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${eH(a.price)} · ${a.bedrooms||""}BD ${a.bathrooms||""}BA ${a.square_footage?a.square_footage.toLocaleString()+" sqft · ":""}${aBe[a.property_type]} in ${a.city}, ${a.state}. ${We.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:Ge}),e.jsx("meta",{property:"og:description",content:`${eH(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}`}),qe&&e.jsx("meta",{property:"og:image",content:qe.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:Ge}),e.jsx("meta",{name:"twitter:description",content:`${eH(a.price)} · ${a.city}, ${a.state}`}),qe&&e.jsx("meta",{name:"twitter:image",content:qe.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:We,url:`https://listings.relevelup.com/${a.slug||a.id}`,datePosted:a.created_at,image:Fe.map(Pt=>Pt.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 ${De?"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(Ln,{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(Hr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:"All Listings"})]}),De&&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(([Pt,Jt])=>e.jsx("a",{href:`#${Pt}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:Jt},Pt))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(m9t,{listingId:a.id,listingAddress:a.property_address?`${a.property_address}, ${a.city}, ${a.state}`:`${a.city}, ${a.state}`,className:"h-9 w-9 rounded-full border border-white/20 bg-white/5 backdrop-blur hover:bg-white/15 flex items-center justify-center transition text-white"}),e.jsx("button",{onClick:Ze,className:"h-9 w-9 rounded-full border border-white/20 bg-white/5 backdrop-blur hover:bg-white/15 flex items-center justify-center transition","aria-label":"Share",children:e.jsx(Hl,{className:"h-4 w-4 text-white"})}),e.jsx(B,{size:"sm",onClick:()=>he(!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:Ae,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[qe?e.jsx("img",{src:qe.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(ze,{className:`${pzt[a.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:fzt[a.status]}),Fe.length>0&&e.jsxs("button",{onClick:()=>ne(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(mf,{className:"h-3.5 w-3.5"}),Fe.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:eH(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:rF(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(Xi,{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}),Be&&e.jsx("p",{className:"text-xs text-white/60",children:Be})]}),e.jsx(B,{size:"sm",onClick:()=>he(!0),className:"bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4",children:"Contact"})]})]}),e.jsxs("div",{className:"mt-10 flex items-center gap-2 text-white/50 text-xs uppercase tracking-widest",children:[e.jsx("span",{className:"h-px w-8 bg-white/30"}),"Scroll to explore"]})]})})]}),He("stats")&&e.jsx("section",{className:"border-b border-white/10 bg-neutral-950",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-8 grid grid-cols-2 md:grid-cols-5 gap-6",children:[a.bedrooms&&{icon:sy,label:"Bedrooms",value:a.bedrooms},a.bathrooms&&{icon:Cp,label:"Bathrooms",value:a.bathrooms},a.square_footage&&{icon:ly,label:"Interior",value:`${rF(a.square_footage)} sqft`},a.lot_size&&{icon:J2,label:"Lot Size",value:a.lot_size},a.year_built&&{icon:yr,label:"Year Built",value:a.year_built},!a.year_built&&a.square_footage&&{icon:fw,label:"Price / sqft",value:`$${rF(Math.round(a.price/a.square_footage))}`}].filter(Boolean).slice(0,5).map((Pt,Jt)=>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(Pt.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:Pt.label}),e.jsx("p",{className:"font-display text-2xl text-white font-light",children:Pt.value})]})]},Jt))})}),e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-16 grid lg:grid-cols-3 gap-12",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-20",children:[He("story")&&We&&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:tt})}),rt&&e.jsx("button",{onClick:()=>pe(!ce),className:"mt-4 text-sm text-white/60 hover:text-white underline underline-offset-4",children:ce?"Show less":"Read more"}),e.jsxs("div",{className:"mt-8 flex flex-wrap gap-2",children:[e.jsxs(ze,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[e.jsx(Va,{className:"h-3 w-3 mr-1.5"}),aBe[a.property_type]]}),a.has_hoa&&e.jsx(ze,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:"HOA"}),a.mls_link&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"ml-2 border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:a.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(bt||a.agent_notes&&a.agent_notes_public)&&e.jsxs("div",{className:"mt-10 rounded-2xl border border-white/10 bg-white/5 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(un,{className:"h-4 w-4 text-amber-300"}),e.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-white/60",children:"A note from the agent"})]}),e.jsxs("p",{className:"text-white/80 whitespace-pre-wrap leading-relaxed italic font-display",children:['"',bt||a.agent_notes,'"']})]})]}),He("gallery")&&Fe.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:()=>ne(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",Fe.length]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:Fe.slice(0,7).map((Pt,Jt)=>{const ft=["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"],Vt=Jt===6&&Fe.length>7;return e.jsxs("button",{onClick:()=>ne(Jt),className:`${ft[Jt]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[e.jsx("img",{src:Pt.photo_url,alt:`Photo ${Jt+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),Vt&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[e.jsx(mf,{className:"h-6 w-6 mb-1"}),e.jsxs("span",{className:"font-medium",children:["+",Fe.length-7," more"]})]})]},Pt.id)})})]}),He("video")&&((Rs=a.video)==null?void 0:Rs.playback_url)&&e.jsxs("section",{id:"video",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Video Tour"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Walk through the home"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:a.video.playback_url,className:"absolute inset-0 h-full w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Video Tour"})})]}),He("map")&&Ye&&e.jsxs("section",{id:"map",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Location"}),e.jsxs("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:[a.neighborhood?a.neighborhood:a.city,", ",a.state]}),e.jsx("div",{className:"rounded-2xl overflow-hidden border border-white/10 shadow-2xl aspect-[16/10]",children:e.jsx("iframe",{src:Ye,className:"w-full h-full grayscale-[.2] contrast-[1.05]",loading:"lazy",title:"Map"})}),e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-white/60 text-sm",children:[e.jsx(ka,{className:"h-4 w-4"}),a.property_address?`${a.property_address}, `:"",a.city,", ",a.state]})]}),He("payment")&&e.jsxs("section",{id:"payment",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Payment"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Estimate your monthly"}),e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-gradient-to-br from-white/5 to-transparent p-6 sm:p-8",children:[e.jsxs("div",{className:"flex items-baseline gap-3 mb-8",children:[e.jsxs("p",{className:"font-display text-5xl sm:text-6xl font-light text-white",children:["$",rF(Math.round(be))]}),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:[le,"%"]})]}),e.jsx(Bm,{value:[le],onValueChange:Pt=>ve(Pt[0]),min:0,max:50,step:1}),e.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",rF(Math.round(a.price*le/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:[ge.toFixed(2),"%"]})]}),e.jsx(Bm,{value:[ge],onValueChange:Pt=>Te(Pt[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:[Me," yr"]})]}),e.jsx(Bm,{value:[Me],onValueChange:Pt=>Ce(Pt[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(Pt=>{const Jt=Pt.type,ft=Pt.data||{};if(Jt==="extra_video"&&ft.url){const Vt=String(ft.url).includes("youtu")?`https://www.youtube.com/embed/${String(ft.url).split(/[/=]/).pop()}`:ft.url;return e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:ft.eyebrow||"Featured Video"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:ft.title||"Watch"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:Vt,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:ft.title||"Video"})})]},Pt.id)}return Jt==="3d_tour"&&ft.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:ft.title||"Step inside"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:ft.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},Pt.id):Jt==="floor_plan"&&ft.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:ft.title||"Layout"}),e.jsx("img",{src:ft.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},Pt.id):Jt==="testimonial"&&ft.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:['"',ft.quote,'"']}),ft.author&&e.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",ft.author]})]},Pt.id):Jt==="custom_cta"&&ft.label?e.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:vt?`${vt}22`:"rgba(255,255,255,0.05)",border:`1px solid ${vt||"rgba(255,255,255,0.1)"}`},children:[ft.title&&e.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:ft.title}),e.jsx(B,{asChild:!0,size:"lg",style:vt?{background:vt}:void 0,children:e.jsx("a",{href:ft.url||"#agent",children:ft.label})})]},Pt.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(Xi,{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}),Be&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:Be})]})]}),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(Ar,{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(Vs,{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(iBe,{submitted:Y,activeTab:F,setActiveTab:z,firstName:d,setFirstName:u,lastName:h,setLastName:p,email:f,setEmail:g,phone:_,setPhone:v,message:j,setMessage:b,preferredDate:S,setPreferredDate:A,preferredTime:T,setPreferredTime:L,showingMode:D,setShowingMode:M,isSubmitting:V,onSubmit:Ne})})]})]}),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:[((ms=a.agent)==null?void 0:ms.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(Ar,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),e.jsxs(B,{onClick:()=>he(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[e.jsx(om,{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:rBe,alt:"LevelUp",className:"h-6 opacity-80"}),e.jsxs("span",{children:["© ",new Date().getFullYear()," LevelUp"]})]}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"hover:text-white",children:"relevelup.com"})]})}),e.jsx(bs,{open:J!==null,onOpenChange:()=>ne(null),children:e.jsxs(vs,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[e.jsx(ws,{className:"sr-only",children:e.jsx(_s,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>ne(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(Bn,{className:"h-5 w-5"})}),J!==null&&Fe[J]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:Fe[J].photo_url,alt:`Photo ${J+1}`,className:"w-full max-h-[85vh] object-contain"}),Fe.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:it,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(pl,{className:"h-6 w-6"})}),e.jsx("button",{onClick:je,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(xa,{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:[J+1," / ",Fe.length]})]})]})]})}),e.jsx(bs,{open:ie,onOpenChange:he,children:e.jsxs(vs,{className:"max-w-md p-0 bg-white text-neutral-900",children:[e.jsx(ws,{className:"sr-only",children:e.jsx(_s,{children:"Contact the agent"})}),e.jsx("div",{className:"p-6",children:e.jsx(iBe,{submitted:Y,activeTab:F,setActiveTab:z,firstName:d,setFirstName:u,lastName:h,setLastName:p,email:f,setEmail:g,phone:_,setPhone:v,message:j,setMessage:b,preferredDate:S,setPreferredDate:A,preferredTime:T,setPreferredTime:L,showingMode:D,setShowingMode:M,isSubmitting:V,onSubmit:Ne})})]})})]})]})}function iBe(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:p,setMessage:f,preferredDate:g,setPreferredDate:_,preferredTime:v,setPreferredTime:j,showingMode:b,setShowingMode:S,isSubmitting:A,onSubmit:T}=s;return t?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"h-14 w-14 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(Ir,{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(Br,{value:n,onValueChange:L=>r(L),children:[e.jsxs(Fr,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(Kt,{value:"info",className:"gap-1.5",children:[e.jsx(Ei,{className:"h-3.5 w-3.5"})," Get Info"]}),e.jsxs(Kt,{value:"showing",className:"gap-1.5",children:[e.jsx(om,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),e.jsxs("form",{onSubmit:T,className:"space-y-3",children:[e.jsxs(is,{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:g,onChange:L=>_(L.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(ds,{value:v,onValueChange:j,children:[e.jsx(ls,{id:"preferredTime",children:e.jsx(us,{placeholder:"Any time"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"morning",children:"Morning (9am–12pm)"}),e.jsx(Qe,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),e.jsx(Qe,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"showingMode",children:"Tour Type"}),e.jsxs(ds,{value:b,onValueChange:L=>S(L),children:[e.jsx(ls,{id:"showingMode",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"in_person",children:"🏡 In-person showing"}),e.jsx(Qe,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),e.jsx(Qe,{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:L=>i(L.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lastName",children:"Last Name"}),e.jsx(ye,{id:"lastName",value:l,onChange:L=>o(L.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email *"}),e.jsx(ye,{id:"email",type:"email",value:c,onChange:L=>d(L.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:L=>h(L.target.value),required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"message",children:n==="showing"?"Anything else?":"Message (optional)"}),e.jsx(Es,{id:"message",value:p,onChange:L=>f(L.target.value),rows:2})]}),e.jsx(B,{type:"submit",disabled:A,className:"w-full bg-neutral-900 hover:bg-neutral-800 text-white h-11",children:A?"Sending…":n==="showing"?"Request Showing":"Get More Info"}),e.jsx("p",{className:"text-[11px] text-neutral-500 text-center",children:"The listing agent will contact you directly. No spam."})]})]})]})}const lfe="/assets/levelup-logo-white-C2RAgAoG.png",xzt="/assets/listings-hero-noir-BHCJrhvU.jpg";var mct={exports:{}};(function(s,t){(function(n,r){s.exports=r()})(Eh,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(w,m){var x=m[0],k=m[1],E=m[2],P=m[3],O=x*P-E*k;return O?(w[0]=P*(O=1/O),w[1]=-k*O,w[2]=-E*O,w[3]=x*O,w):null}function h(){var w=new d(9);return d!=Float32Array&&(w[1]=0,w[2]=0,w[3]=0,w[5]=0,w[6]=0,w[7]=0),w[0]=1,w[4]=1,w[8]=1,w}function p(w,m){var x=m[0],k=m[1],E=m[2],P=m[3],O=m[4],U=m[5],H=m[6],X=m[7],oe=m[8];return w[0]=O*oe-U*X,w[1]=E*X-k*oe,w[2]=k*U-E*O,w[3]=U*H-P*oe,w[4]=x*oe-E*H,w[5]=E*P-x*U,w[6]=P*X-O*H,w[7]=k*H-x*X,w[8]=x*O-k*P,w}function f(w,m,x){var k=m[0],E=m[1],P=m[2],O=m[3],U=m[4],H=m[5],X=m[6],oe=m[7],ue=m[8],me=x[0],_e=x[1],Se=x[2],Pe=x[3],$e=x[4],Ke=x[5],lt=x[6],nt=x[7],pt=x[8];return w[0]=me*k+_e*O+Se*X,w[1]=me*E+_e*U+Se*oe,w[2]=me*P+_e*H+Se*ue,w[3]=Pe*k+$e*O+Ke*X,w[4]=Pe*E+$e*U+Ke*oe,w[5]=Pe*P+$e*H+Ke*ue,w[6]=lt*k+nt*O+pt*X,w[7]=lt*E+nt*U+pt*oe,w[8]=lt*P+nt*H+pt*ue,w}function g(){var w=new d(16);return d!=Float32Array&&(w[1]=0,w[2]=0,w[3]=0,w[4]=0,w[6]=0,w[7]=0,w[8]=0,w[9]=0,w[11]=0,w[12]=0,w[13]=0,w[14]=0),w[0]=1,w[5]=1,w[10]=1,w[15]=1,w}function _(w){var m=new d(16);return m[0]=w[0],m[1]=w[1],m[2]=w[2],m[3]=w[3],m[4]=w[4],m[5]=w[5],m[6]=w[6],m[7]=w[7],m[8]=w[8],m[9]=w[9],m[10]=w[10],m[11]=w[11],m[12]=w[12],m[13]=w[13],m[14]=w[14],m[15]=w[15],m}function v(w){return w[0]=1,w[1]=0,w[2]=0,w[3]=0,w[4]=0,w[5]=1,w[6]=0,w[7]=0,w[8]=0,w[9]=0,w[10]=1,w[11]=0,w[12]=0,w[13]=0,w[14]=0,w[15]=1,w}function j(w,m){var x=m[0],k=m[1],E=m[2],P=m[3],O=m[4],U=m[5],H=m[6],X=m[7],oe=m[8],ue=m[9],me=m[10],_e=m[11],Se=m[12],Pe=m[13],$e=m[14],Ke=m[15],lt=x*U-k*O,nt=x*H-E*O,pt=x*X-P*O,_t=k*H-E*U,jt=k*X-P*U,Yt=E*X-P*H,zt=oe*Pe-ue*Se,Wt=oe*$e-me*Se,$t=oe*Ke-_e*Se,Ut=ue*$e-me*Pe,Bs=ue*Ke-_e*Pe,qs=me*Ke-_e*$e,Qs=lt*qs-nt*Bs+pt*Ut+_t*$t-jt*Wt+Yt*zt;return Qs?(w[0]=(U*qs-H*Bs+X*Ut)*(Qs=1/Qs),w[1]=(E*Bs-k*qs-P*Ut)*Qs,w[2]=(Pe*Yt-$e*jt+Ke*_t)*Qs,w[3]=(me*jt-ue*Yt-_e*_t)*Qs,w[4]=(H*$t-O*qs-X*Wt)*Qs,w[5]=(x*qs-E*$t+P*Wt)*Qs,w[6]=($e*pt-Se*Yt-Ke*nt)*Qs,w[7]=(oe*Yt-me*pt+_e*nt)*Qs,w[8]=(O*Bs-U*$t+X*zt)*Qs,w[9]=(k*$t-x*Bs-P*zt)*Qs,w[10]=(Se*jt-Pe*pt+Ke*lt)*Qs,w[11]=(ue*pt-oe*jt-_e*lt)*Qs,w[12]=(U*Wt-O*Ut-H*zt)*Qs,w[13]=(x*Ut-k*Wt+E*zt)*Qs,w[14]=(Pe*nt-Se*_t-$e*lt)*Qs,w[15]=(oe*_t-ue*nt+me*lt)*Qs,w):null}function b(w,m,x){var k=m[0],E=m[1],P=m[2],O=m[3],U=m[4],H=m[5],X=m[6],oe=m[7],ue=m[8],me=m[9],_e=m[10],Se=m[11],Pe=m[12],$e=m[13],Ke=m[14],lt=m[15],nt=x[0],pt=x[1],_t=x[2],jt=x[3];return w[0]=nt*k+pt*U+_t*ue+jt*Pe,w[1]=nt*E+pt*H+_t*me+jt*$e,w[2]=nt*P+pt*X+_t*_e+jt*Ke,w[3]=nt*O+pt*oe+_t*Se+jt*lt,w[4]=(nt=x[4])*k+(pt=x[5])*U+(_t=x[6])*ue+(jt=x[7])*Pe,w[5]=nt*E+pt*H+_t*me+jt*$e,w[6]=nt*P+pt*X+_t*_e+jt*Ke,w[7]=nt*O+pt*oe+_t*Se+jt*lt,w[8]=(nt=x[8])*k+(pt=x[9])*U+(_t=x[10])*ue+(jt=x[11])*Pe,w[9]=nt*E+pt*H+_t*me+jt*$e,w[10]=nt*P+pt*X+_t*_e+jt*Ke,w[11]=nt*O+pt*oe+_t*Se+jt*lt,w[12]=(nt=x[12])*k+(pt=x[13])*U+(_t=x[14])*ue+(jt=x[15])*Pe,w[13]=nt*E+pt*H+_t*me+jt*$e,w[14]=nt*P+pt*X+_t*_e+jt*Ke,w[15]=nt*O+pt*oe+_t*Se+jt*lt,w}function S(w,m,x){var k,E,P,O,U,H,X,oe,ue,me,_e,Se,Pe=x[0],$e=x[1],Ke=x[2];return m===w?(w[12]=m[0]*Pe+m[4]*$e+m[8]*Ke+m[12],w[13]=m[1]*Pe+m[5]*$e+m[9]*Ke+m[13],w[14]=m[2]*Pe+m[6]*$e+m[10]*Ke+m[14],w[15]=m[3]*Pe+m[7]*$e+m[11]*Ke+m[15]):(E=m[1],P=m[2],O=m[3],U=m[4],H=m[5],X=m[6],oe=m[7],ue=m[8],me=m[9],_e=m[10],Se=m[11],w[0]=k=m[0],w[1]=E,w[2]=P,w[3]=O,w[4]=U,w[5]=H,w[6]=X,w[7]=oe,w[8]=ue,w[9]=me,w[10]=_e,w[11]=Se,w[12]=k*Pe+U*$e+ue*Ke+m[12],w[13]=E*Pe+H*$e+me*Ke+m[13],w[14]=P*Pe+X*$e+_e*Ke+m[14],w[15]=O*Pe+oe*$e+Se*Ke+m[15]),w}function A(w,m,x){var k=x[0],E=x[1],P=x[2];return w[0]=m[0]*k,w[1]=m[1]*k,w[2]=m[2]*k,w[3]=m[3]*k,w[4]=m[4]*E,w[5]=m[5]*E,w[6]=m[6]*E,w[7]=m[7]*E,w[8]=m[8]*P,w[9]=m[9]*P,w[10]=m[10]*P,w[11]=m[11]*P,w[12]=m[12],w[13]=m[13],w[14]=m[14],w[15]=m[15],w}function T(w,m,x){var k=Math.sin(x),E=Math.cos(x),P=m[4],O=m[5],U=m[6],H=m[7],X=m[8],oe=m[9],ue=m[10],me=m[11];return m!==w&&(w[0]=m[0],w[1]=m[1],w[2]=m[2],w[3]=m[3],w[12]=m[12],w[13]=m[13],w[14]=m[14],w[15]=m[15]),w[4]=P*E+X*k,w[5]=O*E+oe*k,w[6]=U*E+ue*k,w[7]=H*E+me*k,w[8]=X*E-P*k,w[9]=oe*E-O*k,w[10]=ue*E-U*k,w[11]=me*E-H*k,w}function L(w,m,x){var k=Math.sin(x),E=Math.cos(x),P=m[0],O=m[1],U=m[2],H=m[3],X=m[8],oe=m[9],ue=m[10],me=m[11];return m!==w&&(w[4]=m[4],w[5]=m[5],w[6]=m[6],w[7]=m[7],w[12]=m[12],w[13]=m[13],w[14]=m[14],w[15]=m[15]),w[0]=P*E-X*k,w[1]=O*E-oe*k,w[2]=U*E-ue*k,w[3]=H*E-me*k,w[8]=P*k+X*E,w[9]=O*k+oe*E,w[10]=U*k+ue*E,w[11]=H*k+me*E,w}function D(w,m,x){var k=Math.sin(x),E=Math.cos(x),P=m[0],O=m[1],U=m[2],H=m[3],X=m[4],oe=m[5],ue=m[6],me=m[7];return m!==w&&(w[8]=m[8],w[9]=m[9],w[10]=m[10],w[11]=m[11],w[12]=m[12],w[13]=m[13],w[14]=m[14],w[15]=m[15]),w[0]=P*E+X*k,w[1]=O*E+oe*k,w[2]=U*E+ue*k,w[3]=H*E+me*k,w[4]=X*E-P*k,w[5]=oe*E-O*k,w[6]=ue*E-U*k,w[7]=me*E-H*k,w}function M(w,m){return w[0]=m[0],w[1]=0,w[2]=0,w[3]=0,w[4]=0,w[5]=m[1],w[6]=0,w[7]=0,w[8]=0,w[9]=0,w[10]=m[2],w[11]=0,w[12]=0,w[13]=0,w[14]=0,w[15]=1,w}function F(w,m,x){var k,E,P,O=x[0],U=x[1],H=x[2],X=Math.sqrt(O*O+U*U+H*H);return X0&&(P=1/Math.sqrt(P)),w[0]=m[0]*P,w[1]=m[1]*P,w[2]=m[2]*P,w}function Fe(w,m){return w[0]*m[0]+w[1]*m[1]+w[2]*m[2]}function qe(w,m,x){var k=m[0],E=m[1],P=m[2],O=x[0],U=x[1],H=x[2];return w[0]=E*H-P*U,w[1]=P*O-k*H,w[2]=k*U-E*O,w}function be(w,m,x,k){var E=m[0],P=m[1],O=m[2];return w[0]=E+k*(x[0]-E),w[1]=P+k*(x[1]-P),w[2]=O+k*(x[2]-O),w}function Ze(w,m,x){var k=m[0],E=m[1],P=m[2],O=x[3]*k+x[7]*E+x[11]*P+x[15];return w[0]=(x[0]*k+x[4]*E+x[8]*P+x[12])/(O=O||1),w[1]=(x[1]*k+x[5]*E+x[9]*P+x[13])/O,w[2]=(x[2]*k+x[6]*E+x[10]*P+x[14])/O,w}function Ne(w,m,x){var k=m[0],E=m[1],P=m[2];return w[0]=k*x[0]+E*x[3]+P*x[6],w[1]=k*x[1]+E*x[4]+P*x[7],w[2]=k*x[2]+E*x[5]+P*x[8],w}function it(w,m,x){var k=x[0],E=x[1],P=x[2],O=x[3],U=m[0],H=m[1],X=m[2],oe=E*X-P*H,ue=P*U-k*X,me=k*H-E*U;return w[0]=U+O*(oe+=oe)+E*(me+=me)-P*(ue+=ue),w[1]=H+O*ue+P*oe-k*me,w[2]=X+O*me+k*ue-E*oe,w}function je(w){return w[0]=0,w[1]=0,w[2]=0,w}function Ge(w,m){return w[0]===m[0]&&w[1]===m[1]&&w[2]===m[2]}var Be=ce,Ye=pe,We=J;function rt(){var w=new d(4);return d!=Float32Array&&(w[0]=0,w[1]=0,w[2]=0,w[3]=0),w}function tt(w,m,x){return w[0]=m[0]*x,w[1]=m[1]*x,w[2]=m[2]*x,w[3]=m[3]*x,w}function at(w,m){var x=m[0],k=m[1],E=m[2],P=m[3],O=x*x+k*k+E*E+P*P;return O>0&&(O=1/Math.sqrt(O)),w[0]=x*O,w[1]=k*O,w[2]=E*O,w[3]=P*O,w}function He(w,m){return w[0]*m[0]+w[1]*m[1]+w[2]*m[2]+w[3]*m[3]}function dt(w,m,x){var k=m[0],E=m[1],P=m[2],O=m[3];return w[0]=x[0]*k+x[4]*E+x[8]*P+x[12]*O,w[1]=x[1]*k+x[5]*E+x[9]*P+x[13]*O,w[2]=x[2]*k+x[6]*E+x[10]*P+x[14]*O,w[3]=x[3]*k+x[7]*E+x[11]*P+x[15]*O,w}function bt(){var w=new d(4);return d!=Float32Array&&(w[0]=0,w[1]=0,w[2]=0),w[3]=1,w}function vt(w){return w[0]=0,w[1]=0,w[2]=0,w[3]=1,w}function Bt(w,m,x){x*=.5;var k=m[0],E=m[1],P=m[2],O=m[3],U=Math.sin(x),H=Math.cos(x);return w[0]=k*H+O*U,w[1]=E*H+P*U,w[2]=P*H-E*U,w[3]=O*H-k*U,w}function Zt(w,m,x){x*=.5;var k=m[0],E=m[1],P=m[2],O=m[3],U=Math.sin(x),H=Math.cos(x);return w[0]=k*H-P*U,w[1]=E*H+O*U,w[2]=P*H+k*U,w[3]=O*H-E*U,w}Y(),rt();var Fs,Rs,ms,Pt=at,Jt=(Fs=Y(),Rs=ne(1,0,0),ms=ne(0,1,0),function(w,m,x){var k=Fe(m,x);return k<-.999999?(qe(Fs,Rs,m),We(Fs)<1e-6&&qe(Fs,ms,m),Ie(Fs,Fs),function(E,P,O){O*=.5;var U=Math.sin(O);E[0]=U*P[0],E[1]=U*P[1],E[2]=U*P[2],E[3]=Math.cos(O)}(w,Fs,Math.PI),w):k>.999999?(w[0]=0,w[1]=0,w[2]=0,w[3]=1,w):(qe(Fs,m,x),w[0]=Fs[0],w[1]=Fs[1],w[2]=Fs[2],w[3]=1+k,Pt(w,w))});function ft(){var w=new d(2);return d!=Float32Array&&(w[0]=0,w[1]=0),w}function Vt(w,m){var x=new d(2);return x[0]=w,x[1]=m,x}function Ms(w,m,x){return w[0]=m,w[1]=x,w}function Xt(w,m,x){return w[0]=m[0]+x[0],w[1]=m[1]+x[1],w}function Js(w,m,x){return w[0]=m[0]-x[0],w[1]=m[1]-x[1],w}function Cs(w,m,x){return w[0]=m[0]*x,w[1]=m[1]*x,w}function As(w){var m=w[0],x=w[1];return Math.sqrt(m*m+x*x)}function rn(w,m){var x=m[0],k=m[1],E=x*x+k*k;return E>0&&(E=1/Math.sqrt(E)),w[0]=m[0]*E,w[1]=m[1]*E,w}function tn(w,m){return w[0]*m[0]+w[1]*m[1]}bt(),bt(),h();var er,gn,In=Js;function Zn(w){return w&&w.__esModule&&Object.prototype.hasOwnProperty.call(w,"default")?w.default:w}ft();var ea=function(){if(gn)return er;function w(m,x,k,E){this.cx=3*m,this.bx=3*(k-m)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*x,this.by=3*(E-x)-this.cy,this.ay=1-this.cy-this.by,this.p1x=m,this.p1y=x,this.p2x=k,this.p2y=E}return gn=1,er=w,w.prototype={sampleCurveX:function(m){return((this.ax*m+this.bx)*m+this.cx)*m},sampleCurveY:function(m){return((this.ay*m+this.by)*m+this.cy)*m},sampleCurveDerivativeX:function(m){return(3*this.ax*m+2*this.bx)*m+this.cx},solveCurveX:function(m,x){if(x===void 0&&(x=1e-6),m<0)return 0;if(m>1)return 1;for(var k=m,E=0;E<8;E++){var P=this.sampleCurveX(k)-m;if(Math.abs(P)P?U=k:H=k,k=.5*(H-U)+U;return k},solve:function(m,x){return this.sampleCurveY(this.solveCurveX(m,x))}},er}(),vi=Zn(ea);function Ls(w,m){this.x=w,this.y=m}function fi(w,m){if(Array.isArray(w)){if(!Array.isArray(m)||w.length!==m.length)return!1;for(let x=0;x=1)return 1;const m=w*w,x=m*w;return 4*(w<.5?x:3*(w-m)+x-.75)}function ss(w,m,x,k){const E=new vi(w,m,x,k);return function(P){return E.solve(P)}}const Oe=ss(.25,.1,.25,1);function Xe(w,m,x){return Math.min(x,Math.max(m,w))}function ot(w,m,x){return(x=Xe((x-w)/(m-w),0,1))*x*(3-2*x)}function Nt(w,m,x){const k=x-m,E=((w-m)%k+k)%k+m;return E===m?x:E}function Rt(w,m,x){if(!w.length)return x(null,[]);let k=w.length;const E=new Array(w.length);let P=null;w.forEach((O,U)=>{m(O,(H,X)=>{H&&(P=H),E[U]=X,--k===0&&x(P,E)})})}let qt=1;function xs(){return qt++}function rs(w){return w<=1?1:Math.pow(2,Math.ceil(Math.log2(w)))}function ks(w,m){w.forEach(x=>{m[x]&&(m[x]=m[x].bind(m))})}function ln(w,m,x){const k={};for(const E in w)k[E]=m.call(this,w[E],E,w);return k}function Gs(w,m,x){const k={};for(const E in w)m.call(this,w[E],E,w)&&(k[E]=w[E]);return k}function Un(w){return Array.isArray(w)?w.map(Un):typeof w=="object"&&w?ln(w,Un):w}function jr(w,m){for(let x=0;x=0)return!0;return!1}const Sr={};function nr(w){Sr[w]||(typeof console<"u"&&console.warn(w),Sr[w]=!0)}function Ot(w,m,x){return(x.y-w.y)*(m.x-w.x)>(m.y-w.y)*(x.x-w.x)}function fn(w){let m=0;for(let x,k,E=0,P=w.length,O=P-1;E@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(x,k,E,P)=>{const O=E||P;return m[k]=!O||O.toLowerCase(),""}),m["max-age"]){const x=parseInt(m["max-age"],10);isNaN(x)?delete m["max-age"]:m["max-age"]=x}return m}let Zr,ur=null;function Mr(w,m){return[w[4*m],w[4*m+1],w[4*m+2],w[4*m+3]]}function zi(w,m,x,k){for(;m>1;w[E]>1;w[E]<=k?m=E+1:x=E}return m}function Za(w){return w>0?1/(1.001-w):1+w}function _i(w){return w>0?1-1/(1.001-w):-w}function qi(w,m,x){return(w-m.min)*(x.max-x.min)/(m.max-m.min)+x.min}const ga={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(!ga.API_URL)return null;try{const w=new URL(ga.API_URL);return w.hostname==="api.mapbox.cn"?"https://events.mapbox.cn/events/v2":w.hostname==="api.mapbox.com"?"https://events.mapbox.com/events/v2":null}catch{return null}},SESSION_PATH:"/map-sessions/v1",FEEDBACK_URL:"https://apps.mapbox.com/feedback",TILE_URL_VERSION:"v4",RASTER_URL_PREFIX:"raster/v1",RASTERARRAYS_URL_PREFIX:"rasterarrays/v1",REQUIRE_ACCESS_TOKEN:!0,ACCESS_TOKEN:null,DEFAULT_STYLE:"mapbox://styles/mapbox/standard",MAX_PARALLEL_IMAGE_REQUESTS:16,DRACO_URL:"/mapbox-gl-js/draco_decoder_gltf_v1.5.6.wasm",MESHOPT_URL:"/mapbox-gl-js/meshopt_base_v0.20.wasm",MESHOPT_SIMD_URL:"/mapbox-gl-js/meshopt_simd_v0.20.wasm",BUILDING_GEN_URL:"/mapbox-gl-js/building-gen/building_gen_v1.2.4.wasm",GLYPHS_URL:"mapbox://fonts/mapbox/{fontstack}/{range}.pbf",TILES3D_URL_PREFIX:"3dtiles/v1",TILE_PROVIDER_URLS:Object.assign(Object.create(null),{pmtiles:"/mapbox-gl-js/mapbox-gl-pmtiles-provider-v0.0.1.js"})};function wn(){return new URL(ga.DRACO_URL,ga.API_URL).href}function Ta(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(Zr===void 0){if(typeof WebAssembly!="object")return!1;const w=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]);Zr=WebAssembly.validate(w)}return Zr}()?ga.MESHOPT_SIMD_URL:ga.MESHOPT_URL,ga.API_URL).href}function Yi(){return new URL(ga.BUILDING_GEN_URL,ga.API_URL).href}function zo(w){return ga.API_URL_REGEX.test(w)}function rl(w){return ga.API_SPRITE_REGEX.test(w)}let po,uc,hc,Tf,Hu,pm;function Gu(){return po==null&&(po=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),po}const qd={now:()=>Tf!==void 0?Tf:performance.now(),setNow(w){Tf=w},restoreNow(){Tf=void 0},frame(w){const m=requestAnimationFrame(w);return{cancel:()=>cancelAnimationFrame(m)}},getImageData(w,m=0){const{width:x,height:k}=w;Hu||(Hu=document.createElement("canvas"));const E=Hu.getContext("2d",{willReadFrequently:!0});if(!E)throw new Error("failed to create canvas 2d context");return(x>Hu.width||k>Hu.height)&&(Hu.width=x,Hu.height=k),E.clearRect(-m,-m,x+2*m,k+2*m),E.drawImage(w,0,0,x,k),E.getImageData(-m,-m,x+2*m,k+2*m)},resolveURL:w=>(uc||(uc=document.createElement("a")),uc.href=w,uc.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(hc==null&&(hc=window.matchMedia("(prefers-reduced-motion: reduce)")),hc.matches)},hasCanvasFingerprintNoise(){if(pm!==void 0)return pm;if(!Gu())return pm=!1,!1;const w=new OffscreenCanvas(85,1),m=w.getContext("2d",{willReadFrequently:!0});let x=0;for(let E=0;E0?`?${P}`:""}`}const fm="mapbox-tiles";let Ay=500,My=50;const Ef=["language","worldview","jobid"];let yh;function mx(){try{return caches}catch{}}function fo(){const w=mx();w&&yh==null&&(yh=w.open(fm))}let qb=1/0;const xm={supported:!1,testSupport:function(w){!Wu&&px&&(al?xu(w):Fh=w)}};let Fh,px,Wu=!1,al=!1;const d0=typeof self<"u"?self:{};function xu(w){const m=w.createTexture();w.bindTexture(w.TEXTURE_2D,m);try{if(w.texImage2D(w.TEXTURE_2D,0,w.RGBA,w.RGBA,w.UNSIGNED_BYTE,px),w.isContextLost())return;xm.supported=!0}catch{}w.deleteTexture(m),Wu=!0}d0.document&&(px=d0.document.createElement("img"),px.onload=function(){Fh&&xu(Fh),Fh=null,al=!0},px.onerror=function(){Wu=!0,Fh=null},px.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const u0={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(u0);class lj extends Error{constructor(m,x,k){x===401&&zo(k)&&(m+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(m),this.status=x,this.url=k}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function Af(w){return typeof w=="object"&&w!==null&&"status"in w&&w.status===404}const Qa=Hn()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,Iy=function(w,m){return/^file:/.test(x=w.url)||/^file:/.test(Qa())&&!/^\w+:/.test(x)?function(k,E){const P=new XMLHttpRequest;P.open(k.method||"GET",k.url,!0),k.type==="arrayBuffer"&&(P.responseType="arraybuffer");for(const O in k.headers)P.setRequestHeader(O,k.headers[O]);return k.type==="json"&&(P.responseType="text",P.setRequestHeader("Accept","application/json")),P.withCredentials=k.credentials==="include",P.onerror=()=>{E(new Error(P.statusText))},P.onload=()=>{if((P.status>=200&&P.status<300||P.status===0)&&P.response!==null){let O=P.response;if(k.type==="json")try{O=JSON.parse(P.response)}catch(H){return E(H)}const U=new Headers;P.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(H=>{const X=H.split(": "),oe=X.shift(),ue=X.join(": ");U.append(oe,ue)}),E(null,O,U)}else E(new lj(P.statusText,P.status,k.url))},P.send(k.body),{cancel:()=>P.abort()}}(w,m):function(k,E){const P=new AbortController,O=new Request(k.url,{method:k.method||"GET",body:k.body,credentials:k.credentials,headers:k.headers,referrer:Qa(),referrerPolicy:k.referrerPolicy,signal:P.signal});let U=!1,H=!1;const X=(oe=O.url).indexOf("sku=")>0&&zo(oe);var oe;k.type==="json"&&O.headers.set("Accept","application/json");const ue=(_e,Se,Pe)=>{if(H)return;if(_e&&_e.message!=="SecurityError"&&nr(_e.toString()),Se&&Pe)return me(Se);const $e=Date.now();fetch(O).then(Ke=>{if(Ke.ok){const lt=X?Ke.clone():null;return me(Ke,lt,$e)}return E(new lj(Ke.statusText,Ke.status,k.url))}).catch(Ke=>{Ke.name!=="AbortError"&&E(new Error(`${Ke.message} ${k.url}`))})},me=(_e,Se,Pe)=>{(k.type==="arrayBuffer"?_e.arrayBuffer():k.type==="json"?_e.json():_e.text()).then($e=>{H||(Se&&Pe&&function(Ke,lt,nt){if(fo(),yh==null)return;const pt=ta(lt.headers.get("cache-control")||"");if(pt["no-store"])return;const _t={status:lt.status,statusText:lt.statusText,headers:new Headers};lt.headers.forEach(($t,Ut)=>_t.headers.set(Ut,$t)),pt["max-age"]&&_t.headers.set("Expires",new Date(nt+1e3*pt["max-age"]).toUTCString());const jt=_t.headers.get("expires");if(!jt||new Date(jt).getTime()-nt<42e4)return;let Yt=oj(Ke.url,{persistentParams:Ef});if(lt.status===206){const $t=Ke.headers.get("Range");if(!$t)return;_t.status=200,Yt=a1(Yt,{range:$t})}const zt=new Response((Wt=lt.status)!==200&&Wt!==404&&[101,103,204,205,304].includes(Wt)?null:lt.body,_t);var Wt;fo(),yh!=null&&yh.then($t=>$t.put(Yt,zt)).catch($t=>nr($t.message))}(O,Se,Pe),U=!0,E(null,$e,_e.headers))}).catch($e=>{H||E(new Error($e.message))})};return X?function(_e,Se){if(fo(),yh==null)return Se(null);yh.then(Pe=>{let $e=oj(_e.url,{persistentParams:Ef});const Ke=_e.headers.get("Range");Ke&&($e=a1($e,{range:Ke})),Pe.match($e).then(lt=>{const nt=function(pt){if(!pt)return!1;const _t=new Date(pt.headers.get("expires")||0),jt=ta(pt.headers.get("cache-control")||"");return Number(_t)>Date.now()&&!jt["no-cache"]}(lt);Pe.delete($e).catch(Se),nt&&Pe.put($e,lt.clone()).catch(Se),Se(null,lt,nt)}).catch(Se)}).catch(Se)}(O,ue):ue(null,null),{cancel:()=>{H=!0,U||P.abort()}}}(w,m);var x},Py=function(w,m){return Iy(Object.assign(w,{type:"arrayBuffer"}),m)};function Xm(w){const m=document.createElement("a");return m.href=w,m.protocol===location.protocol&&m.host===location.host}let Jm,Lp;Jm=[],Lp=0;const fx=function(w,m){if(xm.supported&&(w.headers||(w.headers={}),w.headers.accept="image/webp,*/*"),Lp>=ga.MAX_PARALLEL_IMAGE_REQUESTS){const P={requestParameters:w,callback:m,cancelled:!1,cancel(){this.cancelled=!0}};return Jm.push(P),P}Lp++;let x=!1;const k=()=>{if(!x)for(x=!0,Lp--;Jm.length&&Lp{k(),P?m(P):O&&function(H,X){const oe=new Blob([new Uint8Array(H)],{type:"image/png"});createImageBitmap(oe).then(ue=>{X(null,ue)}).catch(ue=>{X(new Error(`Could not load image because of ${ue.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}(O,(H,X)=>m(H,X,U))});return{cancel:()=>{E.cancel(),k()}}};var dg,Vb,Dp,ep={exports:{}},Mf={exports:{}},Ly={exports:{}},Hb=function(){if(Dp)return ep.exports;Dp=1;var w=(dg||(dg=1,Mf.exports=function(x,k){var E,P,O,U,H,X,oe,ue;for(P=x.length-(E=3&x.length),O=k,H=3432918353,X=461845907,ue=0;ue>>16)*H&65535)<<16)&4294967295)<<15|oe>>>17))*X+(((oe>>>16)*X&65535)<<16)&4294967295)<<13|O>>>19))+((5*(O>>>16)&65535)<<16)&4294967295))+(((U>>>16)+58964&65535)<<16);switch(oe=0,E){case 3:oe^=(255&x.charCodeAt(ue+2))<<16;case 2:oe^=(255&x.charCodeAt(ue+1))<<8;case 1:O^=oe=(65535&(oe=(oe=(65535&(oe^=255&x.charCodeAt(ue)))*H+(((oe>>>16)*H&65535)<<16)&4294967295)<<15|oe>>>17))*X+(((oe>>>16)*X&65535)<<16)&4294967295}return O^=x.length,O=2246822507*(65535&(O^=O>>>16))+((2246822507*(O>>>16)&65535)<<16)&4294967295,O=3266489909*(65535&(O^=O>>>13))+((3266489909*(O>>>16)&65535)<<16)&4294967295,(O^=O>>>16)>>>0}),Mf.exports),m=(Vb||(Vb=1,Ly.exports=function(x,k){for(var E,P=x.length,O=k^P,U=0;P>=4;)E=1540483477*(65535&(E=255&x.charCodeAt(U)|(255&x.charCodeAt(++U))<<8|(255&x.charCodeAt(++U))<<16|(255&x.charCodeAt(++U))<<24))+((1540483477*(E>>>16)&65535)<<16),O=1540483477*(65535&O)+((1540483477*(O>>>16)&65535)<<16)^(E=1540483477*(65535&(E^=E>>>24))+((1540483477*(E>>>16)&65535)<<16)),P-=4,++U;switch(P){case 3:O^=(255&x.charCodeAt(U+2))<<16;case 2:O^=(255&x.charCodeAt(U+1))<<8;case 1:O=1540483477*(65535&(O^=255&x.charCodeAt(U)))+((1540483477*(O>>>16)&65535)<<16)}return O=1540483477*(65535&(O^=O>>>13))+((1540483477*(O>>>16)&65535)<<16),(O^=O>>>15)>>>0}),Ly.exports);return ep.exports=w,ep.exports.murmur3=w,ep.exports.murmur2=m,ep.exports}(),Sd=Zn(Hb);class zc{constructor(m,...x){Object.assign(this,x[0]||{}),this.type=m}}class tp extends zc{constructor(m,x={}){super("error",Object.assign({error:m},x))}}function Zc(w,m,x){x[w]&&x[w].indexOf(m)!==-1||(x[w]=x[w]||[],x[w].push(m))}function sp(w,m,x){if(x&&x[w]){const k=x[w].indexOf(m);k!==-1&&x[w].splice(k,1)}}class Rp{on(m,x){return this._listeners=this._listeners||{},Zc(m,x,this._listeners),this}off(m,x){return sp(m,x,this._listeners),sp(m,x,this._oneTimeListeners),this}once(m,x){return x?(this._oneTimeListeners=this._oneTimeListeners||{},Zc(m,x,this._oneTimeListeners),this):new Promise(k=>{this.once(m,k)})}fire(m,x){const k=typeof m=="string"?new zc(m,x):m,E=k.type;if(this.listens(E)){k.target=this;const P=this._listeners&&this._listeners[E]?this._listeners[E].slice():[];for(const H of P)H.call(this,k);const O=this._oneTimeListeners&&this._oneTimeListeners[E]?this._oneTimeListeners[E].slice():[];for(const H of O)sp(E,H,this._oneTimeListeners),H.call(this,k);const U=this._eventedParent;if(U){const H=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(k,H),U.fire(k)}}else k instanceof tp&&console.error(k.error);return this}listens(m){return!!(this._listeners&&this._listeners[m]&&this._listeners[m].length>0||this._oneTimeListeners&&this._oneTimeListeners[m]&&this._oneTimeListeners[m].length>0||this._eventedParent&&this._eventedParent.listens(m))}setEventedParent(m,x){return this._eventedParent=m,this._eventedParentData=x,this}}class Lt{constructor(m){typeof m=="string"?this.name=m:(this.name=m.name,this.iconsetId=m.iconsetId)}static from(m){return new Lt(m)}static toString(m){return m.iconsetId?`${m.name}${m.iconsetId}`:m.name}static parse(m){const[x,k]=m.split("");return new Lt({name:x,iconsetId:k})}static isEqual(m,x){return m.name===x.name&&m.iconsetId===x.iconsetId}toString(){return Lt.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var hn,zn={},Dr=function(){if(hn)return zn;hn=1;var w={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 m(P){return(P=Math.round(P))<0?0:P>255?255:P}function x(P){return m(P[P.length-1]==="%"?parseFloat(P)/100*255:parseInt(P))}function k(P){return(O=P[P.length-1]==="%"?parseFloat(P)/100:parseFloat(P))<0?0:O>1?1:O;var O}function E(P,O,U){return U<0?U+=1:U>1&&(U-=1),6*U<1?P+(O-P)*U*6:2*U<1?O:3*U<2?P+(O-P)*(2/3-U)*6:P}try{zn.parseCSSColor=function(P){var O,U=P.replace(/ /g,"").toLowerCase();if(U in w)return w[U].slice();if(U[0]==="#")return U.length===4?(O=parseInt(U.substr(1),16))>=0&&O<=4095?[(3840&O)>>4|(3840&O)>>8,240&O|(240&O)>>4,15&O|(15&O)<<4,1]:null:U.length===7&&(O=parseInt(U.substr(1),16))>=0&&O<=16777215?[(16711680&O)>>16,(65280&O)>>8,255&O,1]:null;var H=U.indexOf("("),X=U.indexOf(")");if(H!==-1&&X+1===U.length){var oe=U.substr(0,H),ue=U.substr(H+1,X-(H+1)).split(","),me=1;switch(oe){case"rgba":if(ue.length!==4)return null;me=k(ue.pop());case"rgb":return ue.length!==3?null:[x(ue[0]),x(ue[1]),x(ue[2]),me];case"hsla":if(ue.length!==4)return null;me=k(ue.pop());case"hsl":if(ue.length!==3)return null;var _e=(parseFloat(ue[0])%360+360)%360/360,Se=k(ue[1]),Pe=k(ue[2]),$e=Pe<=.5?Pe*(Se+1):Pe+Se-Pe*Se,Ke=2*Pe-$e;return[m(255*E(Ke,$e,_e+1/3)),m(255*E(Ke,$e,_e)),m(255*E(Ke,$e,_e-1/3)),me];default:return null}}return null}}catch{}return zn}();class Gn{constructor(m,x,k,E=1){this.r=m,this.g=x,this.b=k,this.a=E}static parse(m){if(!m)return;if(m instanceof Gn)return m;if(typeof m!="string")return;const x=Dr.parseCSSColor(m);return x?new Gn(x[0]/255,x[1]/255,x[2]/255,x[3]):void 0}toString(){const[m,x,k,E]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*m)},${Math.round(255*x)},${Math.round(255*k)},${E})`}toNonPremultipliedRenderColor(m){const{r:x,g:k,b:E,a:P}=this;return new Xa(m,x,k,E,P)}toPremultipliedRenderColor(m){const{r:x,g:k,b:E,a:P}=this;return new ii(m,x*P,k*P,E*P,P)}clone(){return new Gn(this.r,this.g,this.b,this.a)}}class fa{constructor(m,x,k,E,P,O=!1){if(this.premultiplied=!1,this.premultiplied=O,m){const U=m.image.height,H=U*U;this.premultiplied?(x=P===0?0:x/P*(U-1),k=P===0?0:k/P*(U-1),E=P===0?0:E/P*(U-1)):(x*=U-1,k*=U-1,E*=U-1),x=Math.max(0,Math.min(U-1,x)),k=Math.max(0,Math.min(U-1,k)),E=Math.max(0,Math.min(U-1,E));const X=Math.floor(x),oe=Math.floor(k),ue=Math.floor(E),me=Math.ceil(x),_e=Math.ceil(k),Se=Math.ceil(E),Pe=x-X,$e=k-oe,Ke=E-ue,lt=m.image.data,nt=4*(X+oe*H+ue*U),pt=4*(X+oe*H+Se*U),_t=4*(X+_e*H+ue*U),jt=4*(X+_e*H+Se*U),Yt=4*(me+oe*H+ue*U),zt=4*(me+oe*H+Se*U),Wt=4*(me+_e*H+ue*U),$t=4*(me+_e*H+Se*U);this.r=zr(zr(zr(lt[nt],lt[pt],Ke),zr(lt[_t],lt[jt],Ke),$e),zr(zr(lt[Yt],lt[zt],Ke),zr(lt[Wt],lt[$t],Ke),$e),Pe)/255*(this.premultiplied?P:1),this.g=zr(zr(zr(lt[nt+1],lt[pt+1],Ke),zr(lt[_t+1],lt[jt+1],Ke),$e),zr(zr(lt[Yt+1],lt[zt+1],Ke),zr(lt[Wt+1],lt[$t+1],Ke),$e),Pe)/255*(this.premultiplied?P:1),this.b=zr(zr(zr(lt[nt+2],lt[pt+2],Ke),zr(lt[_t+2],lt[jt+2],Ke),$e),zr(zr(lt[Yt+2],lt[zt+2],Ke),zr(lt[Wt+2],lt[$t+2],Ke),$e),Pe)/255*(this.premultiplied?P:1),this.a=P}else this.r=x,this.g=k,this.b=E,this.a=P}toArray(){const{r:m,g:x,b:k,a:E}=this;return[255*m,255*x,255*k,E]}toHslaArray(){let{r:m,g:x,b:k,a:E}=this;if(this.premultiplied){if(E===0)return[0,0,0,0];const Se=1/E;m*=Se,x*=Se,k*=Se}const P=Math.min(Math.max(m,0),1),O=Math.min(Math.max(x,0),1),U=Math.min(Math.max(k,0),1),H=Math.min(P,O,U),X=Math.max(P,O,U),oe=X-H,ue=.5*(H+X);if(oe===0)return[0,0,100*ue,E];const me=ue>.5?oe/(2-X-H):oe/(X+H);let _e;switch(X){case P:_e=60*((O-U)/oe+(Ozr(k,m[E],x))}Gn.black=new Gn(0,0,0,1),Gn.white=new Gn(1,1,1,1),Gn.transparent=new Gn(0,0,0,0),Gn.red=new Gn(1,0,0,1),Gn.blue=new Gn(0,0,1,1);var gm=Object.freeze({__proto__:null,array:Cd,color:function(w,m,x){return new Gn(zr(w.r,m.r,x),zr(w.g,m.g,x),zr(w.b,m.b,x),zr(w.a,m.a,x))},number:zr});class Ku extends Error{constructor(m,x){super(x),this.message=x,this.key=m}}class ug{constructor(m,x=[]){this.parent=m,this.bindings={};for(const[k,E]of x)this.bindings[k]=E}concat(m){return new ug(this,m)}get(m){if(this.bindings[m])return this.bindings[m];if(this.parent)return this.parent.get(m);throw new Error(`${m} not found in scope.`)}has(m){return!!this.bindings[m]||!!this.parent&&this.parent.has(m)}}const If={kind:"null"},Tr={kind:"number"},Mi={kind:"string"},Zi={kind:"boolean"},zh={kind:"color"},xx={kind:"object"},to={kind:"value"},gx={kind:"collator"},Dy={kind:"formatted"},Gb={kind:"resolvedImage"};function Yu(w,m){return{kind:"array",itemType:w,N:m}}function Dl(w){if(w.kind==="array"){const m=Dl(w.itemType);return typeof w.N=="number"?`array<${m}, ${w.N}>`:w.itemType.kind==="value"?"array":`array<${m}>`}return w.kind}const p6=[If,Tr,Mi,Zi,zh,Dy,xx,Yu(to),Gb];function Ry(w,m){if(m.kind==="error")return null;if(w.kind==="array"){if(m.kind==="array"&&(m.N===0&&m.itemType.kind==="value"||!Ry(w.itemType,m.itemType))&&(typeof w.N!="number"||w.N===m.N))return null}else{if(w.kind===m.kind)return null;if(w.kind==="value"){for(const x of p6)if(!Ry(x,m))return null}}return`Expected ${Dl(w)} but found ${Dl(m)} instead.`}function Wb(w,m){return m.some(x=>x.kind===w.kind)}function yx(w,m){return m.some(x=>x==="null"?w===null:x==="array"?Array.isArray(w):x==="object"?w&&!Array.isArray(w)&&typeof w=="object":x===typeof w)}function vx(w,m){return w.kind==="array"&&m.kind==="array"?w.N===m.N&&vx(w.itemType,m.itemType):w.kind===m.kind}class cj{constructor(m,x,k){this.sensitivity=m?x?"variant":"case":x?"accent":"base",this.locale=k,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(m,x){return this.collator.compare(m,x)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class Kb{constructor(m,x,k,E,P){this.text=m.normalize?m.normalize():m,this.image=x,this.scale=k,this.fontStack=E,this.textColor=P}}class Vd{constructor(m){this.sections=m}static fromString(m){return new Vd([new Kb(m,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(m=>m.text.length!==0||!!m.image&&m.image.hasPrimary())}static factory(m){return m instanceof Vd?m:Vd.fromString(m)}toString(){return this.sections.length===0?"":this.sections.map(m=>m.text).join("")}serialize(){const m=["format"];for(const x of this.sections){if(x.image){const E=x.image.getPrimary().id.toString();m.push(["image",E]);continue}m.push(x.text);const k={};x.fontStack&&(k["text-font"]=["literal",x.fontStack.split(",")]),x.scale&&(k["font-scale"]=x.scale),x.textColor&&(k["text-color"]=["rgba"].concat(x.textColor.toNonPremultipliedRenderColor(null).toArray())),m.push(k)}return m}}class np{constructor(m,x={}){this.id=Lt.from(m),this.params=x.params,this.sx=x.sx||1,this.sy=x.sy||1}toString(){return JSON.stringify(this)}static parse(m){let x,k,E,P;try{({id:x,params:k,sx:E,sy:P}=JSON.parse(m)||{})}catch{return null}return x?new np(x,{params:k,sx:E,sy:P}):null}scaleSelf(m,x=m){return this.sx*=m,this.sy*=x,this}}class Hd{constructor(m,x,k,E,P=!1){this.primaryId=Lt.from(m),this.primaryOptions=x,k&&(this.secondaryId=Lt.from(k)),this.secondaryOptions=E,this.available=P}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new np(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new np(this.secondaryId,this.secondaryOptions):null}static from(m){return typeof m=="string"?Hd.build({name:m}):m}static build(m,x,k,E){return!m||typeof m=="object"&&!("name"in m)?null:new Hd(m,k,x,E)}}function Op(w,m,x,k){return typeof w=="number"&&w>=0&&w<=255&&typeof m=="number"&&m>=0&&m<=255&&typeof x=="number"&&x>=0&&x<=255?k===void 0||typeof k=="number"&&k>=0&&k<=1?null:`Invalid rgba value [${[w,m,x,k].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof k=="number"?[w,m,x,k]:[w,m,x]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Pf(w){if(w===null||typeof w=="string"||typeof w=="boolean"||typeof w=="number"||w instanceof Gn||w instanceof cj||w instanceof Vd||w instanceof Hd)return!0;if(Array.isArray(w)){for(const m of w)if(!Pf(m))return!1;return!0}if(typeof w=="object"){for(const m in w)if(!Pf(w[m]))return!1;return!0}return!1}function Ml(w){if(w===null)return If;if(typeof w=="string")return Mi;if(typeof w=="boolean")return Zi;if(typeof w=="number")return Tr;if(w instanceof Gn)return zh;if(w instanceof cj)return gx;if(w instanceof Vd)return Dy;if(w instanceof Hd)return Gb;if(Array.isArray(w)){const m=w.length;let x;for(const k of w){const E=Ml(k);if(x){if(x===E)continue;x=to;break}x=E}return Yu(x||to,m)}return xx}function sa(w){const m=typeof w;return w===null?"":m==="string"||m==="number"||m==="boolean"?String(w):w instanceof Vd||w instanceof Hd||w instanceof Gn?w.toString():JSON.stringify(w)}class ar{constructor(m,x){this.type=m,this.value=x}static parse(m,x){if(m.length!==2)return x.error(`'literal' expression requires exactly one argument, but found ${m.length-1} instead.`);if(!Pf(m[1]))return x.error("invalid value");const k=m[1];let E=Ml(k);const P=x.expectedType;return E.kind!=="array"||E.N!==0||!P||P.kind!=="array"||typeof P.N=="number"&&P.N!==0||(E=P),new ar(E,k)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof Gn?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof Vd?this.value.serialize():this.value}}class yl{constructor(m){this.name="ExpressionEvaluationError",this.message=m}toJSON(){return this.message}}const oa={string:Mi,number:Tr,boolean:Zi,object:xx};class rp{constructor(m,x){this.type=m,this.args=x}static parse(m,x){if(m.length<2)return x.error("Expected at least one argument.");let k,E=1;const P=m[0];if(P==="array"){let U,H;if(m.length>2){const X=m[1];if(typeof X!="string"||!(X in oa)||X==="object")return x.error('The item type argument of "array" must be one of string, number, boolean',1);U=oa[X],E++}else U=to;if(m.length>3){if(m[2]!==null&&(typeof m[2]!="number"||m[2]<0||m[2]!==Math.floor(m[2])))return x.error('The length argument to "array" must be a positive integer literal',2);H=m[2],E++}k=Yu(U,H)}else k=oa[P];const O=[];for(;Em.outputDefined())}serialize(){const m=this.type,x=[m.kind];if(m.kind==="array"){const k=m.itemType;if(k.kind==="string"||k.kind==="number"||k.kind==="boolean"){x.push(k.kind);const E=m.N;(typeof E=="number"||this.args.length>1)&&x.push(E)}}return x.concat(this.args.map(k=>k.serialize()))}}class ym{constructor(m){this.type=Dy,this.sections=m}static parse(m,x){if(m.length<2)return x.error("Expected at least one argument.");const k=m[1];if(!Array.isArray(k)&&typeof k=="object")return x.error("First argument must be an image or text section.");const E=[];let P=!1;for(let O=1;O<=m.length-1;++O){const U=m[O];if(P&&typeof U=="object"&&!Array.isArray(U)){P=!1;let H=null;if(U["font-scale"]&&(H=x.parseObjectValue(U["font-scale"],O,"font-scale",Tr),!H))return null;let X=null;if(U["text-font"]&&(X=x.parseObjectValue(U["text-font"],O,"text-font",Yu(Mi)),!X))return null;let oe=null;if(U["text-color"]&&(oe=x.parseObjectValue(U["text-color"],O,"text-color",zh),!oe))return null;const ue=E[E.length-1];ue.scale=H,ue.font=X,ue.textColor=oe}else{const H=x.parse(m[O],O,to);if(!H)return null;const X=H.type.kind;if(X!=="string"&&X!=="value"&&X!=="null"&&X!=="resolvedImage")return x.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");P=!0,E.push({content:H,scale:null,font:null,textColor:null})}}return new ym(E)}evaluate(m){return new Vd(this.sections.map(x=>{const k=x.content.evaluate(m);return vx(Ml(k),Gb)?new Kb("",k,null,null,null):new Kb(sa(k),null,x.scale?x.scale.evaluate(m):null,x.font?x.font.evaluate(m).join(","):null,x.textColor?x.textColor.evaluate(m):null)}))}eachChild(m){for(const x of this.sections)m(x.content),x.scale&&m(x.scale),x.font&&m(x.font),x.textColor&&m(x.textColor)}outputDefined(){return!1}serialize(){const m=["format"];for(const x of this.sections){m.push(x.content.serialize());const k={};x.scale&&(k["font-scale"]=x.scale.serialize()),x.font&&(k["text-font"]=x.font.serialize()),x.textColor&&(k["text-color"]=x.textColor.serialize()),m.push(k)}return m}}class Rr{constructor(m,x,k,E){this._imageWarnHistory={},this.type=Gb,this.namePrimary=m,this.nameSecondary=x,k&&(this.paramsPrimary=k.params,this.iconsetIdPrimary=k.iconset?k.iconset.id:void 0),E&&(this.paramsSecondary=E.params,this.iconsetIdSecondary=E.iconset?E.iconset.id:void 0)}static parse(m,x){if(m.length<2)return x.error("Expected two or more arguments.");let k=1;const E=[];function P(){if(kLt.isEqual(O,P)),E.available){const O=E.getSecondary()?E.getSecondary().id:null;O&&(E.available=m.availableImages.some(U=>Lt.isEqual(U,O)))}}return E}eachChild(m){if(m(this.namePrimary),this.paramsPrimary)for(const x in this.paramsPrimary)this.paramsPrimary[x]&&m(this.paramsPrimary[x]);if(this.nameSecondary&&(m(this.nameSecondary),this.paramsSecondary))for(const x in this.paramsSecondary)this.paramsSecondary[x]&&m(this.paramsSecondary[x])}outputDefined(){return!1}serializeOptions(m,x){const k={};if(x&&(k.iconset={id:x}),m){k.params={};for(const E in m)m[E]&&(k.params[E]=m[E].serialize())}return Object.keys(k).length>0?k:void 0}serialize(){const m=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const x=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);x&&m.push(x)}if(this.nameSecondary&&(m.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const x=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);x&&m.push(x)}return m}}function Oy(w){return i1(w)?"string":Yb(w)?"number":h0(w)?"boolean":Array.isArray(w)?"array":w===null?"null":dj(w)?"object":typeof w}function dj(w){return w!=null&&!Array.isArray(w)&&typeof w!="function"&&!(w instanceof String||w instanceof Number||w instanceof Boolean)&&typeof w=="object"}function i1(w){return typeof w=="string"||w instanceof String}function Yb(w){return typeof w=="number"||w instanceof Number}function h0(w){return typeof w=="boolean"||w instanceof Boolean}const Lf={"to-boolean":Zi,"to-color":zh,"to-number":Tr,"to-string":Mi};class vm{constructor(m,x){this.type=m,this.args=x}static parse(m,x){if(m.length<2)return x.error("Expected at least one argument.");const k=m[0],E=[];let P=If;if(k==="to-array"){if(!Array.isArray(m[1]))return null;const O=m[1].length;if(x.expectedType){if(x.expectedType.kind!=="array")return x.error(`Expected ${x.expectedType.kind} but found array.`);P=Yu(x.expectedType.itemType,O)}else{if(!(O>0&&Pf(m[1][0])))return null;P=Yu(Ml(m[1][0]),O)}for(let U=0;U4?`Invalid rbga value ${JSON.stringify(x)}: expected an array containing either three or four numeric values.`:Op(x[0],x[1],x[2],x[3]),!k))return new Gn(x[0]/255,x[1]/255,x[2]/255,x[3])}throw new yl(k||`Could not parse color from value '${typeof x=="string"?x:String(JSON.stringify(x))}'`)}if(this.type.kind==="number"){let x=null;for(const k of this.args){if(x=k.evaluate(m),x===null)return 0;const E=Number(x);if(!isNaN(E))return E}throw new yl(`Could not convert ${JSON.stringify(x)} to number.`)}return this.type.kind==="formatted"?Vd.fromString(sa(this.args[0].evaluate(m))):this.type.kind==="resolvedImage"?Hd.build(sa(this.args[0].evaluate(m))):this.type.kind==="array"?this.args.map(x=>x.evaluate(m)):sa(this.args[0].evaluate(m))}eachChild(m){this.args.forEach(m)}outputDefined(){return this.args.every(m=>m.outputDefined())}serialize(){if(this.type.kind==="formatted")return new ym([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new Rr(this.args[0]).serialize();const m=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(x=>{m.push(x.serialize())}),m}}const Df=["Unknown","Point","LineString","Polygon"];class ap{constructor(m,x,k){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=m,this.options=x,this.iconImageUseTheme=k}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?Df[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(m){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const m=this.featureDistanceData.center,x=this.featureDistanceData.scale,{x:k,y:E}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(k*x-m[0])+this.featureDistanceData.bearing[1]*(E*x-m[1])}return 0}parseColor(m){let x=this._parseColorCache[m];return x||(x=this._parseColorCache[m]=Gn.parse(m)),x}getConfig(m){return this.options?this.options.get(m):null}}class Bc{constructor(m,x,k,E,P){this.name=m,this.type=x,this._evaluate=k,this.args=E,this._overloadIndex=P}evaluate(m){if(!this._evaluate){const x=Bc.definitions[this.name];this._evaluate=Array.isArray(x)?x[2]:x.overloads[this._overloadIndex][1]}return this._evaluate(m,this.args)}eachChild(m){this.args.forEach(m)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(m=>m.serialize()))}static parse(m,x){const k=m[0],E=Bc.definitions[k];if(!E)return x.error(`Unknown expression "${k}". If you wanted a literal array, use ["literal", [...]].`,0);const P=Array.isArray(E)?E[0]:E.type,O=Array.isArray(E)?[[E[1],E[2]]]:E.overloads,U=[];let H=null,X=-1;for(const[oe,ue]of O){if(Array.isArray(oe)&&oe.length!==m.length-1)continue;U.push(oe),X++,H=new wj(x.registry,x.path,null,x.scope,void 0,x._scope,x.options,x.iconImageUseTheme);const me=[];let _e=!1;for(let Se=1;Seme)).map(Fp).join(" | "),ue=[];for(let me=1;mex;){if(k-x>600){const H=k-x+1,X=m-x+1,oe=Math.log(H),ue=.5*Math.exp(2*oe/3),me=.5*Math.sqrt(oe*ue*(H-ue)/H)*(X-H/2<0?-1:1);PN(w,m,Math.max(x,Math.floor(m-X*ue/H+me)),Math.min(k,Math.floor(m+(H-X)*ue/H+me)),E)}const P=w[m];let O=x,U=k;for(ec(w,x,m),E(w[k],P)>0&&ec(w,x,k);O0;)U--}E(w[x],P)===0?ec(w,x,U):(U++,ec(w,U,k)),U<=m&&(x=U+1),m<=U&&(k=U-1)}}function ec(w,m,x){const k=w[m];w[m]=w[x],w[x]=k}function o1(w,m){return wm?1:0}function LN(w){let m=0;for(let x,k,E=0,P=w.length,O=P-1;E=m[2]||w[1]<=m[1]||w[3]>=m[3])}function xC(w,m,x){const k=w[0]-m[0],E=w[1]-m[1],P=w[0]-x[0],O=w[1]-x[1];return k*O-P*E===0&&k*P<=0&&E*O<=0}function m0(w,m,x){return m[1]>w[1]!=x[1]>w[1]&&w[0]<(x[0]-m[0])*(w[1]-m[1])/(x[1]-m[1])+m[0]}function Wl(w,m,x=!1){let k=!1;for(let E=0,P=m.length;E0&&U<0||O<0&&U>0}function ld(w,m,x,k){return(E=[k[0]-x[0],k[1]-x[1]])[0]*(P=[m[0]-w[0],m[1]-w[1]])[1]-E[1]*P[0]!==0&&!(!Gd(w,m,x,k)||!Gd(x,k,w,m));var E,P}function Zb(w){const m=new Ls(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),x=new Ls(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const k of w[0])m.x>k.x&&(m.x=k.x),m.y>k.y&&(m.y=k.y),x.xx[2]){const E=.5*k;let P=w[0]-x[0]>E?-k:x[0]-w[0]>E?k:0;P===0&&(P=w[0]-x[2]>E?-k:x[2]-w[0]>E?k:0),w[0]+=P}zp(m,w)}function c1(w,m,x,k){const E=Math.pow(2,k.z)*Rf,P=[k.x*Rf,k.y*Rf],O=[];if(!w)return O;for(const U of w)for(const H of U){const X=[H.x+P[0],H.y+P[1]];Qc(X,m,x,E),O.push(X)}return O}function pj(w,m,x,k){const E=Math.pow(2,k.z)*Rf,P=[k.x*Rf,k.y*Rf],O=[];if(!w)return O;for(const H of w){const X=[];for(const oe of H){const ue=[oe.x+P[0],oe.y+P[1]];zp(m,ue),X.push(ue)}O.push(X)}if(m[2]-m[0]<=E/2){(U=m)[0]=U[1]=1/0,U[2]=U[3]=-1/0;for(const H of O)for(const X of H)Qc(X,m,x,E)}var U;return O}class hg{constructor(m,x){this.type=Zi,this.geojson=m,this.geometries=x}static parse(m,x){if(m.length!==2)return x.error(`'within' expression requires exactly one argument, but found ${m.length-1} instead.`);if(Pf(m[1])){const k=m[1];if(k.type==="FeatureCollection")for(let E=0;Ex)return fj(P,O,(x-(k-U))/U)}return m[m.length-1]}pointToSegmentDistance(m,x,k){let[E,P]=x,O=ip(k[0]-E)*this.kx,U=(k[1]-P)*this.ky;if(O!==0||U!==0){const H=(ip(m[0]-E)*this.kx*O+(m[1]-P)*this.ky*U)/(O*O+U*U);H>1?(E=k[0],P=k[1]):H>0&&(E+=O/this.kx*H,P+=U/this.ky*H)}return O=ip(m[0]-E)*this.kx,U=(m[1]-P)*this.ky,Math.sqrt(O*O+U*U)}pointOnLine(m,x){let k=1/0,E=m[0][0],P=m[0][1],O=0,U=0;for(let H=0;H1?(X=m[H+1][0],oe=m[H+1][1]):_e>0&&(X+=ue/this.kx*_e,oe+=me/this.ky*_e)),ue=ip(x[0]-X)*this.kx,me=(x[1]-oe)*this.ky;const Se=ue*ue+me*me;SeP.index||E.index===P.index&&E.t>P.t){const X=E;E=P,P=X}const O=[E.point],U=E.index+1,H=P.index;!FN(k[U],O[0])&&U<=H&&O.push(k[U]);for(let X=U+1;X<=H;X++)O.push(k[X]);return FN(k[H],P.point)||O.push(P.point),O}lineSliceAlong(m,x,k){let E=0;const P=[];for(let O=0;Om&&P.length===0&&P.push(fj(U,H,(m-(E-X))/X)),E>=x)return P.push(fj(U,H,(x-(E-X))/X)),P;E>m&&P.push(H)}return P}bufferPoint(m,x){const k=x/this.ky,E=x/this.kx;return[m[0]-E,m[1]-k,m[0]+E,m[1]+k]}bufferBBox(m,x){const k=x/this.ky,E=x/this.kx;return[m[0]-E,m[1]-k,m[2]+E,m[3]+k]}insideBBox(m,x){return ip(m[0]-x[0])>=0&&ip(m[0]-x[2])<=0&&m[1]>=x[1]&&m[1]<=x[3]}}function FN(w,m){return w[0]===m[0]&&w[1]===m[1]}function fj(w,m,x){const k=ip(m[0]-w[0]);return[w[0]+k*x,w[1]+(m[1]-w[1])*x]}function ip(w){for(;w<-180;)w+=360;for(;w>180;)w-=360;return w}class p0{constructor(m=[],x=(k,E)=>kE?1:0){if(this.data=m,this.length=this.data.length,this.compare=x,this.length>0)for(let k=(this.length>>1)-1;k>=0;k--)this._down(k)}push(m){this.data.push(m),this._up(this.length++)}pop(){if(this.length===0)return;const m=this.data[0],x=this.data.pop();return--this.length>0&&(this.data[0]=x,this._down(0)),m}peek(){return this.data[0]}_up(m){const{data:x,compare:k}=this,E=x[m];for(;m>0;){const P=m-1>>1,O=x[P];if(k(E,O)>=0)break;x[m]=O,m=P}x[m]=E}_down(m){const{data:x,compare:k}=this,E=this.length>>1,P=x[m];for(;m=0)break;x[m]=x[O],m=O}x[m]=P}}var $n=8192;function xj(w,m){return m.dist-w.dist}function gj(w){const m=[1/0,1/0,-1/0,-1/0];if(m.length!==w.length)return!1;for(let x=0;x=w[0]&&w[1]w[1])return[null,null];const x=zy(w);if(m){if(x===2)return[w,null];const k=Math.floor(x/2);return[[w[0],w[0]+k],[w[0]+k,w[1]]]}{if(x===1)return[w,null];const k=Math.floor(x/2)-1;return[[w[0],w[0]+k],[w[0]+k+1,w[1]]]}}function f0(w,m){const x=[1/0,1/0,-1/0,-1/0];if(!Bp(m,w.length))return x;for(let k=m[0];k<=m[1];++k)zp(x,w[k]);return x}function Jb(w){const m=[1/0,1/0,-1/0,-1/0];for(let x=0;xm[2]&&(k=w[0]-m[2]),w[1]>m[3]&&(E=w[1]-m[3]),w[3]=k)return k;if(Fy(E,P)){if(yj(w,m))return 0}else if(yj(m,w))return 0;let O=k;for(const U of w)for(let H=0,X=U.length,oe=X-1;H=P)continue;const oe=X.range1;if(zy(oe)<=U){if(!Bp(oe,w.length))return NaN;if(m){const ue=cl(w,oe,x,k);if((P=Math.min(P,ue))===0)return P}else for(let ue=oe[0];ue<=oe[1];++ue){const me=f6(w[ue],x,k);if((P=Math.min(P,me))===0)return P}}else{const ue=h1(oe,m);if(ue[0]!==null){const me=m1(f0(w,ue[0]),H,k);me=O)continue;const ue=oe.range1,me=oe.range2;if(zy(ue)<=H&&zy(me)<=X){if(!Bp(ue,w.length)||!Bp(me,x.length))return NaN;if(m&&k?O=Math.min(O,zR(w,ue,x,me,E)):m||k?m&&!k?O=Math.min(O,bC(x,me,w,ue,E)):!m&&k&&(O=Math.min(O,bC(w,ue,x,me,E))):O=Math.min(O,wC(w,ue,x,me,E)),O===0)return O}else{const _e=h1(ue,m),Se=h1(me,k);zN(U,O,E,w,x,_e[0],Se[0]),zN(U,O,E,w,x,_e[0],Se[1]),zN(U,O,E,w,x,_e[1],Se[0]),zN(U,O,E,w,x,_e[1],Se[1])}}return O}function vj(w,m,x,k,E=1/0){let P=E;const O=f0(w,[0,w.length-1]);for(const U of x)if(!(P!==1/0&&m1(O,f0(U,[0,U.length-1]),k)>=P)&&(P=Math.min(P,Ff(w,m,U,!0,k,P)),P===0))return P;return P}function p1(w,m,x,k,E=1/0){let P=E;const O=f0(w,[0,w.length-1]);for(const U of x){if(P!==1/0&&m1(O,Jb(U),k)>=P)continue;const H=$R(w,m,U,k,P);if(isNaN(H))return H;if((P=Math.min(P,H))===0)return P}return P}function BN(w){return w==="Point"||w==="MultiPoint"||w==="LineString"||w==="MultiLineString"||w==="Polygon"||w==="MultiPolygon"}class By{constructor(m,x){this.type=Tr,this.geojson=m,this.geometries=x}static parse(m,x){if(m.length!==2)return x.error(`'distance' expression requires either one argument, but found ' ${m.length-1} instead.`);if(Pf(m[1])){const k=m[1];if(k.type==="FeatureCollection"){for(let E=0;E{m&&!$y(x)&&(m=!1)}),m}function Uy(w){if(w instanceof Bc&&w.name==="feature-state")return!1;let m=!0;return w.eachChild(x=>{m&&!Uy(x)&&(m=!1)}),m}function bm(w,m){if(w instanceof Bc&&m.indexOf(w.name)>=0)return!1;let x=!0;return w.eachChild(k=>{x&&!bm(k,m)&&(x=!1)}),x}function $N(w,m,x){return[w,m,x].filter(Boolean).join("")}function bj(w,m){switch(w){case"string":return sa(m);case"number":return+m;case"boolean":return!!m;case"color":return Gn.parse(m);case"formatted":return Vd.fromString(sa(m));case"resolvedImage":return Hd.build(sa(m))}return m}function x6(w,m,x,k){return k!==void 0&&(w=k*Math.round(w/k)),m!==void 0&&wx&&(w=x),w}class f1{constructor(m,x,k,E=!1){this.type=m,this.key=x,this.scope=k,this.featureConstant=E}static parse(m,x){let k=x.expectedType;if(k==null&&(k=to),m.length<2||m.length>3)return x.error("Invalid number of arguments for 'config' expression.");const E=x.parse(m[1],1);if(!(E instanceof ar))return x.error("Key name of 'config' expression must be a string literal.");let P,O=!0;const U=sa(E.value);if(m.length>=3){const H=x.parse(m[2],2);if(!(H instanceof ar))return x.error("Scope of 'config' expression must be a string literal.");P=sa(H.value)}if(x.options){const H=$N(U,P,x._scope),X=x.options.get(H);X&&(O=$y(X.value||X.default))}return new f1(k,U,P,O)}evaluate(m){const x=$N(this.key,this.scope,m.scope),k=m.getConfig(x);if(!k)return null;const{type:E,value:P,values:O,minValue:U,maxValue:H,stepValue:X}=k,oe=k.default.evaluate(m);let ue=oe;if(P){const me=m.scope;m.scope=(me||"").split("").slice(1).join(""),ue=P.evaluate(m),m.scope=me}return E&&(ue=bj(E,ue)),ue===void 0||U===void 0&&H===void 0&&X===void 0||(typeof ue=="number"?ue=x6(ue,U,H,X):Array.isArray(ue)&&(ue=ue.map(me=>typeof me=="number"?x6(me,U,H,X):me))),P!==void 0&&ue!==void 0&&O&&!O.includes(ue)&&(ue=oe,E&&(ue=bj(E,ue))),(E&&E!==this.type||ue!==void 0&&!vx(Ml(ue),this.type))&&(ue=bj(this.type.kind,ue)),ue}eachChild(){}outputDefined(){return!1}serialize(){const m=["config",this.key];return this.scope&&m.concat(this.scope),m}}class _j{constructor(m,x){this.type=x.type,this.name=m,this.boundExpression=x}static parse(m,x){if(m.length!==2||typeof m[1]!="string")return x.error("'var' expression requires exactly one string literal argument.");const k=m[1];return x.scope.has(k)?new _j(k,x.scope.get(k)):x.error(`Unknown variable "${k}". Make sure "${k}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(m){return this.boundExpression.evaluate(m)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class wj{constructor(m,x=[],k,E=new ug,P=[],O,U,H){this.registry=m,this.path=x,this.key=x.map(X=>typeof X=="string"?`['${X}']`:`[${X}]`).join(""),this.scope=E,this.errors=P,this.expectedType=k,this._scope=O,this.options=U,this.iconImageUseTheme=H}parse(m,x,k,E,P={}){return x||k?this.concat(x,null,k,E)._parse(m,P):this._parse(m,P)}parseObjectValue(m,x,k,E,P,O={}){return this.concat(x,k,E,P)._parse(m,O)}_parse(m,x){function k(E,P,O){return O==="assert"?new rp(P,[E]):O==="coerce"?new vm(P,[E]):E}if(m!==null&&typeof m!="string"&&typeof m!="boolean"&&typeof m!="number"||(m=["literal",m]),Array.isArray(m)){if(m.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const E=typeof m[0]=="string"?this.registry[m[0]]:void 0;if(E){let P=E.parse(m,this);if(!P)return null;if(this.expectedType){const O=this.expectedType,U=P.type;if(O.kind!=="string"&&O.kind!=="number"&&O.kind!=="boolean"&&O.kind!=="object"&&O.kind!=="array"||U.kind!=="value")if(O.kind!=="color"&&O.kind!=="formatted"&&O.kind!=="resolvedImage"||U.kind!=="value"&&U.kind!=="string"){if(this.checkSubtype(O,U))return null}else P=k(P,O,x.typeAnnotation||"coerce");else P=k(P,O,x.typeAnnotation||"assert")}if(!(P instanceof ar)&&P.type.kind!=="resolvedImage"&&UN(P)){const O=new ap(this._scope,this.options,this.iconImageUseTheme);try{P=new ar(P.type,P.evaluate(O))}catch(U){return this.error(U.message),null}}return P}return vm.parse(["to-array",m],this)}return this.error(m===void 0?"'undefined' value invalid. Use null instead.":typeof m=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof m} instead.`)}concat(m,x,k,E){let P=typeof m=="number"?this.path.concat(m):this.path;P=typeof x=="string"?P.concat(x):P;const O=E?this.scope.concat(E):this.scope;return new wj(this.registry,P,k||null,O,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(m,...x){const k=`${this.key}${x.map(E=>`[${E}]`).join("")}`;this.errors.push(new Ku(k,m))}checkSubtype(m,x){const k=Ry(m,x);return k&&this.error(k),k}}function UN(w){if(w instanceof _j)return UN(w.boundExpression);if(w instanceof Bc&&w.name==="error"||w instanceof uj||w instanceof hg||w instanceof By||w instanceof f1)return!1;const m=w instanceof vm||w instanceof rp;let x=!0;return w.eachChild(k=>{x=m?x&&UN(k):x&&k instanceof ar}),!!x&&$y(w)&&bm(w,["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 jj(w,m){const x=w.length-1;let k,E,P=0,O=x,U=0;for(;P<=O;)if(U=Math.floor((P+O)/2),k=w[U],E=w[U+1],k<=m){if(U===x||mm))throw new yl("Input is not a number.");O=U-1}return 0}class Nj{constructor(m,x,k){this.type=m,this.input=x,this.labels=[],this.outputs=[];for(const[E,P]of k)this.labels.push(E),this.outputs.push(P)}static parse(m,x){if(m.length-1<4)return x.error(`Expected at least 4 arguments, but found only ${m.length-1}.`);if((m.length-1)%2!=0)return x.error("Expected an even number of arguments.");const k=x.parse(m[1],1,Tr);if(!k)return null;const E=[];let P=null;x.expectedType&&x.expectedType.kind!=="value"&&(P=x.expectedType);for(let O=1;O=U)return x.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',X);const ue=x.parse(H,oe,P);if(!ue)return null;P=P||ue.type,E.push([U,ue])}return new Nj(P,k,E)}evaluate(m){const x=this.labels,k=this.outputs;if(x.length===1)return k[0].evaluate(m);const E=this.input.evaluate(m);if(E<=x[0])return k[0].evaluate(m);const P=x.length;return E>=x[P-1]?k[P-1].evaluate(m):k[jj(x,E)].evaluate(m)}eachChild(m){m(this.input);for(const x of this.outputs)m(x)}outputDefined(){return this.outputs.every(m=>m.outputDefined())}serialize(){const m=["step",this.input.serialize()];for(let x=0;x0&&m.push(this.labels[x]),m.push(this.outputs[x].serialize());return m}}const _m=.95047,$h=1.08883,jC=4/29,x1=6/29,NC=3*x1*x1,g6=x1*x1*x1,y6=Math.PI/180,kC=180/Math.PI;function qN(w){return w>g6?Math.pow(w,1/3):w/NC+jC}function kj(w){return w>x1?w*w*w:NC*(w-jC)}function e_(w){return 255*(w<=.0031308?12.92*w:1.055*Math.pow(w,1/2.4)-.055)}function g1(w){return(w/=255)<=.04045?w/12.92:Math.pow((w+.055)/1.055,2.4)}function Sj(w){const m=g1(w.r),x=g1(w.g),k=g1(w.b),E=qN((.4124564*m+.3575761*x+.1804375*k)/_m),P=qN((.2126729*m+.7151522*x+.072175*k)/1);return{l:116*P-16,a:500*(E-P),b:200*(P-qN((.0193339*m+.119192*x+.9503041*k)/$h)),alpha:w.a}}function VN(w){let m=(w.l+16)/116,x=isNaN(w.a)?m:m+w.a/500,k=isNaN(w.b)?m:m-w.b/200;return m=1*kj(m),x=_m*kj(x),k=$h*kj(k),new Gn(e_(3.2404542*x-1.5371385*m-.4985314*k),e_(-.969266*x+1.8760108*m+.041556*k),e_(.0556434*x-.2040259*m+1.0572252*k),w.alpha)}function v6(w,m,x){const k=m-w;return w+x*(k>180||k<-180?k-360*Math.round(k/360):k)}const y1={forward:Sj,reverse:VN,interpolate:function(w,m,x){return{l:zr(w.l,m.l,x),a:zr(w.a,m.a,x),b:zr(w.b,m.b,x),alpha:zr(w.alpha,m.alpha,x)}}},x0={forward:function(w){const{l:m,a:x,b:k}=Sj(w),E=Math.atan2(k,x)*kC;return{h:E<0?E+360:E,c:Math.sqrt(x*x+k*k),l:m,alpha:w.a}},reverse:function(w){const m=w.h*y6,x=w.c;return VN({l:w.l,a:Math.cos(m)*x,b:Math.sin(m)*x,alpha:w.alpha})},interpolate:function(w,m,x){return{h:v6(w.h,m.h,x),c:zr(w.c,m.c,x),l:zr(w.l,m.l,x),alpha:zr(w.alpha,m.alpha,x)}}};var SC=Object.freeze({__proto__:null,hcl:x0,lab:y1});class gu{constructor(m,x,k,E,P){this.type=m,this.operator=x,this.interpolation=k,this.input=E,this.labels=[],this.outputs=[];for(const[O,U]of P)this.labels.push(O),this.outputs.push(U)}static interpolationFactor(m,x,k,E){let P=0;if(m.name==="exponential")P=t_(x,m.base,k,E);else if(m.name==="linear")P=t_(x,1,k,E);else if(m.name==="cubic-bezier"){const O=m.controlPoints;P=new vi(O[0],O[1],O[2],O[3]).solve(t_(x,1,k,E))}return P}static parse(m,x){let[k,E,P,...O]=m;if(!Array.isArray(E)||E.length===0)return x.error("Expected an interpolation type expression.",1);if(E[0]==="linear")E={name:"linear"};else if(E[0]==="exponential"){const X=E[1];if(typeof X!="number")return x.error("Exponential interpolation requires a numeric base.",1,1);E={name:"exponential",base:X}}else{if(E[0]!=="cubic-bezier")return x.error(`Unknown interpolation type ${String(E[0])}`,1,0);{const X=E.slice(1);if(X.length!==4||X.some(oe=>typeof oe!="number"||oe<0||oe>1))return x.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);E={name:"cubic-bezier",controlPoints:X}}}if(m.length-1<4)return x.error(`Expected at least 4 arguments, but found only ${m.length-1}.`);if(m.length-1>3&&(m.length-1)%2!=0)return x.error("Expected an even number of arguments.");if(P=x.parse(P,2,Tr),!P)return null;const U=[];let H=null;k==="interpolate-hcl"||k==="interpolate-lab"?H=zh:x.expectedType&&x.expectedType.kind!=="value"&&(H=x.expectedType);for(let X=0;X=oe)return x.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',me);const Se=x.parse(ue,_e,H);if(!Se)return null;H=H||Se.type,U.push([oe,Se])}return H.kind==="number"||H.kind==="color"||H.kind==="array"&&H.itemType.kind==="number"&&typeof H.N=="number"?new gu(H,k,E,P,U):x.error(`Type ${Dl(H)} is not interpolatable.`)}evaluate(m){const x=this.labels,k=this.outputs;if(x.length===1)return k[0].evaluate(m);const E=this.input.evaluate(m);if(E<=x[0])return k[0].evaluate(m);const P=x.length;if(E>=x[P-1])return k[P-1].evaluate(m);const O=jj(x,E),U=gu.interpolationFactor(this.interpolation,E,x[O],x[O+1]),H=k[O].evaluate(m),X=k[O+1].evaluate(m);return this.operator==="interpolate"?gm[this.type.kind.toLowerCase()](H,X,U):this.operator==="interpolate-hcl"?x0.reverse(x0.interpolate(x0.forward(H),x0.forward(X),U)):y1.reverse(y1.interpolate(y1.forward(H),y1.forward(X),U))}eachChild(m){m(this.input);for(const x of this.outputs)m(x)}outputDefined(){return this.outputs.every(m=>m.outputDefined())}serialize(){let m;m=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const x=[this.operator,m,this.input.serialize()];for(let k=0;kRy(E,U.type));return new s_(O?to:k,P)}evaluate(m){let x,k=null,E=0;for(const P of this.args){if(E++,k=P.evaluate(m),k&&k instanceof Hd&&!k.available&&(x||(x=k),k=null,E===this.args.length))return x;if(k!==null)break}return k}eachChild(m){this.args.forEach(m)}outputDefined(){return this.args.every(m=>m.outputDefined())}serialize(){const m=["coalesce"];return this.eachChild(x=>{m.push(x.serialize())}),m}}class v1{constructor(m,x){this.type=x.type,this.bindings=[].concat(m),this.result=x}evaluate(m){return this.result.evaluate(m)}eachChild(m){for(const x of this.bindings)m(x[1]);m(this.result)}static parse(m,x){if(m.length<4)return x.error(`Expected at least 3 arguments, but found ${m.length-1} instead.`);const k=[];for(let P=1;P=k.length)throw new yl("Array index out of bounds: index exceeds array size");if(x!==Math.floor(x))throw new yl("Array index must be an integer. Use at-interpolated for fractional indices");return k[x]}eachChild(m){m(this.index),m(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class Cj{constructor(m,x,k){this.type=m,this.index=x,this.input=k}static parse(m,x){if(m.length!==3)return x.error(`Expected 2 arguments, but found ${m.length-1} instead.`);const k=x.parse(m[1],1,Tr),E=x.parse(m[2],2,Yu(x.expectedType||to));return k&&E?new Cj(E.type.itemType,k,E):null}evaluate(m){const x=this.index.evaluate(m),k=this.input.evaluate(m);if(x<0)throw new yl(`Array index out of bounds: ${x} < 0.`);if(x>k.length-1)throw new yl(`Array index out of bounds: ${x} > ${k.length-1}.`);if(x===Math.floor(x))return k[x];const E=Math.floor(x),P=Math.ceil(x),O=k[E],U=k[P];if(typeof O!="number"||typeof U!="number")throw new yl(`Cannot interpolate between non-number values at index ${x}.`);const H=x-E;return O*(1-H)+U*H}eachChild(m){m(this.index),m(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class op{constructor(m,x){this.type=Zi,this.needle=m,this.haystack=x}static parse(m,x){if(m.length!==3)return x.error(`Expected 2 arguments, but found ${m.length-1} instead.`),null;const k=x.parse(m[1],1,to),E=x.parse(m[2],2,to);return k&&E?Wb(k.type,[Zi,Mi,Tr,If,to])?new op(k,E):(x.error(`Expected first argument to be of type boolean, string, number or null, but found ${Dl(k.type)} instead`),null):null}evaluate(m){const x=this.needle.evaluate(m),k=this.haystack.evaluate(m);if(k==null)return!1;if(!yx(x,["boolean","string","number","null"]))throw new yl(`Expected first argument to be of type boolean, string, number or null, but found ${Dl(Ml(x))} instead.`);if(!yx(k,["string","array"]))throw new yl(`Expected second argument to be of type array or string, but found ${Dl(Ml(k))} instead.`);return k.indexOf(x)>=0}eachChild(m){m(this.needle),m(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class Tj{constructor(m,x,k){this.type=Tr,this.needle=m,this.haystack=x,this.fromIndex=k}static parse(m,x){if(m.length<=2||m.length>=5)return x.error(`Expected 3 or 4 arguments, but found ${m.length-1} instead.`),null;const k=x.parse(m[1],1,to),E=x.parse(m[2],2,to);if(!k||!E)return null;if(!Wb(k.type,[Zi,Mi,Tr,If,to]))return x.error(`Expected first argument to be of type boolean, string, number or null, but found ${Dl(k.type)} instead`),null;if(m.length===4){const P=x.parse(m[3],3,Tr);return P?new Tj(k,E,P):null}return new Tj(k,E)}evaluate(m){const x=this.needle.evaluate(m),k=this.haystack.evaluate(m);if(!yx(x,["boolean","string","number","null"]))throw new yl(`Expected first argument to be of type boolean, string, number or null, but found ${Dl(Ml(x))} instead.`);if(!yx(k,["string","array"]))throw new yl(`Expected second argument to be of type array or string, but found ${Dl(Ml(k))} instead.`);if(this.fromIndex){const E=this.fromIndex.evaluate(m);return k.indexOf(x,E)}return k.indexOf(x)}eachChild(m){m(this.needle),m(this.haystack),this.fromIndex&&m(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const m=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),m]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class b1{constructor(m,x,k,E,P,O){this.inputType=m,this.type=x,this.input=k,this.cases=E,this.outputs=P,this.otherwise=O}static parse(m,x){if(m.length<5)return x.error(`Expected at least 4 arguments, but found only ${m.length-1}.`);if(m.length%2!=1)return x.error("Expected an even number of arguments.");let k,E;x.expectedType&&x.expectedType.kind!=="value"&&(E=x.expectedType);const P={},O=[];for(let X=2;XNumber.MAX_SAFE_INTEGER)return me.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof Se=="number"&&Math.floor(Se)!==Se)return me.error("Numeric branch labels must be integer values.");if(k){if(me.checkSubtype(k,Ml(Se)))return null}else k=Ml(Se);if(P[String(Se)]!==void 0)return me.error("Branch labels must be unique.");P[String(Se)]=O.length}const _e=x.parse(ue,X,E);if(!_e)return null;E=E||_e.type,O.push(_e)}const U=x.parse(m[1],1,to);if(!U)return null;const H=x.parse(m[m.length-1],m.length-1,E);return H?U.type.kind!=="value"&&x.concat(1).checkSubtype(k,U.type)?null:new b1(k,E,U,P,O,H):null}evaluate(m){const x=this.input.evaluate(m);return(vx(Ml(x),this.inputType)&&this.outputs[this.cases[x]]||this.otherwise).evaluate(m)}eachChild(m){m(this.input),this.outputs.forEach(m),m(this.otherwise)}outputDefined(){return this.outputs.every(m=>m.outputDefined())&&this.otherwise.outputDefined()}serialize(){const m=["match",this.input.serialize()],x=Object.keys(this.cases).sort(),k=[],E={};for(const O of x){const U=E[this.cases[O]];U===void 0?(E[this.cases[O]]=k.length,k.push([this.cases[O],[O]])):k[U][1].push(O)}const P=O=>this.inputType.kind==="number"?Number(O):O;for(const[O,U]of k)m.push(U.length===1?P(U[0]):U.map(P)),m.push(this.outputs[O].serialize());return m.push(this.otherwise.serialize()),m}}class qy{constructor(m,x,k){this.type=m,this.branches=x,this.otherwise=k}static parse(m,x){if(m.length<4)return x.error(`Expected at least 3 arguments, but found only ${m.length-1}.`),null;if(m.length%2!=0)return x.error("Expected an odd number of arguments."),null;let k;x.expectedType&&x.expectedType.kind!=="value"&&(k=x.expectedType);const E=[];for(let O=1;Ox.outputDefined())&&this.otherwise.outputDefined()}serialize(){const m=["case"];return this.eachChild(x=>{m.push(x.serialize())}),m}}class Vy{constructor(m,x,k,E){this.type=m,this.input=x,this.beginIndex=k,this.endIndex=E}static parse(m,x){if(m.length<=2||m.length>=5)return x.error(`Expected 3 or 4 arguments, but found ${m.length-1} instead.`),null;const k=x.parse(m[1],1,to),E=x.parse(m[2],2,Tr);if(!k||!E)return null;if(!Wb(k.type,[Yu(to),Mi,to]))return x.error(`Expected first argument to be of type array or string, but found ${Dl(k.type)} instead`),null;if(m.length===4){const P=x.parse(m[3],3,Tr);return P?new Vy(k.type,k,E,P):null}return new Vy(k.type,k,E)}evaluate(m){const x=this.input.evaluate(m),k=this.beginIndex.evaluate(m);if(!yx(x,["string","array"]))throw new yl(`Expected first argument to be of type array or string, but found ${Dl(Ml(x))} instead.`);if(this.endIndex){const E=this.endIndex.evaluate(m);return x.slice(k,E)}return x.slice(k)}eachChild(m){m(this.input),m(this.beginIndex),this.endIndex&&m(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const m=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),m]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class n_{constructor(m,x){this.type=Yu(Mi),this.str=m,this.delimiter=x}static parse(m,x){if(m.length!==3)return x.error(`Expected 2 arguments, but found ${m.length-1} instead.`);const k=x.parse(m[1],1,Mi),E=x.parse(m[2],2,Mi);return k&&E?new n_(k,E):void 0}evaluate(m){const x=this.str.evaluate(m),k=this.delimiter.evaluate(m);return x.split(k)}eachChild(m){m(this.str),m(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function CC(w,m){return w==="=="||w==="!="?m.kind==="boolean"||m.kind==="string"||m.kind==="number"||m.kind==="null"||m.kind==="value":m.kind==="string"||m.kind==="number"||m.kind==="value"}function r_(w,m,x,k){return k.compare(m,x)===0}function cd(w,m,x){const k=w!=="=="&&w!=="!=";return class pct{constructor(P,O,U){this.type=Zi,this.lhs=P,this.rhs=O,this.collator=U,this.hasUntypedArgument=P.type.kind==="value"||O.type.kind==="value"}static parse(P,O){if(P.length!==3&&P.length!==4)return O.error("Expected two or three arguments.");const U=P[0];let H=O.parse(P[1],1,to);if(!H)return null;if(!CC(U,H.type))return O.concat(1).error(`"${U}" comparisons are not supported for type '${Dl(H.type)}'.`);let X=O.parse(P[2],2,to);if(!X)return null;if(!CC(U,X.type))return O.concat(2).error(`"${U}" comparisons are not supported for type '${Dl(X.type)}'.`);if(H.type.kind!==X.type.kind&&H.type.kind!=="value"&&X.type.kind!=="value")return O.error(`Cannot compare types '${Dl(H.type)}' and '${Dl(X.type)}'.`);k&&(H.type.kind==="value"&&X.type.kind!=="value"?H=new rp(X.type,[H]):H.type.kind!=="value"&&X.type.kind==="value"&&(X=new rp(H.type,[X])));let oe=null;if(P.length===4){if(H.type.kind!=="string"&&X.type.kind!=="string"&&H.type.kind!=="value"&&X.type.kind!=="value")return O.error("Cannot use collator to compare non-string types.");if(oe=O.parse(P[3],3,gx),!oe)return null}return new pct(H,X,oe)}evaluate(P){const O=this.lhs.evaluate(P),U=this.rhs.evaluate(P);if(k&&this.hasUntypedArgument){const H=Ml(O),X=Ml(U);if(H.kind!==X.kind||H.kind!=="string"&&H.kind!=="number")throw new yl(`Expected arguments for "${w}" to be (string, string) or (number, number), but found (${H.kind}, ${X.kind}) instead.`)}if(this.collator&&!k&&this.hasUntypedArgument){const H=Ml(O),X=Ml(U);if(H.kind!=="string"||X.kind!=="string")return m(P,O,U)}return this.collator?x(P,O,U,this.collator.evaluate(P)):m(P,O,U)}eachChild(P){P(this.lhs),P(this.rhs),this.collator&&P(this.collator)}outputDefined(){return!0}serialize(){const P=[w];return this.eachChild(O=>{P.push(O.serialize())}),P}}}const b6=cd("==",function(w,m,x){return m===x},r_),HN=cd("!=",function(w,m,x){return m!==x},function(w,m,x,k){return!r_(0,m,x,k)}),GN=cd("<",function(w,m,x){return m",function(w,m,x){return m>x},function(w,m,x,k){return k.compare(m,x)>0}),UR=cd("<=",function(w,m,x){return m<=x},function(w,m,x,k){return k.compare(m,x)<=0}),$a=cd(">=",function(w,m,x){return m>=x},function(w,m,x,k){return k.compare(m,x)>=0});class g0{constructor(m,x,k,E,P,O){this.type=Mi,this.number=m,this.locale=x,this.currency=k,this.unit=E,this.minFractionDigits=P,this.maxFractionDigits=O}static parse(m,x){if(m.length!==3)return x.error("Expected two arguments.");const k=x.parse(m[1],1,Tr);if(!k)return null;const E=m[2];if(typeof E!="object"||Array.isArray(E))return x.error("NumberFormat options argument must be an object.");let P=null;if(E.locale&&(P=x.parseObjectValue(E.locale,2,"locale",Mi),!P))return null;let O=null;if(E.currency&&(O=x.parseObjectValue(E.currency,2,"currency",Mi),!O))return null;let U=null;if(E.unit&&(U=x.parseObjectValue(E.unit,2,"unit",Mi),!U))return null;let H=null;if(E["min-fraction-digits"]&&(H=x.parseObjectValue(E["min-fraction-digits"],2,"min-fraction-digits",Tr),!H))return null;let X=null;return E["max-fraction-digits"]&&(X=x.parseObjectValue(E["max-fraction-digits"],2,"max-fraction-digits",Tr),!X)?null:new g0(k,P,O,U,H,X)}evaluate(m){return new Intl.NumberFormat(this.locale?this.locale.evaluate(m):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(m):void 0,unit:this.unit?this.unit.evaluate(m):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(m):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(m):void 0}).format(this.number.evaluate(m))}eachChild(m){m(this.number),this.locale&&m(this.locale),this.currency&&m(this.currency),this.unit&&m(this.unit),this.minFractionDigits&&m(this.minFractionDigits),this.maxFractionDigits&&m(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const m={};return this.locale&&(m.locale=this.locale.serialize()),this.currency&&(m.currency=this.currency.serialize()),this.unit&&(m.unit=this.unit.serialize()),this.minFractionDigits&&(m["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(m["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),m]}}class a_{constructor(m){this.type=Tr,this.input=m}static parse(m,x){if(m.length!==2)return x.error(`Expected 1 argument, but found ${m.length-1} instead.`),null;const k=x.parse(m[1],1);return k?k.type.kind!=="array"&&k.type.kind!=="string"&&k.type.kind!=="value"?(x.error(`Expected argument of type string or array, but found ${Dl(k.type)} instead.`),null):new a_(k):null}evaluate(m){const x=this.input.evaluate(m);if(typeof x=="string"||Array.isArray(x))return x.length;throw new yl(`Expected value to be of type string or array, but found ${Dl(Ml(x))} instead.`)}eachChild(m){m(this.input)}outputDefined(){return!1}serialize(){const m=["length"];return this.eachChild(x=>{m.push(x.serialize())}),m}}function TC(w){return function(){w=1831565813+(w|=0)|0;let m=Math.imul(w^w>>>15,1|w);return m=m+Math.imul(m^m>>>7,61|m)^m,((m^m>>>14)>>>0)/4294967296}}const i_={"==":b6,"!=":HN,">":vh,"<":GN,">=":$a,"<=":UR,array:rp,at:$p,"at-interpolated":Cj,boolean:rp,case:qy,coalesce:s_,collator:uj,format:ym,image:Rr,in:op,"index-of":Tj,interpolate:gu,"interpolate-hcl":gu,"interpolate-lab":gu,length:a_,let:v1,literal:ar,match:b1,number:rp,"number-format":g0,object:rp,slice:Vy,step:Nj,string:rp,"to-boolean":vm,"to-color":vm,"to-number":vm,"to-string":vm,var:_j,within:hg,distance:By,config:f1,split:n_};function o_(w,[m,x,k,E]){m=m.evaluate(w),x=x.evaluate(w),k=k.evaluate(w);const P=E?E.evaluate(w):1,O=Op(m,x,k,P);if(O)throw new yl(O);return new Gn(m/255,x/255,k/255,P)}function Ej(w,[m,x,k,E]){m=m.evaluate(w),x=x.evaluate(w),k=k.evaluate(w);const P=E?E.evaluate(w):1,O=function(X,oe,ue,me){return typeof X=="number"&&X>=0&&X<=360?typeof oe=="number"&&oe>=0&&oe<=100&&typeof ue=="number"&&ue>=0&&ue<=100?me===void 0||typeof me=="number"&&me>=0&&me<=1?null:`Invalid hsla value [${[X,oe,ue,me].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof me=="number"?[X,oe,ue,me]:[X,oe,ue]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof me=="number"?[X,oe,ue,me]:[X,oe,ue]).join(", ")}]: 'h' must be between 0 and 360.`}(m,x,k,P);if(O)throw new yl(O);const U=`hsla(${m}, ${x}%, ${k}%, ${P})`,H=Gn.parse(U);if(!H)throw new yl(`Failed to parse HSLA color: ${U}`);return H}function _1(w,m){return w in m}function Aj(w,m){const x=m[w];return x===void 0?null:x}function y0(w){return{type:w}}function Mj(w){if(w instanceof f1)return new Set([w.key]);let m=new Set;return w.eachChild(x=>{m=new Set([...m,...Mj(x)])}),m}function l_(w){if(w instanceof Bc&&w.name==="is-active-floor")return!0;let m=!1;return w.eachChild(x=>{!m&&l_(x)&&(m=!0)}),m}function WN(w){return{result:"success",value:w}}function $c(w){return{result:"error",value:w}}function wm(w,m){return!!w&&!!w.parameters&&w.parameters.indexOf(m)>-1}function Up(w){return w["property-type"]==="data-driven"}function KN(w){return wm(w.expression,"measure-light")}function YN(w){return wm(w.expression,"zoom")}function lp(w){return!!w.expression&&w.expression.interpolated}function ZN(w){return typeof w=="object"&&w!==null&&!Array.isArray(w)}function bx(w){return w}function _6(w,m){const x=m.type==="color",k=w.stops&&typeof w.stops[0][0]=="object",E=k||!(k||w.property!==void 0),P=w.type||(lp(m)?"exponential":"interval");if(x&&((w=Object.assign({},w)).stops&&(w.stops=w.stops.map(X=>[X[0],Gn.parse(X[1])])),w.default=Gn.parse(w.default?w.default:m.default)),w.colorSpace&&w.colorSpace!=="rgb"&&!SC[w.colorSpace])throw new Error(`Unknown color space: ${w.colorSpace}`);let O,U,H;if(P==="exponential")O=EC;else if(P==="interval")O=j6;else if(P==="categorical"){O=w6,U=Object.create(null);for(const X of w.stops)U[X[0]]=X[1];H=typeof w.stops[0][0]}else{if(P!=="identity")throw new Error(`Unknown function type "${P}"`);O=Ij}if(k){const X={},oe=[];for(let _e=0;_e_e[0]),evaluate:({zoom:_e},Se)=>EC({stops:ue,base:w.base},m,_e).evaluate(_e,Se)}}if(E){const X=P==="exponential"?{name:"exponential",base:w.base!==void 0?w.base:1}:null;return{kind:"camera",interpolationType:X,interpolationFactor:gu.interpolationFactor.bind(void 0,X),zoomStops:w.stops.map(oe=>oe[0]),evaluate:({zoom:oe})=>O(w,m,oe,U,H)}}return{kind:"source",evaluate(X,oe){const ue=oe&&oe.properties?oe.properties[w.property]:void 0;return ue===void 0?_x(w.default,m.default):O(w,m,ue,U,H)}}}function _x(w,m,x){return w!==void 0?w:m!==void 0?m:x!==void 0?x:void 0}function w6(w,m,x,k,E){return _x(typeof x===E?k[x]:void 0,w.default,m.default)}function j6(w,m,x){if(!Yb(x))return _x(w.default,m.default);const k=w.stops.length;if(k===1||x<=w.stops[0][0])return w.stops[0][1];if(x>=w.stops[k-1][0])return w.stops[k-1][1];const E=jj(w.stops.map(P=>P[0]),x);return w.stops[E][1]}function EC(w,m,x){const k=w.base!==void 0?w.base:1;if(!Yb(x))return _x(w.default,m.default);const E=w.stops.length;if(E===1||x<=w.stops[0][0])return w.stops[0][1];if(x>=w.stops[E-1][0])return w.stops[E-1][1];const P=jj(w.stops.map(oe=>oe[0]),x),O=function(oe,ue,me,_e){const Se=_e-me,Pe=oe-me;return Se===0?0:ue===1?Pe/Se:(Math.pow(ue,Pe)-1)/(Math.pow(ue,Se)-1)}(x,k,w.stops[P][0],w.stops[P+1][0]),U=w.stops[P][1],H=w.stops[P+1][1];let X=gm[m.type]||bx;if(w.colorSpace&&w.colorSpace!=="rgb"){const oe=SC[w.colorSpace];X=(ue,me)=>oe.reverse(oe.interpolate(oe.forward(ue),oe.forward(me),O))}return typeof U.evaluate=="function"?{evaluate(...oe){const ue=U.evaluate.apply(void 0,oe),me=H.evaluate.apply(void 0,oe);if(ue!==void 0&&me!==void 0)return X(ue,me,O)}}:X(U,H,O)}function Ij(w,m,x){return m.type==="color"?x=Gn.parse(x):m.type==="formatted"?x=Vd.fromString(x.toString()):m.type==="resolvedImage"?x=Hd.build(x.toString()):Oy(x)===m.type||m.type==="enum"&&m.values[x]||(x=void 0),_x(x,w.default,m.default)}Bc.register(i_,{error:[{kind:"error"},[Mi],(w,[m])=>{throw new yl(m.evaluate(w))}],typeof:[Mi,[to],(w,[m])=>Dl(Ml(m.evaluate(w)))],"to-rgba":[Yu(Tr,4),[zh],(w,[m])=>m.evaluate(w).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[Yu(Tr,4),[zh],(w,[m])=>m.evaluate(w).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[zh,[Tr,Tr,Tr],o_],rgba:[zh,[Tr,Tr,Tr,Tr],o_],hsl:[zh,[Tr,Tr,Tr],Ej],hsla:[zh,[Tr,Tr,Tr,Tr],Ej],has:{type:Zi,overloads:[[[Mi],(w,[m])=>_1(m.evaluate(w),w.properties())],[[Mi,xx],(w,[m,x])=>_1(m.evaluate(w),x.evaluate(w))]]},get:{type:to,overloads:[[[Mi],(w,[m])=>Aj(m.evaluate(w),w.properties())],[[Mi,xx],(w,[m,x])=>Aj(m.evaluate(w),x.evaluate(w))]]},"feature-state":[to,[Mi],(w,[m])=>Aj(m.evaluate(w),w.featureState||{})],properties:[xx,[],w=>w.properties()],"geometry-type":[Mi,[],w=>w.geometryType()],worldview:[Mi,[],w=>w.globals.worldview||""],"is-active-floor":[Zi,y0(Mi),(w,m)=>{if(!(w.globals&&w.globals.activeFloors&&w.globals.activeFloors.size>0))return!1;if(m.length===0)return!0;const x=w.globals.activeFloors;return m.some(k=>{const E=k.evaluate(w);return x.has(E)})}],id:[to,[],w=>w.id()],zoom:[Tr,[],w=>w.globals.zoom],pitch:[Tr,[],w=>w.globals.pitch||0],"distance-from-center":[Tr,[],w=>w.distanceFromCenter()],"measure-light":[Tr,[Mi],(w,[m])=>w.measureLight(m.evaluate(w))],"heatmap-density":[Tr,[],w=>w.globals.heatmapDensity||0],"line-progress":[Tr,[],w=>w.globals.lineProgress||0],"raster-value":[Tr,[],w=>w.globals.rasterValue||0],"raster-particle-speed":[Tr,[],w=>w.globals.rasterParticleSpeed||0],"sky-radial-progress":[Tr,[],w=>w.globals.skyRadialProgress||0],accumulated:[to,[],w=>w.globals.accumulated===void 0?null:w.globals.accumulated],"+":[Tr,y0(Tr),(w,m)=>{let x=0;for(const k of m)x+=k.evaluate(w);return x}],"*":[Tr,y0(Tr),(w,m)=>{let x=1;for(const k of m)x*=k.evaluate(w);return x}],"-":{type:Tr,overloads:[[[Tr,Tr],(w,[m,x])=>m.evaluate(w)-x.evaluate(w)],[[Tr],(w,[m])=>-m.evaluate(w)]]},"/":[Tr,[Tr,Tr],(w,[m,x])=>m.evaluate(w)/x.evaluate(w)],"%":[Tr,[Tr,Tr],(w,[m,x])=>m.evaluate(w)%x.evaluate(w)],ln2:[Tr,[],()=>Math.LN2],pi:[Tr,[],()=>Math.PI],e:[Tr,[],()=>Math.E],"^":[Tr,[Tr,Tr],(w,[m,x])=>Math.pow(m.evaluate(w),x.evaluate(w))],sqrt:[Tr,[Tr],(w,[m])=>Math.sqrt(m.evaluate(w))],log10:[Tr,[Tr],(w,[m])=>Math.log(m.evaluate(w))/Math.LN10],ln:[Tr,[Tr],(w,[m])=>Math.log(m.evaluate(w))],log2:[Tr,[Tr],(w,[m])=>Math.log2(m.evaluate(w))],sin:[Tr,[Tr],(w,[m])=>Math.sin(m.evaluate(w))],cos:[Tr,[Tr],(w,[m])=>Math.cos(m.evaluate(w))],tan:[Tr,[Tr],(w,[m])=>Math.tan(m.evaluate(w))],asin:[Tr,[Tr],(w,[m])=>Math.asin(m.evaluate(w))],acos:[Tr,[Tr],(w,[m])=>Math.acos(m.evaluate(w))],atan:[Tr,[Tr],(w,[m])=>Math.atan(m.evaluate(w))],min:[Tr,y0(Tr),(w,m)=>Math.min(...m.map(x=>x.evaluate(w)))],max:[Tr,y0(Tr),(w,m)=>Math.max(...m.map(x=>x.evaluate(w)))],abs:[Tr,[Tr],(w,[m])=>Math.abs(m.evaluate(w))],round:[Tr,[Tr],(w,[m])=>{const x=m.evaluate(w);return x<0?-Math.round(-x):Math.round(x)}],floor:[Tr,[Tr],(w,[m])=>Math.floor(m.evaluate(w))],ceil:[Tr,[Tr],(w,[m])=>Math.ceil(m.evaluate(w))],"filter-==":[Zi,[Mi,to],(w,[m,x])=>w.properties()[m.value]===x.value],"filter-id-==":[Zi,[to],(w,[m])=>w.id()===m.value],"filter-type-==":[Zi,[Mi],(w,[m])=>w.geometryType()===m.value],"filter-<":[Zi,[Mi,to],(w,[m,x])=>{const k=w.properties()[m.value],E=x.value;return typeof k==typeof E&&k{const x=w.id(),k=m.value;return typeof x==typeof k&&x":[Zi,[Mi,to],(w,[m,x])=>{const k=w.properties()[m.value],E=x.value;return typeof k==typeof E&&k>E}],"filter-id->":[Zi,[to],(w,[m])=>{const x=w.id(),k=m.value;return typeof x==typeof k&&x>k}],"filter-<=":[Zi,[Mi,to],(w,[m,x])=>{const k=w.properties()[m.value],E=x.value;return typeof k==typeof E&&k<=E}],"filter-id-<=":[Zi,[to],(w,[m])=>{const x=w.id(),k=m.value;return typeof x==typeof k&&x<=k}],"filter->=":[Zi,[Mi,to],(w,[m,x])=>{const k=w.properties()[m.value],E=x.value;return typeof k==typeof E&&k>=E}],"filter-id->=":[Zi,[to],(w,[m])=>{const x=w.id(),k=m.value;return typeof x==typeof k&&x>=k}],"filter-has":[Zi,[to],(w,[m])=>m.value in w.properties()],"filter-has-id":[Zi,[],w=>w.id()!==null&&w.id()!==void 0],"filter-type-in":[Zi,[Yu(Mi)],(w,[m])=>m.value.indexOf(w.geometryType())>=0],"filter-id-in":[Zi,[Yu(to)],(w,[m])=>m.value.indexOf(w.id())>=0],"filter-in-small":[Zi,[Mi,Yu(to)],(w,[m,x])=>x.value.indexOf(w.properties()[m.value])>=0],"filter-in-large":[Zi,[Mi,Yu(to)],(w,[m,x])=>function(k,E,P,O){for(;P<=O;){const U=P+O>>1;if(E[U]===k)return!0;E[U]>k?O=U-1:P=U+1}return!1}(w.properties()[m.value],x.value,0,x.value.length-1)],all:{type:Zi,overloads:[[[Zi,Zi],(w,[m,x])=>m.evaluate(w)&&x.evaluate(w)],[y0(Zi),(w,m)=>{for(const x of m)if(!x.evaluate(w))return!1;return!0}]]},any:{type:Zi,overloads:[[[Zi,Zi],(w,[m,x])=>m.evaluate(w)||x.evaluate(w)],[y0(Zi),(w,m)=>{for(const x of m)if(x.evaluate(w))return!0;return!1}]]},"!":[Zi,[Zi],(w,[m])=>!m.evaluate(w)],"is-supported-script":[Zi,[Mi],(w,[m])=>{const x=w.globals&&w.globals.isSupportedScript;return!x||x(m.evaluate(w))}],upcase:[Mi,[Mi],(w,[m])=>m.evaluate(w).toUpperCase()],downcase:[Mi,[Mi],(w,[m])=>m.evaluate(w).toLowerCase()],concat:[Mi,y0(to),(w,m)=>m.map(x=>sa(x.evaluate(w))).join("")],"resolved-locale":[Mi,[gx],(w,[m])=>m.evaluate(w).resolvedLocale()],random:[Tr,[Tr,Tr,to],(w,m)=>{const[x,k,E]=m.map(O=>O.evaluate(w));if(x>k||x===k)return x;let P;if(typeof E=="string")P=function(O){let U=0;if(O.length===0)return U;for(let H=0;HJSON.stringify(ue)).join(", ")}, but found ${JSON.stringify(oe)} instead.`);return oe}catch(oe){const ue=oe;return this._warningHistory[ue.message]||(this._warningHistory[ue.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${ue.message}`)),this._defaultValue}}}function Hy(w){return Array.isArray(w)&&w.length>0&&typeof w[0]=="string"&&w[0]in i_}function wx(w,m,x,k,E){const P=new wj(i_,[],m?function(U){const H={color:zh,string:Mi,number:Tr,enum:Mi,boolean:Zi,formatted:Dy,resolvedImage:Gb};return U.type==="array"?Yu(H[U.value]||to,U.length):H[U.type]}(m):void 0,void 0,void 0,x,k,E),O=P.parse(w,void 0,void 0,void 0,m&&m.type==="string"?{typeAnnotation:"coerce"}:void 0);return O?WN(new w1(O,m,x,k,E)):$c(P.errors)}class v0{constructor(m,x,k,E){this.kind=m,this._styleExpression=x,this.isLightConstant=k,this.isLineProgressConstant=E,this.isStateDependent=m!=="constant"&&!Uy(x.expression),this.configDependencies=Mj(x.expression),this.isIndoorDependent=l_(x.expression)}evaluateWithoutErrorHandling(m,x,k,E,P,O){return this._styleExpression.evaluateWithoutErrorHandling(m,x,k,E,P,O)}evaluate(m,x,k,E,P,O,U){return this._styleExpression.evaluate(m,x,k,E,P,O,void 0,void 0,U)}}class jx{constructor(m,x,k,E,P,O){this.kind=m,this.zoomStops=k,this._styleExpression=x,this.isStateDependent=m!=="camera"&&!Uy(x.expression),this.isIndoorDependent=l_(x.expression),this.isLightConstant=P,this.isLineProgressConstant=O,this.configDependencies=Mj(x.expression),this.interpolationType=E}evaluateWithoutErrorHandling(m,x,k,E,P,O){return this._styleExpression.evaluateWithoutErrorHandling(m,x,k,E,P,O)}evaluate(m,x,k,E,P,O){return this._styleExpression.evaluate(m,x,k,E,P,O)}interpolationFactor(m,x,k){return this.interpolationType?gu.interpolationFactor(this.interpolationType,m,x,k):0}}function Pj(w,m,x,k,E){if((w=wx(w,m,x,k,E)).result==="error")return w;const P=w.value.expression,O=$y(P);if(!O&&!Up(m))return $c([new Ku("","data expressions not supported")]);const U=bm(P,["zoom","pitch","distance-from-center"]);if(!U&&!YN(m))return $c([new Ku("","zoom expressions not supported")]);const H=bm(P,["measure-light"]);if(!H&&!KN(m))return $c([new Ku("","measure-light expression not supported")]);const X=bm(P,["line-progress"]);if(!X&&!function(me){return wm(me.expression,"line-progress")}(m))return $c([new Ku("","line-progress expression not supported")]);const oe=m.expression&&m.expression.relaxZoomRestriction,ue=qp(P);return ue||U||oe?ue instanceof Ku?$c([ue]):ue instanceof gu&&!lp(m)?$c([new Ku("",'"interpolate" expressions cannot be used with this property')]):WN(ue?new jx(O&&X?"camera":"composite",w.value,ue.labels,ue instanceof gu?ue.interpolation:void 0,H,X):new v0(O&&X?"constant":"source",w.value,H,X)):$c([new Ku("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class c_{constructor(m,x){this._parameters=m,this._specification=x,Object.assign(this,_6(this._parameters,this._specification))}static deserialize(m){return new c_(m._parameters,m._specification)}static serialize(m){return{_parameters:m._parameters,_specification:m._specification}}}function qp(w){let m=null;if(w instanceof v1)m=qp(w.result);else if(w instanceof s_){for(const x of w.args)if(m=qp(x),m)break}else(w instanceof Nj||w instanceof gu)&&w.input instanceof Bc&&w.input.name==="zoom"&&(m=w);return m instanceof Ku||w.eachChild(x=>{const k=qp(x);k instanceof Ku?m=k:m&&k&&m!==k&&(m=new Ku("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),m}var QN,XN,Lj=function(){if(XN)return QN;XN=1,QN=m;var w=3;function m(x,k,E){var P=this.cells=[];if(x instanceof ArrayBuffer){this.arrayBuffer=x;var O=new Int32Array(this.arrayBuffer);x=O[0],this.d=(k=O[1])+2*(E=O[2]);for(var U=0;U=me[Pe+0]&&P>=me[Pe+1])?(H[Se]=!0,U.push(ue[Se])):H[Se]=!1}}},m.prototype._forEachCell=function(x,k,E,P,O,U,H,X){for(var oe=this._convertToCellCoord(x),ue=this._convertToCellCoord(k),me=this._convertToCellCoord(E),_e=this._convertToCellCoord(P),Se=oe;Se<=me;Se++)for(var Pe=ue;Pe<=_e;Pe++){var $e=this.d*Pe+Se;if((!X||X(this._convertFromCellCoord(Se),this._convertFromCellCoord(Pe),this._convertFromCellCoord(Se+1),this._convertFromCellCoord(Pe+1)))&&O.call(this,x,k,E,P,$e,U,H,X))return}},m.prototype._convertFromCellCoord=function(x){return(x-this.padding)/this.scale},m.prototype._convertToCellCoord=function(x){return Math.max(0,Math.min(this.d-1,Math.floor(x*this.scale)+this.padding))},m.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var x=this.cells,k=w+this.cells.length+1+1,E=0,P=0;P=0||(E[P]=mc(w[P],m)));w instanceof Error&&(E.message=w.message)}if(E.$name)throw new Error("$name property is reserved for worker serialization logic.");return k!=="Object"&&(E.$name=k),E}throw new Error("can't serialize object of type "+typeof w)}function tc(w){if(w==null||typeof w=="boolean"||typeof w=="number"||typeof w=="string"||w instanceof Boolean||w instanceof Number||w instanceof String||w instanceof Date||w instanceof RegExp||xo(w)||w instanceof ImageBitmap||ArrayBuffer.isView(w)||w instanceof ImageData)return w;if(Array.isArray(w))return w.map(tc);if(typeof w=="object"){const m=w.$name||"Object";if(m==="Map"){const E=w.entries||[],P=new Map;for(let O=0;Ow>=1536&&w<=1791,Uh=w=>w>=1872&&w<=1919,w0=w=>w>=2208&&w<=2303,dd=w=>w>=11904&&w<=12031,Vp=w=>w>=12032&&w<=12255,j0=w=>w>=12272&&w<=12287,Gy=w=>w>=12288&&w<=12351,j1=w=>w>=12352&&w<=12447,Nx=w=>w>=12448&&w<=12543,qh=w=>w>=12544&&w<=12591,d_=w=>w>=12704&&w<=12735,zf=w=>w>=12736&&w<=12783,pg=w=>w>=12784&&w<=12799,N1=w=>w>=12800&&w<=13055,Dj=w=>w>=13056&&w<=13311,Rj=w=>w>=13312&&w<=19903,kx=w=>w>=19968&&w<=40959,Wy=w=>w>=40960&&w<=42127,fg=w=>w>=42128&&w<=42191,u_=w=>w>=44032&&w<=55215,Ky=w=>w>=63744&&w<=64255,Oj=w=>w>=64336&&w<=65023,Fj=w=>w>=65040&&w<=65055,h_=w=>w>=65072&&w<=65103,bh=w=>w>=65104&&w<=65135,xg=w=>w>=65136&&w<=65279,cp=w=>w>=65280&&w<=65519;function Vh(w){for(const m of w)if(IC(m.charCodeAt(0)))return!0;return!1}function N6(w){for(const m of w)if(!AC(m.charCodeAt(0)))return!1;return!0}function AC(w){return!(Zu(w)||Uh(w)||w0(w)||Oj(w)||xg(w))}function MC(w){return!(w<11904||!(d_(w)||qh(w)||h_(w)||Ky(w)||Dj(w)||dd(w)||zf(w)||Gy(w)||Rj(w)||kx(w)||N1(w)||cp(w)||j1(w)||j0(w)||Vp(w)||pg(w)||Nx(w)||Fj(w)||fg(w)||Wy(w)))}function IC(w){return!(w!==746&&w!==747&&(w<4352||!(d_(w)||qh(w)||h_(w)&&!(w>=65097&&w<=65103)||Ky(w)||Dj(w)||dd(w)||zf(w)||!(!Gy(w)||w>=12296&&w<=12305||w>=12308&&w<=12319||w===12336)||Rj(w)||kx(w)||N1(w)||(m=>m>=12592&&m<=12687)(w)||(m=>m>=43360&&m<=43391)(w)||(m=>m>=55216&&m<=55295)(w)||(m=>m>=4352&&m<=4607)(w)||u_(w)||j1(w)||j0(w)||(m=>m>=12688&&m<=12703)(w)||Vp(w)||pg(w)||Nx(w)&&w!==12540||!(!cp(w)||w===65288||w===65289||w===65293||w>=65306&&w<=65310||w===65339||w===65341||w===65343||w>=65371&&w<=65503||w===65507||w>=65512&&w<=65519)||!(!bh(w)||w>=65112&&w<=65118||w>=65123&&w<=65126)||(m=>m>=5120&&m<=5759)(w)||(m=>m>=6320&&m<=6399)(w)||Fj(w)||(m=>m>=19904&&m<=19967)(w)||Wy(w)||fg(w))))}function N0(w){return w===12312||w===12313||w===12316||w===12540||w===12448}function Yy(w){return!(IC(w)||function(m){return!!((x=>x>=128&&x<=255)(m)&&(m===167||m===169||m===174||m===177||m===188||m===189||m===190||m===215||m===247)||(x=>x>=8192&&x<=8303)(m)&&(m===8214||m===8224||m===8225||m===8240||m===8241||m===8251||m===8252||m===8258||m===8263||m===8264||m===8265||m===8273)||(x=>x>=8448&&x<=8527)(m)||(x=>x>=8528&&x<=8591)(m)||(x=>x>=8960&&x<=9215)(m)&&(m>=8960&&m<=8967||m>=8972&&m<=8991||m>=8996&&m<=9e3||m===9003||m>=9085&&m<=9114||m>=9150&&m<=9165||m===9167||m>=9169&&m<=9179||m>=9186&&m<=9215)||(x=>x>=9216&&x<=9279)(m)&&m!==9251||(x=>x>=9280&&x<=9311)(m)||(x=>x>=9312&&x<=9471)(m)||(x=>x>=9632&&x<=9727)(m)||(x=>x>=9728&&x<=9983)(m)&&!(m>=9754&&m<=9759)||(x=>x>=11008&&x<=11263)(m)&&(m>=11026&&m<=11055||m>=11088&&m<=11097||m>=11192&&m<=11243)||Gy(m)||Nx(m)||(x=>x>=57344&&x<=63743)(m)||h_(m)||bh(m)||cp(m)||m===8734||m===8756||m===8757||m>=9984&&m<=10087||m>=10102&&m<=10131||m===65532||m===65533)}(w))}function PC(w){return Zu(w)||Uh(w)||w0(w)||Oj(w)||xg(w)}function zj(w){return w>=1424&&w<=2303||Oj(w)||xg(w)}function gg(w,m){return!(!m&&zj(w)||w>=2304&&w<=3583||w>=3840&&w<=4255||(x=>x>=6016&&x<=6143)(w))}function k6(w){for(const m of w)if(zj(m.charCodeAt(0)))return!0;return!1}const jm={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let Bf=null,Wd=jm.unavailable,Hp=null;const S6=function(w){w&&typeof w=="string"&&w.indexOf("NetworkError")>-1&&(Wd=jm.error),Bf&&Bf(w)};function JN(){ek.fire(new zc("pluginStateChange",{pluginStatus:Wd,pluginURL:Hp}))}const ek=new Rp,k0=function(){return Wd},C6=function(){if(Wd!==jm.deferred||!Hp)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Wd=jm.loading,JN(),Hp&&Py({url:Hp},w=>{w?S6(w):(Wd=jm.loaded,JN())})},Nm={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Wd===jm.loaded||Nm.applyArabicShaping!=null,isLoading:()=>Wd===jm.loading,setState(w){Wd=w.pluginStatus,Hp=w.pluginURL},isParsing:()=>Wd===jm.parsing,isParsed:()=>Wd===jm.parsed,getPluginURL:()=>Hp},LC=function(){Nm.isLoading()||Nm.isLoaded()||k0()!=="deferred"||C6()};class La{constructor(m,x){this.zoom=m,x?(this.now=x.now,this.fadeDuration=x.fadeDuration,this.transition=x.transition,this.pitch=x.pitch,this.brightness=x.brightness,this.worldview=x.worldview,this.activeFloors=x.activeFloors):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0)}isSupportedScript(m){return function(x,k){for(const E of x)if(!gg(E.charCodeAt(0),k))return!1;return!0}(m,Nm.isLoaded())}}class m_{constructor(m,x,k,E,P){this.property=m,this.value=x,this.expression=function(O,U,H,X,oe){if(ZN(O))return new c_(O,U);if(Hy(O)||Array.isArray(O)&&O.length>0){const ue=Pj(O,U,H,X,oe);if(ue.result==="error")throw new Error(ue.value.map(me=>`${me.key}: ${me.message}`).join(", "));return ue.value}{let ue=O;return typeof O=="string"&&U.type==="color"&&(ue=Gn.parse(O)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>ue}}}(x===void 0?m.specification.default:x,m.specification,k,E,P)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(m,x,k,E){return this.property.possiblyEvaluate(this,m,x,k,E)}}class Bj{constructor(m,x,k,E){this.property=m,this.value=new m_(m,void 0,x,k,E)}transitioned(m,x){return new p_(this.property,this.value,x,Object.assign({},m.transition,this.transition),m.now)}untransitioned(){return new p_(this.property,this.value,null,{},0)}}class tk{constructor(m,x,k,E){this._properties=m,this._values=Object.create(m.defaultTransitionablePropertyValues),this._scope=x,this._options=k,this._iconImageUseTheme=E,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(m){return Un(this._values[m].value.value)}setValue(m,x){this._values.hasOwnProperty(m)||(this._values[m]=new Bj(this._values[m].property,this._scope,this._options,this._iconImageUseTheme)),this._values[m].value=new m_(this._values[m].property,x===null?void 0:Un(x),this._scope,this._options,this._iconImageUseTheme),this._values[m].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[m].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[m].value.isIndoorDependent())}setTransitionOrValue(m,x){x&&(this._options=x);const k=this._properties.properties;if(m)for(const E in m){const P=m[E];if(E.endsWith("-transition")){const O=E.slice(0,-11);k[O]&&this.setTransition(O,P)}else k.hasOwnProperty(E)&&this.setValue(E,P)}}getTransition(m){return Un(this._values[m].transition)}setTransition(m,x){this._values.hasOwnProperty(m)||(this._values[m]=new Bj(this._values[m].property)),this._values[m].transition=Un(x)||void 0}serialize(){const m={};for(const x of Object.keys(this._values)){const k=this.getValue(x);k!==void 0&&(m[x]=k);const E=this.getTransition(x);E!==void 0&&(m[`${x}-transition`]=E)}return m}transitioned(m,x){const k=new sk(this._properties);for(const E of Object.keys(this._values))k._values[E]=this._values[E].transitioned(m,x._values[E]);return k}untransitioned(){const m=new sk(this._properties);for(const x of Object.keys(this._values))m._values[x]=this._values[x].untransitioned();return m}isIndoorDependent(){return this._isIndoorDependent}}class p_{constructor(m,x,k,E,P){const O=E.delay||0,U=E.duration||0;P=P||0,this.property=m,this.value=x,this.begin=P+O,this.end=this.begin+U,m.specification.transition&&(E.delay||E.duration)&&(this.prior=k)}possiblyEvaluate(m,x,k){const E=m.now||0,P=this.value.possiblyEvaluate(m,x,k),O=this.prior;if(O){if(E>this.end)return this.prior=null,P;if(this.value.isDataDriven())return this.prior=null,P;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 $j(w){return w instanceof Number||w instanceof String||w instanceof Boolean?w.valueOf():w}function f_(w){if(Array.isArray(w))return w.map(f_);if(w instanceof Object&&!(w instanceof Number||w instanceof String||w instanceof Boolean)){const m={};for(const x in w)m[x]=f_(w[x]);return m}return $j(w)}function Uj(w){if(w===!0||w===!1)return!0;if(!Array.isArray(w)||w.length===0)return!1;switch(w[0]){case"has":return w.length>=2&&w[1]!=="$id"&&w[1]!=="$type";case"in":return w.length>=3&&(typeof w[1]!="string"||Array.isArray(w[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return w.length!==3||Array.isArray(w[1])||Array.isArray(w[2]);case"any":case"all":for(const m of w.slice(1))if(!Uj(m)&&typeof m!="boolean")return!1;return!0;default:return!0}}function rk(w,m="",x=null,k="fill"){if(w==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};Uj(w)||(w=ik(w));const E=w;let P=!0;try{P=function(oe){if(!S1(oe))return oe;let ue=f_(oe);return RC(ue),ue=DC(ue),ue}(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 O=null,U=null;if(k!=="background"&&k!=="sky"&&k!=="slot"){U=fs[`filter_${k}`];const oe=wx(P,U,m,x);if(oe.result==="error")throw new Error(oe.value.map(ue=>`${ue.key}: ${ue.message}`).join(", "));O=(ue,me,_e)=>oe.value.evaluate(ue,me,{},_e)}let H=null,X=null;if(P!==E){const oe=wx(E,U,m,x);if(oe.result==="error")throw new Error(oe.value.map(ue=>`${ue.key}: ${ue.message}`).join(", "));H=(ue,me,_e,Se,Pe)=>oe.value.evaluate(ue,me,{},_e,void 0,void 0,Se,Pe),X=!$y(oe.value.expression)}return{filter:O,dynamicFilter:H||void 0,needGeometry:T6(P),needFeature:!!X}}function DC(w){if(!Array.isArray(w))return w;const m=function(x){if(OC.has(x[0])){for(let k=1;kDC(x))}function RC(w){let m=!1;const x=[];if(w[0]==="case"){for(let k=1;k",">=","<","<=","to-boolean"]);function ak(w,m){return wm?1:0}function T6(w){if(!Array.isArray(w))return!1;if(w[0]==="within"||w[0]==="distance")return!0;for(let m=1;m"||m==="<="||m===">="?Q(w[1],w[2],m):m==="any"?(x=w.slice(1),["any"].concat(x.map(ik))):m==="all"?["all"].concat(w.slice(1).map(ik)):m==="none"?["all"].concat(w.slice(1).map(ik).map(Ve)):m==="in"?ee(w[1],w.slice(2)):m==="!in"?Ve(ee(w[1],w.slice(2))):m==="has"?ke(w[1]):m!=="!has"||Ve(ke(w[1]));var x}function Q(w,m,x){switch(w){case"$type":return[`filter-type-${x}`,m];case"$id":return[`filter-id-${x}`,m];default:return[`filter-${x}`,w,m]}}function ee(w,m){if(m.length===0)return!1;switch(w){case"$type":return["filter-type-in",["literal",m]];case"$id":return["filter-id-in",["literal",m]];default:return m.length>200&&!m.some(x=>typeof x!=typeof m[0])?["filter-in-large",w,["literal",m.sort(ak)]]:["filter-in-small",w,["literal",m]]}}function ke(w){switch(w){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",w]}}function Ve(w){return["!",w]}const et="";function yt(w,m){return m?`${w}${et}${m}`:w}function ps(w){const m=w.indexOf(et);return m>=0?w.slice(m+1):""}let pn;const Wn=()=>pn||(pn=new Wo({"icon-size":new jn(fs.layout_symbol["icon-size"]),"icon-image":new jn(fs.layout_symbol["icon-image"]),"icon-rotate":new jn(fs.layout_symbol["icon-rotate"]),"icon-offset":new jn(fs.layout_symbol["icon-offset"]),"text-size":new jn(fs.layout_symbol["text-size"]),"text-rotate":new jn(fs.layout_symbol["text-rotate"]),"text-offset":new jn(fs.layout_symbol["text-offset"])}));let Ur;const Ua=()=>Ur||(Ur=new Wo({"icon-opacity":new jn(fs.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new jn(fs.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new jn(fs.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new jn(fs.paint_symbol["text-emissive-strength"]),"icon-color":new jn(fs.paint_symbol["icon-color"]),"icon-halo-color":new jn(fs.paint_symbol["icon-halo-color"]),"icon-halo-width":new jn(fs.paint_symbol["icon-halo-width"]),"icon-halo-blur":new jn(fs.paint_symbol["icon-halo-blur"]),"icon-translate":new jn(fs.paint_symbol["icon-translate"]),"text-opacity":new jn(fs.paint_symbol["text-opacity"]),"text-occlusion-opacity":new jn(fs.paint_symbol["text-occlusion-opacity"]),"text-color":new jn(fs.paint_symbol["text-color"],{runtimeType:zh,getOverride:w=>w.textColor,hasOverride:w=>!!w.textColor}),"text-halo-color":new jn(fs.paint_symbol["text-halo-color"]),"text-halo-width":new jn(fs.paint_symbol["text-halo-width"]),"text-halo-blur":new jn(fs.paint_symbol["text-halo-blur"]),"text-translate":new jn(fs.paint_symbol["text-translate"]),"symbol-z-offset":new jn(fs.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"})}));class oo{constructor(m,x,k,E,P,O){this._conditionSpec=m,this._propertiesSpec=k;const U=wx(m,fs.appearance.condition);if(U.result==="success"&&(this.condition=U.value),this.name=x,k){this.layoutProperties=new Kd(Wn()),this.unevaluatedLayout=new nk(Wn(),E,P,O),this.paintProperties=new Kd(Ua()),this.unevaluatedPaint=new nk(Ua(),E,P,"");for(const H in k)H in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(H,k[H]):H in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(H,k[H])}}isActive(m){return!(this.condition||!m.isHidden||this.name!=="hidden")||this.condition.evaluate(m.globals,m.feature,m.featureState,m.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(m){return this.layoutProperties.get(m)}getPaintProperty(m){return this.paintProperties.get(m)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(m){return this.unevaluatedLayout._values[m]}getUnevaluatedPaintProperty(m){return this.unevaluatedPaint._values[m]}recalculate(m,x,k){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(m,void 0,x,k)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(m,void 0,x,""))}serialize(){const m={};m.condition=this.condition.expression.serialize(),this.name&&(m.name=this.name);const x=this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},k=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},E=Object.assign({},x,k);return Object.keys(E).length>0&&(m.properties=E),m}hasIconLayoutProperties(){const m=this.hasLayoutProperty("icon-image"),x=this.hasLayoutProperty("icon-size"),k=this.hasLayoutProperty("icon-offset"),E=this.hasLayoutProperty("icon-rotate");return m||x||k||E}hasTextLayoutProperties(){const m=this.hasLayoutProperty("text-size"),x=this.hasLayoutProperty("text-offset"),k=this.hasLayoutProperty("text-rotate");return m||x||k}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(m=>!m.endsWith("-use-theme")).some(m=>(m.startsWith("icon-")||m==="symbol-z-offset")&&this.hasPaintProperty(m))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(m=>!m.endsWith("-use-theme")).some(m=>(m.startsWith("text-")||m==="symbol-z-offset")&&this.hasPaintProperty(m))}hasLayoutProperty(m){return this.unevaluatedLayout&&this.unevaluatedLayout._values[m].value!==void 0}hasPaintProperty(m){return this.unevaluatedPaint&&this.unevaluatedPaint._values[m].value!==void 0}}const Sa="-transition",Nc=new Set(["fill","line","background","hillshade","raster"]);class lo extends Rp{constructor(m,x,k,E,P,O){if(super(),this.id=m.id,this.fqid=yt(this.id,k),this.type=m.type,this.scope=k,this.lut=E,this.options=P,this.iconImageUseTheme=O,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},m.type!=="custom"){if(this.metadata=m.metadata,this.minzoom=m.minzoom,this.maxzoom=m.maxzoom,m.type&&m.type!=="background"&&m.type!=="sky"&&m.type!=="slot"){this.source=m.source,this.sourceLayer=m["source-layer"],this.filter=m.filter;const U=wx(this.filter,fs[`filter_${m.type}`]);U.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...U.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||U.value.isIndoorDependent)}if(m.slot&&(this.slot=m.slot),m.appearances&&this.setAppearances(m.appearances),x.layout&&(this._unevaluatedLayout=new nk(x.layout,this.scope,P,this.iconImageUseTheme),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._unevaluatedLayout.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._unevaluatedLayout.isIndoorDependent()),x.paint){this._transitionablePaint=new tk(x.paint,this.scope,P);for(const U in m.paint)this.setPaintProperty(U,m.paint[U]);for(const U in m.layout)this.setLayoutProperty(U,m.layout[U]);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 Kd(x.paint)}}}onAdd(m){}onRemove(m){}isDraped(m){return!this.is3D(!0)&&Nc.has(this.type)}getLayoutProperty(m){return m==="visibility"?this.visibility:this._unevaluatedLayout.getValue(m)}setLayoutProperty(m,x){if(this.type==="custom"&&m==="visibility")return void(this.visibility=x);const k=this._unevaluatedLayout;k._properties.properties[m]&&(k.setValue(m,x),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...k.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||k.isIndoorDependent(),m==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(m){this.appearances=[],m.forEach(x=>{this.appearances.push(new oo(x.condition,x.name,x.properties,this.scope,this.options,this.iconImageUseTheme))}),this.appearancesVersion++}possiblyEvaluateVisibility(){this._unevaluatedLayout._values.visibility&&(this.visibility=this._unevaluatedLayout._values.visibility.possiblyEvaluate({zoom:0}))}getPaintProperty(m){return m.endsWith(Sa)?this._transitionablePaint.getTransition(m.slice(0,-11)):this._transitionablePaint.getValue(m)}isPaintProperty(m){return!!this._transitionablePaint._properties.properties[m]}setPaintProperty(m,x){const k=this._transitionablePaint,E=k._properties.properties;if(m.endsWith(Sa)){const ue=m.slice(0,-11);return E[ue]&&k.setTransition(ue,x||void 0),!1}if(!E[m])return!1;const P=k._values[m],O=P.value.isDataDriven(),U=P.value;k.setValue(m,x),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...k.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||k.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(m);const H=k._values[m].value,X=H.isDataDriven(),oe=m.endsWith("pattern")||m==="line-dasharray";return X||O||oe||this._handleOverridablePaintPropertyUpdate(m,U,H)}_handleSpecialPaintPropertyUpdate(m){}getProgramIds(){return null}getDefaultProgramParams(m,x,k){return null}_handleOverridablePaintPropertyUpdate(m,x,k){return!1}isHidden(m){return!!(this.minzoom&&m=this.maxzoom)||this.visibility==="none"}updateTransitions(m){this._transitioningPaint=this._transitionablePaint.transitioned(m,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(m,x){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(m,void 0,x,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(m,void 0,x)}serialize(){const m={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&&(m.appearances=this.appearances.map(x=>x.serialize())),Gs(m,(x,k)=>!(x===void 0||k==="layout"&&!Object.keys(x).length||k==="paint"&&!Object.keys(x).length))}is3D(m){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 m in this.paint._values){const x=this.paint.get(m);if(x instanceof k1&&Up(x.property.specification)&&(x.value.kind==="source"||x.value.kind==="composite")&&x.value.isStateDependent)return!0}for(const m of this.appearances)if(!Uy(m.condition.expression))return!0;return!1}compileFilter(m){this._filterCompiled||(this._featureFilter=rk(this.filter,this.scope,m),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(m){this._stats&&(m.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(m,x,k){return{}}queryRadius(m){}queryIntersectsFeature(m,x,k,E,P,O,U,H,X,oe){}}const _h={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Wp{constructor(m,x){this._structArray=m,this._pos1=x*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const qn=new ArrayBuffer(0);class Ks{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(m,x){return m._trim(),x&&m.arrayBuffer&&x.add(m.arrayBuffer),{length:m.length,arrayBuffer:m.arrayBuffer}}static deserialize(m){const x=Object.create(this.prototype);return x.arrayBuffer=m.arrayBuffer,x.length=m.length,m.arrayBuffer?x.capacity=m.arrayBuffer.byteLength/x.bytesPerElement:(x.capacity=0,x.arrayBuffer=qn),x._refreshViews(),x}_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(m){this.reserve(m),this.length=m}reserve(m){if(m>this.capacity){this._reallocCount++,this.capacity=Math.max(m,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const x=this.uint8;this._refreshViews(),x&&this.uint8.set(x)}}reserveForAdditional(m){this.reserve(this.length+m)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...m){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...m){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 cn(w,m=1){let x=0,k=0;return{members:w.map(E=>{const P=_h[E.type].BYTES_PER_ELEMENT,O=x=Da(x,Math.max(m,P)),U=E.components||1;return k=Math.max(k,P),x+=P*U,{name:E.name,type:E.type,components:U,offset:O}}),size:Da(x,Math.max(k,m)),alignment:m}}function Da(w,m){return Math.ceil(w/m)*m}class Ha extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x){const k=this.length;return this.resize(k+1),this.emplace(k,m,x)}emplace(m,x,k){const E=2*m;return this.int16[E+0]=x,this.int16[E+1]=k,m}}Ha.prototype.bytesPerElement=4,Kn(Ha,"StructArrayLayout2i4");class $i extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k){const E=this.length;return this.resize(E+1),this.emplace(E,m,x,k)}emplace(m,x,k,E){const P=3*m;return this.int16[P+0]=x,this.int16[P+1]=k,this.int16[P+2]=E,m}}$i.prototype.bytesPerElement=6,Kn($i,"StructArrayLayout3i6");class ri extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k,E){const P=this.length;return this.resize(P+1),this.emplace(P,m,x,k,E)}emplace(m,x,k,E,P){const O=4*m;return this.int16[O+0]=x,this.int16[O+1]=k,this.uint16[O+2]=E,this.uint16[O+3]=P,m}}ri.prototype.bytesPerElement=8,Kn(ri,"StructArrayLayout2i2ui8");class ro extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m){const x=this.length;return this.resize(x+1),this.emplace(x,m)}emplace(m,x){return this.float32[1*m+0]=x,m}}ro.prototype.bytesPerElement=4,Kn(ro,"StructArrayLayout1f4");class Yd extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k){const E=this.length;return this.resize(E+1),this.emplace(E,m,x,k)}emplace(m,x,k,E){const P=4*m,O=2*m;return this.int16[P+0]=x,this.int16[P+1]=k,this.float32[O+1]=E,m}}Yd.prototype.bytesPerElement=8,Kn(Yd,"StructArrayLayout2i1f8");class il extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k){const E=this.length;return this.resize(E+1),this.emplace(E,m,x,k)}emplace(m,x,k,E){const P=4*m;return this.int16[P+0]=x,this.int16[P+1]=k,this.int16[P+2]=E,m}}il.prototype.bytesPerElement=8,Kn(il,"StructArrayLayout3i8");class yg extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k,E){const P=this.length;return this.resize(P+1),this.emplace(P,m,x,k,E)}emplace(m,x,k,E,P){const O=4*m;return this.int16[O+0]=x,this.int16[O+1]=k,this.int16[O+2]=E,this.int16[O+3]=P,m}}yg.prototype.bytesPerElement=8,Kn(yg,"StructArrayLayout4i8");class FC extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P){const O=this.length;return this.resize(O+1),this.emplace(O,m,x,k,E,P)}emplace(m,x,k,E,P,O){const U=5*m;return this.int16[U+0]=x,this.int16[U+1]=k,this.int16[U+2]=E,this.int16[U+3]=P,this.int16[U+4]=O,m}}FC.prototype.bytesPerElement=10,Kn(FC,"StructArrayLayout5i10");class zC extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U){const H=this.length;return this.resize(H+1),this.emplace(H,m,x,k,E,P,O,U)}emplace(m,x,k,E,P,O,U,H){const X=6*m,oe=12*m,ue=3*m;return this.int16[X+0]=x,this.int16[X+1]=k,this.uint8[oe+4]=E,this.uint8[oe+5]=P,this.uint8[oe+6]=O,this.uint8[oe+7]=U,this.float32[ue+2]=H,m}}zC.prototype.bytesPerElement=12,Kn(zC,"StructArrayLayout2i4ub1f12");class vg extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k){const E=this.length;return this.resize(E+1),this.emplace(E,m,x,k)}emplace(m,x,k,E){const P=3*m;return this.float32[P+0]=x,this.float32[P+1]=k,this.float32[P+2]=E,m}}vg.prototype.bytesPerElement=12,Kn(vg,"StructArrayLayout3f12");class Zy extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P){const O=this.length;return this.resize(O+1),this.emplace(O,m,x,k,E,P)}emplace(m,x,k,E,P,O){const U=6*m,H=3*m;return this.uint16[U+0]=x,this.uint16[U+1]=k,this.uint16[U+2]=E,this.uint16[U+3]=P,this.float32[H+2]=O,m}}Zy.prototype.bytesPerElement=12,Kn(Zy,"StructArrayLayout4ui1f12");class ok extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k,E){const P=this.length;return this.resize(P+1),this.emplace(P,m,x,k,E)}emplace(m,x,k,E,P){const O=4*m;return this.uint16[O+0]=x,this.uint16[O+1]=k,this.uint16[O+2]=E,this.uint16[O+3]=P,m}}ok.prototype.bytesPerElement=8,Kn(ok,"StructArrayLayout4ui8");class E6 extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O){const U=this.length;return this.resize(U+1),this.emplace(U,m,x,k,E,P,O)}emplace(m,x,k,E,P,O,U){const H=6*m;return this.int16[H+0]=x,this.int16[H+1]=k,this.int16[H+2]=E,this.int16[H+3]=P,this.int16[H+4]=O,this.int16[H+5]=U,m}}E6.prototype.bytesPerElement=12,Kn(E6,"StructArrayLayout6i12");class qR extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U,H,X,oe,ue,me){const _e=this.length;return this.resize(_e+1),this.emplace(_e,m,x,k,E,P,O,U,H,X,oe,ue,me)}emplace(m,x,k,E,P,O,U,H,X,oe,ue,me,_e){const Se=12*m;return this.int16[Se+0]=x,this.int16[Se+1]=k,this.int16[Se+2]=E,this.int16[Se+3]=P,this.uint16[Se+4]=O,this.uint16[Se+5]=U,this.uint16[Se+6]=H,this.uint16[Se+7]=X,this.int16[Se+8]=oe,this.int16[Se+9]=ue,this.int16[Se+10]=me,this.int16[Se+11]=_e,m}}qR.prototype.bytesPerElement=24,Kn(qR,"StructArrayLayout4i4ui4i24");class VR extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O){const U=this.length;return this.resize(U+1),this.emplace(U,m,x,k,E,P,O)}emplace(m,x,k,E,P,O,U){const H=10*m,X=5*m;return this.int16[H+0]=x,this.int16[H+1]=k,this.int16[H+2]=E,this.float32[X+2]=P,this.float32[X+3]=O,this.float32[X+4]=U,m}}VR.prototype.bytesPerElement=20,Kn(VR,"StructArrayLayout3i3f20");class C1 extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E){const P=this.length;return this.resize(P+1),this.emplace(P,m,x,k,E)}emplace(m,x,k,E,P){const O=4*m;return this.float32[O+0]=x,this.float32[O+1]=k,this.float32[O+2]=E,this.float32[O+3]=P,m}}C1.prototype.bytesPerElement=16,Kn(C1,"StructArrayLayout4f16");class BC extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(m){const x=this.length;return this.resize(x+1),this.emplace(x,m)}emplace(m,x){return this.uint32[1*m+0]=x,m}}BC.prototype.bytesPerElement=4,Kn(BC,"StructArrayLayout1ul4");class bg extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x){const k=this.length;return this.resize(k+1),this.emplace(k,m,x)}emplace(m,x,k){const E=2*m;return this.uint16[E+0]=x,this.uint16[E+1]=k,m}}bg.prototype.bytesPerElement=4,Kn(bg,"StructArrayLayout2ui4");class A6 extends Ks{_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(m,x,k,E,P,O,U,H,X,oe,ue,me,_e){const Se=this.length;return this.resize(Se+1),this.emplace(Se,m,x,k,E,P,O,U,H,X,oe,ue,me,_e)}emplace(m,x,k,E,P,O,U,H,X,oe,ue,me,_e,Se){const Pe=20*m,$e=10*m;return this.int16[Pe+0]=x,this.int16[Pe+1]=k,this.int16[Pe+2]=E,this.int16[Pe+3]=P,this.int16[Pe+4]=O,this.float32[$e+3]=U,this.float32[$e+4]=H,this.float32[$e+5]=X,this.float32[$e+6]=oe,this.int16[Pe+14]=ue,this.uint32[$e+8]=me,this.uint16[Pe+18]=_e,this.uint16[Pe+19]=Se,m}}A6.prototype.bytesPerElement=40,Kn(A6,"StructArrayLayout5i4f1i1ul2ui40");class $C extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U){const H=this.length;return this.resize(H+1),this.emplace(H,m,x,k,E,P,O,U)}emplace(m,x,k,E,P,O,U,H){const X=8*m;return this.int16[X+0]=x,this.int16[X+1]=k,this.int16[X+2]=E,this.int16[X+4]=P,this.int16[X+5]=O,this.int16[X+6]=U,this.int16[X+7]=H,m}}$C.prototype.bytesPerElement=16,Kn($C,"StructArrayLayout3i2i2i16");class HR extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P){const O=this.length;return this.resize(O+1),this.emplace(O,m,x,k,E,P)}emplace(m,x,k,E,P,O){const U=4*m,H=8*m;return this.float32[U+0]=x,this.float32[U+1]=k,this.float32[U+2]=E,this.int16[H+6]=P,this.int16[H+7]=O,m}}HR.prototype.bytesPerElement=16,Kn(HR,"StructArrayLayout2f1f2i16");class UC extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O){const U=this.length;return this.resize(U+1),this.emplace(U,m,x,k,E,P,O)}emplace(m,x,k,E,P,O,U){const H=20*m,X=5*m;return this.uint8[H+0]=x,this.uint8[H+1]=k,this.float32[X+1]=E,this.float32[X+2]=P,this.float32[X+3]=O,this.float32[X+4]=U,m}}UC.prototype.bytesPerElement=20,Kn(UC,"StructArrayLayout2ub4f20");class sc extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k){const E=this.length;return this.resize(E+1),this.emplace(E,m,x,k)}emplace(m,x,k,E){const P=3*m;return this.uint16[P+0]=x,this.uint16[P+1]=k,this.uint16[P+2]=E,m}}sc.prototype.bytesPerElement=6,Kn(sc,"StructArrayLayout3ui6");class M6 extends Ks{_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(m,x,k,E,P,O,U,H,X,oe,ue,me,_e,Se,Pe,$e,Ke,lt,nt,pt,_t){const jt=this.length;return this.resize(jt+1),this.emplace(jt,m,x,k,E,P,O,U,H,X,oe,ue,me,_e,Se,Pe,$e,Ke,lt,nt,pt,_t)}emplace(m,x,k,E,P,O,U,H,X,oe,ue,me,_e,Se,Pe,$e,Ke,lt,nt,pt,_t,jt){const Yt=30*m,zt=15*m,Wt=60*m;return this.int16[Yt+0]=x,this.int16[Yt+1]=k,this.int16[Yt+2]=E,this.float32[zt+2]=P,this.float32[zt+3]=O,this.uint16[Yt+8]=U,this.uint16[Yt+9]=H,this.uint32[zt+5]=X,this.uint32[zt+6]=oe,this.uint32[zt+7]=ue,this.uint16[Yt+16]=me,this.uint16[Yt+17]=_e,this.uint16[Yt+18]=Se,this.float32[zt+10]=Pe,this.float32[zt+11]=$e,this.uint8[Wt+48]=Ke,this.uint8[Wt+49]=lt,this.uint8[Wt+50]=nt,this.uint32[zt+13]=pt,this.int16[Yt+28]=_t,this.uint8[Wt+58]=jt,m}}M6.prototype.bytesPerElement=60,Kn(M6,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class GR extends Ks{_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(m,x,k,E,P,O,U,H,X,oe,ue,me,_e,Se,Pe,$e,Ke,lt,nt,pt,_t,jt,Yt,zt,Wt,$t,Ut,Bs,qs,Qs,sn,Xs,xn){const Os=this.length;return this.resize(Os+1),this.emplace(Os,m,x,k,E,P,O,U,H,X,oe,ue,me,_e,Se,Pe,$e,Ke,lt,nt,pt,_t,jt,Yt,zt,Wt,$t,Ut,Bs,qs,Qs,sn,Xs,xn)}emplace(m,x,k,E,P,O,U,H,X,oe,ue,me,_e,Se,Pe,$e,Ke,lt,nt,pt,_t,jt,Yt,zt,Wt,$t,Ut,Bs,qs,Qs,sn,Xs,xn,Os){const en=20*m,on=40*m,yn=80*m;return this.float32[en+0]=x,this.float32[en+1]=k,this.int16[on+4]=E,this.int16[on+5]=P,this.int16[on+6]=O,this.int16[on+7]=U,this.int16[on+8]=H,this.int16[on+9]=X,this.int16[on+10]=oe,this.int16[on+11]=ue,this.int16[on+12]=me,this.uint16[on+13]=_e,this.uint16[on+14]=Se,this.uint16[on+15]=Pe,this.uint16[on+16]=$e,this.uint16[on+17]=Ke,this.uint16[on+18]=lt,this.uint16[on+19]=nt,this.uint16[on+20]=pt,this.uint16[on+21]=_t,this.uint16[on+22]=jt,this.uint16[on+23]=Yt,this.uint16[on+24]=zt,this.uint16[on+25]=Wt,this.uint16[on+26]=$t,this.uint16[on+27]=Ut,this.uint32[en+14]=Bs,this.float32[en+15]=qs,this.float32[en+16]=Qs,this.float32[en+17]=sn,this.float32[en+18]=Xs,this.uint8[yn+76]=xn,this.uint16[on+39]=Os,m}}GR.prototype.bytesPerElement=80,Kn(GR,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class I6 extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O){const U=this.length;return this.resize(U+1),this.emplace(U,m,x,k,E,P,O)}emplace(m,x,k,E,P,O,U){const H=6*m;return this.float32[H+0]=x,this.float32[H+1]=k,this.float32[H+2]=E,this.float32[H+3]=P,this.float32[H+4]=O,this.float32[H+5]=U,m}}I6.prototype.bytesPerElement=24,Kn(I6,"StructArrayLayout6f24");class qj extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P){const O=this.length;return this.resize(O+1),this.emplace(O,m,x,k,E,P)}emplace(m,x,k,E,P,O){const U=5*m;return this.float32[U+0]=x,this.float32[U+1]=k,this.float32[U+2]=E,this.float32[U+3]=P,this.float32[U+4]=O,m}}qj.prototype.bytesPerElement=20,Kn(qj,"StructArrayLayout5f20");class qC extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U){const H=this.length;return this.resize(H+1),this.emplace(H,m,x,k,E,P,O,U)}emplace(m,x,k,E,P,O,U,H){const X=7*m;return this.float32[X+0]=x,this.float32[X+1]=k,this.float32[X+2]=E,this.float32[X+3]=P,this.float32[X+4]=O,this.float32[X+5]=U,this.float32[X+6]=H,m}}qC.prototype.bytesPerElement=28,Kn(qC,"StructArrayLayout7f28");class WR extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U,H,X,oe,ue){const me=this.length;return this.resize(me+1),this.emplace(me,m,x,k,E,P,O,U,H,X,oe,ue)}emplace(m,x,k,E,P,O,U,H,X,oe,ue,me){const _e=11*m;return this.float32[_e+0]=x,this.float32[_e+1]=k,this.float32[_e+2]=E,this.float32[_e+3]=P,this.float32[_e+4]=O,this.float32[_e+5]=U,this.float32[_e+6]=H,this.float32[_e+7]=X,this.float32[_e+8]=oe,this.float32[_e+9]=ue,this.float32[_e+10]=me,m}}WR.prototype.bytesPerElement=44,Kn(WR,"StructArrayLayout11f44");class KR extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U,H,X){const oe=this.length;return this.resize(oe+1),this.emplace(oe,m,x,k,E,P,O,U,H,X)}emplace(m,x,k,E,P,O,U,H,X,oe){const ue=9*m;return this.float32[ue+0]=x,this.float32[ue+1]=k,this.float32[ue+2]=E,this.float32[ue+3]=P,this.float32[ue+4]=O,this.float32[ue+5]=U,this.float32[ue+6]=H,this.float32[ue+7]=X,this.float32[ue+8]=oe,m}}KR.prototype.bytesPerElement=36,Kn(KR,"StructArrayLayout9f36");class Vj extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x){const k=this.length;return this.resize(k+1),this.emplace(k,m,x)}emplace(m,x,k){const E=2*m;return this.float32[E+0]=x,this.float32[E+1]=k,m}}Vj.prototype.bytesPerElement=8,Kn(Vj,"StructArrayLayout2f8");class YR extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k,E){const P=this.length;return this.resize(P+1),this.emplace(P,m,x,k,E)}emplace(m,x,k,E,P){const O=6*m;return this.uint32[3*m+0]=x,this.uint16[O+2]=k,this.uint16[O+3]=E,this.uint16[O+4]=P,m}}YR.prototype.bytesPerElement=12,Kn(YR,"StructArrayLayout1ul3ui12");class Hj extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m){const x=this.length;return this.resize(x+1),this.emplace(x,m)}emplace(m,x){return this.uint16[1*m+0]=x,m}}Hj.prototype.bytesPerElement=2,Kn(Hj,"StructArrayLayout1ui2");class ZR extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U,H,X,oe,ue,me,_e,Se,Pe,$e){const Ke=this.length;return this.resize(Ke+1),this.emplace(Ke,m,x,k,E,P,O,U,H,X,oe,ue,me,_e,Se,Pe,$e)}emplace(m,x,k,E,P,O,U,H,X,oe,ue,me,_e,Se,Pe,$e,Ke){const lt=16*m;return this.float32[lt+0]=x,this.float32[lt+1]=k,this.float32[lt+2]=E,this.float32[lt+3]=P,this.float32[lt+4]=O,this.float32[lt+5]=U,this.float32[lt+6]=H,this.float32[lt+7]=X,this.float32[lt+8]=oe,this.float32[lt+9]=ue,this.float32[lt+10]=me,this.float32[lt+11]=_e,this.float32[lt+12]=Se,this.float32[lt+13]=Pe,this.float32[lt+14]=$e,this.float32[lt+15]=Ke,m}}ZR.prototype.bytesPerElement=64,Kn(ZR,"StructArrayLayout16f64");class P6 extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,E,P,O,U){const H=this.length;return this.resize(H+1),this.emplace(H,m,x,k,E,P,O,U)}emplace(m,x,k,E,P,O,U,H){const X=10*m,oe=5*m;return this.uint16[X+0]=x,this.uint16[X+1]=k,this.uint16[X+2]=E,this.uint16[X+3]=P,this.float32[oe+2]=O,this.float32[oe+3]=U,this.float32[oe+4]=H,m}}P6.prototype.bytesPerElement=20,Kn(P6,"StructArrayLayout4ui3f20");class L6 extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m){const x=this.length;return this.resize(x+1),this.emplace(x,m)}emplace(m,x){return this.int16[1*m+0]=x,m}}L6.prototype.bytesPerElement=2,Kn(L6,"StructArrayLayout1i2");class D6 extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(m){const x=this.length;return this.resize(x+1),this.emplace(x,m)}emplace(m,x){return this.uint8[1*m+0]=x,m}}D6.prototype.bytesPerElement=1,Kn(D6,"StructArrayLayout1ub1");class nq extends Wp{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]}}nq.prototype.size=40;class QR extends A6{get(m){return new nq(this,m)}}Kn(QR,"CollisionBoxArray");class rq extends Wp{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(m){this._structArray.uint8[this._pos1+49]=m}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(m){this._structArray.uint8[this._pos1+50]=m}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(m){this._structArray.uint32[this._pos4+13]=m}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(m){this._structArray.uint8[this._pos1+58]=m}}rq.prototype.size=60;class aq extends M6{get(m){return new rq(this,m)}}Kn(aq,"PlacedSymbolArray");class VC extends Wp{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(m){this._structArray.uint32[this._pos4+14]=m}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(m){this._structArray.float32[this._pos4+18]=m}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}VC.prototype.size=80;class iq extends GR{get(m){return new VC(this,m)}}Kn(iq,"SymbolInstanceArray");class oq extends ro{getoffsetX(m){return this.float32[1*m+0]}}Kn(oq,"GlyphOffsetArray");class HC extends Ha{getx(m){return this.int16[2*m+0]}gety(m){return this.int16[2*m+1]}}Kn(HC,"SymbolLineVertexArray");class lq extends Wp{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]}}lq.prototype.size=12;class XR extends YR{get(m){return new lq(this,m)}}Kn(XR,"FeatureIndexArray");class cq extends bg{geta_centroid_pos0(m){return this.uint16[2*m+0]}geta_centroid_pos1(m){return this.uint16[2*m+1]}}Kn(cq,"FillExtrusionCentroidArray");class JR extends Wp{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]}}JR.prototype.size=6;class eO extends $i{get(m){return new JR(this,m)}}Kn(eO,"FillExtrusionWallArray");const dq=cn([{name:"a_pos",components:2,type:"Int16"}],4),wbe=cn([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),jbe=cn([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Po{constructor(m=[]){this.segments=m}_prepareSegment(m,x,k,E,P){let O=this.segments[this.segments.length-1];return m>Po.MAX_VERTEX_ARRAY_LENGTH&&nr(`Max vertices per segment is ${Po.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${m}`),(!O||O.vertexLength+m>Po.MAX_VERTEX_ARRAY_LENGTH||O.sortKey!==E||P!==void 0&&O&&O.batchIndex!==void 0&&O.batchIndex!==P)&&(O={vertexOffset:x,primitiveOffset:k,vertexLength:0,primitiveLength:0},E!==void 0&&(O.sortKey=E),P!==void 0&&(O.batchIndex=P),this.segments.push(O)),O}prepareSegment(m,x,k,E,P){return this._prepareSegment(m,x.length,k.length,E,P)}get(){return this.segments}destroy(){for(const m of this.segments)for(const x in m.vaos)m.vaos[x].destroy()}static simpleSegment(m,x,k,E){return new Po([{vertexOffset:m,primitiveOffset:x,vertexLength:k,primitiveLength:E,vaos:{},sortKey:0}])}}function R6(w,m){return 256*(w=Xe(Math.floor(w),0,255))+Xe(Math.floor(m),0,255)}Po.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Kn(Po,"SegmentVector");const Nbe=cn([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),kbe=cn([{name:"a_pattern_b",components:4,type:"Uint16"}]),Sbe=cn([{name:"a_dash",components:4,type:"Uint16"}]);class GC{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(m,x,k,E){this.ids.push(tO(m)),this.positions.push(x,k,E)}eachPosition(m,x){const k=tO(m);let E=0,P=this.ids.length-1;for(;E>1;this.ids[O]>=k?P=O:E=O+1}for(;this.ids[E]===k;)x(this.positions[3*E],this.positions[3*E+1],this.positions[3*E+2]),E++}static serialize(m,x){const k=new Float64Array(m.ids),E=new Uint32Array(m.positions);return WC(k,E,0,k.length-1),x&&(x.add(k.buffer),x.add(E.buffer)),{ids:k,positions:E}}static deserialize(m){const x=new GC;let k;x.ids=m.ids,x.positions=m.positions;for(const E of x.ids)E!==k&&x.uniqueIds.push(E),k=E;return x.indexed=!0,x}}function tO(w){const m=+w;return Number.isSafeInteger(m)?m:Sd(String(w))}function WC(w,m,x,k){for(;x>1];let P=x-1,O=k+1;for(;;){do P++;while(w[P]E);if(P>=O)break;Sx(w,P,O),Sx(m,3*P,3*O),Sx(m,3*P+1,3*O+1),Sx(m,3*P+2,3*O+2)}O-x`u_${P}`),this.type=k,this.context=E}setUniform(m,x,k,E,P){const O=E.constantOr(this.value);x.set(m,P,O instanceof Gn?O.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):O)}getBinding(m,x){return this.type==="color"?new Tbe(m):new ud(m)}}class de{constructor(m,x){this.uniformNames=x.map(k=>`u_${k}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(m,x){this.pixelRatio=m.pixelRatio||1,this.pattern=m.tl.concat(m.br),this.patternTransition=x?x.tl.concat(x.br):this.pattern}setUniform(m,x,k,E,P){let O=null;P!=="u_pattern"&&P!=="u_dash"||(O=this.pattern),P==="u_pattern_b"&&(O=this.patternTransition),P==="u_pixel_ratio"&&(O=this.pixelRatio),O&&x.set(m,P,O)}getBinding(m,x){return x==="u_pattern"||x==="u_pattern_b"||x==="u_dash"?new Cbe(m):new ud(m)}}class xe{constructor(m,x,k,E){this.expression=m,this.type=k,this.maxValue=0,this.paintVertexAttributes=x.map(P=>({name:`a_${P}`,type:"Float32",components:k==="color"?2:1,offset:0})),this.paintVertexArray=new E}populatePaintArray(m,x,k,E,P,O,U,H){const X=this.paintVertexArray.length,oe=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new La(0,{brightness:O,worldview:H}),x,{},P,E,U):this.expression.kind==="constant"&&this.expression.value,ue=Z(this.lutExpression,x,{},E,P,O,U,H);this.paintVertexArray.resize(m),this._setPaintValue(X,m,oe,ue?null:this.context.lut)}updatePaintArray(m,x,k,E,P,O,U,H){const X=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:U,worldview:H},k,E,void 0,P):this.expression.kind==="constant"&&this.expression.value,oe=Z(this.lutExpression,k,E,P,void 0,U,void 0,H);this._setPaintValue(m,x,X,oe?null:this.context.lut)}_setPaintValue(m,x,k,E){if(this.type==="color"){const P=G(k.toPremultipliedRenderColor(E));for(let O=m;O`u_${U}_t`),this.type=k,this.useIntegerZoom=E,this.context=P,this.maxValue=0,this.paintVertexAttributes=x.map(U=>({name:`a_${U}`,type:"Float32",components:k==="color"?4:2,offset:0})),this.paintVertexArray=new O}populatePaintArray(m,x,k,E,P,O,U,H){const X=this.expression.evaluate(new La(this.context.zoom,{brightness:O,worldview:H}),x,{},P,E,U),oe=this.expression.evaluate(new La(this.context.zoom+1,{brightness:O,worldview:H}),x,{},P,E,U),ue=Z(this.lutExpression,x,{},E,P,O,U,H),me=this.paintVertexArray.length;this.paintVertexArray.resize(m),this._setPaintValue(me,m,X,oe,ue?null:this.context.lut)}updatePaintArray(m,x,k,E,P,O,U,H){const X=this.expression.evaluate({zoom:this.context.zoom,brightness:U,worldview:H},k,E,void 0,P),oe=this.expression.evaluate({zoom:this.context.zoom+1,brightness:U,worldview:H},k,E,void 0,P),ue=Z(this.lutExpression,k,E,P,void 0,U,void 0,H);this._setPaintValue(m,x,X,oe,ue?null:this.context.lut)}_setPaintValue(m,x,k,E,P){if(this.type==="color"){const O=G(k.toPremultipliedRenderColor(P)),U=G(E.toPremultipliedRenderColor(P));for(let H=m;H!0){this.binders={},this._buffers=[],this.context=x;const E=[],P=m;for(const O in m.paint._values){const U=P.paint.get(O);if(O.endsWith("-use-theme")||!k(O)||!(U instanceof k1&&Up(U.property.specification)))continue;const H=Je(O,m.type),X=U.value,oe=U.property.specification.type,ue=!!U.property.useIntegerZoom,me=O==="line-dasharray"||O.endsWith("pattern"),_e=P.paint.get(`${O}-use-theme`),Se=O==="line-dasharray"&&P.layout.get("line-cap").value.kind!=="constant"||_e&&_e.value.kind!=="constant";if(X.kind!=="constant"||Se)if(X.kind==="source"||Se||me){const Pe=kt(O,oe,"source");this.binders[O]=me?new Re(X,H,oe,Pe,m.id):new xe(X,H,oe,Pe),E.push(`/a_${O}`)}else{const Pe=kt(O,oe,"composite");this.binders[O]=new we(X,H,oe,ue,x,Pe),E.push(`/z_${O}`)}else this.binders[O]=me?new de(X.value,H):new te(X.value,H,oe,x),E.push(`/u_${O}`);_e&&(this.binders[O].lutExpression=_e.value)}this.cacheKey=E.sort().join("")}getMaxValue(m){const x=this.binders[m];return x instanceof xe||x instanceof we?x.maxValue:0}populatePaintArrays(m,x,k,E,P,O,U,H){for(const X in this.binders){const oe=this.binders[X];oe.context=this.context,(oe instanceof xe||oe instanceof we||oe instanceof Re)&&oe.populatePaintArray(m,x,k,E,P,O,U,H)}}setConstantPatternPositions(m,x){for(const k in this.binders){const E=this.binders[k];E instanceof de&&E.setConstantPatternPositions(m,x)}}getPatternTransitionVertexBuffer(m){const x=this.binders[m];return x instanceof Re?x.paintTransitionVertexBuffer:null}updatePaintArrays(m,x,k,E,P,O,U,H,X,oe){let ue=!1;const me=Object.keys(m),_e=me.length!==0&&!H,Se=_e?me:x.uniqueIds;this.context.lut=P.lut;for(const Pe in this.binders){const $e=this.binders[Pe];if($e.context=this.context,($e instanceof xe||$e instanceof we||$e instanceof Re)&&$e.expression&&$e.expression.kind&&$e.expression.kind!=="constant"&&($e.expression.isStateDependent===!0||$e.expression.isLightConstant===!1)){const Ke=P.paint.get(Pe);$e.expression=Ke.value;for(const lt of Se){const nt=m[lt.toString()];x.eachPosition(lt,(pt,_t,jt)=>{const Yt=E.feature(pt);$e.updatePaintArray(_t,jt,Yt,nt,O,U,X,oe)})}if(!_e)for(const lt of k.uniqueIds){const nt=m[lt.toString()];k.eachPosition(lt,(pt,_t,jt)=>{const Yt=E.feature(pt);$e.updatePaintArray(_t,jt,Yt,nt,O,U,X,oe)})}ue=!0}}return ue}defines(){const m=[];for(const x in this.binders){const k=this.binders[x];(k instanceof te||k instanceof de)&&m.push(...k.uniformNames.map(E=>`#define HAS_UNIFORM_${E}`))}return m}getPaintVertexBuffers(){return this._buffers}getUniforms(m){const x=[];for(const k in this.binders){const E=this.binders[k];if(E instanceof te||E instanceof de||E instanceof we)for(const P of E.uniformNames)x.push({name:P,property:k,binding:E.getBinding(m,P)})}return x}setUniforms(m,x,k,E,P){for(const{name:O,property:U,binding:H}of k)this.binders[U].setUniform(m,H,P,E.get(U),O)}updatePaintBuffers(){this._buffers=[];for(const m in this.binders){const x=this.binders[m];(x instanceof xe||x instanceof we||x instanceof Re)&&x.paintVertexBuffer&&this._buffers.push(x.paintVertexBuffer),x instanceof Re&&x.paintTransitionVertexBuffer&&this._buffers.push(x.paintTransitionVertexBuffer)}}upload(m){for(const x in this.binders){const k=this.binders[x];(k instanceof xe||k instanceof we||k instanceof Re)&&k.upload(m)}this.updatePaintBuffers()}destroy(){for(const m in this.binders){const x=this.binders[m];(x instanceof xe||x instanceof we||x instanceof Re)&&x.destroy()}}}class Ue{constructor(m,x,k=()=>!0){this.programConfigurations={};for(const E of m)this.programConfigurations[E.id]=new Le(E,x,k);this.needsUpload=!1,this._featureMap=new GC,this._featureMapWithoutIds=new GC,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(m,x,k,E,P,O,U,H,X){for(const oe in this.programConfigurations)this.programConfigurations[oe].populatePaintArrays(m,x,E,P,O,U,H,X);x.id!==void 0?this._featureMap.add(x.id,k,this._bufferOffset,m):(this._featureMapWithoutIds.add(this._idlessCounter,k,this._bufferOffset,m),this._idlessCounter+=1),this._bufferOffset=m,this.needsUpload=!0}updatePaintArrays(m,x,k,E,P,O,U,H){for(const X of k)this.needsUpload=this.programConfigurations[X.id].updatePaintArrays(m,this._featureMap,this._featureMapWithoutIds,x,X,E,P,O,U||0,H)||this.needsUpload}get(m){return this.programConfigurations[m]}upload(m){if(this.needsUpload){for(const x in this.programConfigurations)this.programConfigurations[x].upload(m);this.needsUpload=!1}}destroy(){for(const m in this.programConfigurations)this.programConfigurations[m].destroy()}}const st={"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 Je(w,m){return st[w]||[w.replace(`${m}-`,"").replace(/-/g,"_")]}const mt={"line-pattern":{source:Zy,composite:Zy},"fill-pattern":{source:Zy,composite:Zy},"fill-extrusion-pattern":{source:Zy,composite:Zy},"line-dasharray":{source:ok,composite:ok}},ht={color:{source:Vj,composite:C1},number:{source:ro,composite:Vj}};function kt(w,m,x){const k=mt[w];return k&&k[x]||ht[m][x]}Kn(te,"ConstantBinder"),Kn(de,"PatternConstantBinder"),Kn(xe,"SourceExpressionBinder"),Kn(Re,"PatternCompositeBinder"),Kn(we,"CompositeExpressionBinder"),Kn(Le,"ProgramConfiguration",{omit:["_buffers"]}),Kn(Ue,"ProgramConfigurationSet");const Tt=$n/Math.PI/2,xt=64,es=[xt,32,16],Ft=-Tt,Qt=Tt;function At(w,m,x,k=Tt){return x=js(x),[w*Math.sin(x)*k,-m*k,w*Math.cos(x)*k]}function Dt(w,m,x){return At(Math.cos(js(w)),Math.sin(js(w)),m,x)}const Gt=63710088e-1,gs=2*Math.PI*Gt;class ns{constructor(m,x){if(isNaN(m)||isNaN(x))throw new Error(`Invalid LngLat object: (${m}, ${x})`);if(this.lng=+m,this.lat=+x,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new ns(Nt(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(m){const x=Math.PI/180,k=this.lat*x,E=m.lat*x,P=Math.sin(k)*Math.sin(E)+Math.cos(k)*Math.cos(E)*Math.cos((m.lng-this.lng)*x);return Gt*Math.acos(Math.min(P,1))}toBounds(m=0){const x=360*m/40075017,k=x/Math.cos(Math.PI/180*this.lat);return new $s({lng:this.lng-k,lat:this.lat-x},{lng:this.lng+k,lat:this.lat+x})}toEcef(m){return Dt(this.lat,this.lng,Tt+m*Tt/Gt)}static convert(m){if(m instanceof ns)return m;if(Array.isArray(m)&&(m.length===2||m.length===3))return new ns(Number(m[0]),Number(m[1]));if(!Array.isArray(m)&&typeof m=="object"&&m!==null)return new ns(Number("lng"in m?m.lng:m.lon),Number(m.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 $s{constructor(m,x){m&&(x?this.setSouthWest(m).setNorthEast(x):Array.isArray(m)&&m.length===4?this.setSouthWest([m[0],m[1]]).setNorthEast([m[2],m[3]]):this.setSouthWest(m[0]).setNorthEast(m[1]))}setNorthEast(m){return this._ne=m instanceof ns?new ns(m.lng,m.lat):ns.convert(m),this}setSouthWest(m){return this._sw=m instanceof ns?new ns(m.lng,m.lat):ns.convert(m),this}extend(m){const x=this._sw,k=this._ne;let E,P;if(m instanceof ns)E=m,P=m;else{if(!(m instanceof $s))return Array.isArray(m)?m.length===4||m.every(Array.isArray)?this.extend($s.convert(m)):this.extend(ns.convert(m)):typeof m=="object"&&m!==null&&m.hasOwnProperty("lat")&&(m.hasOwnProperty("lon")||m.hasOwnProperty("lng"))?this.extend(ns.convert(m)):this;if(E=m._sw,P=m._ne,!E||!P)return this}return x||k?(x.lng=Math.min(E.lng,x.lng),x.lat=Math.min(E.lat,x.lat),k.lng=Math.max(P.lng,k.lng),k.lat=Math.max(P.lat,k.lat)):(this._sw=new ns(E.lng,E.lat),this._ne=new ns(P.lng,P.lat)),this}getCenter(){return new ns((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 ns(this.getWest(),this.getNorth())}getSouthEast(){return new ns(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(m){const{lng:x,lat:k}=ns.convert(m);let E=this._sw.lng<=x&&x<=this._ne.lng;return this._sw.lng>this._ne.lng&&(E=this._sw.lng>=x&&x>=this._ne.lng),this._sw.lat<=k&&k<=this._ne.lat&&E}static convert(m){if(m)return m instanceof $s?m:new $s(m)}}function Ps(w){return gs*Math.cos(w*Math.PI/180)}function an(w){return(180+w)/360}function mn(w){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+w*Math.PI/360)))/360}function Ns(w,m){return w/Ps(m)}function hs(w){return 360*w-180}function zs(w){return 360/Math.PI*Math.atan(Math.exp((180-360*w)*Math.PI/180))-90}function Us(w,m){return w*Ps(zs(m))}const Ys=85.051129;function Rn(w){return Math.cos(js(Xe(w,-85.051129,Ys)))}function Sn(w,m){const x=Xe(m,0,25.5),k=Math.pow(2,x);return Rn(w)*gs/(512*k)}function Cn(w){return 1/Math.cos(w*Math.PI/180)}function dn(w,m=0){const x=Math.exp(Math.PI*(1-(w.y+m/$n)/(1<=H?(Cr(w,m,x,X,oe,P,ue,U,H),Cr(w,X,oe,k,E,ue,O,U,H)):w.push(O)}function ir(w,m,x){let k=w[0],E=k.x,P=k.y;m(k);const O=[k];for(let U=1;Uw.x+1||kw.y+1)&&nr("Geometry exceeds allowed extent, reduce your vector tile buffer size"),w}function Gr(w,m,x){const k=w.loadGeometry(),E=w.extent,P=$n/E;if(m&&x&&x.projection.isReprojectedInTileSpace){const O=1<{const _e=hs((m.x+me.x/E)/O),Se=zs((m.y+me.y/E)/O),Pe=oe.project(_e,Se);me.x=(Pe.x*U-H)*E,me.y=(Pe.y*U-X)*E};for(let me=0;me=E||Se.y<0||Se.y>=E||(ue(Se),_e.push(Se));k[me]=_e}}for(const O of k)for(const U of O)Ga(U,P);return k}function Wa(w,m){return{type:w.type,id:w.id,properties:w.properties,geometry:m?Gr(w):[]}}class va{constructor(m,x,k,E,P){this.properties={},this.extent=k,this.type=0,this.id=void 0,this._pbf=m,this._geometry=-1,this._keys=E,this._values=P,m.readFields(Ii,this,x)}loadGeometry(){const m=this._pbf;m.pos=this._geometry;const x=m.readVarint()+m.pos,k=[];let E,P=1,O=0,U=0,H=0;for(;m.pos>3}if(O--,P===1||P===2)U+=m.readSVarint(),H+=m.readSVarint(),P===1&&(E&&k.push(E),E=[]),E&&E.push(new Ls(U,H));else{if(P!==7)throw new Error(`unknown command ${P}`);E&&E.push(E[0].clone())}}return E&&k.push(E),k}bbox(){const m=this._pbf;m.pos=this._geometry;const x=m.readVarint()+m.pos;let k=1,E=0,P=0,O=0,U=1/0,H=-1/0,X=1/0,oe=-1/0;for(;m.pos>3}if(E--,k===1||k===2)P+=m.readSVarint(),O+=m.readSVarint(),PH&&(H=P),Ooe&&(oe=O);else if(k!==7)throw new Error(`unknown command ${k}`)}return[U,X,H,oe]}toGeoJSON(m,x,k){const E=this.extent*Math.pow(2,k),P=this.extent*m,O=this.extent*x,U=this.loadGeometry();function H(me){return[360*(me.x+P)/E-180,360/Math.PI*Math.atan(Math.exp((1-2*(me.y+O)/E)*Math.PI))-90]}function X(me){return me.map(H)}let oe;if(this.type===1){const me=[];for(const Se of U)me.push(Se[0]);const _e=X(me);oe=me.length===1?{type:"Point",coordinates:_e[0]}:{type:"MultiPoint",coordinates:_e}}else if(this.type===2){const me=U.map(X);oe=me.length===1?{type:"LineString",coordinates:me[0]}:{type:"MultiLineString",coordinates:me}}else{if(this.type!==3)throw new Error("unknown feature type");{const me=function(Se){const Pe=Se.length;if(Pe<=1)return[Se];const $e=[];let Ke,lt;for(let nt=0;nt=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[m];const x=this._pbf.readVarint()+this._pbf.pos;return new va(this._pbf,x,this.extent,this._keys,this._values)}}function Lo(w,m,x){w===15?m.version=x.readVarint():w===1?m.name=x.readString():w===5?m.extent=x.readVarint():w===2?m._features.push(x.pos):w===3?m._keys.push(x.readString()):w===4&&m._values.push(function(k){let E=null;const P=k.readVarint()+k.pos;for(;k.pos>3;E=O===1?k.readString():O===2?k.readFloat():O===3?k.readDouble():O===4?k.readVarint64():O===5?k.readVarint():O===6?k.readSVarint():O===7?k.readBoolean():null}if(E==null)throw new Error("unknown feature value");return E}(x))}class Vi{constructor(m,x){this.layers=m.readFields(Fa,{},x)}}function Fa(w,m,x){if(w===3){const k=new vl(x,x.readVarint()+x.pos);k.length&&(m[k.name]=k)}}const za="3d_elevation_id",Do="level";class Nl{constructor(){this._valid=!1}reset(m){return this.feature=m,this._valid=!0,this._geometry=m.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(m,x){return this._valid&&m(x(this._geometry)),this}require(m,x,k){return this.get(m,!0,x,k)}optional(m,x,k){return this.get(m,!1,x,k)}success(){return this._valid}get(m,x,k,E){const P=this.feature.properties.hasOwnProperty(m)?+this.feature.properties[m]:void 0;return this._valid&&P!==void 0&&!Number.isNaN(P)?k(E?E(P):P):x&&(this._valid=!1),this}}class Hi{constructor(m,x){this.featureFunc=m,this.vertexFunc=x}parseFeature(m,x,k){return this.featureFunc(m,x,k)}parseVertex(m,x,k){return this.vertexFunc(m,x,k)}}const Ca=new Hi((w,m,x)=>w.reset(m).require(za,k=>{x.id=k}).optional("fixed_height_relative",k=>{x.constantHeight=k},_o.decodeRelativeHeight).geometry(k=>{x.bounds=k},Zb).success(),(w,m,x)=>w.reset(m).require(za,k=>{x.id=k}).require("elevation_idx",k=>{x.idx=k}).require("extent",k=>{x.extent=k}).require("height_relative",k=>{x.height=k},_o.decodeRelativeHeight).geometry(k=>{x.position=k},_o.getPoint).success()),dl=new Hi((w,m,x)=>w.reset(m).require(za,k=>{x.id=k}).optional("fixed_height",k=>{x.constantHeight=k},_o.decodeMetricHeight).geometry(k=>{x.bounds=k},Zb).success(),(w,m,x)=>w.reset(m).require(za,k=>{x.id=k}).require("elevation_idx",k=>{x.idx=k}).require("extent",k=>{x.extent=k}).require("height",k=>{x.height=k},_o.decodeMetricHeight).geometry(k=>{x.position=k},_o.getPoint).success());class _o{static getPoint(m){return Vt(m[0][0].x,m[0][0].y)}static decodeRelativeHeight(m){return 1e-4*m*5}static decodeMetricHeight(m){return 1e-4*m}static getVersionSchema(m){return m?m==="1.0.1"?dl:void 0:Ca}static parse(m){const x=[],k=[],E=m.length,P=new Nl;for(let O=0;O=0);if(P===0)return 0;P!==m.length&&(x=!1)}return x?2:1}function hd(w,m){for(const x of w.projections){const k=Xc(m,w.points[0],x.axis);if(x.projection[1]k[1])return 0}return 1}function yu(w,m){let x=0;const k=[0,0,0,0];for(let E=0;E=0&&x++;return x}class $f{constructor(m,x){this.points=m||new Array(8).fill([0,0,0]),this.planes=x||new Array(6).fill([0,0,0,0]),this.bounds=so.fromPoints(this.points),this.projections=[],this.frustumEdges=[Be([],this.points[2],this.points[3]),Be([],this.points[0],this.points[3]),Be([],this.points[4],this.points[0]),Be([],this.points[5],this.points[1]),Be([],this.points[6],this.points[2]),Be([],this.points[7],this.points[3])];for(const k of this.frustumEdges){const E=[0,-k[2],k[1]],P=[k[2],0,-k[0]];this.projections.push({axis:E,projection:Xc(this.points,this.points[0],E)}),this.projections.push({axis:P,projection:Xc(this.points,this.points[0],P)})}}static fromInvProjectionMatrix(m,x,k,E){const P=Math.pow(2,k),O=[[-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(X=>{const oe=dt([],X,m),ue=1/oe[3]/x*P;return(me=oe)[0]=(_e=oe)[0]*(Se=[ue,ue,E?1/oe[3]:ue,ue])[0],me[1]=_e[1]*Se[1],me[2]=_e[2]*Se[2],me[3]=_e[3]*Se[3],me;var me,_e,Se}),U=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(X=>{const oe=Ie([],qe([],Be([],O[X[0]],O[X[1]]),Be([],O[X[2]],O[X[1]]))),ue=-Fe(oe,O[X[1]]);return oe.concat(ue)}),H=[];for(let X=0;XX[1]||X[0]>H[1])return 0}return 1}containsPoint(m){for(const x of this.planes){const k=x[3];if(Fe([x[0],x[1],x[2]],m)+k<0)return!1}return!0}}class so{static fromPoints(m){const x=[1/0,1/0,1/0],k=[-1/0,-1/0,-1/0];for(const E of m)le(x,x,E),ve(k,k,E);return new so(x,k)}static fromTileIdAndHeight(m,x,k){const E=1<m.max[x]||m.min[x]>this.max[x])return!1;return!0}intersectsAabbXY(m){return!(this.min[0]>m.max[0]||m.min[0]>this.max[0]||this.min[1]>m.max[1]||m.min[1]>this.max[1])}encapsulate(m){for(let x=0;x<3;x++)this.min[x]=Math.min(this.min[x],m.min[x]),this.max[x]=Math.max(this.max[x],m.max[x])}encapsulatePoint(m){for(let x=0;x<3;x++)this.min[x]=Math.min(this.min[x],m[x]),this.max[x]=Math.max(this.max[x],m[x])}closestPoint(m){return[Math.max(Math.min(this.max[0],m[0]),this.min[0]),Math.max(Math.min(this.max[1],m[1]),this.min[1]),Math.max(Math.min(this.max[2],m[2]),this.min[2])]}}Kn(so,"Aabb");class Cx{constructor(m,x){this.feature=m,this.metersToTile=x,this.index=0}get(){const m=this.feature.vertices[this.index],x=this.feature.vertexProps[this.index].dir,k=x[1],E=-x[0],P=(m.extent+1)*this.metersToTile;return[new Ls(Math.trunc(m.position[0]+k*P),Math.trunc(m.position[1]+E*P)),new Ls(Math.trunc(m.position[0]-k*P),Math.trunc(m.position[1]-E*P))]}next(){this.index++}valid(){return this.index{return U.a0?ge(H,H,1/X):ie(H,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(m){if(this.edges.length===0)return;let x=0,k=Number.POSITIVE_INFINITY,E=0;const[P,O,U,H,X,oe,ue]=this._tmpVec2;Ms(ue,m.x,m.y);const me=new kc(ue,null);for(let _e=0;_e0?tn(H,U)/pt:0,jt=Xe(_t,0,1),Yt=Math.abs((_t-jt)*this.edgeProps[_e].len);Js(X,ue,$e),Ms(oe,Pe[1],-Pe[0]);const zt=Yt+Math.abs(tn(X,oe));zt=0;--O){const U=this.edges[O].a,H=this.edges[O].b,{position:X,height:oe,extent:ue}=this.vertices[U],{position:me,height:_e,extent:Se}=this.vertices[H],Pe=this.vertexProps[U].dir,$e=this.vertexProps[H].dir;if(ie(x,X[0]/m,X[1]/m,oe),ie(k,me[0]/m,me[1]/m,_e),ie(E,Pe[1],-Pe[0],0),ge(E,E,ue),ie(P,$e[1],-$e[0],0),ge(P,P,Se),this.distSqLines(ne(x[0]+.5*E[0],x[1]+.5*E[1],x[2]+.5*E[2]),ne(k[0]-.5*P[0],k[1]-.5*P[1],k[2]-.5*P[2]),ne(x[0]-.5*E[0],x[1]-.5*E[1],x[2]-.5*E[2]),ne(k[0]+.5*P[0],k[1]+.5*P[1],k[2]+.5*P[2]))<=.0025000000000000005)continue;const Ke=this.vertices.length,lt=Xt(ft(),X,me);this.vertices.push({position:Cs(lt,lt,.5),height:.5*(oe+_e),extent:.5*(ue+Se)});const nt=Xt(ft(),Pe,$e);this.vertexProps.push({dir:rn(nt,nt)}),this.edges.splice(O,1),this.edgeProps.splice(O,1),this.edges.push({a:U,b:Ke}),this.edges.push({a:Ke,b:H});const pt=Js(ft(),this.vertices[Ke].position,X),_t=As(pt),jt={vec:pt,dir:Cs(ft(),pt,1/_t),len:_t};this.edgeProps.push(jt),this.edgeProps.push(jt)}}distSqLines(m,x,k,E){const P=ce(Y(),x,m),O=ce(Y(),E,k),U=ce(Y(),m,k),H=Fe(P,P),X=Fe(P,O),oe=Fe(P,U),ue=Fe(O,O),me=Fe(O,U),_e=H*ue-X*X;if(_e===0)return Ce(be(P,k,E,Fe(U,O)/Fe(O,O)),m);const Se=(H*me-X*oe)/_e;return Ce(be(P,m,x,(X*me-oe*ue)/_e),be(O,k,E,Se))}}class Bo{static parseFrom(m,x){const k=_o.parse(m);if(!k)return[];let{vertices:E,features:P}=k;const O=1/dn(x);P.sort((oe,ue)=>oe.id-ue.id),E.sort((oe,ue)=>oe.id-ue.id||oe.idx-ue.idx),E=E.filter((oe,ue,me)=>ue===me.findIndex(_e=>_e.id===oe.id&&_e.idx===oe.idx));const U=new Array;let H=0;const X=E.length;for(const oe of P){if(oe.constantHeight){U.push(new Tx(oe.id,oe.bounds,oe.constantHeight));continue}for(;H!==X&&E[H].idE.id===k)}}class Ko{constructor(m,x){this.zScale=1,this.xOffset=0,this.yOffset=0,m.equals(x)||(this.zScale=Math.pow(2,x.z-m.z),this.xOffset=(m.x*this.zScale-x.x)*$n,this.yOffset=(m.y*this.zScale-x.y)*$n)}constantElevation(m,x){if(m.constantHeight!=null)return this.computeBiasedHeight(m.constantHeight,x)}pointElevation(m,x,k){const E=this.constantElevation(x,k);return E??(m.x=m.x*this.zScale+this.xOffset,m.y=m.y*this.zScale+this.yOffset,this.computeBiasedHeight(x.pointElevation(m),k))}computeBiasedHeight(m,x){return x<=0?m:m+x*ot(0,x,m>=0?m:Math.abs(.5*m))}}Kn(Tx,"ElevationFeature");class co{constructor(m){this.zoom=m.zoom,this.overscaling=m.overscaling,this.layers=m.layers,this.layerIds=this.layers.map(x=>x.fqid),this.index=m.index,this.hasPattern=!1,this.projection=m.projection,this.layoutVertexArray=new Ha,this.indexArray=new sc,this.segments=new Po,this.programConfigurations=new Ue(m.layers,{zoom:m.zoom,lut:m.lut}),this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.elevationMode=this.layers[0].layout.get("circle-elevation-reference"),this.hasElevation=!1,this.elevationMode!=="none"&&(this.elevatedLayoutVertexArray=new ro),this.worldview=m.worldview,this.hasAppearances=null}updateFootprints(m,x){}updateAppearances(m,x,k,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,E){const P=this.layers[0],O=[];let U=null;P.type==="circle"&&(U=P.layout.get("circle-sort-key"));for(const{feature:X,id:oe,index:ue,sourceLayerIndex:me}of m){const _e=this.layers[0]._featureFilter.needGeometry,Se=Wa(X,_e);if(!this.layers[0]._featureFilter.filter(new La(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),Se,k))continue;const Pe=U?U.evaluate(Se,{},k):void 0,$e={id:oe,properties:X.properties,type:X.type,sourceLayerIndex:me,index:ue,geometry:_e?Se.geometry:Gr(X,k,E),patterns:{},sortKey:Pe};O.push($e)}U&&O.sort((X,oe)=>X.sortKey-oe.sortKey);let H=null;E.projection.name==="globe"&&(this.globeExtVertexArray=new E6,H=E.projection);for(const X of O){const{geometry:oe,index:ue,sourceLayerIndex:me}=X,_e=m[ue].feature;this.addFeature(X,oe,ue,x.availableImages,k,H,x.brightness,x.elevationFeatures),x.featureIndex.insert(_e,oe,ue,me,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(m,x,k,E,P,O,U){this.programConfigurations.updatePaintArrays(m,x,P,k,E,O,U,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(m){this.uploaded||(this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,dq.members),this.indexBuffer=m.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=m.createVertexBuffer(this.globeExtVertexArray,jbe.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=m.createVertexBuffer(this.elevatedLayoutVertexArray,wbe.members))),this.programConfigurations.upload(m),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(m,x,k,E,P,O,U,H){let X;this.elevationMode!=="none"&&(X=Bo.getElevationFeature(m,H));for(const oe of x)for(const ue of oe){const me=ue.x,_e=ue.y;if(me<0||me>=$n||_e<0||_e>=$n)continue;if(O){const $e=O.projectTilePoint(me,_e,P),Ke=O.upVector(P,me,_e);this.addGlobeExtVertex($e,Ke),this.addGlobeExtVertex($e,Ke),this.addGlobeExtVertex($e,Ke),this.addGlobeExtVertex($e,Ke)}const Se=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,m.sortKey),Pe=Se.vertexLength;if(this.addCircleVertex(me,_e,-1,-1),this.addCircleVertex(me,_e,1,-1),this.addCircleVertex(me,_e,1,1),this.addCircleVertex(me,_e,-1,1),this.elevationMode!=="none"){const $e=X?X.pointElevation(new Ls(me,_e)):0;this.hasElevation=this.hasElevation||$e!==0;for(let Ke=0;Ke<4;Ke++)this.elevatedLayoutVertexArray.emplaceBack($e)}this.indexArray.emplaceBack(Pe,Pe+1,Pe+2),this.indexArray.emplaceBack(Pe,Pe+2,Pe+3),Se.vertexLength+=4,Se.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,m,k,{},E,P,U,void 0,this.worldview)}addCircleVertex(m,x,k,E){this.layoutVertexArray.emplaceBack(2*m+(k+1)/2,2*x+(E+1)/2)}addGlobeExtVertex(m,x){this.globeExtVertexArray.emplaceBack(m.x,m.y,m.z,x[0]*16384,x[1]*16384,x[2]*16384)}}function pc(w,m){for(let x=0;x1){if(x_(w,m))return!0;for(let k=0;k1?x:x.sub(m)._mult(E)._add(m))}function ck(w,m){let x,k,E,P=!1;for(let O=0;Om.y!=E.y>m.y&&m.x<(E.x-k.x)*(m.y-k.y)/(E.y-k.y)+k.x&&(P=!P)}return P}function Kp(w,m){let x=!1;for(let k=0,E=w.length-1;km.y!=O.y>m.y&&m.x<(O.x-P.x)*(m.y-P.y)/(O.y-P.y)+P.x&&(x=!x)}return x}function g_(w,m,x,k,E){for(const O of w)if(m<=O.x&&x<=O.y&&k>=O.x&&E>=O.y)return!0;const P=[new Ls(m,x),new Ls(m,E),new Ls(k,E),new Ls(k,x)];if(w.length>2){for(const O of P)if(Kp(w,O))return!0}for(let O=0;OE.x&&m.x>E.x||w.yE.y&&m.y>E.y)return!1;const P=Ot(w,m,x[0]);return P!==Ot(w,m,x[1])||P!==Ot(w,m,x[2])||P!==Ot(w,m,x[3])}function v_(w,m,x,k,E,P){let O=m.y-w.y,U=w.x-m.x;if(P=P||0){const H=O*O+U*U;if(H===0)return!0;const X=Math.sqrt(H);O/=X,U/=X}return!((x.x-w.x)*O+(x.y-w.y)*U-P<0||(k.x-w.x)*O+(k.y-w.y)*U-P<0||(E.x-w.x)*O+(E.y-w.y)*U-P<0)}function F6(w,m,x,k,E,P,O){return!(v_(w,m,k,E,P,O)||v_(m,x,k,E,P,O)||v_(x,w,k,E,P,O)||v_(k,E,w,m,x,O)||v_(E,P,w,m,x,O)||v_(P,k,w,m,x,O))}function dk(w,m,x){const k=m.paint.get(w).value;return k.kind==="constant"?k.value:x.programConfigurations.get(m.id).getMaxValue(w)}function uq(w){return Math.sqrt(w[0]*w[0]+w[1]*w[1])}function vDe(w,m,x,k,E){if(!m[0]&&!m[1])return w;const P=Ls.convert(m)._mult(E);x==="viewport"&&P._rotate(-k);const O=[];for(let U=0;U>x&&m.y===this.y>>x}url(m,x){const k=function(P,O,U){const H=2**U,X=2*Math.PI*6378137,oe=X*(P/H-.5),ue=X*(.5-(O+1)/H);return`${oe},${ue},${oe+X/H},${ue+X/H}`}(this.x,this.y,this.z),E=function(P,O,U){let H,X="";for(let oe=P;oe>0;oe--)H=1<this.canonical.z?new dp(m,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new dp(m,this.wrap,m,this.canonical.x>>x,this.canonical.y>>x)}calculateScaledKey(m,x=!0){if(this.overscaledZ===m&&x)return this.key;if(m>this.canonical.z)return z6(this.wrap*+x,m,this.canonical.z,this.canonical.x,this.canonical.y);{const k=this.canonical.z-m;return z6(this.wrap*+x,m,m,this.canonical.x>>k,this.canonical.y>>k)}}isChildOf(m){if(m.wrap!==this.wrap)return!1;const x=this.canonical.z-m.canonical.z;return m.overscaledZ===0||m.overscaledZ>x&&m.canonical.y===this.canonical.y>>x}children(m){if(this.overscaledZ>=m)return[new dp(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const x=this.canonical.z+1,k=2*this.canonical.x,E=2*this.canonical.y;return[new dp(x,this.wrap,x,k,E),new dp(x,this.wrap,x,k+1,E),new dp(x,this.wrap,x,k,E+1),new dp(x,this.wrap,x,k+1,E+1)]}isLessThan(m){return this.wrapm.wrap)&&(this.overscaledZm.overscaledZ)&&(this.canonical.xm.canonical.x)&&this.canonical.y{let m=w.canonical.x-1,x=w.wrap;return m<0&&(m=(1<{let m=w.canonical.x+1,x=w.wrap;return m===1<new dp(w.overscaledZ,w.wrap,w.canonical.z,w.canonical.x,(w.canonical.y===0?1<new dp(w.overscaledZ,w.wrap,w.canonical.z,w.canonical.x,w.canonical.y===(1<1?null:function(k,E,P,O){const U=Math.sin(P);return k*(Math.sin((1-O)*P)/U)+E*(Math.sin(O*P)/U)}(w.a[m],w.b[m],w.angle,Xe(x,0,1))+w.center[m]}function b_(w){if(w.z<=1)return j4t[w.z+2*w.y+w.x];const m=Abe(pq(w));return so.fromPoints(m)}function Kj(w,m,x){return ge(w,w,1-x),Te(w,w,m,x)}function SDe(w,m){const x=Yj(m.zoom);if(x===0)return b_(w);const k=pq(w),E=Abe(k),P=an(k.getWest())*m.worldSize,O=an(k.getEast())*m.worldSize,U=mn(k.getNorth())*m.worldSize,H=mn(k.getSouth())*m.worldSize,X=[P,U,0],oe=[O,U,0],ue=[P,H,0],me=[O,H,0],_e=j([],m.globeMatrix);return Ze(X,X,_e),Ze(oe,oe,_e),Ze(ue,ue,_e),Ze(me,me,_e),E[0]=Kj(E[0],ue,x),E[1]=Kj(E[1],me,x),E[2]=Kj(E[2],oe,x),E[3]=Kj(E[3],X,x),so.fromPoints(E)}function CDe(w,m,x){for(const k of w)Ze(k,k,m),ge(k,k,x)}function TDe(w,m,x,k){const E=m/w.worldSize,P=w.globeMatrix;if(x.z<=1){const Wt=b_(x).getCorners();return CDe(Wt,P,E),so.fromPoints(Wt)}const O=pq(x,k),U=Abe(O,Tt+mq(w._tileCoverLift));CDe(U,P,E);const H=Number.MAX_VALUE,X=[-H,-H,-H],oe=[H,H,H];if(O.contains(w.center)){for(const Ut of U)le(oe,oe,Ut),ve(X,X,Ut);X[2]=0;const Wt=w.point,$t=[Wt.x*E,Wt.y*E,0];return le(oe,oe,$t),ve(X,X,$t),new so(oe,X)}if(w._tileCoverLift>0){for(const Wt of U)le(oe,oe,Wt),ve(X,X,Wt);return new so(oe,X)}const ue=[P[12]*E,P[13]*E,P[14]*E],me=O.getCenter(),_e=Xe(w.center.lat,-85.051129,Ys),Se=Xe(me.lat,-85.051129,Ys),Pe=an(w.center.lng),$e=mn(_e);let Ke=Pe-an(me.lng);const lt=$e-mn(Se);Ke>.5?Ke-=1:Ke<-.5&&(Ke+=1);let nt=0;Math.abs(Ke)>Math.abs(lt)?nt=Ke>=0?1:3:(nt=lt>=0?0:2,Te(ue,ue,[P[4]*E,P[5]*E,P[6]*E],-Math.sin(js(lt>=0?O.getSouth():O.getNorth()))*Tt));const pt=U[nt],_t=U[(nt+1)%4],jt=new N4t(pt,_t,ue),Yt=[Ebe(jt,0)||pt[0],Ebe(jt,1)||pt[1],Ebe(jt,2)||pt[2]],zt=Yj(w.zoom);if(zt>0){const Wt=function({x:Ut,y:Bs,z:qs},Qs,sn,Xs,xn){const Os=1/(1<.5?or=-1:Fn<-.5&&(or=1),en=((en+or)*Qs-(Xs*=Qs))*sn+Xs,on=((on+or)*Qs-Xs)*sn+Xs,yn=(yn*Qs-(xn*=Qs))*sn+xn,Tn=(Tn*Qs-xn)*sn+xn,[[en,Tn,0],[on,Tn,0],[on,yn,0],[en,yn,0]]}(x,m,w._pixelsPerMercatorPixel,Pe,$e);for(let Ut=0;UtMath.PI/2*1.01}const PDe=js(85),k4t=Math.cos(PDe),S4t=Math.sin(PDe),C4t=g(),LDe=w=>{const m=[];return w.paint.get("circle-pitch-alignment")==="map"&&m.push("PITCH_WITH_MAP"),w.paint.get("circle-pitch-scale")==="map"&&m.push("SCALE_WITH_MAP"),m};function DDe(w,m,x,k,E,P,O,U,H){if(P&&w.queryGeometry.isAboveHorizon)return!1;P&&(H*=w.pixelToTileUnitsFactor);const X=w.tileID.canonical,oe=x.projection.upVectorScale(X,x.center.lat,x.worldSize).metersToTile;for(const ue of m)for(const me of ue){const _e=me.add(U),Se=E&&x.elevation?x.elevation.exaggeration()*E.getElevationAt(_e.x,_e.y,!0):0,Pe=x.projection.projectTilePoint(_e.x,_e.y,X);if(Se>0){const nt=x.projection.upVector(X,_e.x,_e.y);Pe.x+=nt[0]*oe*Se,Pe.y+=nt[1]*oe*Se,Pe.z+=nt[2]*oe*Se}const $e=P?_e:T4t(Pe.x,Pe.y,Pe.z,k),Ke=P?w.tilespaceRays.map(nt=>A4t(nt,Se)):w.queryGeometry.screenGeometry,lt=dt([],[Pe.x,Pe.y,Pe.z,1],k);if(!O&&P?H*=lt[3]/x.cameraToCenterDistance:O&&!P&&(H*=x.cameraToCenterDistance/lt[3]),P){const nt=zs((me.y/$n+X.y)/(1<w.width||E.height>w.height||x.x>w.width-E.width||x.y>w.height-E.height)throw new RangeError("out of range source coordinates for image copy");if(E.width>m.width||E.height>m.height||k.x>m.width-E.width||k.y>m.height-E.height)throw new RangeError("out of range destination coordinates for image copy");const H=w.data,X=m.data,oe=P===4&&U;for(let ue=0;ue{m[w.evaluationKey]=H;const X=w.expression.evaluate(m),oe=X?X.toNonPremultipliedRenderColor(null):null;oe&&(E.data[O+U+0]=Math.floor(255*oe.r),E.data[O+U+1]=Math.floor(255*oe.g),E.data[O+U+2]=Math.floor(255*oe.b),E.data[O+U+3]=Math.floor(255*oe.a))};if(w.clips)for(let O=0,U=0;O80*x){U=w[0],H=w[1];let oe=U,ue=H;for(let me=x;meoe&&(oe=_e),Se>ue&&(ue=Se)}X=Math.max(oe-U,ue-H),X=X!==0?32767/X:0}return iO(P,O,x,U,H,X,0),O}function HDe(w,m,x,k,E){let P;if(E===function(O,U,H,X){let oe=0;for(let ue=U,me=H-X;ue0)for(let O=m;O=m;O-=k)P=YDe(O/k|0,w[O],w[O+1],P);return P&&$6(P,P.next)&&(cO(P),P=P.next),P}function QC(w,m){if(!w)return w;m||(m=w);let x,k=w;do if(x=!1,k.steiner||!$6(k,k.next)&&vu(k.prev,k,k.next)!==0)k=k.next;else{if(cO(k),k=m=k.prev,k===k.next)break;x=!0}while(x||k!==m);return m}function iO(w,m,x,k,E,P,O){if(!w)return;!O&&P&&function(H,X,oe,ue){let me=H;do me.z===0&&(me.z=Dbe(me.x,me.y,X,oe,ue)),me.prevZ=me.prev,me.nextZ=me.next,me=me.next;while(me!==H);me.prevZ.nextZ=null,me.prevZ=null,function(_e){let Se,Pe=1;do{let $e,Ke=_e;_e=null;let lt=null;for(Se=0;Ke;){Se++;let nt=Ke,pt=0;for(let jt=0;jt0||_t>0&&nt;)pt!==0&&(_t===0||!nt||Ke.z<=nt.z)?($e=Ke,Ke=Ke.nextZ,pt--):($e=nt,nt=nt.nextZ,_t--),lt?lt.nextZ=$e:_e=$e,$e.prevZ=lt,lt=$e;Ke=nt}lt.nextZ=null,Pe*=2}while(Se>1)}(me)}(w,k,E,P);let U=w;for(;w.prev!==w.next;){const H=w.prev,X=w.next;if(P?R4t(w,k,E,P):D4t(w))m.push(H.i,w.i,X.i),cO(w),w=X.next,U=X.next;else if((w=X)===U){O?O===1?iO(w=O4t(QC(w),m),m,x,k,E,P,2):O===2&&F4t(w,m,x,k,E,P):iO(QC(w),m,x,k,E,P,1);break}}}function D4t(w){const m=w.prev,x=w,k=w.next;if(vu(m,x,k)>=0)return!1;const E=m.x,P=x.x,O=k.x,U=m.y,H=x.y,X=k.y,oe=Math.min(E,P,O),ue=Math.min(U,H,X),me=Math.max(E,P,O),_e=Math.max(U,H,X);let Se=k.next;for(;Se!==m;){if(Se.x>=oe&&Se.x<=me&&Se.y>=ue&&Se.y<=_e&&oO(E,U,P,H,O,X,Se.x,Se.y)&&vu(Se.prev,Se,Se.next)>=0)return!1;Se=Se.next}return!0}function R4t(w,m,x,k){const E=w.prev,P=w,O=w.next;if(vu(E,P,O)>=0)return!1;const U=E.x,H=P.x,X=O.x,oe=E.y,ue=P.y,me=O.y,_e=Math.min(U,H,X),Se=Math.min(oe,ue,me),Pe=Math.max(U,H,X),$e=Math.max(oe,ue,me),Ke=Dbe(_e,Se,m,x,k),lt=Dbe(Pe,$e,m,x,k);let nt=w.prevZ,pt=w.nextZ;for(;nt&&nt.z>=Ke&&pt&&pt.z<=lt;){if(nt.x>=_e&&nt.x<=Pe&&nt.y>=Se&&nt.y<=$e&&nt!==E&&nt!==O&&oO(U,oe,H,ue,X,me,nt.x,nt.y)&&vu(nt.prev,nt,nt.next)>=0||(nt=nt.prevZ,pt.x>=_e&&pt.x<=Pe&&pt.y>=Se&&pt.y<=$e&&pt!==E&&pt!==O&&oO(U,oe,H,ue,X,me,pt.x,pt.y)&&vu(pt.prev,pt,pt.next)>=0))return!1;pt=pt.nextZ}for(;nt&&nt.z>=Ke;){if(nt.x>=_e&&nt.x<=Pe&&nt.y>=Se&&nt.y<=$e&&nt!==E&&nt!==O&&oO(U,oe,H,ue,X,me,nt.x,nt.y)&&vu(nt.prev,nt,nt.next)>=0)return!1;nt=nt.prevZ}for(;pt&&pt.z<=lt;){if(pt.x>=_e&&pt.x<=Pe&&pt.y>=Se&&pt.y<=$e&&pt!==E&&pt!==O&&oO(U,oe,H,ue,X,me,pt.x,pt.y)&&vu(pt.prev,pt,pt.next)>=0)return!1;pt=pt.nextZ}return!0}function O4t(w,m){let x=w;do{const k=x.prev,E=x.next.next;!$6(k,E)&&WDe(k,x,x.next,E)&&lO(k,E)&&lO(E,k)&&(m.push(k.i,x.i,E.i),cO(x),cO(x.next),x=w=E),x=x.next}while(x!==w);return QC(x)}function F4t(w,m,x,k,E,P){let O=w;do{let U=O.next.next;for(;U!==O.prev;){if(O.i!==U.i&&q4t(O,U)){let H=KDe(O,U);return O=QC(O,O.next),H=QC(H,H.next),iO(O,m,x,k,E,P,0),void iO(H,m,x,k,E,P,0)}U=U.next}O=O.next}while(O!==w)}function z4t(w,m){let x=w.x-m.x;return x===0&&(x=w.y-m.y,x===0)&&(x=(w.next.y-w.y)/(w.next.x-w.x)-(m.next.y-m.y)/(m.next.x-m.x)),x}function B4t(w,m){const x=function(E,P){let O=P;const U=E.x,H=E.y;let X,oe=-1/0;if($6(E,O))return O;do{if($6(E,O.next))return O.next;if(H<=O.y&&H>=O.next.y&&O.next.y!==O.y){const Pe=O.x+(H-O.y)*(O.next.x-O.x)/(O.next.y-O.y);if(Pe<=U&&Pe>oe&&(oe=Pe,X=O.x=O.x&&O.x>=me&&U!==O.x&&GDe(H<_e?U:oe,H,me,_e,H<_e?oe:U,H,O.x,O.y)){const Pe=Math.abs(H-O.y)/(U-O.x);lO(O,E)&&(PeX.x||O.x===X.x&&$4t(X,O)))&&(X=O,Se=Pe)}O=O.next}while(O!==ue);return X}(w,m);if(!x)return m;const k=KDe(x,w);return QC(k,k.next),QC(x,x.next)}function $4t(w,m){return vu(w.prev,w,m.prev)<0&&vu(m.next,w,w.next)<0}function Dbe(w,m,x,k,E){return(w=1431655765&((w=858993459&((w=252645135&((w=16711935&((w=(w-x)*E|0)|w<<8))|w<<4))|w<<2))|w<<1))|(m=1431655765&((m=858993459&((m=252645135&((m=16711935&((m=(m-k)*E|0)|m<<8))|m<<4))|m<<2))|m<<1))<<1}function U4t(w){let m=w,x=w;do(m.x=(w-O)*(P-U)&&(w-O)*(k-U)>=(x-O)*(m-U)&&(x-O)*(P-U)>=(E-O)*(k-U)}function oO(w,m,x,k,E,P,O,U){return!(w===O&&m===U)&&GDe(w,m,x,k,E,P,O,U)}function q4t(w,m){return w.next.i!==m.i&&w.prev.i!==m.i&&!function(x,k){let E=x;do{if(E.i!==x.i&&E.next.i!==x.i&&E.i!==k.i&&E.next.i!==k.i&&WDe(E,E.next,x,k))return!0;E=E.next}while(E!==x);return!1}(w,m)&&(lO(w,m)&&lO(m,w)&&function(x,k){let E=x,P=!1;const O=(x.x+k.x)/2,U=(x.y+k.y)/2;do E.y>U!=E.next.y>U&&E.next.y!==E.y&&O<(E.next.x-E.x)*(U-E.y)/(E.next.y-E.y)+E.x&&(P=!P),E=E.next;while(E!==x);return P}(w,m)&&(vu(w.prev,w,m.prev)||vu(w,m.prev,m))||$6(w,m)&&vu(w.prev,w,w.next)>0&&vu(m.prev,m,m.next)>0)}function vu(w,m,x){return(m.y-w.y)*(x.x-m.x)-(m.x-w.x)*(x.y-m.y)}function $6(w,m){return w.x===m.x&&w.y===m.y}function WDe(w,m,x,k){const E=gq(vu(w,m,x)),P=gq(vu(w,m,k)),O=gq(vu(x,k,w)),U=gq(vu(x,k,m));return E!==P&&O!==U||!(E!==0||!xq(w,x,m))||!(P!==0||!xq(w,k,m))||!(O!==0||!xq(x,w,k))||!(U!==0||!xq(x,m,k))}function xq(w,m,x){return m.x<=Math.max(w.x,x.x)&&m.x>=Math.min(w.x,x.x)&&m.y<=Math.max(w.y,x.y)&&m.y>=Math.min(w.y,x.y)}function gq(w){return w>0?1:w<0?-1:0}function lO(w,m){return vu(w.prev,w,w.next)<0?vu(w,m,w.next)>=0&&vu(w,w.prev,m)>=0:vu(w,m,w.prev)<0||vu(w,w.next,m)<0}function KDe(w,m){const x=Rbe(w.i,w.x,w.y),k=Rbe(m.i,m.x,m.y),E=w.next,P=m.prev;return w.next=m,m.prev=w,x.next=E,E.prev=x,k.next=x,x.prev=k,P.next=k,k.prev=P,k}function YDe(w,m,x,k){const E=Rbe(w,m,x);return k?(E.next=k.next,E.prev=k,k.next.prev=E,k.next=E):(E.prev=E,E.next=E),E}function cO(w){w.next.prev=w.prev,w.prev.next=w.next,w.prevZ&&(w.prevZ.nextZ=w.nextZ),w.nextZ&&(w.nextZ.prevZ=w.prevZ)}function Rbe(w,m,x){return{i:w,x:m,y:x,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function dO(w,m){const x=w.length;if(x<=1)return[w];const k=[];let E,P;for(let O=0;O1)for(let O=0;O=$n&&x>=$n}static evaluate(m){if(m.length===0)return new Zj;let x=[];for(const H of m)x.push(...H.portals);if(x.length===0)return new Zj;for(const H of x){const X=H.va,oe=H.vb;(Zj.isOnBorder(X.x,oe.x)||Zj.isOnBorder(X.y,oe.y))&&(H.type="border")}const k=x.filter(H=>H.type!=="unevaluated"),E=x.filter(H=>H.type==="unevaluated");if(E.length===0)return new Zj;E.sort((H,X)=>H.hash===X.hash?H.isTunnel===X.isTunnel?0:H.isTunnel?-1:1:H.hashH.hashP!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new Ue(x,{zoom:k,lut:E},P=>P!=="fill-bridge-guard-rail-color")}addVertices(m,x){const k=this.unevalVertices.length;for(let E=0;E=P.min.x&&ue.x<=P.max.x&&ue.y>=P.min.y&&ue.y<=P.max.y||me.x>=P.min.x&&me.x<=P.max.x&&me.y>=P.min.y&&me.y<=P.max.y||y_(ue,me,U))||this.isOnBorder(ue.x,me.x)||this.isOnBorder(ue.y,me.y))continue;const _e=Ex.computeEdgeHash(this.unevalVertices[X],this.unevalVertices[oe]);let Se,Pe=this.vertexHashLookup.get(Ex.computePosHash(ue));Pe!=null?Se=Pe.next:(Pe=this.vertexHashLookup.get(Ex.computePosHash(me)),Se=Pe!=null?Pe.prev:_e),this.unevalEdges.push({polygonIdx:m,a:X,b:oe,hash:_e,portalHash:Se,isTunnel:E,type:"unevaluated",featureInfo:O})}}addPortalCandidates(m,x,k,E,P){if(x.length!==0){this.vertexHashLookup.clear();for(const O of x){if(O.length===0)continue;const U=O[0];let H=Ex.computeEdgeHash(U[U.length-2],U[U.length-1]);for(let X=0;X({vertexOffset:0,primitiveOffset:this.indexArray.length}),k=me=>{me.primitiveLength=this.indexArray.length-me.primitiveOffset},E=new H4t(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(m.portals,this.unevalEdges);const P=x(),O=x(),U=x(),H=(me,_e)=>{me.sort((Pe,$e)=>Pe.type===_e&&$e.type!==_e?-1:Pe.type!==_e&&$e.type===_e?1:0);const Se=me.findIndex(Pe=>Pe.type!==_e);return Se>=0?Se:me.length};let X=0;this.unevalEdges.length>0&&(X=H(this.unevalEdges,"none"),this.constructBridgeStructures(E,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:X},this.tileToMeters)),k(U);const oe=x(),ue=x();if(this.unevalEdges.length>0){const me=this.unevalEdges.splice(X),_e=H(me,"tunnel")+X;this.unevalEdges.push(...me),this.constructTunnelStructures(E,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:X},{min:X,max:_e})}k(oe),E.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),k(ue),E.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),k(O),E.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),k(P),this.maskSegments=Po.simpleSegment(0,ue.primitiveOffset,0,ue.primitiveLength),this.depthSegments=Po.simpleSegment(0,O.primitiveOffset,0,O.primitiveLength),this.renderableBridgeSegments=Po.simpleSegment(0,U.primitiveOffset,0,U.primitiveLength),this.renderableTunnelSegments=Po.simpleSegment(0,oe.primitiveOffset,0,oe.primitiveLength),this.shadowCasterSegments=Po.simpleSegment(0,P.primitiveOffset,0,P.primitiveLength)}update(m,x,k,E,P,O,U,H){this.bridgeProgramConfigurations.updatePaintArrays(m,x,P,k,E,O,U,H),this.tunnelProgramConfigurations.updatePaintArrays(m,x,P,k,E,O,U,H)}upload(m){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=m.createVertexBuffer(this.vertexPositions,P4t.members),this.vertexBufferNormal=m.createVertexBuffer(this.vertexNormals,L4t.members),this.indexBuffer=m.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(m),this.tunnelProgramConfigurations.upload(m))}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(m,x,k,E,P){const O=(U,H)=>{for(let X=0;Xie(sn,x[Xs].x,x[Xs].y,k[Xs]*H),ue=Y(),me=Y(),_e=Y(),Se=Y(),Pe=Y(),$e=(sn,Xs)=>{const xn=U.get(Ex.computePosHash(x[Xs])),Os=xn.from,en=xn.to;if(!Os||!en)return;oe(ue,Os),oe(me,Xs),oe(_e,en),je(Se),Ge(ue,me)||(Be(Pe,me,ue),Ie(Se,Pe)),Ge(_e,me)||(Be(Pe,_e,me),he(Se,Se,Ie(Pe,Pe)));const on=We(Se);return on>0?ge(sn,Se,1/on):void 0};let Ke=Number.POSITIVE_INFINITY;this.sortSubarray(E,P.min,P.max,(sn,Xs)=>sn.featureInfo.featureIndex-Xs.featureInfo.featureIndex);const lt=Y(),nt=Y(),pt=Y(),_t=Y(),jt=Y(),Yt=Y(),zt=Y(),Wt=Y(),$t=Y(),Ut=[Y(),Y(),Y(),Y()],Bs=[Y(),Y(),Y(),Y()],qs=[{coord:new Ls(0,0),height:0},{coord:new Ls(0,0),height:0}],Qs=(sn,Xs)=>sn>Xs;for(let sn=P.min;snKe.featureInfo.featureIndex-lt.featureInfo.featureIndex;this.sortSubarray(E,P.min,P.max,H),this.sortSubarray(E,O.min,O.max,H);const X=Ke=>Ie(Ke,Ke),oe=[{coord:new Ls(0,0),height:0},{coord:new Ls(0,0),height:0}],ue=(Ke,lt)=>KeU.hash===H.hash?H.polygonIdx-U.polygonIdx:H.hash>U.hash?1:-1);let k=0,E=0,P=0,O=x[k].polygonIdx;do E++,(E===x.length||x[k].hash!==x[E].hash)&&((E-k===1||x[E-1].polygonIdx!==O)&&(PX.portalHashoe.hash?U++:oe.hash>X.portalHash?H++:(X.type=oe.type,U++)}}}isOnBorder(m,x){return m<=0&&x<=0||m>=$n&&x>=$n}addFeatureSection(m,x,k,E){return m!==x&&(x=m,k.push({featureIndex:m,vertexStart:E.getVertexCount()}),E.clearVertexLookup()),x}sortSubarray(m,x,k,E){const P=m.slice(x,k);P.sort(E),m.splice(x,P.length,...P)}static computeEdgeHash(m,x){return(m.y===x.y&&m.x>x.x||m.y>x.y)&&([m,x]=[x,m]),BigInt(Ex.computePosHash(m))<<32n|BigInt(Ex.computePosHash(x))}static computePosHash(m){return((65535&m.x)<<16|65535&m.y)>>>0}}function G4t(w,m){return w>m?1:w0))return x;x=x.left}}return null}contains(m){for(var x=this._root,k=this._compare;x;){var E=k(m,x.key);if(E===0)return!0;x=E<0?x.left:x.right}return!1}remove(m){var x=this.find(m);if(!x)return!1;if(this.splay(x),x.left)if(x.right){var k=this.minNode(x.right);k.parent!==x&&(this.replace(k,k.right),k.right=x.right,k.right.parent=k),this.replace(x,k),k.left=x.left,k.left.parent=k}else this.replace(x,x.left);else this.replace(x,x.right);return this._size--,!0}removeNode(m){if(!m)return!1;if(this.splay(m),m.left)if(m.right){var x=this.minNode(m.right);x.parent!==m&&(this.replace(x,x.right),x.right=m.right,x.right.parent=x),this.replace(m,x),x.left=m.left,x.left.parent=x}else this.replace(m,m.left);else this.replace(m,m.right);return this._size--,!0}erase(m){var x=this.find(m);if(x){this.splay(x);var k=x.left,E=x.right,P=null;k&&(k.parent=null,P=this.maxNode(k),this.splay(P),this._root=P),E&&(k?P.right=E:this._root=E,E.parent=P),this._size--}}pop(){var m=this._root,x=null;if(m){for(;m.left;)m=m.left;x={key:m.key,data:m.data},this.remove(m.key)}return x}next(m){var x=m;if(x)if(x.right)for(x=x.right;x&&x.left;)x=x.left;else for(x=m.parent;x&&x.right===m;)m=x,x=x.parent;return x}prev(m){var x=m;if(x)if(x.left)for(x=x.left;x&&x.right;)x=x.right;else for(x=m.parent;x&&x.left===m;)m=x,x=x.parent;return x}forEach(m){for(var x=this._root,k=[],E=!1,P=0;!E;)x?(k.push(x),x=x.left):k.length>0?(m(x=k.pop(),P++),x=x.right):E=!0;return this}range(m,x,k,E){const P=[],O=this._compare;let U,H=this._root;for(;P.length!==0||H;)if(H)P.push(H),H=H.left;else{if(H=P.pop(),U=O(H.key,x),U>0)break;if(O(H.key,m)>=0&&k.call(E,H))return this;H=H.right}return this}keys(){for(var m=this._root,x=[],k=[],E=!1;!E;)m?(x.push(m),m=m.left):x.length>0?(m=x.pop(),k.push(m.key),m=m.right):E=!0;return k}values(){for(var m=this._root,x=[],k=[],E=!1;!E;)m?(x.push(m),m=m.left):x.length>0?(m=x.pop(),k.push(m.data),m=m.right):E=!0;return k}at(m){for(var x=this._root,k=[],E=!1,P=0;!E;)if(x)k.push(x),x=x.left;else if(k.length>0){if(x=k.pop(),P===m)return x;P++,x=x.right}else E=!0;return null}load(m=[],x=[],k=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const E=m.length;return k&&$be(m,x,0,E-1,this._compare),this._root=Bbe(null,m,x,0,E),this._size=E,this}min(){var m=this.minNode(this._root);return m?m.key:null}max(){var m=this.maxNode(this._root);return m?m.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(m,x,k,E,P){return new zbe(k,P).load(m,x,E)}}function Bbe(w,m,x,k,E){const P=E-k;if(P>0){const O=k+Math.floor(P/2),U={key:m[O],data:x[O],parent:w};return U.left=Bbe(U,m,x,k,O),U.right=Bbe(U,m,x,O+1,E),U}return null}function $be(w,m,x,k,E){if(x>=k)return;const P=w[x+k>>1];let O=x-1,U=k+1;for(;;){do O++;while(E(w[O],P)<0);do U--;while(E(w[U],P)>0);if(O>=U)break;let H=w[O];w[O]=w[U],w[U]=H,H=m[O],m[O]=m[U],m[U]=H}$be(w,m,x,U,E),$be(w,m,U+1,k,E)}const QDe=11102230246251565e-32,qf=134217729,W4t=(3+8*QDe)*QDe;function Ube(w,m,x,k,E){let P,O,U,H,X=m[0],oe=k[0],ue=0,me=0;oe>X==oe>-X?(P=X,X=m[++ue]):(P=oe,oe=k[++me]);let _e=0;if(ueX==oe>-X?(O=X+P,U=P-(O-X),X=m[++ue]):(O=oe+P,U=P-(O-oe),oe=k[++me]),P=O,U!==0&&(E[_e++]=U);ueX==oe>-X?(O=P+X,H=O-P,U=P-(O-H)+(X-H),X=m[++ue]):(O=P+oe,H=O-P,U=P-(O-H)+(oe-H),oe=k[++me]),P=O,U!==0&&(E[_e++]=U);for(;ue0:(k[0]-m[0])*(x[1]-m[1])-(x[0]-m[0])*(k[1]-m[1])>0}isAbove(m){return!this.isBelow(m)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const m=new q6(this.point,this.left,this.otherEvent,this.isSubject,this.type);return m.contourId=this.contourId,m.resultTransition=this.resultTransition,m.prevInResult=this.prevInResult,m.isExteriorRing=this.isExteriorRing,m.inOut=this.inOut,m.otherInOut=this.otherInOut,m}}function __(w,m){return w[0]===m[0]&&w[1]===m[1]}function qbe(w,m,x){const k=function(E,P,O,U,H,X){const oe=(P-X)*(O-H),ue=(E-H)*(U-X),me=oe-ue;if(oe===0||ue===0||oe>0!=ue>0)return me;const _e=Math.abs(oe+ue);return Math.abs(me)>=33306690738754716e-32*_e?me:-function(Se,Pe,$e,Ke,lt,nt,pt){let _t,jt,Yt,zt,Wt,$t,Ut,Bs,qs,Qs,sn,Xs,xn,Os,en,on,yn,Tn;const or=Se-lt,Fn=$e-lt,On=Pe-nt,En=Ke-nt;Os=or*En,$t=qf*or,Ut=$t-($t-or),Bs=or-Ut,$t=qf*En,qs=$t-($t-En),Qs=En-qs,en=Bs*Qs-(Os-Ut*qs-Bs*qs-Ut*Qs),on=On*Fn,$t=qf*On,Ut=$t-($t-On),Bs=On-Ut,$t=qf*Fn,qs=$t-($t-Fn),Qs=Fn-qs,yn=Bs*Qs-(on-Ut*qs-Bs*qs-Ut*Qs),sn=en-yn,Wt=en-sn,U6[0]=en-(sn+Wt)+(Wt-yn),Xs=Os+sn,Wt=Xs-Os,xn=Os-(Xs-Wt)+(sn-Wt),sn=xn-on,Wt=xn-sn,U6[1]=xn-(sn+Wt)+(Wt-on),Tn=Xs+sn,Wt=Tn-Xs,U6[2]=Xs-(Tn-Wt)+(sn-Wt),U6[3]=Tn;let rr=function(Ni,Aa){let Ci=Aa[0];for(let Ka=1;Ka<4;Ka++)Ci+=Aa[Ka];return Ci}(0,U6),pr=22204460492503146e-32*pt;if(rr>=pr||-rr>=pr||(Wt=Se-or,_t=Se-(or+Wt)+(Wt-lt),Wt=$e-Fn,Yt=$e-(Fn+Wt)+(Wt-lt),Wt=Pe-On,jt=Pe-(On+Wt)+(Wt-nt),Wt=Ke-En,zt=Ke-(En+Wt)+(Wt-nt),_t===0&&jt===0&&Yt===0&&zt===0)||(pr=11093356479670487e-47*pt+W4t*Math.abs(rr),rr+=or*zt+En*_t-(On*Yt+Fn*jt),rr>=pr||-rr>=pr))return rr;Os=_t*En,$t=qf*_t,Ut=$t-($t-_t),Bs=_t-Ut,$t=qf*En,qs=$t-($t-En),Qs=En-qs,en=Bs*Qs-(Os-Ut*qs-Bs*qs-Ut*Qs),on=jt*Fn,$t=qf*jt,Ut=$t-($t-jt),Bs=jt-Ut,$t=qf*Fn,qs=$t-($t-Fn),Qs=Fn-qs,yn=Bs*Qs-(on-Ut*qs-Bs*qs-Ut*Qs),sn=en-yn,Wt=en-sn,Ax[0]=en-(sn+Wt)+(Wt-yn),Xs=Os+sn,Wt=Xs-Os,xn=Os-(Xs-Wt)+(sn-Wt),sn=xn-on,Wt=xn-sn,Ax[1]=xn-(sn+Wt)+(Wt-on),Tn=Xs+sn,Wt=Tn-Xs,Ax[2]=Xs-(Tn-Wt)+(sn-Wt),Ax[3]=Tn;const Vr=Ube(4,U6,4,Ax,XDe);Os=or*zt,$t=qf*or,Ut=$t-($t-or),Bs=or-Ut,$t=qf*zt,qs=$t-($t-zt),Qs=zt-qs,en=Bs*Qs-(Os-Ut*qs-Bs*qs-Ut*Qs),on=On*Yt,$t=qf*On,Ut=$t-($t-On),Bs=On-Ut,$t=qf*Yt,qs=$t-($t-Yt),Qs=Yt-qs,yn=Bs*Qs-(on-Ut*qs-Bs*qs-Ut*Qs),sn=en-yn,Wt=en-sn,Ax[0]=en-(sn+Wt)+(Wt-yn),Xs=Os+sn,Wt=Xs-Os,xn=Os-(Xs-Wt)+(sn-Wt),sn=xn-on,Wt=xn-sn,Ax[1]=xn-(sn+Wt)+(Wt-on),Tn=Xs+sn,Wt=Tn-Xs,Ax[2]=Xs-(Tn-Wt)+(sn-Wt),Ax[3]=Tn;const kr=Ube(Vr,XDe,4,Ax,JDe);Os=_t*zt,$t=qf*_t,Ut=$t-($t-_t),Bs=_t-Ut,$t=qf*zt,qs=$t-($t-zt),Qs=zt-qs,en=Bs*Qs-(Os-Ut*qs-Bs*qs-Ut*Qs),on=jt*Yt,$t=qf*jt,Ut=$t-($t-jt),Bs=jt-Ut,$t=qf*Yt,qs=$t-($t-Yt),Qs=Yt-qs,yn=Bs*Qs-(on-Ut*qs-Bs*qs-Ut*Qs),sn=en-yn,Wt=en-sn,Ax[0]=en-(sn+Wt)+(Wt-yn),Xs=Os+sn,Wt=Xs-Os,xn=Os-(Xs-Wt)+(sn-Wt),sn=xn-on,Wt=xn-sn,Ax[1]=xn-(sn+Wt)+(Wt-on),Tn=Xs+sn,Wt=Tn-Xs,Ax[2]=Xs-(Tn-Wt)+(sn-Wt),Ax[3]=Tn;const Ea=Ube(kr,JDe,4,Ax,eRe);return eRe[Ea-1]}(E,P,O,U,H,X,_e)}(w[0],w[1],m[0],m[1],x[0],x[1]);return k>0?-1:k<0?1:0}function hk(w,m){const x=w.point,k=m.point;return x[0]>k[0]?1:x[0]k[1]?1:-1:function(E,P,O){return E.left!==P.left?E.left?1:-1:qbe(O,E.otherEvent.point,P.otherEvent.point)!==0?E.isBelow(P.otherEvent.point)?-1:1:!E.isSubject&&P.isSubject?1:-1}(w,m,x)}function mk(w,m,x){const k=new q6(m,!1,w,w.isSubject),E=new q6(m,!0,w.otherEvent,w.isSubject);return __(w.point,w.otherEvent.point)&&console.warn("what is that, a collapsed segment?",w),k.contourId=E.contourId=w.contourId,hk(E,w.otherEvent)>0&&(w.otherEvent.left=!0,E.left=!1),w.otherEvent.otherEvent=E,w.otherEvent=k,x.push(E),x.push(k),x}function yq(w,m){return w[0]*m[1]-w[1]*m[0]}function Vbe(w,m){return w[0]*m[0]+w[1]*m[1]}function Hbe(w,m,x){const k=function(H,X,oe,ue){const me=[X[0]-H[0],X[1]-H[1]],_e=[ue[0]-oe[0],ue[1]-oe[1]];function Se(Yt,zt,Wt){return[Yt[0]+zt*Wt[0],Yt[1]+zt*Wt[1]]}const Pe=[oe[0]-H[0],oe[1]-H[1]];let $e=yq(me,_e),Ke=$e*$e;const lt=Vbe(me,me);if(Ke>0){const Yt=yq(Pe,_e)/$e;if(Yt<0||Yt>1)return null;const zt=yq(Pe,me)/$e;return zt<0||zt>1?null:Yt===0||Yt===1?[Se(H,Yt,me)]:zt===0||zt===1?[Se(oe,zt,_e)]:[Se(H,Yt,me)]}if($e=yq(Pe,me),Ke=$e*$e,Ke>0)return null;const nt=Vbe(me,Pe)/lt,pt=nt+Vbe(me,_e)/lt,_t=Math.min(nt,pt),jt=Math.max(nt,pt);return _t<=1&&jt>=0?_t===1?[Se(H,_t>0?_t:0,me)]:jt===0?[Se(H,jt<1?jt:1,me)]:[Se(H,_t>0?_t:0,me),Se(H,jt<1?jt:1,me)]:null}(w.point,w.otherEvent.point,m.point,m.otherEvent.point),E=k?k.length:0;if(E===0||E===1&&(__(w.point,m.point)||__(w.otherEvent.point,m.otherEvent.point))||E===2&&w.isSubject===m.isSubject)return 0;if(E===1)return!__(w.point,k[0])&&!__(w.otherEvent.point,k[0])&&mk(w,k[0],x),!__(m.point,k[0])&&!__(m.otherEvent.point,k[0])&&mk(m,k[0],x),1;const P=[];let O=!1,U=!1;return __(w.point,m.point)?O=!0:hk(w,m)===1?P.push(m,w):P.push(w,m),__(w.otherEvent.point,m.otherEvent.point)?U=!0:hk(w.otherEvent,m.otherEvent)===1?P.push(m.otherEvent,w.otherEvent):P.push(w.otherEvent,m.otherEvent),O&&U||O?(m.type=1,w.type=m.inOut===w.inOut?2:3,O&&!U&&mk(P[1].otherEvent,P[0].point,x),2):U?(mk(P[0],P[1].point,x),3):P[0]!==P[3].otherEvent?(mk(P[0],P[1].point,x),mk(P[1],P[2].point,x),3):(mk(P[0],P[1].point,x),mk(P[3].otherEvent,P[2].point,x),3)}function K4t(w,m){if(w===m)return 0;if(qbe(w.point,w.otherEvent.point,m.point)!==0||qbe(w.point,w.otherEvent.point,m.otherEvent.point)!==0)return __(w.point,m.point)?w.isBelow(m.otherEvent.point)?-1:1:w.point[0]===m.point[0]?w.point[1](m.contourId??0)?1:-1}return hk(w,m)===1?1:-1}class Y4t{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function Z4t(w,m,x,k){let E,P=w+1,O=m[w].point;const U=m.length;for(Pk;)P--;return P}function Q4t(w,m,x){const k=new Y4t;if(w.prevInResult!=null){const E=w.prevInResult,P=E.outputContourId;if(E.resultTransition>0){const O=m[P];if(O.holeOf!=null){const U=O.holeOf;m[U].holeIds.push(x),k.holeOf=U,k.depth=m[P].depth}else m[P].holeIds.push(x),k.holeOf=P,k.depth=m[P].depth+1}else k.holeOf=null,k.depth=m[P].depth}else k.holeOf=null,k.depth=0;return k}const sRe=Math.max,nRe=Math.min;let vq=0;function rRe(w,m,x,k,E,P){let O,U,H,X,oe,ue;for(O=0,U=w.length-1;O0?ue.left=!0:oe.left=!0;const me=H[0],_e=H[1];E[0]=nRe(E[0],me),E[1]=nRe(E[1],_e),E[2]=sRe(E[2],me),E[3]=sRe(E[3],_e),k.push(oe),k.push(ue)}}const bq=[];function aRe(w,m,x){let k=w,E=m;typeof w[0][0][0]=="number"&&(k=[w]),typeof m[0][0][0]=="number"&&(E=[m]);let P=function(me,_e,Se){let Pe=null;return me.length*_e.length===0&&(Se===0?Pe=bq:Se===2?Pe=me:(Se===1||Se===3)&&(Pe=me.length===0?_e:me)),Pe}(k,E,x);if(P)return P===bq?null:P;const O=[1/0,1/0,-1/0,-1/0],U=[1/0,1/0,-1/0,-1/0],H=function(me,_e,Se,Pe,$e){const Ke=new p0(void 0,hk);let lt,nt,pt,_t,jt,Yt;for(pt=0,_t=me.length;pt<_t;pt++)for(lt=me[pt],jt=0,Yt=lt.length;jtPe[2]||Pe[0]>Se[2]||Se[1]>Pe[3]||Pe[1]>Se[3])&&($e===0?Ke=bq:$e===2?Ke=me:($e===1||$e===3)&&(Ke=me.concat(_e))),Ke}(k,E,O,U,x),P)return P===bq?null:P;const X=function(me,_e,Se,Pe,$e,Ke){const lt=new zbe(K4t),nt=[],pt=Math.min(Pe[2],$e[2]);let _t,jt,Yt;for(;me.length!==0;){let zt=me.pop();if(nt.push(zt),Ke===0&&zt.point[0]>pt||Ke===2&&zt.point[0]>Pe[2])break;if(zt.left){jt=_t=lt.insert(zt),Yt=lt.minNode(),_t=_t!==Yt?lt.prev(_t):null,jt=lt.next(jt);const Wt=_t?_t.key:null;let $t;if(hO(zt,Wt,Ke),jt&&Hbe(zt,jt.key,me)===2&&(hO(zt,Wt,Ke),hO(jt.key,zt,Ke)),_t&&Hbe(_t.key,zt,me)===2){let Ut=_t;Ut=Ut!==Yt?lt.prev(Ut):null,$t=Ut?Ut.key:null,hO(Wt,$t,Ke),hO(zt,Wt,Ke)}}else zt=zt.otherEvent,jt=_t=lt.find(zt),_t&&jt&&(_t=_t!==Yt?lt.prev(_t):null,jt=lt.next(jt),lt.remove(zt),jt&&_t&&Hbe(_t.key,jt.key,me))}return nt}(H,0,0,O,U,x),oe=function(me){let _e,Se;const Pe=function(lt){let nt,pt,_t,jt,Yt;const zt=[];for(pt=0,_t=lt.length;pt<_t;pt++)nt=lt[pt],(nt.left&&nt.inResult||!nt.left&&nt.otherEvent.inResult)&&zt.push(nt);let Wt=!1;for(;!Wt;)for(Wt=!0,pt=0,_t=zt.length;pt<_t;pt++)pt+1<_t&&hk(zt[pt],zt[pt+1])===1&&(jt=zt[pt],zt[pt]=zt[pt+1],zt[pt+1]=jt,Wt=!1);for(pt=0,_t=zt.length;pt<_t;pt++)nt=zt[pt],nt.otherPos=pt;for(pt=0,_t=zt.length;pt<_t;pt++)nt=zt[pt],nt.left||(Yt=nt.otherPos,nt.otherPos=nt.otherEvent.otherPos,nt.otherEvent.otherPos=Yt);return zt}(me),$e={},Ke=[];for(_e=0,Se=Pe.length;_e{$e[Yt]=!0,Yt=Pe.length)&&Pe[_t];);Ke.push(nt)}return Ke}(X),ue=[];for(let me=0;me{O.push(new Ls(ue,H+(ue-U)/(X-U)*(oe-H)))}:(O,U,H,X,oe,ue)=>{O.push(new Ls(U+(ue-H)/(oe-H)*(X-U),ue))};for(const O of w){const U=[];for(const H of O){if(H.length<=2)continue;const X=[];for(let me=0;mem&&P(X,_e,Se,Pe,$e,m):Ke>x?lt=m&&P(X,_e,Se,Pe,$e,m),lt>x&&Ke<=x&&P(X,_e,Se,Pe,$e,x)}let oe=H[H.length-1];const ue=k===0?oe.x:oe.y;ue>=m&&ue<=x&&X.push(oe),X.length&&(oe=X[X.length-1],X[0].x===oe.x&&X[0].y===oe.y||X.push(X[0]),U.push(X))}U.length&&E.push(U)}return E}function X4t(w,m){const x=aRe(Gbe(w),Gbe([m]),0);return x==null?[]:iRe(x)}function J4t(w,m,x=0){let E=Gbe(w,65536);const P=[];for(;m.valid();m.next()){const[O,U]=m.get();let H=O.x*65536,X=O.y*65536,oe=U.x*65536,ue=U.y*65536;const me=oe-H,_e=ue-X,Se=Math.hypot(me,_e);if(Se===0)continue;H-=me*x,X-=_e*x,oe+=me*x,ue+=_e*x;const Pe=Math.trunc(_e/Se*3),$e=-Math.trunc(me/Se*3);P.push([[[H,X],[oe,ue],[oe+Pe,ue+$e],[H+Pe,X+$e],[H,X]]])}return P.length>0&&(E=aRe(E,P,2)),iRe(E,1/65536,128)}function Gbe(w,m=1){return[w.map(x=>x.map(k=>[k.x*m,k.y*m]))]}function iRe(w,m=1,x){return w.map(k=>k.map((E,P)=>{const O=E.map(U=>{let H=U[0],X=U[1];return x&&(H=Math.round(H/x)*x,X=Math.round(X/x)*x),new Ls(H*m,X*m)._round()});return P>0&&O.reverse(),O}))}class Wbe{constructor(m,x){this.layoutVertexArray=new Ha,this.indexArray=new sc,this.lineIndexArray=new bg,this.triangleSegments=new Po,this.lineSegments=new Po,this.programConfigurations=new Ue(m.layers,{zoom:m.zoom,lut:m.lut}),this.uploaded=!1,x&&(this.elevatedLayoutVertexArray=new ro)}update(m,x,k,E,P,O,U,H){this.programConfigurations.updatePaintArrays(m,x,P,k,E,O,U,H)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(m){this.uploaded||(this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,M4t.members),this.indexBuffer=m.createIndexBuffer(this.indexArray),this.lineIndexBuffer=m.createIndexBuffer(this.lineIndexArray),this.elevatedLayoutVertexArray&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=m.createVertexBuffer(this.elevatedLayoutVertexArray,I4t.members))),this.programConfigurations.upload(m),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(m,x,k,E,P,O,U){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,m,x,k,E,P,O,void 0,U)}}class wq{constructor(m){this.zoom=m.zoom,this.pixelRatio=m.pixelRatio,this.overscaling=m.overscaling,this.layers=m.layers,this.layerIds=this.layers.map(x=>x.fqid),this.index=m.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=m.lut,this.bufferData=new Wbe(m,!1),this.elevationBufferData=new Wbe(m,!0),this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.projection=m.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=m.sourceLayerIndex,this.worldview=m.worldview,this.hasAppearances=null}updateFootprints(m,x){}updateAppearances(m,x,k,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,E){this.hasPattern=Obe("fill",this.layers,this.pixelRatio,x);const P=this.layers[0].layout.get("fill-sort-key"),O=[];for(const{feature:U,id:H,index:X,sourceLayerIndex:oe}of m){const ue=this.layers[0]._featureFilter.needGeometry,me=Wa(U,ue);if(!this.layers[0]._featureFilter.filter(new La(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),me,k))continue;const _e=P?P.evaluate(me,{},k,x.availableImages):void 0,Se={id:H,properties:U.properties,type:U.type,sourceLayerIndex:oe,index:X,geometry:ue?me.geometry:Gr(U,k,E),patterns:{},sortKey:_e};O.push(Se)}P&&O.sort((U,H)=>U.sortKey-H.sortKey);for(const U of O){const{geometry:H,index:X,sourceLayerIndex:oe}=U;if(this.hasPattern){const ue=Fbe("fill",this.layers,U,this.zoom,this.pixelRatio,x);this.patternFeatures.push(ue)}else this.addFeature(U,H,X,k,{},x.availableImages,x.brightness,x.elevationFeatures);x.featureIndex.insert(m[X].feature,H,X,oe,this.index)}}update(m,x,k,E,P,O,U){this.bufferData.update(m,x,k,E,P,O,U,this.worldview),this.elevationBufferData.update(m,x,k,E,P,O,U,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(m,x,k,E,P,O,U,this.worldview)}addFeatures(m,x,k,E,P,O){for(const U of this.patternFeatures)this.addFeature(U,U.geometry,U.index,x,k,E,O,m.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(m){this.bufferData.upload(m),this.elevationBufferData.upload(m),this.elevatedStructures&&this.elevatedStructures.upload(m)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(m,x,k,E,P,O=[],U,H){const X=dO(x,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(m,X,E,k,H):this.addGeometry(X,this.bufferData),this.bufferData.populatePaintArrays(m,k,P,O,E,U,this.worldview),this.elevationBufferData.populatePaintArrays(m,k,P,O,E,U,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(m,x,k,E,P){this.elevatedStructures&&(this.elevatedStructures.construct(m),this.elevatedStructures.populatePaintArrays(x,k,E,P,this.worldview))}addElevatedRoadFeature(m,x,k,E,P){const O=new Array,U=Bo.getElevationFeature(m,P);if(!U)return void this.addGeometry(x,this.bufferData);{const X=this.clipPolygonsToTile(x,1);X.length>0&&O.push({polygons:X,elevationFeature:U,elevationTileID:k})}const H={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(m,{},k),featureIndex:E};for(const X of O)if(X.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new Ex(X.elevationTileID,this.layers,this.zoom,this.lut));const ue=X.elevationFeature.isTunnel();let me=0;m.properties.hasOwnProperty(Do)&&(me=+m.properties[Do]),this.elevatedStructures.addPortalCandidates(X.elevationFeature.id,X.polygons,ue,X.elevationFeature,me)}X.elevationFeature.constantHeight==null&&(X.polygons=this.prepareElevatedPolygons(X.polygons,X.elevationFeature,X.elevationTileID));const oe=new Ko(k,X.elevationTileID);this.addElevatedGeometry(X.polygons,oe,X.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,E,H)}}addElevatedGeometry(m,x,k,E,P,O){const U={elevation:k,elevationSampler:x,bias:E,index:P,featureInfo:O},[H,X]=this.addGeometry(m,this.elevationBufferData,U);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:H,max:X}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,H),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,X))}addGeometry(m,x,k){let E=Number.POSITIVE_INFINITY,P=Number.NEGATIVE_INFINITY,O=null;k&&(O=k.elevationSampler.constantElevation(k.elevation,k.bias),O!=null&&(E=O,P=O));const U=(H,X,oe)=>{if(k!=null)if(X.push(H),O!=null)x.elevatedLayoutVertexArray.emplaceBack(O),oe.push(O);else{const ue=k.elevationSampler.pointElevation(H,k.elevation,k.bias);x.elevatedLayoutVertexArray.emplaceBack(ue),oe.push(ue),E=Math.min(E,ue),P=Math.max(P,ue)}};for(const H of m){let X=0;for(const nt of H)X+=nt.length;const oe=x.triangleSegments.prepareSegment(X,x.layoutVertexArray,x.indexArray),ue=oe.vertexLength,me=[],_e=[],Se=[],Pe=[],$e=[],Ke=x.layoutVertexArray.length;for(const nt of H){if(nt.length===0)continue;nt!==H[0]&&_e.push(me.length/2);const pt=x.lineSegments.prepareSegment(nt.length,x.layoutVertexArray,x.lineIndexArray),_t=pt.vertexLength;k&&$e.push(x.layoutVertexArray.length-Ke),U(nt[0],Se,Pe),x.layoutVertexArray.emplaceBack(nt[0].x,nt[0].y),x.lineIndexArray.emplaceBack(_t+nt.length-1,_t),me.push(nt[0].x),me.push(nt[0].y);for(let jt=1;jt0&&k&&this.elevationMode==="hd-road-base"){const nt=k.elevation.isTunnel(),pt=k.elevation.safeArea,_t=this.elevatedStructures.addVertices(Se,Pe);this.elevatedStructures.addTriangles(lt,_t,nt);const jt=$e.length;if(jt>0){for(let Yt=0;Yt=k&&_e.max.x<=P&&_e.min.y>=E&&_e.max.y<=O?H:X).push(me)}if(H.length===m.length)return m;const oe=[new Ls(k,E),new Ls(P,E),new Ls(P,O),new Ls(k,O),new Ls(k,E)],ue=H;for(const me of X)ue.push(...X4t(me,oe));return ue}}let oRe,lRe,cRe,dRe;Kn(wq,"FillBucket",{omit:["layers","patternFeatures"]}),Kn(Wbe,"FillBufferData"),Kn(Ex,"ElevatedStructures");class jq{constructor(m,x,k,E){if(this.triangleCount=x.length/3,this.min=new Ls(0,0),this.max=new Ls(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],this.triangleCount===0||m.length===0)return;const[P,O]=[m[0].clone(),m[0].clone()];for(let ue=1;ueue.cellIdx-me.cellIdx||ue.triIdx-me.triIdx);let oe=0;for(;oethis.max.x||this.min.x>m.x||m.y>this.max.y||this.min.y>m.y)return;const k=w_(m.x-this.min.x,this.xScale,this.cellsX),E=w_(m.y-this.min.y,this.yScale,this.cellsY),P=this.cells[E*this.cellsX+k];if(P){this._lazyInitLookup();for(let O=0;Othis.max.x||this.min.x>x.x||m.y>this.max.y||this.min.y>x.y)return;this._lazyInitLookup();const E=w_(m.x-this.min.x,this.xScale,this.cellsX),P=w_(x.x-this.min.x,this.xScale,this.cellsX),O=w_(m.y-this.min.y,this.yScale,this.cellsY),U=w_(x.y-this.min.y,this.yScale,this.cellsY);for(let H=O;H<=U;H++)for(let X=E;X<=P;X++){const oe=this.cells[H*this.cellsX+X];if(oe)for(let ue=0;uex.fqid),this.index=m.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.footprints=[],this.worldview=m.worldview,this.hasAppearances=null}updateFootprints(m,x){for(const k of this.footprints)x.push({footprint:k,id:m})}updateAppearances(m,x,k,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,E){const P=[];for(const{feature:O,id:U,index:H,sourceLayerIndex:X}of m){const oe=this.layers[0]._featureFilter.needGeometry,ue=Wa(O,oe);if(!this.layers[0]._featureFilter.filter(new La(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),ue,k))continue;const me={id:U,properties:O.properties,type:O.type,sourceLayerIndex:X,index:H,geometry:oe?ue.geometry:Gr(O,k,E),patterns:{}};P.push(me)}for(const O of P){const{geometry:U,index:H,sourceLayerIndex:X}=O;this.addFeature(O,U,H,k,{},x.availableImages,x.brightness),x.featureIndex.insert(m[H].feature,U,H,X,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(m){}update(m,x,k,E,P,O,U){}destroy(){}addFeature(m,x,k,E,P,O=[],U){for(const H of dO(x,2)){const X=[],oe=[],ue=[],me=new Ls(1/0,1/0),_e=new Ls(-1/0,-1/0);for(const $e of H)if($e.length!==0){$e!==H[0]&&ue.push(oe.length/2);for(let Ke=0;Ke<$e.length;Ke++)oe.push($e[Ke].x),oe.push($e[Ke].y),X.push($e[Ke]),me.x=Math.min(me.x,$e[Ke].x),me.y=Math.min(me.y,$e[Ke].y),_e.x=Math.max(_e.x,$e[Ke].x),_e.y=Math.max(_e.y,$e[Ke].y)}const Se=B6(oe,ue),Pe=new jq(X,Se,8,256);this.footprints.push({vertices:X,indices:Se,grid:Pe,min:me,max:_e})}}}Kn(uRe,"ClipBucket",{omit:["layers"]});const eCt=cn([{name:"a_pos_normal_ed",components:4,type:"Int16"}]),tCt=cn([{name:"a_pos_end",components:4,type:"Int16"},{name:"a_angular_offset_factor",components:1,type:"Int16"}]),sCt=cn([{name:"a_flood_light_ground_radius",components:1,type:"Float32"}]),nCt=cn([{name:"a_centroid_pos",components:2,type:"Uint16"}]),rCt=cn([{name:"a_join_normal_inside",components:3,type:"Int16"}]),aCt=cn([{name:"a_hidden_by_landmark",components:1,type:"Uint8"}]),iCt=cn([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]),{members:oCt}=eCt,mO=Number.MAX_SAFE_INTEGER,lCt=mO-1;function hRe(w,m,x,k){return w.orderm.max.x||w.max.xm.max.y||w.max.ynew Ls((H.x+P.x*$n)*U-O.x*$n,(H.y+P.y*$n)*U-O.y*$n))}return Ybe(x,E,w.indices,0,w.indices.length,0,0)}function xRe(w,m,x,k){const E=Math.pow(2,k.z-x.z);return new Ls((w+x.x*$n)*E-k.x*$n,(m+x.y*$n)*E-k.y*$n)}function gRe(w,m){const x=[];m.grid.queryPoint(w,x);const k=m.indices,E=m.vertices;for(let P=0;P0&&(k.length>1&&x.push(k),k=[])}return k.length>1&&x.push(k),x}const Qbe=va.types,dCt=["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"],uCt=["fill-extrusion-flood-light-ground-radius"],hCt=Math.pow(2,13),mCt=Math.pow(2,15)-1,Cq=new Ls(0,1),Qj=2147483648,Tq=1073741824;function pO(w,m,x,k,E,P,O,U){w.emplaceBack((m<<1)+O,(x<<1)+P,(Math.floor(k*hCt)<<1)+E,Math.round(U))}function fO(w,m,x){w.emplaceBack(m.x*$n,m.y*$n,x?1:0)}function Eq(w,m,x,k,E,P){w.emplaceBack(m.x,m.y,(x.x<<1)+k,(x.y<<1)+E,P)}function xO(w,m,x){w.emplaceBack(m.x,m.y,m.z,x[0]*16384,x[1]*16384,x[2]*16384)}class vRe{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class Xbe{constructor(){this.centroidXY=new Ls(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 Ls(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new Ls(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0,this.groupCentroidPos=new Ls(0,0)}span(){return new Ls(this.max.x-this.min.x,this.max.y-this.min.y)}}class Jbe{constructor(){this.acc=new Ls(0,0),this.accCount=0,this.centroidDataIndex=0}startRing(m,x){m.min.x===Number.MAX_VALUE&&(m.min.x=m.max.x=x.x,m.min.y=m.max.y=x.y)}appendEdge(m,x,k){this.accCount++,this.acc._add(x);let E=!!this.borders;x.xm.max.x&&(m.max.x=x.x,E=!0),x.ym.max.y&&(m.max.y=x.y,E=!0),((x.x===0||x.x===$n)&&x.x===k.x)!=((x.y===0||x.y===$n)&&x.y===k.y)&&this.processBorderOverlap(x,k),E&&this.checkBorderIntersection(x,k)}checkBorderIntersection(m,x){x.x<0!=m.x<0&&this.addBorderIntersection(0,zr(x.y,m.y,(0-x.x)/(m.x-x.x))),x.x>$n!=m.x>$n&&this.addBorderIntersection(1,zr(x.y,m.y,($n-x.x)/(m.x-x.x))),x.y<0!=m.y<0&&this.addBorderIntersection(2,zr(x.x,m.x,(0-x.y)/(m.y-x.y))),x.y>$n!=m.y>$n&&this.addBorderIntersection(3,zr(x.x,m.x,($n-x.y)/(m.y-x.y)))}addBorderIntersection(m,x){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 k=this.borders[m];xk[1]&&(k[1]=x)}processBorderOverlap(m,x){if(m.x===x.x){if(m.y===x.y)return;const k=m.x===0?0:1;this.addBorderIntersection(k,x.y),this.addBorderIntersection(k,m.y)}else{const k=m.y===0?2:3;this.addBorderIntersection(k,x.x),this.addBorderIntersection(k,m.x)}}centroid(){return this.accCount===0?new Ls(0,0):new Ls(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((m,x)=>m+ +(x[0]!==Number.MAX_VALUE),0):0}}function bRe(w,m){const x=w.add(m)._unit(),k=Xe(w.x*x.x+w.y*x.y,-1,1);var E,P,O;return O=Math.acos(k),Math.min(4,Math.max(-4,Math.tan(O)))/4*mCt*((E=w).x*(P=m).y-E.y*P.x<0?-1:1)}const pCt=[w=>w.x<0,w=>w.x>$n,w=>w.y<0,w=>w.y>$n];function fCt(w,m,x,k){const E=[4];if(k===0)return E;x._mult(k);const P=w.sub(x),O=m.sub(x),U=[w,m,P,O];for(let H=0;H<4;H++)for(const X of U)if(pCt[H](X)){E.push(H);break}return E}class e_e{constructor(m){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new FC,this.indexArray=new sc,this.programConfigurations=new Ue(m.layers,{zoom:m.zoom,lut:m.lut},x=>uCt.includes(x)),this._segments=new Po,this.hiddenByLandmarkVertexArray=new D6,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Po}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(m,x,k,E=!1){const P=m.length;if(P>2){let O=Math.max(0,this._segments.get().length-1);const U=this._segments._prepareSegment(4*P,this.vertexArray.length,2*this._segmentToGroundQuads[O].length);let H;O!==this._segments.get().length-1&&(O++,this._segmentToGroundQuads[O]=[],this._segmentToRegionTriCounts[O]=[0,0,0,0,0]);{const X=m[0],oe=m[1];H=bRe(X.sub(m[P-1])._perp()._unit(),oe.sub(X)._perp()._unit())}for(let X=0;XE.region-P.region);for(let k=0;kH+X,0);let U=0;for(let H=0;H<=4;H++){const X=O[H];if(X!==0){let oe=this.regionSegments[H];oe||(oe=this.regionSegments[H]=new Po);const ue={vertexOffset:P.vertexOffset,primitiveOffset:P.primitiveOffset+U,vertexLength:P.vertexLength,primitiveLength:X};oe.get().push(ue)}U+=X}for(let H=0;H0?this.hiddenByLandmarkVertexBuffer=m.createVertexBuffer(this.hiddenByLandmarkVertexArray,aCt.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 m=0;m<=4;m++){const x=this.regionSegments[m];x&&x.destroy()}}}}class Aq{constructor(m){this.zoom=m.zoom,this.canonical=m.canonical,this.overscaling=m.overscaling,this.layers=m.layers,this.pixelRatio=m.pixelRatio,this.layerIds=this.layers.map(x=>x.fqid),this.index=m.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=m.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=[],this.footprintIndices=new sc,this.footprintVertices=new Ha,this.footprintSegments=[],this.layoutVertexArray=new yg,this.centroidVertexArray=new cq,this.wallVertexArray=new eO,this.indexArray=new sc,this.programConfigurations=new Ue(m.layers,{zoom:m.zoom,lut:m.lut},x=>dCt.includes(x)),this.segments=new Po,this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.groundEffect=new e_e(m),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=m.worldview,this.hasAppearances=null}updateFootprints(m,x){}updateAppearances(m,x,k,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,E){this.features=[],this.hasPattern=Obe("fill-extrusion",this.layers,this.pixelRatio,x),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=dn(k),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:P,id:O,index:U,sourceLayerIndex:H}of m){const X=this.layers[0]._featureFilter.needGeometry,oe=Wa(P,X);if(!this.layers[0]._featureFilter.filter(new La(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),oe,k))continue;const ue={id:O,sourceLayerIndex:H,index:U,geometry:X?oe.geometry:Gr(P,k,E),properties:P.properties,type:P.type,patterns:{}},me=this.layoutVertexArray.length,_e=Qbe[ue.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:P.id,feature:Fbe("fill-extrusion",this.layers,ue,this.zoom,this.pixelRatio,x)});else if(this.wallMode)for(const Se of ue.geometry)for(const Pe of yRe(Se,_e))this.addFeature(P.id,ue,[Pe],U,k,{},x.availableImages,E,x.brightness);else this.addFeature(P.id,ue,ue.geometry,U,k,{},x.availableImages,E,x.brightness);x.featureIndex.insert(P,ue.geometry,U,H,this.index,me)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(m,x,k,E,P,O){for(const{featureId:U,feature:H}of this.features){const X=Qbe[H.type]==="Polygon",{geometry:oe}=H;if(this.wallMode)for(const ue of oe)for(const me of yRe(ue,X))this.addFeature(U,H,[me],H.index,x,k,E,P,O);else this.addFeature(U,H,oe,H.index,x,k,E,P,O)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(m,x,k,E,P,O,U){this.programConfigurations.updatePaintArrays(m,x,P,k,E,O,U,this.worldview),this.groundEffect.update(m,x,P,k,E,O,U,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(m){this.uploaded||(this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,oCt),this.indexBuffer=m.createIndexBuffer(this.indexArray),this.wallVertexBuffer=m.createVertexBuffer(this.wallVertexArray,rCt.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=m.createVertexBuffer(this.layoutVertexExtArray,iCt.members,!0)),this.groundEffect.upload(m)),this.groundEffect.uploadPaintProperties(m),this.programConfigurations.upload(m),this.uploaded=!0}uploadCentroid(m){this.groundEffect.uploadHiddenByLandmark(m),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=m.createVertexBuffer(this.centroidVertexArray,nCt.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(m,x,k,E,P,O,U,H,X){const oe=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(x,{})/this.tileToMeter,ue=[new Ls(0,0),new Ls($n,$n)],me=H.projection,_e=me.name==="globe",Se=this.wallMode||Qbe[x.type]==="Polygon",Pe=new Jbe;Pe.centroidDataIndex=this.centroidData.length;const $e=new Xbe;$e.buildingId=m,x.properties&&x.properties.hasOwnProperty("building_id")&&($e.buildingId=Number(x.properties.building_id)),Pe.buildingId=$e.buildingId;const Ke=this.layers[0].paint.get("fill-extrusion-base").evaluate(x,{},P)<=0,lt=this.layers[0].paint.get("fill-extrusion-height").evaluate(x,{},P);let nt;if($e.height=lt,$e.vertexArrayOffset=this.layoutVertexArray.length,$e.groundVertexArrayOffset=this.groundEffect.vertexArray.length,_e&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new E6),this.wallMode){if(_e)return void nr("Non zero fill-extrusion-line-width is not yet supported on globe.");if(k.length!==1)return;nt=function($t){const Ut=$t[0].x===$t[$t.length-1].x&&$t[0].y===$t[$t.length-1].y;(function(On){let En=0;const rr=On.length;for(let pr=0;pr=0})($t)||($t=$t.reverse());const qs={geometry:[],joinNormals:[],indices:[]},Qs=[],sn=[],Xs=[];let xn=$t.length;for(;xn>=2&&$t[xn-1].equals($t[xn-2]);)xn--;if(xn<(Ut?3:2))return qs;let Os,en,on,yn,Tn,or=0;for(;or0;let kr="miter";const Ea=2;kr==="miter"&&pr>Ea&&(kr="bevel"),kr==="bevel"&&(pr>100&&(kr="flipbevel"),pr{const Ji=new Ls(Aa.x,Aa.y),Di=new Ls(Aa.x,Aa.y);Ji.x+=Ci.x*Ol,Ji.y+=Ci.y*Ol,Di.x-=Ci.x*Math.max(Ka,1),Di.y-=Ci.y*Math.max(Ka,1),Xs.push(Ci),Qs.push(Ji),sn.push(Di)};if(kr==="miter")En._mult(pr),Ni(Os,En,0,0);else if(kr==="flipbevel")En=Tn.mult(-1),Ni(Os,En,0,0),Ni(Os,En.mult(-1),0,0);else{const Aa=-Math.sqrt(pr*pr-1),Ci=Vr?Aa:0,Ka=Vr?0:Aa;en&&Ni(Os,yn,Ci,Ka),on&&Ni(Os,Tn,Ci,Ka)}}qs.geometry=[...Qs,...sn.reverse(),Qs[0]],qs.joinNormals=[...Xs,...Xs.reverse(),Xs[Xs.length-1]];const Fn=qs.geometry.length-1;for(let On=0;On$t<(Ut.length-1)/2||$t===Ut.length-1,_t=this.wallMode?[k]:dO(k,500);for(let $t=_t.length-1;$t>=0;$t--){const Ut=_t[$t];(Ut.length===0||gCt(Ut[0]))&&_t.splice($t,1)}let jt;if(_e)jt=CRe(_t,ue,P);else{jt=[];for(const $t of _t)jt.push({polygon:$t,bounds:ue})}const Yt=Se?this.edgeRadius:0,zt=Yt>0&&this.zoom<17,Wt=($t,Ut)=>{if($t.length===0)return!1;const Bs=$t[$t.length-1];return Ut.x===Bs.x&&Ut.y===Bs.y};for(const{polygon:$t,bounds:Ut}of jt){let Bs=0,qs=0;for(const xn of $t)Se&&!xn[0].equals(xn[xn.length-1])&&xn.push(xn[0]),qs+=Se?xn.length-1:xn.length;const Qs=this.segments.prepareSegment((Se?5:4)*qs,this.layoutVertexArray,this.indexArray);$e.footprintSegIdx<0&&($e.footprintSegIdx=this.footprintSegments.length),$e.polygonSegIdx<0&&($e.polygonSegIdx=this.polygonSegments.length);const sn={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},Xs=new vRe;if(Xs.vertexOffset=this.footprintVertices.length,Xs.indexOffset=3*this.footprintIndices.length,Xs.ringIndices=[],Se){const xn=[],Os=[];Bs=Qs.vertexLength;for(let on=0;on<$t.length;on++){const yn=$t[on];yn.length&&on!==0&&Os.push(xn.length/2);const Tn=[];let or,Fn;or=yn[1].sub(yn[0])._perp()._unit(),Xs.ringIndices.push(yn.length-1);for(let On=1;On4&&NRe(Os[Os.length-2],Os[0],Os[1]),on=Yt?xCt(Os[Os.length-2],Os[0],Os[1],Yt):0;const yn=[];let Tn,or,Fn;or=Os[1].sub(Os[0])._perp()._unit();let On=!0;for(let En=1,rr=0;En0?1:0,Ci=pr.dist(Vr);if(rr+Ci>32768&&(rr=0),Yt){Fn=kr.sub(Vr)._perp()._unit();let Di=wRe(pr,Vr,kr,_Re(or,Fn),Yt);isNaN(Di)&&(Di=0);const Ro=Vr.sub(pr)._unit();pr=pr.add(Ro.mult(on))._round(),Vr=Vr.add(Ro.mult(-Di))._round(),on=Di,or=Fn,Ke&&this.zoom>=17&&(Wt(yn,pr)||yn.push(pr),Wt(yn,Vr)||yn.push(Vr))}const Ka=Qs.vertexLength,Ol=Os.length>4&&NRe(pr,Vr,kr);let Ji=kRe(rr,en,On);if(pO(this.layoutVertexArray,pr.x,pr.y,Ni,Aa,0,0,Ji),pO(this.layoutVertexArray,pr.x,pr.y,Ni,Aa,0,1,Ji),this.wallMode){const Di=pt(En-1,Os),Ro=nt.joinNormals[En-1];fO(this.wallVertexArray,Ro,Di),fO(this.wallVertexArray,Ro,Di)}if(rr+=Ci,Ji=kRe(rr,Ol,!On),en=Ol,pO(this.layoutVertexArray,Vr.x,Vr.y,Ni,Aa,0,0,Ji),pO(this.layoutVertexArray,Vr.x,Vr.y,Ni,Aa,0,1,Ji),this.wallMode){const Di=pt(En,Os),Ro=nt.joinNormals[En];fO(this.wallVertexArray,Ro,Di),fO(this.wallVertexArray,Ro,Di)}if(Qs.vertexLength+=4,this.indexArray.emplaceBack(Ka+0,Ka+1,Ka+2),this.indexArray.emplaceBack(Ka+1,Ka+3,Ka+2),Qs.primitiveLength+=2,Yt){const Di=Bs+(En===1?Os.length-2:En-2),Ro=En===1?Bs:Di+1;if(this.indexArray.emplaceBack(Ka+1,Di,Ka+3),this.indexArray.emplaceBack(Di,Ro,Ka+3),Qs.primitiveLength+=2,Tn===void 0&&(Tn=Ka),!t_e(kr,Os[En],Ut)){const Il=En===Os.length-1?Tn:Qs.vertexLength;this.indexArray.emplaceBack(Ka+2,Ka+3,Il),this.indexArray.emplaceBack(Ka+3,Il+1,Il),this.indexArray.emplaceBack(Ka+3,Ro,Il+1),Qs.primitiveLength+=3}On=!On}if(_e){const Di=this.layoutVertexExtArray,Ro=me.projectTilePoint(pr.x,pr.y,P),Il=me.projectTilePoint(Vr.x,Vr.y,P),Qd=me.upVector(P,pr.x,pr.y),Pl=me.upVector(P,Vr.x,Vr.y);xO(Di,Ro,Qd),xO(Di,Ro,Qd),xO(Di,Il,Pl),xO(Di,Il,Pl)}}Se&&(Bs+=Os.length-1),Ke&&Yt&&this.zoom>=17&&(yn.length!==0&&Wt(yn,yn[0])&&yn.pop(),this.groundEffect.addData(yn,Ut,oe,Yt>0))}this.footprintSegments.push(Xs),sn.triangleCount=this.indexArray.length-sn.triangleArrayOffset,this.polygonSegments.push(sn),++$e.footprintSegLen,++$e.polygonSegLen}if($e.vertexCount=this.layoutVertexArray.length-$e.vertexArrayOffset,$e.groundVertexCount=this.groundEffect.vertexArray.length-$e.groundVertexArrayOffset,$e.vertexCount!==0){if($e.centroidXY=Pe.borders?Cq:this.encodeCentroid(Pe,$e),x.properties&&x.properties.hasOwnProperty("building_id")){const $t=$e.buildingId;let Ut=this.buildingGroups.get($t);Ut||(Ut={accX:0,accY:0,accCount:0,mergedMin:new Ls(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new Ls(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set($t,Ut)),Ut.accX+=Pe.acc.x,Ut.accY+=Pe.acc.y,Ut.accCount+=Pe.accCount,Ut.mergedMin.x=Math.min(Ut.mergedMin.x,$e.min.x),Ut.mergedMin.y=Math.min(Ut.mergedMin.y,$e.min.y),Ut.mergedMax.x=Math.max(Ut.mergedMax.x,$e.max.x),Ut.mergedMax.y=Math.max(Ut.mergedMax.y,$e.max.y),Ut.partIndices.push(this.centroidData.length)}if(this.centroidData.push($e),Pe.borders){this.featuresOnBorder.push(Pe);const $t=this.featuresOnBorder.length-1;for(let Ut=0;Utthis.featuresOnBorder[x].borders[m][0]-this.featuresOnBorder[k].borders[m][0])}splitToSubtiles(){const m=[];for(let U=0;U$n),oe=2*X+(+(H.min.x+H.max.x>$n)^X);for(let ue=0;ueU.triangleSegmentIdx===H.triangleSegmentIdx?U.subtile-H.subtile:U.triangleSegmentIdx-H.triangleSegmentIdx);let k=0,E=0,P=0;for(const U of m){if(U.triangleSegmentIdx!==k)break;P++}const O=m.length;for(;E!==m.length;){k=m[E].triangleSegmentIdx;let U=0,H=E,X=E;for(let oe=H;oe0&&this.triangleSubSegments.push({segment:_e,min:ue,max:me}),H=X;for(let Se=H;Se[Pe[0]*(1-Ke[0])+$e[0]*Ke[0],Pe[1]*(1-Ke[1])+$e[1]*Ke[1]],_e=[],Se=[];for(const Pe of this.triangleSubSegments){_e[0]=Pe.min.x/$n,_e[1]=Pe.min.y/$n,Se[0]=Pe.max.x/$n,Se[1]=Pe.max.y/$n;const $e=me(oe,ue,_e),Ke=me(oe,ue,Se);if(new so([$e[0],$e[1],P],[Ke[0],Ke[1],O]).intersectsPrecise(k)===0){X&&(E.segments.push(X),X=void 0);continue}const lt=Pe.segment;X&&X.vertexOffset!==lt.vertexOffset&&(E.segments.push(X),X=void 0),X?(X.vertexLength+=lt.vertexLength,X.primitiveLength+=lt.primitiveLength):X={vertexOffset:lt.vertexOffset,primitiveLength:lt.primitiveLength,vertexLength:lt.vertexLength,primitiveOffset:lt.primitiveOffset,sortKey:void 0,vaos:{}}}return X&&E.segments.push(X),E}encodeCentroid(m,x){const k=m.centroid(),E=x.span(),P=Math.min(7,Math.round(E.x*this.tileToMeter/10)),O=Math.min(6,Math.round(E.y*this.tileToMeter/10));return new Ls(Xe(k.x,1,8191)<<3|P,Xe(k.y,1,8191)<<3|O)}encodeBorderCentroid(m){if(!m.borders)return new Ls(0,0);const x=m.borders,k=Number.MAX_VALUE;if(x[0][0]!==k||x[1][0]!==k){const E=x[0][0]!==k?0:1;return new Ls(6|(x[0][0]!==k?0:65528),(x[E][0]+x[E][1])/2<<3|6)}{const E=x[2][0]!==k?2:3;return new Ls((x[E][0]+x[E][1])/2<<3|6,6|(x[2][0]!==k?0:65528))}}showCentroid(m){const x=this.centroidData[m.centroidDataIndex];if(x.flags&=Qj,x.groupCentroidPos.x!==0||x.groupCentroidPos.y!==0){const k=x.span(),E=Math.min(7,Math.round(k.x*this.tileToMeter/10)),P=Math.min(6,Math.round(k.y*this.tileToMeter/10));x.centroidXY=new Ls(Xe(x.groupCentroidPos.x,1,8191)<<3|E,Xe(x.groupCentroidPos.y,1,8191)<<3|P)}else x.centroidXY=new Ls(0,0);this.writeCentroidToBuffer(x)}writeCentroidToBuffer(m){this.groundEffect.updateHiddenByLandmark(m);const x=m.vertexArrayOffset,k=m.vertexCount+m.vertexArrayOffset,E=-1073741824&m.flags?Cq:m.centroidXY,P=this.centroidVertexArray.geta_centroid_pos0(x);if(this.centroidVertexArray.geta_centroid_pos1(x)!==E.y||P!==E.x){for(let O=x;OH.max.x||H.min.x>O.max.x||O.min.y>H.max.y||H.min.y>O.max.y||O.footprint.buildingIds.has(H.buildingId)&&(H.flags|=O.clipMask!==Sq.None?-1073741824:Qj);else for(const H of this.centroidData)if(!(H.flags&Qj||H.flags&Tq||O.min.x>H.max.x||H.min.x>O.max.x||O.min.y>H.max.y||H.min.y>O.max.y))for(let X=0;Xx!=_e>x&&m<(this.footprintVertices.int16[2*(oe+O.vertexOffset)+0]-ue)*(x-me)/(_e-me)+ue&&(E=!E)}U=H}}return E}getHeightAtTileCoord(m,x){let k=Number.NEGATIVE_INFINITY,E=!0;const P=4*(m+$n)*$n+(x+$n);if(this.partLookup.hasOwnProperty(P)){const O=this.partLookup[P];return O?{height:O.height,hidden:!!(O.flags&Qj)}:void 0}for(const O of this.centroidData)m>O.max.x||O.min.x>m||x>O.max.y||O.min.y>x||O.height<=k||this.footprintContainsPoint(m,x,O)&&(k=O.height,this.partLookup[P]=O,E=!!(O.flags&Qj));if(k!==Number.NEGATIVE_INFINITY)return{height:k,hidden:E};this.partLookup[P]=void 0}}function _Re(w,m){const x=w.add(m)._unit();return w.x*x.x+w.y*x.y}function xCt(w,m,x,k){const E=m.sub(w)._perp()._unit(),P=x.sub(m)._perp()._unit();return wRe(w,m,x,_Re(E,P),k)}function wRe(w,m,x,k,E){const P=Math.sqrt(1-k*k);return Math.min(w.dist(m)/3,m.dist(x)/3,E*P/k)}function t_e(w,m,x){return w.xx[1].x&&m.x>x[1].x||w.yx[1].y&&m.y>x[1].y}function jRe(w,m){return w.xm[1].x||w.ym[1].y}function gCt(w){return w.every(m=>m.x<=0)||w.every(m=>m.x>=$n)||w.every(m=>m.y<=0)||w.every(m=>m.y>=$n)}function NRe(w,m,x){if(w.x<0||w.x>=$n||m.x<0||m.x>=$n||x.x<0||x.x>=$n)return!1;const k=x.sub(m),E=k.perp(),P=w.sub(m);return(k.x*P.x+k.y*P.y)/Math.sqrt((k.x*k.x+k.y*k.y)*(P.x*P.x+P.y*P.y))>-.866&&E.x*P.x+E.y*P.y<0}function kRe(w,m,x){const k=m?2|w:-3&w;return x?1|k:-2&k}function SRe(){const w=Math.PI/32,m=Math.tan(w),x=Gt;return x*Math.sqrt(1+2*m*m)-x}function CRe(w,m,x){const k=1<{for(const zt of jt)Se.push({polygon:zt,bounds:Yt})},$e=Math.ceil(Math.log2(oe)),Ke=Math.ceil(Math.log2(ue)),lt=$e-Ke,nt=[];for(let jt=0;jt0?0:1);for(let jt=0;jtYt+1?_t.push({polygons:Qs,bounds:Xs,depth:Yt+1}):Pe(Qs,Xs)}if(sn.length){const Xs=[new Ls(zt===0?qs:Wt.x,zt===1?qs:Wt.y),$t];nt.length>Yt+1?_t.push({polygons:sn,bounds:Xs,depth:Yt+1}):Pe(sn,Xs)}}return Se}(w,m,Math.ceil((P-E)/11.25),Math.ceil((O-U)/11.25),1,(H,X,oe)=>{if(H===0)return .5*(X+oe);{const ue=zs((x.y+X/$n)/k);return(mn(.5*(zs((x.y+oe/$n)/k)+ue))*k-x.y)*$n}})}function yCt(w,m,x,k,E,P){const O=Math.pow(2,k.z-E.z);for(let U=0;U=H[O]&&(U=m,H=w),U[O]E&&MRe(U,H,O,E),U[O]P&&MRe(H,U,O,P)}}function Mq(w,m,x,k,E,P){const O=[];for(let U=0;U=k&&Se.x>=k||(_e.x>=k?_e=new Ls(k,_e.y+(k-_e.x)/(Se.x-_e.x)*(Se.y-_e.y))._round():Se.x>=k&&(Se=new Ls(k,_e.y+(k-_e.x)/(Se.x-_e.x)*(Se.y-_e.y))._round()),_e.y>=E&&Se.y>=E||(_e.y>=E?_e=new Ls(_e.x+(E-_e.y)/(Se.y-_e.y)*(Se.x-_e.x),E)._round():Se.y>=E&&(Se=new Ls(_e.x+(E-_e.y)/(Se.y-_e.y)*(Se.x-_e.x),E)._round()),X&&_e.equals(X[X.length-1])||(X=[_e],O.push(X),P&&P.push({progress:{min:$e+PRe(Ke,lt,_e)*Pe,max:1},parentIndex:U,prevPoint:Ke,nextPoint:lt})),X.push(Se),P&&(P[P.length-1].progress.max=$e+PRe(Ke,lt,Se)*Pe,P[P.length-1].nextPoint=lt)))))}if(P&&ue>0)for(let me=oe;meX.t-oe.t);let O=0,U=0,H=[];for(k.push(H);O!==w.length;){if(U===P.length){for(;O!==w.length;)H.length!==0&&H[H.length-1].equals(w[O])||H.push(w[O]),O++;break}P[U].t<=O?(H.length!==0&&H[H.length-1].equals(P[U].point)||H.push(P[U].point),Math.trunc(P[U].t),U++):(H.length!==0&&H[H.length-1].equals(w[O])||H.push(w[O]),O++)}}function PRe(w,m,x){return w.x!==m.x?(x.x-w.x)/(m.x-w.x):w.y!==m.y?(x.y-w.y)/(m.y-w.y):0}function gO(w,m){return w.x*m.x+w.y*m.y}function LRe(w,m){if(w.length===1){let x=0;const k=m[x++];let E;for(;!E||k.equals(E);)if(E=m[x++],!E)return 1/0;for(;x{qs[0]=Qs,qs[1]=sn,qs[2]=Xs,qs[3]=1},Bs=SRe();_e>0&&(_e+=Bs),Se+=Bs;for(const qs of me){const Qs=[],sn=[];for(const Xs of qs){const xn=Xs.x+Pe.x,Os=Xs.y+Pe.y,en=ue.projection.projectTilePoint(xn,Os,_t),on=ue.projection.upVector(_t,Xs.x,Xs.y);let yn=_e,Tn=Se;if(Ke){const or=ORe(xn,Os,_e,Se,Ke,lt,nt,pt);yn+=or.base,Tn+=or.top}_e!==0?Ut(Wt,en.x+on[0]*zt*yn,en.y+on[1]*zt*yn,en.z+on[2]*zt*yn):Ut(Wt,en.x,en.y,en.z),Ut($t,en.x+on[0]*zt*Tn,en.y+on[1]*zt*Tn,en.z+on[2]*zt*Tn),Ze(Wt,Wt,$e),Ze($t,$t,$e),Qs.push(new XC(Wt[0],Wt[1],Wt[2])),sn.push(new XC($t[0],$t[1],$t[2]))}jt.push(Qs),Yt.push(sn)}return[jt,Yt]}(w,m,x,k,E,P,O,U,H,X,oe):O?function(ue,me,_e,Se,Pe,$e,Ke,lt,nt){const pt=[],_t=[],jt=[0,0,0,1];for(const Yt of ue){const zt=[],Wt=[];for(const $t of Yt){const Ut=$t.x+Se.x,Bs=$t.y+Se.y,qs=ORe(Ut,Bs,me,_e,$e,Ke,lt,nt);jt[0]=Ut,jt[1]=Bs,jt[2]=qs.base,jt[3]=1,dt(jt,jt,Pe),jt[3]=Math.max(jt[3],1e-5);const Qs=new XC(jt[0]/jt[3],jt[1]/jt[3],jt[2]/jt[3]);jt[0]=Ut,jt[1]=Bs,jt[2]=qs.top,jt[3]=1,dt(jt,jt,Pe),jt[3]=Math.max(jt[3],1e-5);const sn=new XC(jt[0]/jt[3],jt[1]/jt[3],jt[2]/jt[3]);zt.push(Qs),Wt.push(sn)}pt.push(zt),_t.push(Wt)}return[pt,_t]}(m,x,k,E,P,O,U,H,X):function(ue,me,_e,Se,Pe){const $e=[],Ke=[],lt=Pe[8]*me,nt=Pe[9]*me,pt=Pe[10]*me,_t=Pe[11]*me,jt=Pe[8]*_e,Yt=Pe[9]*_e,zt=Pe[10]*_e,Wt=Pe[11]*_e;for(const $t of ue){const Ut=[],Bs=[];for(const qs of $t){const Qs=qs.x+Se.x,sn=qs.y+Se.y,Xs=Pe[0]*Qs+Pe[4]*sn+Pe[12],xn=Pe[1]*Qs+Pe[5]*sn+Pe[13],Os=Pe[2]*Qs+Pe[6]*sn+Pe[14],en=Pe[3]*Qs+Pe[7]*sn+Pe[15],on=Xs+lt,yn=xn+nt,Tn=Os+pt,or=Math.max(en+_t,1e-5),Fn=Xs+jt,On=xn+Yt,En=Os+zt,rr=Math.max(en+Wt,1e-5);Ut.push(new XC(on/or,yn/or,Tn/or)),Bs.push(new XC(Fn/rr,On/rr,En/rr))}$e.push(Ut),Ke.push(Bs)}return[$e,Ke]}(m,x,k,E,P)}function ORe(w,m,x,k,E,P,O,U){const H=O*E.getElevationAt(w,m,!0,!0),X=P[0]!==0,oe=X?P[1]===0?O*(P[0]/7-450):O*function(ue,me,_e){const Se=Math.floor(me[0]/8),Pe=Math.floor(me[1]/8),$e=10*(me[0]-8*Se),Ke=10*(me[1]-8*Pe),lt=ue.getElevationAt(Se,Pe,!0,!0),nt=ue.getMeterToDEM(_e),pt=Math.floor(.5*($e*nt-1)),_t=Math.floor(.5*(Ke*nt-1)),jt=ue.tileCoordToPixel(Se,Pe),Yt=2*pt+1,zt=2*_t+1,Wt=function(sn,Xs,xn,Os,en){return[sn.getElevationAtPixel(Xs,xn,!0),sn.getElevationAtPixel(Xs+en,xn,!0),sn.getElevationAtPixel(Xs,xn+en,!0),sn.getElevationAtPixel(Xs+Os,xn+en,!0)]}(ue,jt.x-pt,jt.y-_t,Yt,zt),$t=Math.abs(Wt[0]-Wt[1]),Ut=Math.abs(Wt[2]-Wt[3]),Bs=Math.abs(Wt[0]-Wt[2])+Math.abs(Wt[1]-Wt[3]),qs=Math.min(.25,.5*nt*($t+Ut)/Yt),Qs=Math.min(.25,.5*nt*Bs/zt);return lt+Math.max(qs*$e,Qs*Ke)}(E,P,U):H;return{base:H+(x===0?-1:x),top:X?Math.max(oe+k,H+x+2):H+k}}const s_e=4096;class bCt{constructor(m){this.module=m,this.memoryStack=this.module.malloc(s_e),this.memoryStackNextFree=this.memoryStack}createIntArray(m){const x=this.memoryStackNextFree;return this.memoryStackNextFree+=m.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>s_e?-1:(new Int32Array(this.module.heap32.buffer,x,m.length).set(m),x)}createFloatArray(m){const x=this.memoryStackNextFree;return this.memoryStackNextFree+=m.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>s_e?-1:(new Float32Array(this.module.heapF32.buffer,x,m.length).set(m),x)}readStringBuffer(m){let x="";for(;this.module.heapU8[m]!==0;)x+=String.fromCharCode(this.module.heapU8[m]),++m;return x}setStyle(m){const x=m.normalScale;this.module.setStyle(x[0],x[1],x[2],m.tileToMeters)}setAOOptions(m,x){this.module.setAOOptions(m?1:0,x)}setMetricOptions(m,x){this.module.setMetricOptions(m?1:0,x)}setStructuralOptions(m){this.module.setStructuralOptions(m?1:0)}setFacadeOptions(m,x){this.module.setFacadeOptions(m,x?1:0)}setFauxFacadeOptions(m,x,k){this.module.setFauxFacadeOptions(m?1:0,x?1:0,k)}setFacadeClassifierOptions(m){this.module.setFacadeClassifierOptions(m)}generateMesh(m,x){this.memoryStackNextFree=this.memoryStack;for(const U of m){const H=this.createIntArray(U.ringIndices),X=this.createFloatArray(U.coordinates);if(H===-1||X===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(U.id,U.sourceId,U.minHeight,U.height,U.roofType,X,H,U.ringIndices.length-1)}for(const U of x){let H;H=U.entrances?JSON.parse(U.entrances):[];const X=this.createFloatArray(H),oe=this.createFloatArray(U.coordinates);if(X===-1||oe===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(U.sourceId,U.crossPerc,U.distanceToRoad,X,H.length,oe,U.coordinates.length)}if(!this.module.generateMesh()){const U=this.module.getLastError();return this.readStringBuffer(U)}const k=this.module.getMeshCount(),E=new Array(k);for(let U=0;U>2)-3,$e=_e[Se++]>>2;if(Se++,E.json=JSON.parse(WRe.decode(_e.subarray(Se,Se+$e))),Se+=$e,Se>>0,Math.ceil(1.2*pt)),jt=Math.ceil((_t-pt)/65536);try{return Pe.grow(jt),$e(),!0}catch{return!1}},b:Ke}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(_e,lt):_e.then(nt=>nt.arrayBuffer()).then(nt=>WebAssembly.instantiate(nt,lt))).then(nt=>{const{Rb:pt,Qb:_t,P:jt,T:Yt,X:zt,Ja:Wt,La:$t,Qa:Ut,Va:Bs,Wa:qs,eb:Qs,jb:sn,f:Xs,e:xn,yb:Os,zb:en,Ab:on,Bb:yn,Db:Tn,Gb:or}=nt.instance.exports;Pe=xn;const Fn=(()=>{let On=0,En=0,rr=0,pr=0;return Vr=>{rr&&(pt(pr),pt(On),En+=rr,rr=On=0),On||(En+=128,On=_t(En));const kr=Vr.length+7&-8;let Ea=On;kr>=En&&(rr=kr,Ea=pr=_t(kr));for(let Ni=0;Ni{E1=_e,yO=void 0}))}()),me&&oe.push(function(){if(n_e)return;const _e=function(Se){let Pe;const $e=WebAssembly.instantiateStreaming(Se,{}).then(nt=>{Pe=nt.instance,Pe.exports.__wasm_call_ctors()}),Ke={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},lt={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return{ready:$e,supported:!0,decodeGltfBuffer(nt,pt,_t,jt,Yt,zt){(function(Wt,$t,Ut,Bs,qs,Qs,sn){const Xs=Wt.exports.sbrk,xn=Bs+3&-4,Os=Xs(xn*qs),en=Xs(Qs.length),on=new Uint8Array(Wt.exports.memory.buffer);on.set(Qs,en);const yn=$t(Os,Bs,qs,en,Qs.length);if(yn===0&&sn&&sn(Os,xn,qs),Ut.set(on.subarray(Os,Os+Bs*qs)),Xs(Os-Xs(0)),yn!==0)throw new Error(`Malformed buffer data: ${yn}`)})(Pe,Pe.exports[lt[Yt]],nt,pt,_t,jt,Pe.exports[Ke[zt]])}}}(fetch(Ta()));return _e.ready.then(()=>{n_e=_e})}()),O)for(let _e=0;_e{const U=Iy(k,(H,X)=>{H?O(H):P(X)});E&&E.addEventListener("abort",()=>{U.cancel(),O(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:w,type:"arrayBuffer"},m);return ZRe(x,0,w,m)}function a_e(w){switch(w){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 i_e(w){switch(w){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 j_{constructor(m,x,k,E){this.context=m,this.format=k,this.useMipmap=E&&E.useMipmap,this.texture=m.gl.createTexture(),this.update(x,{premultiply:E&&E.premultiply})}update(m,x){const k=m&&m instanceof HTMLVideoElement&&m.width===0?m.videoWidth:m.width,E=m&&m instanceof HTMLVideoElement&&m.height===0?m.videoHeight:m.height,{context:P}=this,{gl:O}=P,{x:U,y:H}=x&&x.position?x.position:{x:0,y:0},X=U+k,oe=H+E;this.size&&(this.size[0]!==X||this.size[1]!==oe)&&(!x||x.recreateWhenResize===void 0||x.recreateWhenResize)&&(O.bindTexture(O.TEXTURE_2D,null),O.deleteTexture(this.texture),this.texture=O.createTexture(),this.size=null),O.bindTexture(O.TEXTURE_2D,this.texture),P.pixelStoreUnpackFlipY.set(!1),P.pixelStoreUnpack.set(1),P.pixelStoreUnpackPremultiplyAlpha.set(this.format===O.RGBA8&&(!x||x.premultiply!==!1));const ue=m instanceof HTMLImageElement||m instanceof HTMLCanvasElement||m instanceof HTMLVideoElement||m instanceof ImageData||ImageBitmap&&m instanceof ImageBitmap;if(!this.size&&X>0&&oe>0){const me=this.useMipmap?Math.floor(Math.log2(Math.max(X,oe)))+1:1;O.texStorage2D(O.TEXTURE_2D,me,this.format,X,oe),this.size=[X,oe]}this.size&&(ue?O.texSubImage2D(O.TEXTURE_2D,0,U,H,a_e(this.format),i_e(this.format),m):"data"in m&&m.data&&O.texSubImage2D(O.TEXTURE_2D,0,U,H,k,E,a_e(this.format),i_e(this.format),m.data)),this.useMipmap&&O.generateMipmap(O.TEXTURE_2D)}bind(m,x,k=!1){const{context:E}=this,{gl:P}=E;P.bindTexture(P.TEXTURE_2D,this.texture),m!==this.minFilter&&(P.texParameteri(P.TEXTURE_2D,P.TEXTURE_MAG_FILTER,m),P.texParameteri(P.TEXTURE_2D,P.TEXTURE_MIN_FILTER,this.useMipmap&&!k?m===P.NEAREST?P.NEAREST_MIPMAP_NEAREST:P.LINEAR_MIPMAP_LINEAR:m),this.minFilter=m),x!==this.wrapS&&(P.texParameteri(P.TEXTURE_2D,P.TEXTURE_WRAP_S,x),P.texParameteri(P.TEXTURE_2D,P.TEXTURE_WRAP_T,x),this.wrapS=x)}bindExtraParam(m,x,k,E,P){const{context:O}=this,{gl:U}=O;U.bindTexture(U.TEXTURE_2D,this.texture),x!==this.magFilter&&(U.texParameteri(U.TEXTURE_2D,U.TEXTURE_MAG_FILTER,x),this.magFilter=x),m!==this.minFilter&&(U.texParameteri(U.TEXTURE_2D,U.TEXTURE_MIN_FILTER,this.useMipmap?m===U.NEAREST?U.NEAREST_MIPMAP_NEAREST:U.LINEAR_MIPMAP_LINEAR:m),this.minFilter=m),k!==this.wrapS&&(U.texParameteri(U.TEXTURE_2D,U.TEXTURE_WRAP_S,k),this.wrapS=k),E!==this.wrapT&&(U.texParameteri(U.TEXTURE_2D,U.TEXTURE_WRAP_T,E),this.wrapT=E),P!==this.compareMode&&(P?(U.texParameteri(U.TEXTURE_2D,U.TEXTURE_COMPARE_MODE,U.COMPARE_REF_TO_TEXTURE),U.texParameteri(U.TEXTURE_2D,U.TEXTURE_COMPARE_FUNC,P)):U.texParameteri(U.TEXTURE_2D,U.TEXTURE_COMPARE_MODE,U.NONE),this.compareMode=P)}destroy(){const{gl:m}=this.context;m.deleteTexture(this.texture),this.texture=null}}class bO{constructor(m,x){this.context=m,this.texture=x}bind(m,x){const{context:k}=this,{gl:E}=k;E.bindTexture(E.TEXTURE_2D,this.texture),m!==this.minFilter&&(E.texParameteri(E.TEXTURE_2D,E.TEXTURE_MAG_FILTER,m),E.texParameteri(E.TEXTURE_2D,E.TEXTURE_MIN_FILTER,m),this.minFilter=m),x!==this.wrapS&&(E.texParameteri(E.TEXTURE_2D,E.TEXTURE_WRAP_S,x),E.texParameteri(E.TEXTURE_2D,E.TEXTURE_WRAP_T,x),this.wrapS=x)}}const CCt=cn([{name:"a_pos_3f",components:3,type:"Float32"}]),TCt=cn([{name:"a_color_3f",components:3,type:"Float32"}]),ECt=cn([{name:"a_color_4f",components:4,type:"Float32"}]),ACt=cn([{name:"a_uv_2f",components:2,type:"Float32"}]),MCt=cn([{name:"a_normal_3f",components:3,type:"Float32"}]),ICt=cn([{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"}]),PCt=cn([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function XRe(w,m){const x=Dq(w.projection,w.zoom,w.width,w.height),k=function(P,O,U,H,X){const oe=new ns(U.lng-180*pk,U.lat),ue=new ns(U.lng+180*pk,U.lat),me=P.project(oe.lng,oe.lat),_e=P.project(ue.lng,ue.lat),Se=-Math.atan2(_e.y-me.y,_e.x-me.x),Pe=mr.fromLngLat(U);Pe.y=Xe(Pe.y,-1+pk,1-pk);const $e=Pe.toLngLat(),Ke=P.project($e.lng,$e.lat),lt=mr.fromLngLat($e);lt.x+=pk;const nt=lt.toLngLat(),pt=P.project(nt.lng,nt.lat),_t=eOe(pt.x-Ke.x,pt.y-Ke.y,Se),jt=mr.fromLngLat($e);jt.y+=pk;const Yt=jt.toLngLat(),zt=P.project(Yt.lng,Yt.lat),Wt=eOe(zt.x-Ke.x,zt.y-Ke.y,Se),$t=Math.abs(_t.x)/Math.abs(Wt.y),Ut=v([]);D(Ut,Ut,-Se*(1-(X?0:H)));const Bs=v([]);return A(Bs,Bs,[1,1-(1-$t)*H,1]),Bs[4]=-Wt.x/Wt.y*H,D(Bs,Bs,Se),b(Bs,Ut,Bs),Bs}(w.projection,0,w.center,x,m),E=JRe(w);return A(k,k,[E,E,1]),k}function JRe(w){const m=w.projection,x=Dq(w.projection,w.zoom,w.width,w.height),k=o_e(m,w.center),E=o_e(m,ns.convert(m.center));return Math.pow(2,k*x+(1-x)*E)}function Dq(w,m,x,k,E=1/0){const P=w.range;if(!P)return 0;const O=Math.min(E,Math.max(x,k)),U=Math.log2(O/1024);return ot(P[0]+U,P[1]+U,m)}const pk=1/4e4;function o_e(w,m){const x=Xe(m.lat,-85.051129,Ys),k=new ns(m.lng-180*pk,x),E=new ns(m.lng+180*pk,x),P=w.project(k.lng,x),O=w.project(E.lng,x),U=mr.fromLngLat(k),H=mr.fromLngLat(E),X=O.x-P.x,oe=O.y-P.y,ue=H.x-U.x,me=H.y-U.y,_e=Math.sqrt((ue*ue+me*me)/(X*X+oe*oe));return Math.log2(_e)}function eOe(w,m,x){const k=Math.cos(x),E=Math.sin(x);return{x:w*k-m*E,y:w*E+m*k}}function tOe(w,m,x){v(w),D(w,w,js(m[2])),T(w,w,js(m[0])),L(w,w,js(m[1])),A(w,w,x),b(w,w,[1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1])}function Rq(w,m,x,k,E,P,O,U){const H=[x[0]-m[0],x[1]-m[1],0],X=[k[0]-m[0],k[1]-m[1],0];if(J(H)<1e-12||J(X)<1e-12)return vt(w);const oe=qe([],H,X);Ie(oe,oe),ce(X,k,m),H[2]=(P-E)*U,X[2]=(O-E)*U;const ue=H;return qe(ue,H,X),Ie(ue,ue),Jt(w,oe,ue)}function Oq(w,m,x=!1){const k=Yj(m.zoom),E=function(P,O,U){const H=O.worldSize,X=[P[12],P[13],P[14]],oe=zs(X[1]/H),ue=hs(X[0]/H),me=v([]),_e=Ns(1,oe)*H,Se=Ns(1,0)*H*Sn(oe,O.zoom),Pe=1/Ibe(H);let $e=Se*Pe;if(U){const pt=Dq(O.projection,O.zoom,O.width,O.height,1024);$e=Pe*O.projection.pixelSpaceConversion(O.center.lat,H,pt)}const Ke=Dt(oe,ue);he(Ke,Ke,ge([],Ie([],Ke),_e*$e*X[2]));const lt=function(pt){const _t=[pt[0],pt[1],pt[2]];let jt=[0,1,0];const Yt=qe([],jt,_t);return qe(jt,_t,Yt),Ae(jt)===0&&(jt=[0,1,0],qe(Yt,_t,jt)),Ie(Yt,Yt),Ie(jt,jt),Ie(_t,_t),[Yt[0],Yt[1],Yt[2],0,jt[0],jt[1],jt[2],0,_t[0],_t[1],_t[2],0,pt[0],pt[1],pt[2],1]}(Ke);A(me,me,[$e,$e,$e*_e]),S(me,me,[-X[0],-X[1],-X[2]]);const nt=b([],O.globeMatrix,lt);return b(nt,nt,me),b(nt,nt,P),nt}(w,m,x);if(k>0){const P=function(O,U){const H=U.worldSize,X=Ns(1,0)*H*Sn(U.center.lat,U.zoom)/Ibe(H),oe=Ns(1,U.center.lat)*H,ue=v([]);L(ue,ue,js(U.center.lng)),T(ue,ue,js(U.center.lat)),S(ue,ue,[0,0,Tt]),A(ue,ue,[X,X,X*oe]);const me=U.point;return S(ue,ue,[-me.x,-me.y,0]),b(ue,ue,O),b(ue,U.globeMatrix,ue)}(w,m);return function(O,U,H){const X=(Se,Pe,$e)=>{const Ke=J(Se),lt=J(Pe),nt=Kj(Se,Pe,$e);return ge(nt,nt,1/J(nt)*zr(Ke,lt,$e))},oe=X([O[0],O[1],O[2]],[U[0],U[1],U[2]],H),ue=X([O[4],O[5],O[6]],[U[4],U[5],U[6]],H),me=X([O[8],O[9],O[10]],[U[8],U[9],U[10]],H),_e=Kj([O[12],O[13],O[14]],[U[12],U[13],U[14]],H);return[oe[0],oe[1],oe[2],0,ue[0],ue[1],ue[2],0,me[0],me[1],me[2],0,_e[0],_e[1],_e[2],1]}(E,P,k)}return E}function l_e(w,m,x,k){const E=so.projectAabbCorners(k,x);let P=Number.MAX_VALUE;for(let U=0;U0||$e===0&&Se[0]*Pe[0]+Se[1]*Pe[1]>=0&&Se[0]*Se[0]+Se[1]*Se[1]>Pe[0]*Pe[0]+Pe[1]*Pe[1])&&(oe=_e)}ue=oe}while(ue!==X);return H.length>0&&H.push(H[0]),H}(E);if(pc(w,O))return P}const JC=64,H6={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function Fq(w,m,x,k,E,P,O,U,H,X=!1){const oe=x.zoom,ue=x.project(k),me=Sn(k.lat,oe),_e=1/me;v(w),S(w,w,[ue.x+O[0]*_e,ue.y+O[1]*_e,O[2]]);let Se=1,Pe=1;const $e=x.worldSize;if(X){if(x.projection.name==="mercator"){let pt=0;x.elevation&&(pt=x.elevation.getAtPointOrZero(new mr(ue.x/$e,ue.y/$e),0));const _t=dt([],[ue.x,ue.y,pt,1],x.projMatrix)[3]/x.cameraToCenterDistance;Se=_t,Pe=_t*Sn(x.center.lat,oe)}else if(x.projection.name==="globe"){const pt=Oq(w,x),_t=[0,0,0,1];dt(_t,_t,b([],x.projMatrix,pt));const jt=_t[3]/x.cameraToCenterDistance,Yt=Yj(oe),zt=x.projection.pixelsPerMeter(k.lat,$e)*Sn(k.lat,oe),Wt=x.projection.pixelsPerMeter(x.center.lat,$e)*Sn(x.center.lat,oe);Se=jt/zr(zt,Rn(x.center.lat),Yt),Pe=jt*me/zt,Se*=Wt,Pe*=Wt}}else Se=_e;A(w,w,[Se,Se,Pe]);const Ke=[...w],lt=m.orientation,nt=[];if(tOe(nt,[lt[0]+(E?E[0]:0),lt[1]+(E?E[1]:0),lt[2]+(E?E[2]:0)],P),b(w,Ke,nt),U&&x.elevation){let pt=0;const _t=[];if(H&&x.elevation){pt=function(Yt,zt,Wt,$t,Ut){const Bs=zt.elevation;if(!Bs)return 0;const qs=so.projectAabbCorners(Wt,$t),Qs=Ns(1,Ut.lat)*zt.worldSize,sn=function(En,rr){const pr=[0,0,1],Vr=[{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 kr of Vr){const Ea=En[kr.corners[0]],Ni=En[kr.corners[1]],Aa=En[kr.corners[2]],Ci=[Ni[0]-Ea[0],Ni[1]-Ea[1],rr*(Ni[2]-Ea[2])],Ka=qe(Ci,Ci,[Aa[0]-Ea[0],Aa[1]-Ea[1],rr*(Aa[2]-Ea[2])]);Ie(Ka,Ka),kr.dotProductWithUp=Fe(Ka,pr)}return Vr.sort((kr,Ea)=>kr.dotProductWithUp-Ea.dotProductWithUp),Vr[0].corners}(qs,Qs),Xs=qs[sn[0]],xn=qs[sn[1]],Os=qs[sn[2]],en=qs[sn[3]],on=Bs.getAtPointOrZero(new mr(Xs[0]/zt.worldSize,Xs[1]/zt.worldSize),0),yn=Bs.getAtPointOrZero(new mr(xn[0]/zt.worldSize,xn[1]/zt.worldSize),0),Tn=Bs.getAtPointOrZero(new mr(Os[0]/zt.worldSize,Os[1]/zt.worldSize),0),or=Bs.getAtPointOrZero(new mr(en[0]/zt.worldSize,en[1]/zt.worldSize),0),Fn=(on+or)/2,On=(yn+Tn)/2;return Fn>On?yn=m.gl.NEAREST_MIPMAP_NEAREST}),w.uploaded=!0,w.image=null)}function LCt(w,m,x){w.indexBuffer=m.createIndexBuffer(w.indexArray,!1,!0),w.vertexBuffer=m.createVertexBuffer(w.vertexArray,CCt.members,!1,!0),w.normalArray&&(w.normalBuffer=m.createVertexBuffer(w.normalArray,MCt.members,!1,!0)),w.texcoordArray&&(w.texcoordBuffer=m.createVertexBuffer(w.texcoordArray,ACt.members,!1,!0)),w.colorArray&&(w.colorBuffer=m.createVertexBuffer(w.colorArray,(w.colorArray.bytesPerElement===12?TCt:ECt).members,!1,!0)),w.featureArray&&(w.pbrBuffer=m.createVertexBuffer(w.featureArray,PCt.members,!0)),w.segments=Po.simpleSegment(0,0,w.vertexArray.length,w.indexArray.length);const k=w.material;k.pbrMetallicRoughness.baseColorTexture&&_O(k.pbrMetallicRoughness.baseColorTexture,m),k.pbrMetallicRoughness.metallicRoughnessTexture&&_O(k.pbrMetallicRoughness.metallicRoughnessTexture,m),k.normalTexture&&_O(k.normalTexture,m),k.occlusionTexture&&_O(k.occlusionTexture,m,x),k.emissionTexture&&_O(k.emissionTexture,m)}function c_e(w,m,x){if(w.meshes)for(const k of w.meshes)LCt(k,m,x);if(w.children)for(const k of w.children)c_e(k,m,x)}function zq(w){if(w.meshes)for(const m of w.meshes)m.indexArray.destroy(),m.vertexArray.destroy(),m.colorArray&&m.colorArray.destroy(),m.normalArray&&m.normalArray.destroy(),m.texcoordArray&&m.texcoordArray.destroy(),m.featureArray&&m.featureArray.destroy();if(w.children)for(const m of w.children)zq(m)}function DCt(w){w.pbrMetallicRoughness.baseColorTexture&&w.pbrMetallicRoughness.baseColorTexture.gfxTexture&&w.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),w.pbrMetallicRoughness.metallicRoughnessTexture&&w.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&w.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),w.normalTexture&&w.normalTexture.gfxTexture&&w.normalTexture.gfxTexture.destroy(),w.emissionTexture&&w.emissionTexture.gfxTexture&&w.emissionTexture.gfxTexture.destroy(),w.occlusionTexture&&w.occlusionTexture.gfxTexture&&w.occlusionTexture.gfxTexture.destroy()}function d_e(w){if(w.meshes)for(const m of w.meshes)m.vertexBuffer&&(m.vertexBuffer.destroy(),m.indexBuffer.destroy(),m.normalBuffer&&m.normalBuffer.destroy(),m.texcoordBuffer&&m.texcoordBuffer.destroy(),m.colorBuffer&&m.colorBuffer.destroy(),m.pbrBuffer&&m.pbrBuffer.destroy(),m.segments.destroy(),m.material&&DCt(m.material));if(w.footprintDebugMesh&&(w.footprintDebugMesh.vertexBuffer.destroy(),w.footprintDebugMesh.indexBuffer.destroy(),w.footprintDebugMesh.segments.destroy()),w.children)for(const m of w.children)d_e(m)}function e3(w,m){const x=w.json.bufferViews[m.bufferView],k=Pq[m.componentType];return new k(w.buffers[x.buffer],(m.byteOffset||0)+(x.byteOffset||0),m.count*(x.byteStride&&x.byteStride!==vO[m.type]*k.BYTES_PER_ELEMENT?x.byteStride/k.BYTES_PER_ELEMENT:vO[m.type]))}function u_e(w,m,x,k){const E=Pq[m.componentType],P=function(oe){switch(oe){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(E),O=w.json.bufferViews[m.bufferView],U=O.byteStride?O.byteStride/E.BYTES_PER_ELEMENT:vO[m.type],H=x.float32,X=H.length/x.capacity;for(let oe=0,ue=0;oe0){for(let $e=0;$e0){P.texcoordArray=new Vj;const me=m.json.accessors[E.TEXCOORD_0];P.texcoordArray.resize(me.count);const _e=e3(m,me);u_e(m,me,P.texcoordArray,_e)}if(E._FEATURE_ID_RGBA4444!==void 0){const me=m.json.accessors[E._FEATURE_ID_RGBA4444];m.json.extensionsUsed&&m.json.extensionsUsed.includes("EXT_meshopt_compression")&&(P.featureData=e3(m,me))}E._FEATURE_RGBA4444!==void 0&&(P.featureData=new Uint32Array(e3(m,m.json.accessors[E._FEATURE_RGBA4444]).buffer));const ue=w.material;return P.material=function(me,_e){const{emissiveFactor:Se=[0,0,0],alphaMode:Pe="OPAQUE",alphaCutoff:$e=.5,normalTexture:Ke,occlusionTexture:lt,emissiveTexture:nt,doubleSided:pt,name:_t}=me,{baseColorFactor:jt=[1,1,1,1],metallicFactor:Yt=1,roughnessFactor:zt=1,baseColorTexture:Wt,metallicRoughnessTexture:$t}=me.pbrMetallicRoughness||{},Ut=lt?_e[lt.index]:void 0;if(lt&<.extensions&<.extensions.KHR_texture_transform&&Ut){const Bs=lt.extensions.KHR_texture_transform;Ut.offsetScale=[Bs.offset[0],Bs.offset[1],Bs.scale[0],Bs.scale[1]]}return{name:_t,pbrMetallicRoughness:{baseColorFactor:new Gn(...jt),metallicFactor:Yt,roughnessFactor:zt,baseColorTexture:Wt?_e[Wt.index]:void 0,metallicRoughnessTexture:$t?_e[$t.index]:void 0},doubleSided:pt,emissiveFactor:new Gn(...Se),alphaMode:Pe,alphaCutoff:$e,normalTexture:Ke?_e[Ke.index]:void 0,occlusionTexture:Ut,emissionTexture:nt?_e[nt.index]:void 0,defined:me.defined===void 0}}(ue!==void 0?m.json.materials[ue]:{defined:!1},x),P}function nOe(w,m,x){const{matrix:k,rotation:E,translation:P,scale:O,mesh:U,extras:H,children:X,name:oe}=w,ue={};if(ue.name=oe,ue.localMatrix=k||function(me,_e,Se,Pe){var $e=_e[0],Ke=_e[1],lt=_e[2],nt=_e[3],pt=$e+$e,_t=Ke+Ke,jt=lt+lt,Yt=$e*pt,zt=$e*_t,Wt=$e*jt,$t=Ke*_t,Ut=Ke*jt,Bs=lt*jt,qs=nt*pt,Qs=nt*_t,sn=nt*jt,Xs=Pe[0],xn=Pe[1],Os=Pe[2];return me[0]=(1-($t+Bs))*Xs,me[1]=(zt+sn)*Xs,me[2]=(Wt-Qs)*Xs,me[3]=0,me[4]=(zt-sn)*xn,me[5]=(1-(Yt+Bs))*xn,me[6]=(Ut+qs)*xn,me[7]=0,me[8]=(Wt+Qs)*Os,me[9]=(Ut-qs)*Os,me[10]=(1-(Yt+$t))*Os,me[11]=0,me[12]=Se[0],me[13]=Se[1],me[14]=Se[2],me[15]=1,me}([],E||[0,0,0,1],P||[0,0,0],O||[1,1,1]),ue.globalMatrix=_(ue.localMatrix),U!==void 0){ue.meshes=x[U];const me=ue.anchor=[0,0];for(const _e of ue.meshes){const{min:Se,max:Pe}=_e.aabb;me[0]+=Se[0]+Pe[0],me[1]+=Se[1]+Pe[1]}me[0]=Math.floor(me[0]/ue.meshes.length/2),me[1]=Math.floor(me[1]/ue.meshes.length/2)}if(H&&(H.id&&(ue.id=H.id),H.lights&&(ue.lights=function(me){if(!me.length)return[];const _e=function(lt){const nt=atob(lt),pt=new Uint8Array(nt.length);for(let _t=0;_t1&&k[k.length-1].equals(k[0])&&k.pop();let E=0;for(let O=0;O0&&k.reverse();const P=B6(k.flatMap(O=>[O.x,O.y]),[]);return P.length===0?null:{vertices:k,indices:P}}function zCt(w,m){const x=[],k=[];let E=0;const P=[];for(const O of w){E=x.length;const U=O.vertexArray.float32,H=O.indexArray.uint16;for(let X=0;X0&&([k[O+1],k[O+2]]=[k[O+2],k[O+1]])}return{vertices:x,indices:k}}function h_e(w){const m=function(H,X){const oe=[],ue=WebGL2RenderingContext;if(H.json.textures)for(const me of H.json.textures){const _e={magFilter:ue.LINEAR,minFilter:ue.NEAREST,wrapS:ue.REPEAT,wrapT:ue.REPEAT};me.sampler!==void 0&&Object.assign(_e,H.json.samplers[me.sampler]),oe.push({image:X[me.source],sampler:_e,uploaded:!1})}return oe}(w,w.images),x=function(H,X){const oe=[];for(const ue of H.json.meshes){const me=[];for(const _e of ue.primitives)me.push(RCt(_e,H,X));oe.push(me)}return oe}(w,m),{scenes:k,scene:E,nodes:P}=w.json,O=k?k[E||0].nodes:[...P.keys()],U=[];for(const H of O)U.push(nOe(P[H],w,x));return function(H,X,oe){const ue={},me=new Set;for(let _e=0;_e0){const _e=Array.from(me.values()).sort((Se,Pe)=>Se-Pe);for(let Se=_e.length-1;Se>=0;Se--)H.splice(_e[Se],1)}}(U,O,w.json.nodes),U}function BCt(w){w.heightmap=new Float32Array(4096),w.heightmap.fill(-1);const m=w.vertexArray.float32,x=w.aabb.min[0]-1,k=w.aabb.min[1]-1,E=JC/(w.aabb.max[0]-x+2),P=JC/(w.aabb.max[1]-k+2);for(let O=0;Ow.heightmap[X*JC+H]&&(w.heightmap[X*JC+H]=U)}}function rOe(w,m,x,k,E){x.reserve(x.length+4*w.length),k.reserve(k.length+10*w.length),E.reserve(E.length+10*w.length);let P=k.length;for(const O of w){const U=Math.min(10,Math.max(4,1.3*O.height))*m,H=[-O.normal[1],O.normal[0],0],X=Math.min(.29,.1*O.width/O.depth),oe=O.width-2*O.depth*m*(X+.01),ue=Te([],O.pos,H,oe/2),me=Te([],O.pos,H,-oe/2),_e=[ue[0],ue[1],ue[2]+O.height],Se=[me[0],me[1],me[2]+O.height],Pe=Te([],O.normal,H,X);ge(Pe,Pe,U);const $e=Te([],O.normal,H,-X);ge($e,$e,U),he(Pe,ue,Pe),he($e,me,$e),ue[2]+=.1,me[2]+=.1,k.emplaceBack(Pe[0],Pe[1],Pe[2]),k.emplaceBack($e[0],$e[1],$e[2]),k.emplaceBack(ue[0],ue[1],ue[2]),k.emplaceBack(me[0],me[1],me[2]),k.emplaceBack(_e[0],_e[1],_e[2]),k.emplaceBack(Se[0],Se[1],Se[2]),k.emplaceBack(ue[0],ue[1],ue[2]),k.emplaceBack(me[0],me[1],me[2]),k.emplaceBack(Pe[0],Pe[1],Pe[2]),k.emplaceBack($e[0],$e[1],$e[2]);const Ke=oe/U/2;E.emplaceBack(-Ke-X,-1,Ke,.8),E.emplaceBack(Ke+X,-1,Ke,.8),E.emplaceBack(-Ke,0,Ke,1.3),E.emplaceBack(Ke,0,Ke,1.3),E.emplaceBack(Ke+X,-.8,Ke,.7),E.emplaceBack(Ke+X,-.8,Ke,.7),E.emplaceBack(0,0,Ke,1.3),E.emplaceBack(0,0,Ke,1.3),E.emplaceBack(Ke+X,-1.2,Ke,.8),E.emplaceBack(Ke+X,-1.2,Ke,.8),x.emplaceBack(6+P,4+P,8+P),x.emplaceBack(7+P,9+P,5+P),x.emplaceBack(0+P,1+P,2+P),x.emplaceBack(1+P,3+P,2+P),P+=10}}function $Ct(w,m){const x={};x.indexArray=new sc,x.vertexArray=new vg,x.colorArray=new C1,rOe(w,m,x.indexArray,x.vertexArray,x.colorArray);const k={defined:!0};k.emissiveFactor=Gn.black;const E={};return E.baseColorFactor=Gn.white,k.pbrMetallicRoughness=E,x.material=k,x.aabb=new so([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),x}const aOe=cn([{name:"a_pos_3f",components:3,type:"Float32"}]),UCt=cn([{name:"a_normal_3",components:3,type:"Int16"}]),qCt=cn([{name:"a_centroid_3",components:3,type:"Int16"}]),iOe=cn([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),VCt=cn([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),HCt=cn([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),GCt=cn([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),WCt=cn([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),KCt=cn([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),oOe=va.types,Bq=32767;function YCt(w,m){const x=$n+m;for(const k of w)for(const E of k)if(E.x<-m||E.x>x||E.y<-m||E.y>x)return!1;return!0}function ZCt(w){switch(w){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: ${w}`)}}class m_e{constructor(){this.layoutVertexArray=new vg,this.layoutAttenuationArray=new C1,this.layoutColorArray=new bg,this.indexArray=new sc,this.indexArrayForConflation=new sc,this.segmentsBucket=new Po}}class p_e{constructor(m){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Po,this.entranceBloom=new m_e;const x=66560;this.layoutVertexArray=new vg,this.layoutVertexArray.reserve(x),this.layoutNormalArray=new $i,this.layoutNormalArray.reserve(x),this.layoutCentroidArray=new $i,this.layoutCentroidArray.reserve(x),this.layoutColorArray=new bg,this.layoutColorArray.reserve(x),this.layoutFloodLightDataArray=new L6,this.layoutFloodLightDataArray.reserve(x),this.layoutAOArray=new D6,this.layoutAOArray.reserve(x),this.indexArray=new sc,this.indexArray.reserve(66560),this.indexArrayForConflation=new sc,this.segmentsBucket=new Po,this.entranceBloom=new m_e,m&&(this.layoutFacadePaintArray=new bg,this.layoutFacadeDataArray=new ok,this.layoutFacadeVerticalRangeArray=new bg)}reserve(m,x,k){this.layoutVertexArray.reserveForAdditional(m),this.layoutCentroidArray.reserveForAdditional(m),this.layoutFloodLightDataArray.reserveForAdditional(m),this.layoutNormalArray.reserveForAdditional(m),this.layoutAOArray.reserveForAdditional(m),this.layoutColorArray.reserveForAdditional(m),this.indexArray.reserveForAdditional(x),k&&(this.layoutFacadePaintArray.reserveForAdditional(m),this.layoutFacadeDataArray.reserveForAdditional(m),this.layoutFacadeVerticalRangeArray.reserveForAdditional(m))}}class lOe{constructor(m){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new Vj,this.footprintsIndices=new Hj,this.footprintsMin=new Ls(1/0,1/0),this.footprintsMax=new Ls(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new p_e(!1),this.buildingWithFacade=new p_e(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=m.zoom,this.canonical=m.canonical,this.layers=m.layers,this.layerIds=this.layers.map(x=>x.fqid),this.index=m.index,this.hasPattern=!1,this.worldview=m.worldview,this.lut=m.lut,this.programConfigurations=new Ue(m.layers,{zoom:m.zoom,lut:m.lut}),this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.projection=m.projection,this.groundEffect=new e_e(m),this.groundEffect.groundRadiusArray=new ro,this.hasAppearances=null}updateFootprints(m,x){const k=new jq([],[],1),E={vertices:[],indices:new Uint32Array(0),grid:k,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};x.push({footprint:E,id:m})}updateAppearances(m,x,k,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}prepare(){return function(){if(Iq!=null||FRe!=null)return null;if(V6!=null)return V6;const m=fetch(Yi());return V6=function(x){let k,E,P,O,U;function H(){k=new Uint8Array(U.buffer),E=new Int16Array(U.buffer),P=new Int32Array(U.buffer),O=new Float32Array(U.buffer)}function X(){throw new Error("Unexpected BuildingGen error.")}const oe=()=>{},ue={a:{a:X,f:function(me){const _e=k.length,Se=Math.max(me>>>0,Math.ceil(1.2*_e)),Pe=Math.ceil((Se-_e)/65536);try{return U.grow(Pe),H(),!0}catch{return!1}},g:X,b:oe,c:oe,d:oe,e:oe}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(x,ue):x.then(me=>me.arrayBuffer()).then(me=>WebAssembly.instantiate(me,ue))).then(me=>{const _e=me.instance.exports;return(0,_e.g)(),U=_e.f,H(),new bCt({setStyle:_e.h,setAOOptions:_e.i,setMetricOptions:_e.j,setStructuralOptions:_e.k,setFacadeOptions:_e.l,setFauxFacadeOptions:_e.m,setFacadeClassifierOptions:_e.n,addFeature:_e.o,addFacade:_e.p,generateMesh:_e.q,getLastError:_e.r,getOuterRingLength:_e.s,getMeshCount:_e.t,getPositionsPtr:_e.u,getPositionsLength:_e.v,getNormalsPtr:_e.w,getNormalsLength:_e.x,getAOPtr:_e.y,getAOLength:_e.z,getUVPtr:_e.A,getUVLength:_e.B,getFauxFacadePtr:_e.C,getFauxFacadeLength:_e.D,getIndicesPtr:_e.E,getIndicesLength:_e.F,getBuildingPart:_e.G,getRingCount:_e.H,getRingPtr:_e.I,getRingLength:_e.J,malloc:_e.K,free:_e.L,heapU8:k,heap16:E,heap32:P,heapF32:O})})}(m).then(x=>(V6=null,Iq=x,Iq)).catch(x=>{nr("Could not load building-gen"),V6=null,FRe=x instanceof Error?x:new Error("Unknown error")}),V6}()}populate(m,x,k,E){const P=_Ct();if(!P)return;const O=dn(k);this.tileToMeter=O,this.brightness=x.brightness,P.setStyle({normalScale:[1,-1,O],tileToMeters:O}),P.setAOOptions(!1,.3),P.setMetricOptions(!1,16),P.setStructuralOptions(!0),P.setFacadeClassifierOptions(3);const U=new Map,H=new Map;let X=0;for(const{feature:Ke}of m){if(oOe[Ke.type]!=="LineString"){U.set(Ke.id,Ke.properties.source_id);continue}const lt=this.layers[0]._featureFilter.needGeometry;if(lt&&!this.layers[0]._featureFilter.filter(new La(this.zoom),Ke,k))continue;const nt=Wa(Ke,lt);if(!lt&&!this.layers[0]._featureFilter.filter(new La(this.zoom),nt,k))continue;const pt=lt?nt.geometry:Gr(Ke,k,E),_t=[];for(const Wt of pt)for(const $t of Wt)_t.push($t.x),_t.push($t.y);const jt={coordinates:_t,crossPerc:Ke.properties.cross_perc,distanceToRoad:Ke.properties.distance_to_road,entrances:Ke.properties.entrances,sourceId:0},Yt=Ke.properties.source_id;let zt=H.get(Yt);zt||(zt=[],H.set(Yt,zt)),zt.push(jt),++X}this.maxHeight=0;const oe=new Array,ue=new Set,me=Ke=>{Ke!=null&&ue.add(Ke)},_e=(Ke,lt)=>{Ke!=null&&oe.push({buildingId:Ke,footprintIndex:lt})},Se=64*(m.length-X),Pe=Se/2;this.buildingWithFacade.reserve(Se,Pe,!0),this.buildingWithoutFacade.reserve(2*Se,2*Pe,!1),this.footprintsIndices.reserve(16*(m.length-X)),this.footprintsVertices.reserve(8*(m.length-X));for(const{feature:Ke,id:lt,index:nt,sourceLayerIndex:pt}of m){if(oOe[Ke.type]==="LineString")continue;const _t=this.layers[0]._featureFilter.needGeometry;if(_t&&!this.layers[0]._featureFilter.filter(new La(this.zoom),Ke,k))continue;let jt=null;if(Ke.properties&&Ke.properties.hasOwnProperty("building_id")&&(jt=Number(Ke.properties.building_id),ue.has(jt)))continue;const Yt=Wa(Ke,_t);if(!_t&&!this.layers[0]._featureFilter.filter(new La(this.zoom),Yt,k))continue;const zt=_t?Yt.geometry:Gr(Ke,k,E),Wt=dO(zt,500);let $t=!1;for(const ai of Wt)if(ai.length!==1){$t=!0;break}if($t){me(jt);continue}if(!YCt(zt,163)){me(jt);continue}const Ut=this.layers[0],Bs=ZCt(Ut.layout.get("building-roof-shape").evaluate(Ke,{},k)),qs=Ut.layout.get("building-base").evaluate(Ke,{},k),Qs=Ut.layout.get("building-height").evaluate(Ke,{},k),sn=Ut.layout.get("building-flood-light-ground-radius").evaluate(Ke,{},k),Xs=Ut.paint.get("building-ambient-occlusion-intensity"),xn=sn/this.tileToMeter;Ke.properties["building-part"]="roof";const Os=Ut.paint.get("building-color").evaluate(Ke,{},this.canonical).toPremultipliedRenderColor(this.lut),en=Ut.paint.get("building-emissive-strength").evaluate(Ke,{},this.canonical);Ke.properties["building-part"]="wall";const on=Ut.paint.get("building-color").evaluate(Ke,{},this.canonical).toPremultipliedRenderColor(this.lut),yn=Ut.paint.get("building-emissive-strength").evaluate(Ke,{},this.canonical);Ke.properties["building-part"]="window";const Tn=Ut.paint.get("building-color").evaluate(Ke,{},this.canonical).toPremultipliedRenderColor(this.lut),or=Ut.paint.get("building-emissive-strength").evaluate(Ke,{},this.canonical);Ke.properties["building-part"]="door";const Fn=Ut.paint.get("building-color").evaluate(Ke,{},this.canonical).toPremultipliedRenderColor(this.lut),On=Ut.paint.get("building-emissive-strength").evaluate(Ke,{},this.canonical);let En=Ut.layout.get("building-flood-light-wall-radius").evaluate(Ke,{},k);En=Xe(En,0,2048);const rr=En/2048*Bq,pr=U.get(lt),Vr=H.get(pr)||[],kr=Vr.length!==0&&Ut.layout.get("building-facade").evaluate(Ke,{},k);P.setFacadeOptions(4,!0),P.setFauxFacadeOptions(kr,!1,1);let Ea=0,Ni=0,Aa=0,Ci=0,Ka=0,Ol=0,Ji=0,Di=0,Ro=0,Il=0,Qd=0;if(kr){let ai=Math.round(Ut.layout.get("building-facade-floors").evaluate(Ke,{},k));if(qs===0){ai=Math.max(1,ai-(Vr.length>0?1:0));let ac=4;if(Qs>100){const Ed=[10,13,15];ac=Ed[Ke.id?Ke.id%Ed.length:0]}else Qs<=10&&(ac=3);P.setFacadeOptions(ac,!0),Ka=(Qs<15?1.3:1.61803)*ac/O}else Ka=qs/O;Ol=Qs/O,Ka=Math.min(Ka,Ol),Aa=Ut.layout.get("building-facade-unit-width").evaluate(Ke,{},k)/O,Ci=(Ol-Ka)/ai,P.setFauxFacadeOptions(!0,!0,Aa);const wu=Ut.layout.get("building-facade-window").evaluate(Ke,{},k);Ea=wu[0],Ni=wu[1],Ji=Math.floor(65535*Math.min(1,Ka/$n)),Di=Math.floor(65535*Math.min(1,Ol/$n)),Ro=Math.floor(255*Ea)<<8|Math.floor(255*Ni),Il=Math.floor(65535*Math.min(1,Aa/$n)),Qd=Math.floor(65535*Math.min(1,Ci/$n))}const Pl=Array(Wt.length),nc={x:1/0,y:1/0},Uc={x:-1/0,y:-1/0},rc={x:0,y:0};let jh=0;for(let ai=0;ai0){const ac=[],Ed=Array(wu.length+1);Ed[0]=0;for(let E0=0;E0$n||nc.y<0||Uc.y>$n)&&this.featuresOnBorder.push({featureId:Ke.id,footprintIndex:this.footprints.length});{const ai=B6(t2,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+ai.length),this.footprintsIndices.uint16.set(ai,rI),this.buildingIds.add(jt??Ke.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,C0.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,C0.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,T0.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,T0.y);const wu={footprintVertexOffset:e2,footprintVertexLength:this.footprintsVertices.length-e2,footprintIndexOffset:rI,footprintIndexLength:this.footprintsIndices.length-rI,min:C0,max:T0,hiddenFlags:0,indicesOffset:fV,indicesLength:rwe,bloomIndicesOffset:Nh,bloomIndicesLength:Fl,groundEffectVertexOffset:o3,groundEffectVertexLength:aI,hasFauxFacade:kr,height:nI,promoteId:lt,feature:Yt,parts:bu,buildingBloom:hp},ac=this.footprints.length;Ke.id!==void 0&&this.featureFootprintLookup.set(Ke.id,ac),_e(jt,ac),this.footprints.push(wu)}this.programConfigurations.populatePaintArrays(Ja.layoutVertexArray.length,Ke,nt,{},x.availableImages,k,x.brightness),this.groundEffect.addPaintPropertiesData(Ke,nt,{},x.availableImages,k,x.brightness),x.featureIndex.insert(Ke,zt,nt,pt,this.index,km)}oe.forEach(({buildingId:Ke,footprintIndex:lt})=>{ue.has(Ke)&&(this.footprints[lt].hiddenFlags|=4)});const $e=new Set;this.buildingIds.forEach((Ke,lt,nt)=>{ue.has(Ke)||$e.add(Ke)}),this.buildingIds=$e,this.groundEffect.prepareBorderSegments()}update(m,x,k,E,P,O,U){this.programConfigurations.updatePaintArrays(m,x,P,k,E,O,U),this.groundEffect.update(m,x,P,k,E,O,U),this.evaluate(this.layers[0],m),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(m){const x=k=>{k.layoutVertexBuffer=m.createVertexBuffer(k.layoutVertexArray,aOe.members),k.layoutNormalBuffer=m.createVertexBuffer(k.layoutNormalArray,UCt.members),k.layoutCentroidBuffer=m.createVertexBuffer(k.layoutCentroidArray,qCt.members),k.layoutFloodLightDataBuffer=m.createVertexBuffer(k.layoutFloodLightDataArray,KCt.members),k.layoutFacadeDataArray&&k.layoutFacadeDataArray.length&&(k.layoutFacadeDataBuffer=m.createVertexBuffer(k.layoutFacadeDataArray,HCt.members)),k.layoutFacadeVerticalRangeArray&&k.layoutFacadeVerticalRangeArray.length&&(k.layoutFacadeVerticalRangeBuffer=m.createVertexBuffer(k.layoutFacadeVerticalRangeArray,GCt.members)),k.entranceBloom.layoutVertexArray.length&&(k.entranceBloom.layoutVertexBuffer=m.createVertexBuffer(k.entranceBloom.layoutVertexArray,aOe.members),k.entranceBloom.layoutAttenuationBuffer=m.createVertexBuffer(k.entranceBloom.layoutAttenuationArray,WCt.members)),this.uploadUpdatedColorBuffer(m),this.uploadUpdatedIndexBuffer(m)};this.uploaded||(x(this.buildingWithoutFacade),x(this.buildingWithFacade),this.groundEffect.upload(m)),this.groundEffect.uploadPaintProperties(m),this.programConfigurations.upload(m),this.uploaded=!0}destroy(){const m=x=>{x.layoutVertexBuffer&&(x.layoutVertexBuffer.destroy(),x.layoutNormalBuffer.destroy(),x.layoutColorBuffer.destroy(),x.segmentsBucket.destroy(),x.indexBuffer&&x.indexBuffer.destroy(),x.entranceBloom.layoutVertexBuffer&&(x.entranceBloom.layoutVertexBuffer.destroy(),x.entranceBloom.layoutColorBuffer.destroy(),x.entranceBloom.layoutAttenuationBuffer.destroy(),x.entranceBloom.indexBuffer.destroy(),x.entranceBloom.segmentsBucket.destroy()))};m(this.buildingWithoutFacade),m(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(m,x,k=!0){let E=!1;const P=k?x:0,O=0|(k?-1:~x);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const U of m){const H=this.footprints[U],X=H.hiddenFlags&O|P;H.hiddenFlags!==X&&(H.hiddenFlags=X,E=!0,this.groundEffect.updateHiddenByLandmarkRange(H.groundEffectVertexOffset,H.groundEffectVertexLength,H.hiddenFlags!==0))}return E&&(this.indexArrayForConflationUploaded=!1),E}uploadUpdatedIndexBuffer(m){if(this.groundEffect.uploadHiddenByLandmark(m),this.indexArrayForConflationUploaded)return;const x=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))};x(this.buildingWithoutFacade),x(this.buildingWithFacade);for(const E of this.footprints){const P=E.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,O=E.indicesOffset+E.indicesLength;if(E.hiddenFlags!==0){for(let H=E.indicesOffset;H{E.indexArray.length!==0&&(E.indexBuffer?E.indexBuffer.updateData(E.indexArrayForConflation):E.indexBuffer=m.createIndexBuffer(E.indexArrayForConflation,!0),E.entranceBloom.indexBuffer?E.entranceBloom.indexBuffer.updateData(E.entranceBloom.indexArrayForConflation):E.entranceBloom.indexBuffer=m.createIndexBuffer(E.entranceBloom.indexArrayForConflation,!0))};k(this.buildingWithoutFacade),k(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(m){const x=k=>{k.layoutColorBuffer?k.layoutColorBuffer.updateData(k.layoutColorArray):k.layoutColorBuffer=m.createVertexBuffer(k.layoutColorArray,iOe.members,!0),k.layoutFacadePaintArray&&(k.layoutFacadePaintBuffer?k.layoutFacadePaintBuffer.updateData(k.layoutFacadePaintArray):k.layoutFacadePaintBuffer=m.createVertexBuffer(k.layoutFacadePaintArray,VCt.members,!0)),k.entranceBloom.layoutColorBuffer?k.entranceBloom.layoutColorBuffer.updateData(k.entranceBloom.layoutColorArray):k.entranceBloom.layoutColorBuffer=m.createVertexBuffer(k.entranceBloom.layoutColorArray,iOe.members,!0)};x(this.buildingWithoutFacade),x(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(m,x){const k=m.paint.get("building-ambient-occlusion-intensity");for(const E of this.footprints){if(4&E.hiddenFlags)continue;const P=x[E.promoteId],O=E.feature;O.properties["building-part"]="roof";const U=m.paint.get("building-color").evaluate(O,P,this.canonical).toPremultipliedRenderColor(this.lut),H=m.paint.get("building-emissive-strength").evaluate(O,P,this.canonical);O.properties["building-part"]="wall";const X=m.paint.get("building-color").evaluate(O,P,this.canonical).toPremultipliedRenderColor(this.lut),oe=m.paint.get("building-emissive-strength").evaluate(O,P,this.canonical);O.properties["building-part"]="window";const ue=m.paint.get("building-color").evaluate(O,P,this.canonical).toPremultipliedRenderColor(this.lut),me=m.paint.get("building-emissive-strength").evaluate(O,P,this.canonical);O.properties["building-part"]="door";const _e=m.paint.get("building-color").evaluate(O,P,this.canonical).toPremultipliedRenderColor(this.lut),Se=m.paint.get("building-emissive-strength").evaluate(O,P,this.canonical),Pe=E.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const Ke of E.parts){let lt,nt=U;Ke.part===1?(nt=U,lt=H):Ke.part===0?(nt=X,lt=oe):Ke.part===2?(nt=ue,lt=me):Ke.part===3&&(nt=_e,lt=Se),lt=Xe(lt,0,1);for(let pt=0;ptO.max.x||H.max.xO.max.y||H.max.yU.max.x||U.min.x>m||x>U.max.y||U.min.y>x||U.height<=k||QCt(O,this.footprintsVertices.float32.subarray(2*U.footprintVertexOffset,2*(U.footprintVertexOffset+U.footprintVertexLength)),this.footprintsIndices.uint16.subarray(U.footprintIndexOffset,U.footprintIndexOffset+U.footprintIndexLength))&&(k=U.height,this.footprintLookup[P]=U,E=U.hiddenFlags!==0);if(k!==Number.NEGATIVE_INFINITY)return{height:k,hidden:E};this.footprintLookup[P]=void 0}}function QCt(w,m,x){for(let k=0;k1&&(H=m[++U]);const oe=Math.abs(X-H.left),ue=Math.abs(X-H.right),me=Math.min(oe,ue);let _e;const Se=P/k*(E+1);if(H.isDash){const Pe=E-Math.abs(Se);_e=Math.sqrt(me*me+Pe*Pe)}else _e=E-Math.sqrt(me*me+Se*Se);this.image.data[O+X]=Math.max(0,Math.min(255,_e+128))}}}addRegularDash(m,x){for(let H=m.length-1;H>=0;--H){const X=m[H],oe=m[H+1];X.zeroLength?m.splice(H,1):oe&&oe.isDash===X.isDash&&(oe.left=X.left,m.splice(H,1))}const k=m[0],E=m[m.length-1];k.isDash===E.isDash&&(k.left=E.left-this.width,E.right=k.right+this.width);const P=this.width*this.nextRow;let O=0,U=m[O];for(let H=0;H1&&(U=m[++O]);const X=Math.abs(H-U.left),oe=Math.abs(H-U.right),ue=Math.min(X,oe);this.image.data[P+H]=Math.max(0,Math.min(255,(U.isDash?ue:-ue)+x+128))}}addDash(m,x){const k=this.getKey(m,x);if(this.positions[k])return this.positions[k];const E=x==="round",P=E?7:0,O=2*P+1;if(this.nextRow+O>this.height)return nr("LineAtlas out of space"),null;m.length===0&&m.push(1);let U=0;for(let ue=0;uex.fqid),this.index=m.index,this.projection=m.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach(x=>{this.gradients[x.id]={}}),this.layoutVertexArray=new zC,this.layoutVertexArray2=new vg,this.patternVertexArray=new vg,this.indexArray=new sc,this.programConfigurations=new Ue(m.layers,{zoom:m.zoom,lut:m.lut}),this.segments=new Po,this.maxLineLength=0,this.zOffsetVertexArray=new vg,this.elevationGroundScaleVertexArray=new ro,this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.tessellationStep=m.tessellationStep?m.tessellationStep:128,this.worldview=m.worldview,this.hasAppearances=null}updateFootprints(m,x){}updateAppearances(m,x,k,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,E){this.hasPattern=Obe("line",this.layers,this.pixelRatio,x);const P=this.layers[0].layout.get("line-sort-key");this.tileToMeter=dn(k);const O=this.layers[0].layout.get("line-elevation-reference");if(O==="hd-road-markup")this.elevationType="road";else{const me=this.layers[0].layout.get("line-z-offset"),_e=me.isConstant()&&!me.constantOr(0);this.elevationType=O!=="sea"&&O!=="ground"&&_e?"none":"offset",this.elevationType==="offset"&&O==="none"&&nr(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=O==="sea"}const U=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&U!==void 0;const H=[];for(const{feature:me,id:_e,index:Se,sourceLayerIndex:Pe}of m){const $e=this.layers[0]._featureFilter.needGeometry,Ke=Wa(me,$e);if(!this.layers[0]._featureFilter.filter(new La(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),Ke,k))continue;const lt=P?P.evaluate(Ke,{},k):void 0,nt={id:_e,properties:me.properties,type:me.type,sourceLayerIndex:Pe,index:Se,geometry:$e?Ke.geometry:Gr(me,k,E),patterns:{},sortKey:lt};H.push(nt)}P&&H.sort((me,_e)=>me.sortKey-_e.sortKey);const{lineAtlas:X,featureIndex:oe}=x,ue=this.addConstantDashes(X);for(const me of H){const{geometry:_e,index:Se,sourceLayerIndex:Pe}=me;if(ue&&this.addFeatureDashes(me,X),this.hasPattern){const $e=Fbe("line",this.layers,me,this.zoom,this.pixelRatio,x);this.patternFeatures.push($e)}else this.addFeature(me,_e,Se,k,X.positions,x.availableImages,x.brightness,x.elevationFeatures);oe.insert(m[Se].feature,_e,Se,Pe,this.index)}}addConstantDashes(m){let x=!1;for(const k of this.layers){const E=k.paint.get("line-dasharray").value,P=k.layout.get("line-cap").value;if(E.kind!=="constant"||P.kind!=="constant")x=!0;else{const O=P.value,U=E.value;if(!U)continue;m.addDash(U,O)}}return x}addFeatureDashes(m,x){const k=this.zoom;for(const E of this.layers){const P=E.paint.get("line-dasharray").value,O=E.layout.get("line-cap").value;if(P.kind==="constant"&&O.kind==="constant")continue;let U,H;if(P.kind==="constant"){if(U=P.value,!U)continue}else U=P.evaluate({zoom:k},m);H=O.kind==="constant"?O.value:O.evaluate({zoom:k},m),x.addDash(U,H),m.patterns[E.id]=[x.getKey(U,H)]}}update(m,x,k,E,P,O,U,H,X){this.programConfigurations.updatePaintArrays(m,x,P,k,E,O,U,X)}addFeatures(m,x,k,E,P,O){for(const U of this.patternFeatures)this.addFeature(U,U.geometry,U.index,x,k,E,O,m.elevationFeatures)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(m){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=m.createVertexBuffer(this.layoutVertexArray2,r3t)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=m.createVertexBuffer(this.patternVertexArray,i3t)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=m.createVertexBuffer(this.zOffsetVertexArray,e3t.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=m.createVertexBuffer(this.elevationGroundScaleVertexArray,t3t.members,!0)),this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,s3t),this.indexBuffer=m.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(m),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(m,x){let k,E;if(x&&x>0?(k=`mapbox_clip_start_${x}`,E=`mapbox_clip_end_${x}`):(k="mapbox_clip_start",E="mapbox_clip_end"),m.properties&&m.properties.hasOwnProperty(k)&&m.properties.hasOwnProperty(E))return{start:+m.properties[k],end:+m.properties[E]}}addFeature(m,x,k,E,P,O,U,H){const X=this.layers[0].layout,oe=X.get("line-join").evaluate(m,{}),ue=X.get("line-cap").evaluate(m,{}),me=X.get("line-miter-limit"),_e=X.get("line-round-limit");this.lineClips=this.lineFeatureClips(m),this.lineFeature=m;const Se=!(!m.properties||!m.properties.hasOwnProperty("mapbox_line_metrics"))&&m.properties.mapbox_line_metrics;this.zOffsetValue=X.get("line-z-offset").value;const Pe=this.layers[0].paint.get("line-width").value;if(Pe.kind!=="constant"&&Pe.isLineProgressConstant===!1&&(this.variableWidthValue=Pe),this.isSeaLevelReference){const $e=X.get("line-elevation-ground-scale").value;$e.kind==="constant"&&$e.value===0||(this.elevationGroundScaleValue=$e)}if(this.elevationType==="road"){const $e=this.layoutVertexArray.length;if(!this.addElevatedRoadFeature(m,x,E,H,oe,ue,me,_e)){const[Ke,lt]=this.clipRuntimeLinesToTile(x,1);for(let nt=0;nt0?_t.parentIndex:null)}this.fillNonElevatedRoadSegment($e)}}else for(let $e=0;$e0?$e:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,m,k,P,O,E,U,void 0,this.worldview)}computeSegNextDir(m,x){return m.nextPoint.sub(x.at(-2)).unit()}computeSegPrevDir(m,x){return x[1].sub(m.prevPoint).unit()}clipLinesToTile(m,x){return Mq(m,-x,-x,$n+x,$n+x)}clipRuntimeLinesToTile(m,x){const k=[];return[Mq(m,-x,-x,$n+x,$n+x,k),k]}addElevatedRoadFeature(m,x,k,E,P,O,U,H){const X=[],oe=Bo.getElevationFeature(m,E);if(oe){const ue=this.clipLinesToTile(x,1),me=this.prepareElevatedLines(ue,oe,k);for(const _e of me)X.push({geometry:_e,elevation:oe,elevationTileID:k,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(X.length===0)return!1;for(const ue of X){const me=this.layoutVertexArray.length;this.addLine(ue.geometry,m,k,P,O,U,H);const _e=new Ko(k,ue.elevationTileID);if(ue.elevation)for(let Se=me;Se>1,this.layoutVertexArray.int16[6*Se+1]>>1),$e=_e.pointElevation(Pe,ue.elevation,.05);this.updateHeightRange($e),this.zOffsetVertexArray.emplaceBack($e,0,0)}else this.fillNonElevatedRoadSegment(me)}return!0}prepareElevatedLines(m,x,k){if(x.constantHeight!=null)return m;const E=[],P=1/dn(k);for(const O of m)vCt(O,new Cx(x,P),0,E);return E}fillNonElevatedRoadSegment(m){for(let x=m;x0,me=H&&H.progress.max<1;if(this.lineClips){let Wt={min:this.lineClips.start,max:this.lineClips.end},$t=1;if(H){const qs=this.lineClips.end-this.lineClips.start;Wt=function(Qs,sn,Xs){return{min:qi(Qs.min,sn,Xs),max:qi(Qs.max,sn,Xs)}}(H.progress,{min:0,max:1},Wt),qs>0&&($t=(Wt.max-Wt.min)/qs)}const Ut=+x.properties.mapbox_clip_feature_len,Bs=+x.properties.mapbox_clip_seg_len;if(Number.isNaN(Ut)||Number.isNaN(Bs)){for(let Qs=0;Qs=2&&m[Se-1].equals(m[Se-2]);)Se--;let Pe=0;for(;Pe0,en=this.overscaling<=16?122880/(512*this.overscaling):0;if($t&&Ut==="round"){if(snO&&(Ut="bevel"),Ut==="bevel"&&(sn>2&&(Ut="flipbevel"),sn2*en){const Tn=Ke.sub(Ke.sub(lt)._mult(en/on)._round());this.updateDistance(lt,Tn),this.addCurrentVertex(Tn,pt,0,0,$e,zt),lt=Tn}this.updateDistance(lt,Ke),qs._mult(sn),this.addCurrentVertex(Ke,qs,0,0,$e,zt);const yn=Ke.dist(nt);if(yn>2*en){const Tn=Ke.add(nt.sub(Ke)._mult(en/yn)._round());this.updateDistance(Ke,Tn),this.addCurrentVertex(Tn,_t,0,0,$e,zt),Ke=Tn}}else qs._mult(sn),this.addCurrentVertex(Ke,qs,0,0,$e,zt);else if(Ut==="flipbevel"){if(sn>100)qs=_t.mult(-1);else{const on=sn*pt.add(_t).mag()/pt.sub(_t).mag();qs._perp()._mult(on*(Os?-1:1))}this.addCurrentVertex(Ke,qs,0,0,$e,zt),this.addCurrentVertex(Ke,qs.mult(-1),0,0,$e,zt)}else if(Ut==="bevel"||Ut==="fakeround"){const on=Ke.dist(lt);let yn=1;if(this.elevationType==="offset"&&Ut==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&zt!=null&<&&nt){const rr=4*en;on1){this.lineSoFar=m.w;const Pe=(x.x-m.x)/ue,$e=(x.y-m.y)/ue,Ke=(x.z-m.z)/ue,lt=(x.w-m.w)/ue,nt=x.x-m.x,pt=x.y-m.y,_t=Math.sqrt(nt*nt+pt*pt);if(_t===0)return;const jt=-pt/_t,Yt=nt/_t,zt=jt,Wt=Yt,$t=-jt,Ut=-Yt;for(let Bs=1;Bs=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,oe),H.primitiveLength++),O?this.e2=oe:this.e1=oe,X!=null&&this.zOffsetVertexArray.emplaceBack(X.zOffset,X.variableWidth,X.variableWidth),this.elevationGroundScaleValue){const ue=X?X.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(ue)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(m,x){this.prevDistance=this.distance,this.distance+=m.dist(x),this.updateScaledDistance()}}function f_e(w,m,x){return w.xx||w.yx}let hOe,mOe;function pOe(w,m,x){return m*($n/(w.tileSize*Math.pow(2,x-w.tileID.overscaledZ)))}Kn($q,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const fOe=(w,m,x)=>(1-x)*w+x*m;function xOe(w,m){return 1/pOe(w,1,m.tileZoom)}function gOe(w,m,x,k){return w.translatePosMatrix(k||m.tileID.projMatrix,m,x.paint.get("line-translate"),x.paint.get("line-translate-anchor"))}const yOe=w=>{const m=[];vOe(w)&&m.push("RENDER_LINE_DASH"),w.paint.get("line-gradient")&&m.push("RENDER_LINE_GRADIENT"),w.paint.get("line-blend-mode")==="multiply"&&m.push("LINE_BLEND_MULTIPLY");const x=w.paint.get("line-trim-offset");x[0]===0&&x[1]===0||m.push("RENDER_LINE_TRIM_OFFSET"),w.paint.get("line-border-width").constantOr(1)!==0&&m.push("RENDER_LINE_BORDER");const k=w.layout.get("line-join").constantOr("miter")==="none",E=!!w.paint.get("line-pattern").constantOr(1);return k&&E&&m.push("LINE_JOIN_NONE"),m};function vOe(w){const m=w.paint.get("line-dasharray").value;return m.kind!=="constant"||m.value}let x_e;const bOe=()=>x_e||(x_e={layout:hOe||(hOe=new Wo({"line-cap":new jn(fs.layout_line["line-cap"]),"line-join":new jn(fs.layout_line["line-join"]),"line-miter-limit":new kn(fs.layout_line["line-miter-limit"]),"line-round-limit":new kn(fs.layout_line["line-round-limit"]),"line-sort-key":new jn(fs.layout_line["line-sort-key"]),"line-z-offset":new jn(fs.layout_line["line-z-offset"]),"line-elevation-reference":new kn(fs.layout_line["line-elevation-reference"]),"line-cross-slope":new kn(fs.layout_line["line-cross-slope"]),visibility:new kn(fs.layout_line.visibility),"line-width-unit":new kn(fs.layout_line["line-width-unit"]),"line-elevation-ground-scale":new jn(fs.layout_line["line-elevation-ground-scale"])})),paint:mOe||(mOe=new Wo({"line-opacity":new jn(fs.paint_line["line-opacity"]),"line-color":new jn(fs.paint_line["line-color"]),"line-translate":new kn(fs.paint_line["line-translate"]),"line-translate-anchor":new kn(fs.paint_line["line-translate-anchor"]),"line-width":new jn(fs.paint_line["line-width"]),"line-gap-width":new jn(fs.paint_line["line-gap-width"]),"line-offset":new jn(fs.paint_line["line-offset"]),"line-blur":new jn(fs.paint_line["line-blur"]),"line-dasharray":new jn(fs.paint_line["line-dasharray"]),"line-pattern":new jn(fs.paint_line["line-pattern"]),"line-pattern-cross-fade":new kn(fs.paint_line["line-pattern-cross-fade"]),"line-gradient":new Gp(fs.paint_line["line-gradient"]),"line-trim-offset":new kn(fs.paint_line["line-trim-offset"]),"line-trim-fade-range":new kn(fs.paint_line["line-trim-fade-range"]),"line-trim-color":new kn(fs.paint_line["line-trim-color"]),"line-emissive-strength":new jn(fs.paint_line["line-emissive-strength"]),"line-border-width":new jn(fs.paint_line["line-border-width"]),"line-border-color":new jn(fs.paint_line["line-border-color"]),"line-occlusion-opacity":new kn(fs.paint_line["line-occlusion-opacity"]),"line-blend-mode":new kn(fs.paint_line["line-blend-mode"]),"line-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"})}))},x_e);class d3t extends jn{possiblyEvaluate(m,x){return x=new La(Math.floor(x.zoom),{now:x.now,fadeDuration:x.fadeDuration,transition:x.transition,worldview:x.worldview}),super.possiblyEvaluate(m,x)}evaluate(m,x,k,E){return x=Object.assign({},x,{zoom:Math.floor(x.zoom)}),super.evaluate(m,x,k,E)}}let wO;function _Oe(w,m){return m>0?m+2*w:w}const u3t=cn([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),h3t=cn([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),m3t=cn([{name:"a_projected_pos",components:4,type:"Float32"}],4);cn([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const p3t=cn([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),f3t=cn([{name:"a_feature_index",components:1,type:"Float32"}],4),x3t=cn([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),g3t=cn([{name:"a_texb",components:2,type:"Uint16"}]),y3t=cn([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),v3t=cn([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);cn([{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 wOe=cn([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),b3t=cn([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);cn([{name:"triangle",components:3,type:"Uint16"}]),cn([{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"}]),cn([{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"}]),cn([{type:"Float32",name:"offsetX"}]),cn([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const g_e=class Mme{constructor(m=null,x=0,k=4096){this.batchIndex=x,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=m||null,this.propsDwords=k,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(Mme.HEADER_DWORDS),this.propertiesData=new Float32Array(this.propsDwords),this.blockIndicesData=new Uint32Array(this.propsDwords);for(let E=0;Em.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${m.maxUniformBlockSize}`);if(this.headerBuffer=x.createBuffer(),!this.headerBuffer)throw new Error("Failed to create header UBO buffer");if(x.bindBuffer(x.UNIFORM_BUFFER,this.headerBuffer),x.bufferData(x.UNIFORM_BUFFER,Mme.HEADER_BYTES,x.DYNAMIC_DRAW),this.propertiesBuffer=x.createBuffer(),!this.propertiesBuffer)throw new Error("Failed to create properties UBO buffer");if(x.bindBuffer(x.UNIFORM_BUFFER,this.propertiesBuffer),x.bufferData(x.UNIFORM_BUFFER,this.totalBytes,x.DYNAMIC_DRAW),this.blockIndicesBuffer=x.createBuffer(),!this.blockIndicesBuffer)throw new Error("Failed to create block-indices UBO buffer");x.bindBuffer(x.UNIFORM_BUFFER,this.blockIndicesBuffer),x.bufferData(x.UNIFORM_BUFFER,this.totalBytes,x.DYNAMIC_DRAW),x.bindBuffer(x.UNIFORM_BUFFER,null)}writeHeader(m){const x=this.headerData;x[0]=m.dataDrivenMask,x[1]=m.zoomDependentMask,x[2]=m.dataDrivenBlockSizeVec4,x[3]=m.offsets[0],x[4]=m.offsets[1],x[5]=m.offsets[2],x[6]=m.offsets[3],x[7]=m.offsets[4],x[8]=m.offsets[5],x[9]=m.offsets[6],x[10]=m.offsets[7],x[11]=m.offsets[8]}writeDataDrivenBlock(m,x,k){const E=4*k.dataDrivenBlockSizeVec4;if(E===0)return;const P=x*E;if(P+E>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${x} exceeds propertiesData capacity`);for(let O=0;O<9;O++)k.dataDrivenMask&1<{if(!U)return;const X=k.getUniformBlockIndex(x,O);X!==k.INVALID_INDEX&&(k.uniformBlockBinding(x,X,H),k.bindBufferBase(k.UNIFORM_BUFFER,H,U))},P=3*this.batchIndex;E("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,P),E("SymbolPaintPropertiesUniform",this.propertiesBuffer,P+1),E("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,P+2)}destroy(){if(this.context){const m=this.context.gl;this.headerBuffer&&(m.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(m.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(m.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};g_e.HEADER_DWORDS=12,g_e.HEADER_BYTES=48;let y_e=g_e;function v_e(w,m,x,k){return[R6(255*w,255*m),R6(255*x,255*k)]}function jOe(w,m,x,k,E,P,O,U){return!!w&&(w.kind==="constant"?w.value==="none":w.kind==="composite"||w.kind==="source"?w.evaluate({zoom:0,brightness:P,worldview:U},m,x,E,k,O)==="none":typeof w=="string"&&w==="none")}Kn(y_e,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class b_e{constructor(m,x,k,E,P="",O,U){this.layer=m,this.zoom=x,this.lut=k,this.isText=E,this.propDefs=this._getPropDefs(),this.worldview=P,this.maxUniformBufferBindings=O||24,this.uboSizeDwords=U||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(m,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 m=this.isText?"text":"icon";return[{name:`${m}-color`,useThemeName:`${m}-color-use-theme`,isColor:!0},{name:`${m}-halo-color`,useThemeName:`${m}-halo-color-use-theme`,isColor:!0},{name:`${m}-opacity`,useThemeName:null,isColor:!1},{name:`${m}-halo-width`,useThemeName:null,isColor:!1},{name:`${m}-halo-blur`,useThemeName:null,isColor:!1},{name:`${m}-emissive-strength`,useThemeName:null,isColor:!1},{name:`${m}-occlusion-opacity`,useThemeName:null,isColor:!1},{name:"symbol-z-offset",useThemeName:null,isColor:!1},{name:`${m}-translate`,useThemeName:null,isColor:!1,isVec2:!0}]}buildHeader(){const m=this.layer.paint,x=this.propDefs;let k=0,E=0,P=0,O=0;const U=[0,0,0,0,0,0,0,0,0];for(let H=0;H<9;H++){const{name:X,isColor:oe,isVec2:ue}=x[H],me=m.get(X),_e=!(!me||typeof me.isConstant!="function"||me.isConstant()),Se=this._appearancesHavePaintProperties(X),Pe=_e||Se,$e=!(!me||!me.value||me.value.kind!=="composite"),Ke=this.layer._transitionablePaint._values[X],lt=!Pe&&(Ke&&Ke.value&&Ke.value.expression&&Ke.value.expression.kind)==="camera";Pe?(k|=1<x.hasPaintProperty(m):this.isText?x=>x.hasTextPaintProperties():x=>x.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(m,x){const k=m.paint,E=x?"text":"icon",P=[`${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 O of P){const U=k.get(O);if(U&&typeof U=="object"&&"isConstant"in U&&!U.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(m,x){if(x.dataDrivenMask===0)return"";const k=[];for(let E=0;E<9;E++){if(!(x.dataDrivenMask&1<=Se){nr(`Too many symbol features: batch ${me} requires binding points up to ${3*me+2}, device limit ${Se}. Some features will render incorrectly.`);const $e={batchIndex:0,localFeatureIndex:0,vtFeatureIndex:x,featureId:H};return this.allFeatures.push($e),H!=null&&(this.featureVertexRangesFromId.has(H)||this.featureVertexRangesFromId.set(H,[]),this.featureVertexRangesFromId.get(H).push($e)),0}this.ubos[me]||(this.ubos[me]=new y_e(U,me,this.uboSizeDwords),this.ubos[me].writeHeader(X)),this.ubos[me].writeDataDrivenBlock(oe,_e,X);const Pe={batchIndex:me,localFeatureIndex:_e,vtFeatureIndex:x,featureId:H};return this.allFeatures.push(Pe),H!=null&&(this.featureVertexRangesFromId.has(H)||this.featureVertexRangesFromId.set(H,[]),this.featureVertexRangesFromId.get(H).push(Pe)),_e}updateFeatures(m,x,k,E,P,O,U){if(this.layer=x,this.cachedConstantUniforms=null,!this.cachedHeader)return;const H=this.cachedHeader;for(const X of m){const oe=this.featureVertexRangesFromId.get(X);if(!oe)continue;const ue=O[X]||{};for(const me of oe){if(!k)continue;const _e=k.feature(me.vtFeatureIndex);if(!_e)continue;const Se={type:_e.type,id:X,properties:_e.properties||{},geometry:[]},Pe=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(me.vtFeatureIndex):void 0,$e=this.evaluateAllProperties(Se,ue,E,P,U,void 0,Pe);this.ubos[me.batchIndex]&&this.ubos[me.batchIndex].writeDataDrivenBlock($e,me.localFeatureIndex,H)}}}updateDynamicExpressions(m,x,k,E,P,O){if(this.layer=m,this.cachedConstantUniforms=null,!this.cachedHeader)return;const U=this.cachedHeader;for(const H of this.allFeatures){if(!x)continue;const X=x.feature(H.vtFeatureIndex);if(!X)continue;const oe=H.featureId!=null&&P[H.featureId]||{},ue={type:X.type,id:H.featureId,properties:X.properties||{},geometry:[]},me=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(H.vtFeatureIndex):void 0,_e=this.evaluateAllProperties(ue,oe,k,E,O,void 0,me);this.ubos[H.batchIndex]&&this.ubos[H.batchIndex].writeDataDrivenBlock(_e,H.localFeatureIndex,U)}}updateFeaturePaintForAppearance(m,x,k,E,P,O,U){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(m,U||null),!this.cachedHeader))return!1;const H=this.cachedHeader;if(H.dataDrivenMask===0)return!1;let X=!1;for(const oe of this.allFeatures){if(oe.vtFeatureIndex!==m)continue;const ue=this.evaluateAllProperties(x,k,E,P,O,void 0,U);this.ubos[oe.batchIndex]&&(this.ubos[oe.batchIndex].writeDataDrivenBlock(ue,oe.localFeatureIndex,H),X=!0)}return X}getConstantUniformValues(m,x){const k=this.cachedHeader,E=!(!k||!k.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===x&&(!E||this.cachedConstantRenderZoom===m))return this.cachedConstantUniforms;const P=this.layer.paint,O=this.propDefs,U=E?new La(m,{brightness:x,worldview:this.worldview}):null,H={type:1,id:void 0,properties:{},geometry:[]},X=me=>{const _e=O[me],Se=P.get(_e.name);if(!Se)return[0,0,0,1];const Pe=_e.useThemeName?P.get(_e.useThemeName):void 0,$e=jOe(Pe&&typeof Pe!="string"?Pe.value:void 0,H,{},[],void 0,x,void 0,this.worldview)?null:this.lut;let Ke;Ke=k&&k.cameraMask&1<{const Se=P.get(O[me].name);if(!Se)return _e;if(k&&k.cameraMask&1<{k.text=function(E,P,O){const U=P.layout.get("text-transform").evaluate(O,{});return U==="uppercase"?E=E.toLocaleUpperCase():U==="lowercase"&&(E=E.toLocaleLowerCase()),Nm.applyArabicShaping&&(E=Nm.applyArabicShaping(E)),E}(k.text,m,x)}),w}const jO={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function w3t(w){return w==="︶"||w==="﹈"||w==="︸"||w==="﹄"||w==="﹂"||w==="︾"||w==="︼"||w==="︺"||w==="︘"||w==="﹀"||w==="︐"||w==="︓"||w==="︔"||w==="`"||w===" ̄"||w==="︑"||w==="︒"}function j3t(w){return w==="︵"||w==="﹇"||w==="︷"||w==="﹃"||w==="﹁"||w==="︽"||w==="︻"||w==="︹"||w==="︗"||w==="︿"}const __e=4294967296,NOe=1/__e,kOe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let Uq=class{constructor(w=new Uint8Array(16)){this.buf=ArrayBuffer.isView(w)?w:new Uint8Array(w),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(w,m,x=this.length){for(;this.pos>3,P=this.pos;this.type=7&k,w(E,m,this),this.pos===P&&this.skip(k)}return m}readMessage(w,m){return this.readFields(w,m,this.readVarint()+this.pos)}readFixed32(){const w=this.dataView.getUint32(this.pos,!0);return this.pos+=4,w}readSFixed32(){const w=this.dataView.getInt32(this.pos,!0);return this.pos+=4,w}readFixed64(){const w=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*__e;return this.pos+=8,w}readSFixed64(){const w=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*__e;return this.pos+=8,w}readFloat(){const w=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,w}readDouble(){const w=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,w}readVarint(w){const m=this.buf;let x,k;return k=m[this.pos++],x=127&k,k<128?x:(k=m[this.pos++],x|=(127&k)<<7,k<128?x:(k=m[this.pos++],x|=(127&k)<<14,k<128?x:(k=m[this.pos++],x|=(127&k)<<21,k<128?x:(k=m[this.pos],x|=(15&k)<<28,function(E,P,O){const U=O.buf;let H,X;if(X=U[O.pos++],H=(112&X)>>4,X<128||(X=U[O.pos++],H|=(127&X)<<3,X<128)||(X=U[O.pos++],H|=(127&X)<<10,X<128)||(X=U[O.pos++],H|=(127&X)<<17,X<128)||(X=U[O.pos++],H|=(127&X)<<24,X<128)||(X=U[O.pos++],H|=(1&X)<<31,X<128))return G6(E,H,P);throw new Error("Expected varint not more than 10 bytes")}(x,w,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const w=this.readVarint();return w%2==1?(w+1)/-2:w/2}readBoolean(){return!!this.readVarint()}readString(){const w=this.readVarint()+this.pos,m=this.pos;return this.pos=w,w-m>=12&&kOe?kOe.decode(this.buf.subarray(m,w)):function(x,k,E){let P="",O=k;for(;O239?4:U>223?3:U>191?2:1;if(O+me>E)break;me===1?U<128&&(ue=U):me===2?(H=x[O+1],(192&H)==128&&(ue=(31&U)<<6|63&H,ue<=127&&(ue=null))):me===3?(H=x[O+1],X=x[O+2],(192&H)==128&&(192&X)==128&&(ue=(15&U)<<12|(63&H)<<6|63&X,(ue<=2047||ue>=55296&&ue<=57343)&&(ue=null))):me===4&&(H=x[O+1],X=x[O+2],oe=x[O+3],(192&H)==128&&(192&X)==128&&(192&oe)==128&&(ue=(15&U)<<18|(63&H)<<12|(63&X)<<6|63&oe,(ue<=65535||ue>=1114112)&&(ue=null))),ue===null?(ue=65533,me=1):ue>65535&&(ue-=65536,P+=String.fromCharCode(ue>>>10&1023|55296),ue=56320|1023&ue),P+=String.fromCharCode(ue),O+=me}return P}(this.buf,m,w)}readBytes(){const w=this.readVarint()+this.pos,m=this.buf.subarray(this.pos,w);return this.pos=w,m}readPackedVarint(w=[],m){const x=this.readPackedEnd();for(;this.pos127;);else if(m===2)this.pos=this.readVarint()+this.pos;else if(m===5)this.pos+=4;else{if(m!==1)throw new Error(`Unimplemented type: ${m}`);this.pos+=8}}writeTag(w,m){this.writeVarint(w<<3|m)}realloc(w){let m=this.length||16;for(;m268435455||w<0?function(m,x){let k,E;if(m>=0?(k=m%4294967296|0,E=m/4294967296|0):(k=~(-m%4294967296),E=~(-m/4294967296),4294967295^k?k=k+1|0:(k=0,E=E+1|0)),m>=18446744073709552e3||m<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");x.realloc(10),function(P,O,U){U.buf[U.pos++]=127&P|128,P>>>=7,U.buf[U.pos++]=127&P|128,P>>>=7,U.buf[U.pos++]=127&P|128,P>>>=7,U.buf[U.pos++]=127&P|128,U.buf[U.pos]=127&(P>>>=7)}(k,0,x),function(P,O){const U=(7&P)<<4;O.buf[O.pos++]|=U|((P>>>=3)?128:0),P&&(O.buf[O.pos++]=127&P|((P>>>=7)?128:0),P&&(O.buf[O.pos++]=127&P|((P>>>=7)?128:0),P&&(O.buf[O.pos++]=127&P|((P>>>=7)?128:0),P&&(O.buf[O.pos++]=127&P|((P>>>=7)?128:0),P&&(O.buf[O.pos++]=127&P)))))}(E,x)}(w,this):(this.realloc(4),this.buf[this.pos++]=127&w|(w>127?128:0),w<=127||(this.buf[this.pos++]=127&(w>>>=7)|(w>127?128:0),w<=127||(this.buf[this.pos++]=127&(w>>>=7)|(w>127?128:0),w<=127||(this.buf[this.pos++]=w>>>7&127))))}writeSVarint(w){this.writeVarint(w<0?2*-w-1:2*w)}writeBoolean(w){this.writeVarint(+w)}writeString(w){w=String(w),this.realloc(4*w.length),this.pos++;const m=this.pos;this.pos=function(k,E,P){for(let O,U,H=0;H55295&&O<57344){if(!U){O>56319||H+1===E.length?(k[P++]=239,k[P++]=191,k[P++]=189):U=O;continue}if(O<56320){k[P++]=239,k[P++]=191,k[P++]=189,U=O;continue}O=U-55296<<10|O-56320|65536,U=null}else U&&(k[P++]=239,k[P++]=191,k[P++]=189,U=null);O<128?k[P++]=O:(O<2048?k[P++]=O>>6|192:(O<65536?k[P++]=O>>12|224:(k[P++]=O>>18|240,k[P++]=O>>12&63|128),k[P++]=O>>6&63|128),k[P++]=63&O|128)}return P}(this.buf,w,this.pos);const x=this.pos-m;x>=128&&SOe(m,x,this),this.pos=m-1,this.writeVarint(x),this.pos+=x}writeFloat(w){this.realloc(4),this.dataView.setFloat32(this.pos,w,!0),this.pos+=4}writeDouble(w){this.realloc(8),this.dataView.setFloat64(this.pos,w,!0),this.pos+=8}writeBytes(w){const m=w.length;this.writeVarint(m),this.realloc(m);for(let x=0;x=128&&SOe(x,k,this),this.pos=x-1,this.writeVarint(k),this.pos+=k}writeMessage(w,m,x){this.writeTag(w,2),this.writeRawMessage(m,x)}writePackedVarint(w,m){m.length&&this.writeMessage(w,N3t,m)}writePackedSVarint(w,m){m.length&&this.writeMessage(w,k3t,m)}writePackedBoolean(w,m){m.length&&this.writeMessage(w,T3t,m)}writePackedFloat(w,m){m.length&&this.writeMessage(w,S3t,m)}writePackedDouble(w,m){m.length&&this.writeMessage(w,C3t,m)}writePackedFixed32(w,m){m.length&&this.writeMessage(w,E3t,m)}writePackedSFixed32(w,m){m.length&&this.writeMessage(w,A3t,m)}writePackedFixed64(w,m){m.length&&this.writeMessage(w,M3t,m)}writePackedSFixed64(w,m){m.length&&this.writeMessage(w,I3t,m)}writeBytesField(w,m){this.writeTag(w,2),this.writeBytes(m)}writeFixed32Field(w,m){this.writeTag(w,5),this.writeFixed32(m)}writeSFixed32Field(w,m){this.writeTag(w,5),this.writeSFixed32(m)}writeFixed64Field(w,m){this.writeTag(w,1),this.writeFixed64(m)}writeSFixed64Field(w,m){this.writeTag(w,1),this.writeSFixed64(m)}writeVarintField(w,m){this.writeTag(w,0),this.writeVarint(m)}writeSVarintField(w,m){this.writeTag(w,0),this.writeSVarint(m)}writeStringField(w,m){this.writeTag(w,2),this.writeString(m)}writeFloatField(w,m){this.writeTag(w,5),this.writeFloat(m)}writeDoubleField(w,m){this.writeTag(w,1),this.writeDouble(m)}writeBooleanField(w,m){this.writeVarintField(w,+m)}};function G6(w,m,x){return x?4294967296*m+(w>>>0):4294967296*(m>>>0)+(w>>>0)}function SOe(w,m,x){const k=m<=16383?1:m<=2097151?2:m<=268435455?3:Math.floor(Math.log(m)/(7*Math.LN2));x.realloc(k);for(let E=x.pos-1;E>=w;E--)x.buf[E+k]=x.buf[E]}function N3t(w,m){for(let x=0;x=0&&k>=m&&qq[this.text.charCodeAt(k)];k--)x--;this.text=this.text.substring(m,x),this.sectionIndex=this.sectionIndex.slice(m,x)}substring(m,x){const k=new W6;return k.text=this.text.substring(m,x),k.sectionIndex=this.sectionIndex.slice(m,x),k.sections=this.sections,k}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((m,x)=>Math.max(m,this.sections[x].scale),0)}addTextSection(m,x){this.text+=m.text,this.sections.push(NO.forText(m.scale,m.fontStack||x));const k=this.sections.length-1;for(let E=0;E=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function w_e(w,m,x,k,E,P,O,U,H,X,oe,ue,me,_e,Se,Pe=1,$e=1){const Ke=W6.fromFeature(w,E,Pe,$e);ue===Mx.vertical&&Ke.verticalizePunctuation(me);let lt=[];const nt=function(zt,Wt,$t,Ut,Bs,qs,Qs=1){if(!zt)return[];const sn=[],Xs=function(en,on,yn,Tn,or,Fn,On=1){let En=0;for(let rr=0;rr=0;let Os=0;for(let en=0;en0&&km>Ka&&(Ka=km)}else{const bu=$t[Il.fontStack];if(!bu)continue;bu[Pl]&&(rc=bu[Pl]);const hp=Wt[Il.fontStack];if(!hp)continue;const Nh=hp.glyphs[Pl];if(!Nh)continue;if(Uc=Nh.metrics,Xd=Pl!==8203?Zd:0,On){const Fl=hp.ascender!==void 0?Math.abs(hp.ascender):0,km=hp.descender!==void 0?Math.abs(hp.descender):0,_u=(Fl+km)*nc;Ol<_u&&(Ol=_u,Ji=(Fl-km)/2*nc),Ja=-Fl*nc}else Ja=(Ea-nc)*Zd-17}fc?(zt.verticalizable=!0,Ci.push({glyph:Pl,image:jh,x:yn,y:Tn+Ja,vertical:fc,scale:nc,localGlyph:Uc.localGlyph,fontStack:Il.fontStack,sectionIndex:Qd,metrics:Uc,rect:rc}),yn+=Xd*nc+xn):(Ci.push({glyph:Pl,image:jh,x:yn,y:Tn+Ja,vertical:fc,scale:nc,localGlyph:Uc.localGlyph,fontStack:Il.fontStack,sectionIndex:Qd,metrics:Uc,rect:rc}),yn+=Uc.advance*nc+xn)}Ci.length!==0&&(or=Math.max(yn-xn,or),On?MOe(Ci,Fn,Ka,Ji,qs*Ea/2):MOe(Ci,Fn,Ka,0,qs/2)),yn=0;const Di=qs*Ea+Ka;Aa.lineOffset=Math.max(Ka,Ni),Tn+=Di,++En}const rr=Tn,{horizontalAlign:pr,verticalAlign:Vr}=j_e(Qs);(function(kr,Ea,Ni,Aa,Ci,Ka){const Ol=(Ea-Ni)*Ci,Ji=-Ka*Aa;for(const Di of kr)for(const Ro of Di.positionedGlyphs)Ro.x+=Ol,Ro.y+=Ji})(zt.positionedLines,Fn,pr,Vr,or,rr),zt.top+=-Vr*rr,zt.bottom=zt.top+rr,zt.left+=-pr*or,zt.right=zt.left+or,zt.hasBaseline=On}(Yt,m,x,k,lt,O,U,H,ue,X,me,Se,$e),!function(zt){for(const Wt of zt)if(Wt.positionedGlyphs.length!==0)return!1;return!0}(jt))return Yt}const qq={9:!0,10:!0,11:!0,12:!0,13:!0,32:!0},R3t={10:!0,32:!0,38:!0,40:!0,41:!0,43:!0,45:!0,47:!0,173:!0,183:!0,8203:!0,8208:!0,8211:!0,8231:!0};function COe(w,m,x,k,E,P,O=1){if(m.image){const U=k.get(m.image.toString());return U?U.displaySize[0]*O*m.scale*Zd/P+E:0}{const U=x[m.fontStack],H=U&&U.glyphs[w];return H?H.metrics.advance*m.scale+E:0}}function TOe(w,m,x,k){const E=Math.pow(w-m,2);return k?w-x/2;){if(O--,O<0)return!1;U-=w[O].dist(P),P=w[O]}U+=w[O].dist(w[O+1]),O++;const H=[];let X=0;for(;Uk;)X-=H.shift().angleDelta;if(X>E)return!1;O++,U+=oe.dist(ue)}return!0}function ROe(w){let m=0;for(let x=0;xX){const Se=(X-H)/_e,Pe=zr(ue.x,me.x,Se),$e=zr(ue.y,me.y,Se),Ke=new Jj(Pe,$e,0,me.angleTo(ue),oe);return!O||DOe(w,Ke,U,O,m)?Ke:void 0}H+=_e}}function z3t(w,m,x,k,E,P,O,U,H){const X=OOe(k,P,O),oe=FOe(k,E),ue=oe*O,me=w[0].x===0||w[0].x===H||w[0].y===0||w[0].y===H;return m-ue=0&&pt=0&&_t=0&&me+X<=oe){const jt=new Jj(pt,_t,0,lt,Se);k&&!DOe(w,jt,P,k,E)||_e.push(jt)}}ue+=Ke}return U||_e.length||O||(_e=zOe(w,ue/2,x,k,E,P,O,!0,H)),_e}function BOe(w){let m=0,x=0;for(const O of w)m+=O.w*O.h,x=Math.max(x,O.w);w.sort((O,U)=>U.h-O.h);const k=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(m/.95)),x),h:1/0}];let E=0,P=0;for(const O of w)for(let U=k.length-1;U>=0;U--){const H=k[U];if(!(O.w>H.w||O.h>H.h)){if(O.x=H.x,O.y=H.y,P=Math.max(P,O.y+O.h),E=Math.max(E,O.x+O.w),O.w===H.w&&O.h===H.h){const X=k.pop();X&&Um.id?1:w.versionm.version?1:w.sxm.sx?1:w.sym.sy?1:0}function C_e(w){let m=0;for(let x=0;x0,$Oe(m,k,this.iconDescriptors,P),$Oe(x,k,this.patternDescriptors,P),this.iconDescriptors.sort(Hq),this.patternDescriptors.sort(Hq);let O=0;const U=E?E.data:"";U&&(O=A1(O,C_e(U))),O=A1(O,1);for(const H of this.iconDescriptors)O=A1(O,C_e(H.id)),O=A1(O,H.version),O=A1(O,H.sx),O=A1(O,H.sy);O=A1(O,1);for(const H of this.patternDescriptors)O=A1(O,C_e(H.id)),O=A1(O,H.version),O=A1(O,H.sx),O=A1(O,H.sy);this.hash=O}subsetOf(m){return this.isSubsetArray(this.iconDescriptors,m.iconDescriptors,Hq)&&this.isSubsetArray(this.patternDescriptors,m.patternDescriptors,Hq)}isSubsetArray(m,x,k){let E=0,P=0;if(m.length>x.length)return!1;for(;E{const O=E.variant.id.toString().localeCompare(P.variant.id.toString());return O!==0?O:E.variant.sx!==P.variant.sx?E.variant.sx-P.variant.sx:E.variant.sy!==P.variant.sy?E.variant.sy-P.variant.sy:0});const k=new Map;for(const E of x)k.set(E.key,E.value);return k}class UOe{constructor(m){this.sourceAtlasHash=m}}class qOe{constructor(m,x,k,E){const P=new Map,O=new Map;this.haveRenderCallbacks=[];const U=[],H=E!==void 0,X=H?new Map:void 0,oe=H?A_e(m,X):m,ue=H?A_e(x,X):x;this.addImages(oe,P,1,U),this.addImages(ue,O,2,U);const{w:me,h:_e}=BOe(U),Se=new Gh({width:me||1,height:_e||1});for(const[Pe,$e]of oe.entries()){const Ke=P.get(Pe).paddedRect;Gh.copy($e.data,Se,{x:0,y:0},{x:Ke.x+1,y:Ke.y+1},$e.data,null,$e.sdf)}for(const[Pe,$e]of ue.entries()){const Ke=O.get(Pe),lt=Ke.paddedRect;let nt=Ke.padding;const pt=lt.x+nt,_t=lt.y+nt,jt=$e.data.width,Yt=$e.data.height;nt=nt>1?nt-1:nt,Gh.copy($e.data,Se,{x:0,y:0},{x:pt,y:_t},$e.data,k),Gh.copy($e.data,Se,{x:0,y:Yt-nt},{x:pt,y:_t-nt},{width:jt,height:nt},k),Gh.copy($e.data,Se,{x:0,y:0},{x:pt,y:_t+Yt},{width:jt,height:nt},k),Gh.copy($e.data,Se,{x:jt-nt,y:0},{x:pt-nt,y:_t},{width:nt,height:Yt},k),Gh.copy($e.data,Se,{x:0,y:0},{x:pt+jt,y:_t},{width:nt,height:Yt},k),Gh.copy($e.data,Se,{x:jt-nt,y:Yt-nt},{x:pt-nt,y:_t-nt},{width:nt,height:nt},k),Gh.copy($e.data,Se,{x:0,y:Yt-nt},{x:pt+jt,y:_t-nt},{width:nt,height:nt},k),Gh.copy($e.data,Se,{x:0,y:0},{x:pt+jt,y:_t+Yt},{width:nt,height:nt},k),Gh.copy($e.data,Se,{x:jt-nt,y:0},{x:pt-nt,y:_t+Yt},{width:nt,height:nt},k)}this.lut=k,this.image=Se,this.iconPositions=P,this.patternPositions=O,H&&(this.contentDescriptor=new T_e(oe,ue,E,k,X))}addImages(m,x,k,E){for(const[P,O]of m.entries()){const{bin:U,imagePosition:H,imageVariant:X}=E_e(P,O,k);x.set(P,H),E.push(U),O.hasRenderCallback&&this.haveRenderCallbacks.push(X.id)}}patchUpdatedImages(m,x,k,E){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(P=>m.hasImage(P,k)),m.dispatchRenderCallbacks(this.haveRenderCallbacks,k);for(const P of m.getUpdatedImages(k)){for(const O of this.iconPositions.keys()){const U=np.parse(O);if(Lt.isEqual(U.id,P)){const H=m.getImage(P,k);this.patchUpdatedImage(this.iconPositions.get(O),H,x,null)}}for(const O of this.patternPositions.keys()){const U=np.parse(O);if(Lt.isEqual(U.id,P)){const H=m.getImage(P,k);this.patchUpdatedImage(this.patternPositions.get(O),H,x,E||this.lut)}}}}patchUpdatedImage(m,x,k,E=null){if(!m||!x||m.version===x.version)return;m.version=x.version;const[P,O]=m.tl,U=m.sdf;if(this.lut||U){const H={width:x.data.width,height:x.data.height},X=new Gh(H);Gh.copy(x.data,X,{x:0,y:0},{x:0,y:0},H,E,U),k.update(X,{position:{x:P,y:O},recreateWhenResize:!1})}else k.update(x.data,{position:{x:P,y:O},recreateWhenResize:!1})}}Kn(kO,"ImagePosition"),Kn(qOe,"ImageAtlas",{omit:["lut"]}),Kn(UOe,"ImageAtlasReference");class SO{constructor(m){this.pendingRequests=new Map,this.cachedRanges=new Map,this.useServerFontComposition=!m||m.useServerFontComposition===void 0||m.useServerFontComposition}loadGlyphRange(m,x,k,E,P){if(this.useServerFontComposition)return void SO.loadGlyphRange(m,x,k,E,P);const O=m.split(",").map(U=>U.trim()).filter(U=>U.length>0);O.length!==0?O.length!==1?this._loadMultipleFonts(O,x,k,E,P):this._loadFont(O[0],x,k,E,P):P(new Error("Empty fontstack"))}_loadMultipleFonts(m,x,k,E,P){const O=m.map(()=>null),U={completed:0,firstError:null,callbackCalled:!1},H=(X,oe,ue)=>{if(!U.callbackCalled&&(oe&&!U.firstError&&(U.firstError=oe),ue&&(O[X]=ue),U.completed++,U.completed===m.length)){U.callbackCalled=!0;const me=O.filter(Se=>Se!==null);if(me.length===0)return void P(U.firstError||new Error("All fonts failed to load"));const _e=this._composeGlyphs(me);P(null,_e)}};for(let X=0;X{H(X,oe,ue)})}_loadFont(m,x,k,E,P){const O=`${m}:${x}`;if(this.cachedRanges.has(O)){const H=this.cachedRanges.get(O);return void qd.frame(()=>P(null,H))}const U=this.pendingRequests.get(O);U?U.push(P):(this.pendingRequests.set(O,[P]),SO.loadGlyphRange(m,x,k,E,(H,X)=>{H||this.cachedRanges.set(O,X||null);const oe=this.pendingRequests.get(O);if(this.pendingRequests.delete(O),oe)for(const ue of oe)ue(H,X)}))}_composeGlyphs(m){const x={};let k,E;for(const P of m)if(k===void 0&&P.ascender!==void 0&&(k=P.ascender),E===void 0&&P.descender!==void 0&&(E=P.descender),P.glyphs)for(const O in P.glyphs)x[O]===void 0&&(x[O]=P.glyphs[O]);return{glyphs:x,ascender:k,descender:E}}}SO.loadGlyphRange=function(w,m,x,k,E){const P=256*m,O=P+255,U=k.transformRequest(k.normalizeGlyphsURL(x).replace("{fontstack}",w).replace("{range}",`${P}-${O}`),u0.Glyphs);Py(U,(H,X)=>{if(H)E(H);else if(X){const oe={},ue=function(me){return new Uq(me).readFields(P3t,{})}(X);for(const me of ue.glyphs)oe[me.id]=me;E(null,{glyphs:oe,ascender:ue.ascender,descender:ue.descender})}})};const CO=1e20;function VOe(w,m,x,k,E,P,O,U,H){for(let X=m;X-1);H++,P[H]=U,O[H]=X,O[H+1]=CO}for(let U=0,H=0;U{if(O){E.ascender=O.ascender,E.descender=O.descender;for(const U in O.glyphs)this._doesCharSupportLocalGlyph(+U)||(E.glyphs[+U]=O.glyphs[+U]);E.ranges[x]=!0}for(const U of E.requests[x]||[])U(P,O);delete E.requests[x]}))}getGlyphs(m,x){const k=[],E=this.url||ga.GLYPHS_URL;for(const P in m)for(const O of m[P])k.push({stack:P,id:O});Rt(k,({stack:P,id:O},U)=>{let H=this.entries[P];H||(H=this.entries[P]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let X=H.glyphs[O];if(X!==void 0)return void U(null,{stack:P,id:O,glyph:X});if(X=this._tinySDF(H,P,O),X)return H.glyphs[O]=X,void U(null,{stack:P,id:O,glyph:X});const oe=Math.floor(O/256);if(256*oe>65535)return nr("glyphs > 65535 not supported"),void U(null,{stack:P,id:O,glyph:X});if(H.ranges[oe])return void U(null,{stack:P,id:O,glyph:X});let ue=H.requests[oe];ue||(ue=H.requests[oe]=[],this.glyphLoader.loadGlyphRange(P,oe,E,this.requestManager,(me,_e)=>{if(_e){H.ascender=_e.ascender,H.descender=_e.descender;for(const Se in _e.glyphs)this._doesCharSupportLocalGlyph(+Se)||(H.glyphs[+Se]=_e.glyphs[+Se]);H.ranges[oe]=!0}for(const Se of ue)Se(me,_e);delete H.requests[oe]})),ue.push((me,_e)=>{me?U(me):_e&&U(null,{stack:P,id:O,glyph:_e.glyphs[O]||null})})},(P,O)=>{if(P)x(P);else if(O){const U={};for(const{stack:H,id:X,glyph:oe}of O)U[H]===void 0&&(U[H]={}),U[H].glyphs===void 0&&(U[H].glyphs={}),U[H].glyphs[X]=oe&&{id:oe.id,bitmap:oe.bitmap.clone(),metrics:oe.metrics},U[H].ascender=this.entries[H].ascender,U[H].descender=this.entries[H].descender;x(null,U)}})}_doesCharSupportLocalGlyph(m){return this.localGlyphMode!==M_e.none&&(this.localGlyphMode===M_e.all?!!this.localFontFamily:!!this.localFontFamily&&(kx(m)||u_(m)||j1(m)||Nx(m)||Gy(m)||Rj(m)||(x=m)>=131072&&x<=173791||(k=>k>=66736&&k<=66815)(m)));var x}_tinySDF(m,x,k){const E=this.localFontFamily;if(!E||!this._doesCharSupportLocalGlyph(k))return;let P=m.tinySDF;if(!P){let $e="400";/bold/i.test(x)?$e="900":/medium/i.test(x)?$e="500":/light/i.test(x)&&($e="200"),P=m.tinySDF=new Gq.TinySDF({fontFamily:E,fontWeight:$e,fontSize:48,buffer:6,radius:16}),P.fontWeight=$e}const O=P.fontWeight;if(this.localGlyphs[O][k])return this.localGlyphs[O][k];const U=String.fromCodePoint(k),{data:H,width:X,height:oe,glyphWidth:ue,glyphHeight:me,glyphLeft:_e,glyphTop:Se,glyphAdvance:Pe}=P.draw(U);return this.localGlyphs[O][k]={id:k,bitmap:new uk({width:X,height:oe},H),metrics:{width:ue/2,height:me/2,left:_e/2,top:Se/2-27,advance:Pe/2,localGlyph:!0}}}}function GOe(w,m){return w+m[1]-m[0]}function I_e(w,m,x,k,E=1){const P=[],O=w.imagePrimary,U=O.pixelRatio,H=O.paddedRect.w-2,X=O.paddedRect.h-2,oe=(w.right-w.left)*E,ue=(w.bottom-w.top)*E,me=O.stretchX||[[0,H]],_e=O.stretchY||[[0,X]],Se=me.reduce(GOe,0),Pe=_e.reduce(GOe,0),$e=H-Se,Ke=X-Pe;let lt=0,nt=Se,pt=0,_t=Pe,jt=0,Yt=$e,zt=0,Wt=Ke;if(O.content&&k){const Ut=O.content;lt=Wq(me,0,Ut[0]),pt=Wq(_e,0,Ut[1]),nt=Wq(me,Ut[0],Ut[2]),_t=Wq(_e,Ut[1],Ut[3]),jt=Ut[0]-lt,zt=Ut[1]-pt,Yt=Ut[2]-Ut[0]-nt,Wt=Ut[3]-Ut[1]-_t}const $t=(Ut,Bs,qs,Qs)=>{const sn=Kq(Ut.stretch-lt,nt,oe,w.left*E),Xs=Yq(Ut.fixed-jt,Yt,Ut.stretch,Se),xn=Kq(Bs.stretch-pt,_t,ue,w.top*E),Os=Yq(Bs.fixed-zt,Wt,Bs.stretch,Pe),en=Kq(qs.stretch-lt,nt,oe,w.left*E),on=Yq(qs.fixed-jt,Yt,qs.stretch,Se),yn=Kq(Qs.stretch-pt,_t,ue,w.top*E),Tn=Yq(Qs.fixed-zt,Wt,Qs.stretch,Pe),or=new Ls(sn,xn),Fn=new Ls(en,xn),On=new Ls(en,yn),En=new Ls(sn,yn),rr=new Ls(Xs/U,Os/U),pr=new Ls(on/U,Tn/U),Vr=m*Math.PI/180;if(Vr){const Ka=Math.sin(Vr),Ol=Math.cos(Vr),Ji=[Ol,-Ka,Ka,Ol];or._matMult(Ji),Fn._matMult(Ji),En._matMult(Ji),On._matMult(Ji)}const kr=Ut.stretch+Ut.fixed,Ea=qs.stretch+qs.fixed,Ni=Bs.stretch+Bs.fixed,Aa=Qs.stretch+Qs.fixed,Ci=w.imageSecondary;return{tl:or,tr:Fn,bl:En,br:On,texPrimary:{x:O.paddedRect.x+1+kr,y:O.paddedRect.y+1+Ni,w:Ea-kr,h:Aa-Ni},texSecondary:Ci?{x:Ci.paddedRect.x+1+kr,y:Ci.paddedRect.y+1+Ni,w:Ea-kr,h:Aa-Ni}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:rr,pixelOffsetBR:pr,minFontScaleX:Yt/U/oe,minFontScaleY:Wt/U/ue,isSDF:x}};if(O.stretchX||O.stretchY){const Ut=WOe(me,$e,Se),Bs=WOe(_e,Ke,Pe);for(let qs=0;qs0?[lt,-nt]:pt<0?[-lt,nt]:lt===0?[nt,lt]:[nt,-lt]}(x);let _e=Math.abs(m.top-m.bottom);for(const Ke of m.positionedLines)_e-=Ke.lineOffset;const Se=m.positionedLines.length,Pe=_e/Se;let $e=m.top-x[1];for(let Ke=0;KeP)&&(P=Se.x),(!_e||Se.y>O)&&(O=Se.y)}const H=Math.min(P-k,O-E);let X=H/2;const oe=new p0([],q3t);if(H===0)return new Ls(k,E);for(let _e=k;_eue.d||!ue.d)&&(ue=_e,x&&console.log("found best %d after %d probes",Math.round(1e4*_e.d)/1e4,me)),_e.max-ue.d<=m||(X=_e.h/2,oe.push(new Y6(_e.p.x-X,_e.p.y-X,X,w)),oe.push(new Y6(_e.p.x+X,_e.p.y-X,X,w)),oe.push(new Y6(_e.p.x-X,_e.p.y+X,X,w)),oe.push(new Y6(_e.p.x+X,_e.p.y+X,X,w)),me+=4)}return x&&(console.log(`num probes: ${me}`),console.log(`best distance: ${ue.d}`)),ue.p}function q3t(w,m){return m.max-w.max}Gq.TinySDF=class{constructor({fontSize:w=24,buffer:m=3,radius:x=8,cutoff:k=.25,fontFamily:E="sans-serif",fontWeight:P="normal",fontStyle:O="normal",lang:U=null}={}){this.buffer=m,this.cutoff=k,this.radius=x,this.lang=U;const H=this.size=w+4*m,X=this._createCanvas(H),oe=this.ctx=X.getContext("2d",{willReadFrequently:!0});oe.font=`${O} ${P} ${w}px ${E}`,oe.textBaseline="alphabetic",oe.textAlign="left",oe.fillStyle="black",this.gridOuter=new Float64Array(H*H),this.gridInner=new Float64Array(H*H),this.f=new Float64Array(H),this.z=new Float64Array(H+1),this.v=new Uint16Array(H)}_createCanvas(w){const m=document.createElement("canvas");return m.width=m.height=w,m}draw(w){const{width:m,actualBoundingBoxAscent:x,actualBoundingBoxDescent:k,actualBoundingBoxLeft:E,actualBoundingBoxRight:P}=this.ctx.measureText(w),O=Math.ceil(x),U=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(P-E))),H=Math.min(this.size-this.buffer,O+Math.ceil(k)),X=U+2*this.buffer,oe=H+2*this.buffer,ue=Math.max(X*oe,0),me=new Uint8ClampedArray(ue),_e={data:me,width:X,height:oe,glyphWidth:U,glyphHeight:H,glyphTop:O,glyphLeft:0,glyphAdvance:m};if(U===0||H===0)return _e;const{ctx:Se,buffer:Pe,gridInner:$e,gridOuter:Ke}=this;this.lang&&(Se.lang=this.lang),Se.clearRect(Pe,Pe,U,H),Se.fillText(w,Pe,Pe+O);const lt=Se.getImageData(Pe,Pe,U,H);Ke.fill(CO,0,ue),$e.fill(0,0,ue);for(let nt=0;nt0?Yt*Yt:0,$e[jt]=Yt<0?Yt*Yt:0}}VOe(Ke,0,0,X,oe,X,this.f,this.v,this.z),VOe($e,Pe,Pe,U,H,X,this.f,this.v,this.z);for(let nt=0;ntP.y!=Pe.y>P.y&&P.x<(Pe.x-Se.x)*(P.y-Se.y)/(Pe.y-Se.y)+Se.x&&(U=!U),H=Math.min(H,Qy(P,Se,Pe))}}return(U?1:-1)*Math.sqrt(H)}(this.p,E),this.max=this.d+this.h*Math.SQRT2}}const V3t=Object.keys,P_e=Number.POSITIVE_INFINITY,H3t=Math.sqrt(2);function fk(w,m,x,k,E,P){const O=N_e(w)&&w.collisionPadding?w.collisionPadding:[0,0,0,0],U={top:w.top-O[1],bottom:w.bottom+O[3],left:w.left-O[0],right:w.right+O[2],scaled:!1};return k!==void 0&&function(H,X){H.top*=X,H.bottom*=X,H.left*=X,H.right*=X,H.scaled=!0}(U,k),P&&(U.left+=P[0],U.right+=P[0],U.top+=P[1],U.bottom+=P[1]),x&&function(H,X,oe){if(!X)return;const ue=js(X),me=new Ls(oe?oe[0]:0,oe?oe[1]:0),_e=new Ls(H.left,H.top),Se=new Ls(H.right,H.top),Pe=new Ls(H.left,H.bottom),$e=new Ls(H.right,H.bottom);_e._rotateAround(ue,me),Se._rotateAround(ue,me),Pe._rotateAround(ue,me),$e._rotateAround(ue,me),H.left=Math.min(_e.x,Se.x,Pe.x,$e.x),H.right=Math.max(_e.x,Se.x,Pe.x,$e.x),H.top=Math.min(_e.y,Se.y,Pe.y,$e.y),H.bottom=Math.max(_e.y,Se.y,Pe.y,$e.y)}(U,x,E),m?{top:Math.min(m.top,U.top),bottom:Math.max(m.bottom,U.bottom),left:Math.min(m.left,U.left),right:Math.max(m.right,U.right),scaled:m.scaled||U.scaled}:U}function ZOe(w,[m,x]){let k=0,E=0;if(x===P_e){m<0&&(m=0);const P=m/H3t;switch(w){case"top-right":case"top-left":E=P-7;break;case"bottom-right":case"bottom-left":E=7-P;break;case"bottom":E=7-m;break;case"top":E=m-7}switch(w){case"top-right":case"bottom-right":k=-P;break;case"top-left":case"bottom-left":k=P;break;case"left":k=m;break;case"right":k=-m}}else{switch(m=Math.abs(m),x=Math.abs(x),w){case"top-right":case"top-left":case"top":E=x-7;break;case"bottom-right":case"bottom-left":case"bottom":E=7-x}switch(w){case"top-right":case"bottom-right":case"right":k=-m;break;case"top-left":case"bottom-left":case"left":k=m}}return[k,E]}function G3t(w,m,x,k,E,P,O,U,H,X,oe,ue,me,_e,Se){const Pe=w.layers[0],$e=Pe.appearances;if($e.length===0)return{iconBBox:null,iconVerticalBBox:null,textBBox:null,textVerticalBBox:null};const Ke={iconBBox:null,iconVerticalBBox:null},lt={textBBox:null,textVerticalBBox:null},{baseIconRotate:nt,baseTextRotate:pt,iconScaleFactor:_t}=function(Yt,zt,Wt){const $t=Yt.get("icon-rotate").evaluate(zt,{},Wt),Ut=Yt.get("text-rotate").evaluate(zt,{},Wt),[Bs,qs]=Yt.get("icon-size-scale-range");return{baseIconRotate:$t,baseTextRotate:Ut,iconScaleFactor:Xe(1,Bs,qs)}}(k,E,P);m&&(Ke.iconBBox=fk(m,Ke.iconBBox,nt),x)&&(Ke.iconVerticalBBox=fk(x,Ke.iconVerticalBBox,nt+90));const jt=Qq(ue.horizontal);jt&&(lt.textBBox=fk(jt,lt.textBBox,pt,1,_e)),ue.vertical&&(lt.textVerticalBBox=fk(ue.vertical,lt.textVerticalBBox,pt+90,1,_e));for(const Yt of $e)Yt.hasIconLayoutProperties()&&W3t(Ke,w,Pe,Yt,E,P,U,nt,O,H,m,X,_t,oe,Se),Yt.hasTextLayoutProperties()&&K3t(lt,Pe,Yt,E,P,_e,pt,me,jt,ue.vertical);return{iconBBox:Ke.iconBBox,iconVerticalBBox:Ke.iconVerticalBBox,textBBox:lt.textBBox,textVerticalBBox:lt.textVerticalBBox}}function W3t(w,m,x,k,E,P,O,U,H,X,oe,ue,me,_e,Se){const{appearanceIconOffset:Pe,appearanceIconRotate:$e,appearanceIconSize:Ke}=QOe(k,x,E,P,O,U,H,X.iconScaleFactor);let lt=null,nt=null,pt=null;k.hasLayoutProperty("icon-image")?pt=function(jt,Yt,zt,Wt,$t,Ut,Bs,qs){let Qs=null;const sn=Yt.getAppearanceValueAndResolveTokens(zt,"icon-image",Wt,$t,qs);if(sn){const Xs=jt.getResolvedImageFromTokens(sn),xn=zt.hasLayoutProperty("icon-size")?zt.getUnevaluatedLayoutProperty("icon-size"):Yt._unevaluatedLayout._values["icon-size"],Os=TO(Xs,t3(jt.zoom,xn,jt.worldview,qs),xn,$t,jt.zoom,Wt,jt.pixelRatio,Bs,jt.worldview,qs);Qs=Ut.get(Os.iconPrimary.toString())}return Qs}(m,x,k,E,P,ue,me,Se):oe&&(pt=oe.imagePrimary),pt&&(lt=Vq(pt,null,Pe,_e),m.allowVerticalPlacement&&(nt=Vq(pt,null,Pe,_e)));const _t=H>0?Ke/H:1;lt&&(w.iconBBox=fk(lt,w.iconBBox,$e,_t!==1?_t:void 0)),nt&&(w.iconVerticalBBox=fk(nt,w.iconVerticalBBox,$e+90,_t!==1?_t:void 0))}function QOe(w,m,x,k,E,P,O,U){const H=w.hasLayoutProperty("icon-offset")?m.getAppearanceValueAndResolveTokens(w,"icon-offset",x,k,[]):null,X=H&&Array.isArray(H)?H:E,oe=w.hasLayoutProperty("icon-rotate")?m.getAppearanceValueAndResolveTokens(w,"icon-rotate",x,k,[]):null,ue=typeof oe=="number"?oe:P,me=w.hasLayoutProperty("icon-size")?m.getAppearanceValueAndResolveTokens(w,"icon-size",x,k,[]):null;return{appearanceIconOffset:X,appearanceIconRotate:ue,appearanceIconSize:typeof me=="number"?me*U:O}}function K3t(w,m,x,k,E,P,O,U,H,X){const{appearanceTextOffset:oe,appearanceTextRotate:ue,appearanceTextSize:me}=XOe(x,m,k,E,P,O,U),_e=me/U,Se=[(oe[0]-P[0])*_e,(oe[1]-P[1])*_e],Pe=Se[0]!==0||Se[1]!==0;H&&(w.textBBox=fk(H,w.textBBox,ue,_e,oe,Pe?Se:void 0)),X&&(w.textVerticalBBox=fk(X,w.textVerticalBBox,ue+90,_e,oe,Pe?Se:void 0))}function XOe(w,m,x,k,E,P,O){const U=w.hasLayoutProperty("text-offset")?m.getAppearanceValueAndResolveTokens(w,"text-offset",x,k,[]):null,H=U&&Array.isArray(U)?[U[0]*Zd,U[1]*Zd]:E,X=w.hasLayoutProperty("text-rotate")?m.getAppearanceValueAndResolveTokens(w,"text-rotate",x,k,[]):null,oe=typeof X=="number"?X:P,ue=w.hasLayoutProperty("text-size")?m.getAppearanceValueAndResolveTokens(w,"text-size",x,k,[]):null;return{appearanceTextOffset:H,appearanceTextRotate:oe,appearanceTextSize:typeof ue=="number"?ue:O}}function Zq(w,m,x,k,E,P,O,U,H){if(!m||!m.usvg)return;const X=LOe(k),oe=LOe(E),ue=P!=="both"&&P!=="width"||!IOe(k)?1:oe.width/X.width,me=P!=="both"&&P!=="height"||!POe(k)?1:oe.height/X.height;x.scaleSelf(ue,me);const _e=x.toString();O.set(_e,x),U.set(_e,m);const{imagePosition:Se}=E_e(_e,m,1);H.set(_e,Se)}function JOe(w,m,x,k,E,P,O,U,H,X){if(!w)return;const oe=function(ue,me,_e,Se,Pe,$e,Ke){if(ue.kind==="camera")return ue.maxSize;if(ue.kind==="composite"){const lt=me.possiblyEvaluate(new La(ue.maxZoom,{worldview:$e}),_e,Ke).evaluate(Pe,{},_e,Ke),nt=me.possiblyEvaluate(new La(ue.minZoom,{worldview:$e}),_e,Ke).evaluate(Pe,{},_e,Ke);return Math.max(lt,nt)}return me.possiblyEvaluate(new La(Se,{worldview:$e}),_e,Ke).evaluate(Pe,{},_e,Ke)}(m,x,k,E,P,H,X);return w.scaleSelf(oe*U*O)}function TO(w,m,x,k,E,P,O,U,H,X){return{iconPrimary:JOe(w.getPrimary(),m,x,k,E,P,O,U,H,X),iconSecondary:JOe(w.getSecondary(),m,x,k,E,P,O,U,H,X)}}function Y3t(w,m,x){if(!m)return;const k=x.get(w.toString()),E=x.get(m.toString());k&&E&&(k.paddedRect.w===E.paddedRect.w&&k.paddedRect.h===E.paddedRect.h||nr(`Mismatch in icon variant sizes: ${w.toString()} and ${m.toString()}`),k.usvg!==E.usvg&&nr(`Mismatch in icon variant image types: ${w.id} and ${m.id}`))}function eFe(w,m,x,k){if(!w)return;const E=m.get(x.toString());if(E&&(w.imagePrimary=E),k){const P=m.get(k.toString());w.imageSecondary=P}}function Z3t(w,m){for(const x in w.horizontal)tFe(w.horizontal[x],m);tFe(w.vertical,m)}function tFe(w,m){if(w){for(const x of w.positionedLines)for(const k of x.positionedGlyphs)if(k.image!==null){const E=k.image.toString();k.rect=m.get(E).paddedRect}}}function L_e(w){switch(w){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"}function Q3t(w,m,x,k,E,P,O,U,H){const X=Qq(P.horizontal)||P.vertical,oe=x.get("icon-text-fit-padding").evaluate(k,{},E);let ue,me=m;return m&&H!=="none"&&(w.allowVerticalPlacement&&P.vertical&&(ue=k_e(m,P.vertical,H,oe,U,O)),X&&(me=k_e(m,X,H,oe,U,O))),{defaultShapedIcon:me,verticallyShapedIcon:ue}}function sFe(w,m){return w*m/24}function X3t(w,m,x,k,E,P,O,U,H,X,oe,ue,me,_e,Se,Pe,$e,Ke,lt,nt,pt,_t,jt,Yt){let zt=O.textMaxSize.evaluate(m,{},me);zt===void 0?zt=U*O.textScaleFactor:zt*=O.textScaleFactor;const Wt=w.layers[0].layout,$t=sFe(U,O.textScaleFactor),Ut=Qq(x.horizontal)||x.vertical,Bs=w.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),qs=w.getAppearanceFeatureData(m.index);($e!=="none"||Bs)&&qs&&(qs.textShaping=Ut,qs.iconTextFitPadding=Wt.get("icon-text-fit-padding").evaluate(m,{},me),qs.fontScale=$t,qs.textScaleFactor=O.textScaleFactor);const Qs=_e.name==="globe",sn=w.tilePixelRatio*zt/24,Xs=(Tn=w.overscaling,w.zoom>18&&Tn>2&&(Tn>>=1),Math.max($n/(512*Tn),1)*Wt.get("symbol-spacing")),xn=Wt.get("text-padding")*w.tilePixelRatio,Os=Wt.get("icon-padding")*w.tilePixelRatio,en=js(Wt.get("text-max-angle")),on=Wt.get("icon-rotation-alignment")==="map"&&nt!=="point",yn=Xs/2;var Tn;w.hasAnyIconTextFit===!1&&$e!=="none"&&(w.hasAnyIconTextFit=!0);const or=m.properties?+m.properties[za]:null,Fn=or&&w.elevationFeatureIdToIndex?w.elevationFeatureIdToIndex.get(or):65535,On=(En,rr,pr)=>{if(rr.x<0||rr.x>=$n||rr.y<0||rr.y>=$n)return;let Vr=null;if(Qs){const{x:kr,y:Ea,z:Ni}=_e.projectTilePoint(rr.x,rr.y,pr);Vr={anchor:new Jj(kr,Ea,Ni,0,void 0),up:_e.upVector(pr,rr.x,rr.y)}}(function(kr,Ea,Ni,Aa,Ci,Ka,Ol,Ji,Di,Ro,Il,Qd,Pl,nc,Uc,rc,jh,Xd,Ja,up,fc,bu,hp,Nh,Fl,km,_u,fV,nI,Yp,rwe,rI){const e2=kr.addToLineVertexArray(Ea,Aa);let t2,C0,T0,o3,aI,ai,wu,ac=0,Ed=0,E0=0,Ix=0,Px=-1,Lx=-1;const ev={};let xV=Sd("");const L1=Ni?Ni.anchor:Ea,iI=fV!=="none";let oI=0,md=0;if(Di._unevaluatedLayout.getValue("text-radial-offset")===void 0){const xc=Di.layout.get("text-offset").evaluate(fc,{},Fl);oI=xc[0]*Zd,md=xc[1]*Zd}else oI=Di.layout.get("text-radial-offset").evaluate(fc,{},Fl)*Zd,md=P_e;if(kr.allowVerticalPlacement&&Ci.vertical){const xc=Ci.vertical;if(Uc)ai=O_e(xc),Ji&&(wu=O_e(Ji));else{const mp=Di.layout.get("text-rotate").evaluate(fc,{},Fl)+90;T0=Xq(Ro,L1,Ea,Il,Qd,Pl,xc,nc,mp,rc,rI),Ji&&(o3=Xq(Ro,L1,Ea,Il,Qd,Pl,Ji,Xd,mp,null,rwe))}}if(Ka){const xc=Di.layout.get("icon-rotate").evaluate(fc,{},Fl),mp=I_e(Ka,xc,hp,iI,bu.iconScaleFactor),Zp=Ji?I_e(Ji,xc,hp,iI,bu.iconScaleFactor):void 0;C0=Xq(Ro,L1,Ea,Il,Qd,Pl,Ka,Xd,xc,null,Yp);const sv=function(D1,qO,lI,mTt,pTt,j7e,N7e,fTt,rxn,iwe){const k7e=D1.layers[0],S7e=k7e.appearances;let cI=qO.length;if(lI&&(cI=Math.max(cI,lI.length)),S7e.length===0)return cI;const[xTt,gTt]=mTt.get("icon-size-scale-range"),yTt=Xe(1,xTt,gTt);for(const bV of S7e)if(bV.hasLayoutProperty("icon-image")){const C7e=k7e.getAppearanceValueAndResolveTokens(bV,"icon-image",j7e,N7e,iwe);if(C7e){const T7e=D1.getResolvedImageFromTokens(C7e);if(T7e){const E7e=bV.hasLayoutProperty("icon-size")?bV.getUnevaluatedLayoutProperty("icon-size"):pTt._values["icon-size"],vTt=TO(T7e,t3(D1.zoom,E7e,D1.worldview,iwe),E7e,N7e,D1.zoom,j7e,D1.pixelRatio,yTt,D1.worldview,iwe),A7e=fTt.get(vTt.iconPrimary.toString());A7e&&(cI=Math.max(cI,B3t(A7e)))}}}return cI}(kr,mp,Zp,Di.layout,Di._unevaluatedLayout,fc,Fl,kr.iconAtlasPositions,0,Nh);ac=4*sv;const gV=Di.layout.get("icon-size").evaluate(fc,{},Fl,Nh),yV=bu.compositeIconSizes?bu.compositeIconSizes[0].evaluate(fc,{},Fl,Nh):0,awe=bu.compositeIconSizes?bu.compositeIconSizes[1].evaluate(fc,{},Fl,Nh):0,vV=R_e(kr.layerIds[0],kr.iconSizeData,gV,bu.iconScaleFactor,yV,awe);kr.addSymbols(kr.icon,mp,vV,up,Ja,fc,void 0,Ni,Ea,e2.lineStartIndex,e2.lineLength,-1,Nh,Fl,km,_u,kr.symbolInstances.length,sv),Px=kr.icon.placedSymbolArray.length-1,Zp&&(Ed=4*sv,kr.addSymbols(kr.icon,Zp,vV,up,Ja,fc,Mx.vertical,Ni,Ea,e2.lineStartIndex,e2.lineLength,-1,Nh,Fl,km,_u,kr.symbolInstances.length,sv),Lx=kr.icon.placedSymbolArray.length-1)}for(const xc in Ci.horizontal){const mp=xc,Zp=Ci.horizontal[mp];t2||(xV=Sd(Zp.text),Uc?aI=O_e(Zp):t2=Xq(Ro,L1,Ea,Il,Qd,Pl,Zp,nc,Di.layout.get("text-rotate").evaluate(fc,{},Fl),rc,rI));const sv=Zp.positionedLines.length===1;if(E0+=nFe(kr,Ni,Ea,Zp,Ol,Di,Uc,fc,rc,e2,Ci.vertical?Mx.horizontal:Mx.horizontalOnly,sv?V3t(Ci.horizontal):[mp],ev,Px,bu,Nh,Fl,kr.symbolInstances.length,km),sv)break}Ci.vertical&&(Ix+=nFe(kr,Ni,Ea,Ci.vertical,Ol,Di,Uc,fc,rc,e2,Mx.vertical,["vertical"],ev,Lx,bu,Nh,Fl,kr.symbolInstances.length,km));let Jc=-1;const Ad=(xc,mp)=>xc?Math.max(xc,mp):mp;Jc=Ad(aI,Jc),Jc=Ad(ai,Jc),Jc=Ad(wu,Jc);const tv=Jc>-1?1:0;kr.glyphOffsetArray.length>=65535&&nr("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),fc.sortKey!==void 0&&kr.addToSortKeyRanges(kr.symbolInstances.length,fc.sortKey),kr.symbolInstances.emplaceBack(Ea.x,Ea.y,L1.x,L1.y,L1.z,ev.right>=0?ev.right:-1,ev.center>=0?ev.center:-1,ev.left>=0?ev.left:-1,ev.vertical>=0?ev.vertical:-1,Px,Lx,xV,t2!==void 0?t2:kr.collisionBoxArray.length,t2!==void 0?t2+1:kr.collisionBoxArray.length,T0!==void 0?T0:kr.collisionBoxArray.length,T0!==void 0?T0+1:kr.collisionBoxArray.length,C0!==void 0?C0:kr.collisionBoxArray.length,C0!==void 0?C0+1:kr.collisionBoxArray.length,o3||kr.collisionBoxArray.length,o3?o3+1:kr.collisionBoxArray.length,Il,E0,Ix,ac,Ed,tv,0,oI,md,Jc,0,iI?1:0,nI)})(w,rr,Vr,En,x,k,P,E,w.layers[0],w.collisionBoxArray,m.index,m.sourceLayerIndex,w.index,xn,lt,X,0,Os,on,Ke,m,O,oe,ue,me,Se,Pe,$e,Fn,pt,_t,jt)};if(nt==="line")for(const En of Mq(m.geometry,0,0,$n,$n)){const rr=z3t(En,Xs,en,x.vertical||Ut,k,24,sn,w.overscaling,$n);for(const pr of rr)Ut&&J3t(w,Ut.text,yn,pr)||On(En,pr,me)}else if(nt==="line-center"){for(const En of m.geometry)if(En.length>1){const rr=F3t(En,en,x.vertical||Ut,k,24,sn);rr&&On(En,rr,me)}}else if(m.type==="Polygon")for(const En of dO(m.geometry,0)){const rr=U3t(En,16);On(En[0],new Jj(rr.x,rr.y,0,0,void 0),me)}else if(m.type==="LineString")for(const En of m.geometry)On(En,new Jj(En[0].x,En[0].y,0,0,void 0),me);else if(m.type==="Point")for(const En of m.geometry)for(const rr of En)On([rr],new Jj(rr.x,rr.y,0,0,void 0),me)}const D_e=255,s3=D_e*Xj;function nFe(w,m,x,k,E,P,O,U,H,X,oe,ue,me,_e,Se,Pe,$e,Ke,lt){const nt=YOe(0,k,H,P,O,U,E,w.allowVerticalPlacement,void 0,Se.textScaleFactor),pt=P.layout.get("text-size").evaluate(U,{},$e),_t=Se.compositeTextSizes?Se.compositeTextSizes[0].evaluate(U,{},$e):0,jt=Se.compositeTextSizes?Se.compositeTextSizes[1].evaluate(U,{},$e):0,Yt=R_e(w.layerIds[0],w.textSizeData,pt,Se.textScaleFactor,_t,jt);w.addSymbols(w.text,nt,Yt,H,O,U,oe,m,x,X.lineStartIndex,X.lineLength,_e,Pe,$e,lt,!1,Ke,nt.length);for(const zt of ue)me[zt]=w.text.placedSymbolArray.length-1;return 4*nt.length}function R_e(w,m,x,k,E,P){const O=m;let U=null;return O.kind==="source"?(U=[Xj*x*k],U[0]>s3&&nr(`${w}: Value for "text-size" is >= ${D_e}. Reduce your "text-size".`)):O.kind==="composite"&&(U=[Xj*E*k,Xj*P*k],(U[0]>s3||U[1]>s3)&&nr(`${w}: Value for "text-size" is >= ${D_e}. Reduce your "text-size".`)),U}function Qq(w){for(const m in w)return w[m];return null}function Xq(w,m,x,k,E,P,O,U,H,X,oe){let ue,me,_e,Se;if(ue=oe?oe.top:O.top,me=oe?oe.bottom:O.bottom,_e=oe?oe.left:O.left,Se=oe?oe.right:O.right,N_e(O)&&O.collisionPadding){const Pe=O.collisionPadding;_e-=Pe[0],ue-=Pe[1],Se+=Pe[2],me+=Pe[3]}if(H){const Pe=new Ls(_e,ue),$e=new Ls(Se,ue),Ke=new Ls(_e,me),lt=new Ls(Se,me),nt=js(H);let pt=new Ls(0,0);X&&(pt=new Ls(X[0],X[1])),Pe._rotateAround(nt,pt),$e._rotateAround(nt,pt),Ke._rotateAround(nt,pt),lt._rotateAround(nt,pt),_e=Math.min(Pe.x,$e.x,Ke.x,lt.x),Se=Math.max(Pe.x,$e.x,Ke.x,lt.x),ue=Math.min(Pe.y,$e.y,Ke.y,lt.y),me=Math.max(Pe.y,$e.y,Ke.y,lt.y)}return w.emplaceBack(m.x,m.y,m.z,x.x,x.y,_e,ue,Se,me,U,k,E,P),w.length-1}function O_e(w){N_e(w)&&w.collisionPadding&&(w.top-=w.collisionPadding[1],w.bottom+=w.collisionPadding[3]);const m=w.bottom-w.top;return m>0?Math.max(10,m):null}function J3t(w,m,x,k){const E=w.compareText;if(m in E){const P=E[m];for(let O=P.length-1;O>=0;O--)if(k.dist(P[O])nt&&(pt(jt,Qs,zt,Wt,Bs,qs),pt(Qs,Yt,Bs,qs,$t,Ut))}pt(ue,me,k,P,E,P),pt(me,_e,E,P,E,O),pt(_e,Se,E,O,k,O),pt(Se,ue,k,O,k,P),Pe-=nt,$e-=nt,Ke+=nt,lt+=nt;const _t=1/Math.max(Ke-Pe,lt-$e);return{scale:_t,x:Pe*_t,y:$e*_t,x2:Ke*_t,y2:lt*_t,projection:m}}function aFe(w,{x:m,y:x},k=0){return new Ls(((m-k)*w.scale-w.x)*$n,(x*w.scale-w.y)*$n)}const e5t=v(new Float32Array(16));class xk{constructor(m){this.spec=m,this.name=m.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(m,x){return{x:0,y:0,z:0}}unproject(m,x){return new ns(0,0)}projectTilePoint(m,x,k){return{x:m,y:x,z:0}}locationPoint(m,x,k,E=!0){return m._coordinatePoint(m.locationCoordinate(x,k),E)}pixelsPerMeter(m,x){return Ns(1,m)*x}pixelSpaceConversion(m,x,k){return 1}farthestPixelDistance(m){return rFe(m,m.pixelsPerMeter)}pointCoordinate(m,x,k,E){const P=m.horizonLineFromTop(!1),O=new Ls(x,Math.max(P,k));return m.rayIntersectionCoordinate(m.pointRayIntersection(O,E))}pointCoordinate3D(m,x,k){const E=new Ls(x,k);if(m.elevation)return m.elevation.pointCoordinate(E);{const P=this.pointCoordinate(m,E.x,E.y,0);return[P.x,P.y,P.z]}}isPointAboveHorizon(m,x){if(m.elevation&&m.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(m,x.x,x.y);const k=m.horizonLineFromTop();return x.y0?x<-Z6+k&&(x=-Z6+k):x>Z6-k&&(x=Z6-k);const O=P/Math.pow(eV(x),E);let U=O*Math.sin(E*m),H=P-O*Math.cos(E*m);return U=.5*(U/Math.PI+.5),H=.5*(H/Math.PI+.5),{x:U,y:this.southernCenter?H:1-H,z:0}}unproject(m,x){m=(2*m-.5)*Math.PI,this.southernCenter&&(x=1-x),x=(2*(1-x)-.5)*Math.PI;const{n:k,f:E}=this,P=E-x,O=Math.sign(P),U=Math.sign(k)*Math.sqrt(m*m+P*P);let H=Math.atan2(m,Math.abs(P))*O;P*k<0&&(H-=Math.PI*Math.sign(m)*O);const X=Xe(Dn(H/k)+this.center[0],-180,180),oe=Xe(Dn(2*Math.atan(Math.pow(E/U,1/k))-Z6),-85.051129,Ys);return new ns(X,this.southernCenter?-oe:oe)}}class iFe extends xk{constructor(m){super(m),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(m,x){return{x:an(m),y:mn(x),z:0}}unproject(m,x){const k=hs(m),E=zs(x);return new ns(k,E)}}const oFe=js(Ys);class a5t extends xk{project(m,x){const k=(x=js(x))*x,E=k*k;return{x:.5*((m=js(m))*(.8707-.131979*k+E*(E*(.003971*k-.001529*E)-.013791))/Math.PI+.5),y:1-.5*(x*(1.007226+k*(.015085+E*(.028874*k-.044475-.005916*E)))/Math.PI+1),z:0}}unproject(m,x){m=(2*m-.5)*Math.PI;let k=x=(2*(1-x)-1)*Math.PI,E=25,P=0,O=k*k;do{O=k*k;const X=O*O;P=(k*(1.007226+O*(.015085+X*(.028874*O-.044475-.005916*X)))-x)/(1.007226+O*(.045255+X*(.259866*O-.311325-.005916*11*X))),k=Xe(k-P,-oFe,oFe)}while(Math.abs(P)>1e-6&&--E>0);O=k*k;const U=Xe(Dn(m/(.8707+O*(O*(O*O*O*(.003971-.001529*O)-.013791)-.131979))),-180,180),H=Dn(k);return new ns(U,H)}}const lFe=js(Ys);class i5t extends xk{project(m,x){x=js(x),m=js(m);const k=Math.cos(x),E=2/Math.PI,P=Math.acos(k*Math.cos(m/2)),O=Math.sin(P)/P,U=.5*(m*E+2*k*Math.sin(m/2)/O)||0,H=.5*(x+Math.sin(x)/O)||0;return{x:.5*(U/Math.PI+.5),y:1-.5*(H/Math.PI+1),z:0}}unproject(m,x){let k=m=(2*m-.5)*Math.PI,E=x=(2*(1-x)-1)*Math.PI,P=25;const O=1e-6;let U=0,H=0;do{const X=Math.cos(E),oe=Math.sin(E),ue=2*oe*X,me=oe*oe,_e=X*X,Se=Math.cos(k/2),Pe=Math.sin(k/2),$e=2*Se*Pe,Ke=Pe*Pe,lt=1-_e*Se*Se,nt=lt?1/lt:0,pt=lt?Math.acos(X*Se)*Math.sqrt(1/lt):0,_t=.5*(2*pt*X*Pe+2*k/Math.PI)-m,jt=.5*(pt*oe+E)-x,Yt=.5*nt*(_e*Ke+pt*X*Se*me)+1/Math.PI,zt=nt*($e*ue/4-pt*oe*Pe),Wt=.125*nt*(ue*Pe-pt*oe*_e*$e),$t=.5*nt*(me*Se+pt*Ke*X)+.5,Ut=zt*Wt-$t*Yt;U=(jt*zt-_t*$t)/Ut,H=(_t*Wt-jt*Yt)/Ut,k=Xe(k-U,-Math.PI,Math.PI),E=Xe(E-H,-lFe,lFe)}while((Math.abs(U)>O||Math.abs(H)>O)&&--P>0);return new ns(Dn(k),Dn(E))}}class cFe extends xk{constructor(m){super(m),this.center=m.center||[0,0],this.parallels=m.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(js(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(m,x){const{scale:k,cosPhi:E}=this;return{x:js(m)*E*k+.5,y:-Math.sin(js(x))/E*k+.5,z:0}}unproject(m,x){const{scale:k,cosPhi:E}=this,P=-(x-.5)/k,O=Xe(Dn((m-.5)/k)/E,-180,180),U=Math.asin(Xe(P*E,-1,1)),H=Xe(Dn(U),-85.051129,Ys);return new ns(O,H)}}class o5t extends iFe{constructor(m){super(m),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(m,x,k){const E=nO(m,x,k);return Ze(E,E,rO(b_(k))),{x:E[0],y:E[1],z:E[2]}}locationPoint(m,x,k){const E=Dt(x.lat,x.lng),P=Ie([],E),O=k?m._centerAltitude+k:m.elevation?m.elevation.getAtPointOrZero(m.locationCoordinate(x),m._centerAltitude):m._centerAltitude;Te(E,E,P,Ns(1,0)*$n*O);const U=v(new Float64Array(16));return b(U,m.pixelMatrix,m.globeMatrix),Ze(E,E,U),new Ls(E[0],E[1])}pixelsPerMeter(m,x){return Ns(1,0)*x}pixelSpaceConversion(m,x,k){const E=Ns(1,m)*x,P=zr(Ns(1,45)*x,E,k);return this.pixelsPerMeter(m,x)/P}createTileMatrix(m,x,k){const E=Mbe(b_(k.canonical));return b(new Float64Array(16),m.globeMatrix,E)}createInversionMatrix(m,x){const{center:k}=m,E=rO(b_(x));return L(E,E,js(k.lng)),T(E,E,js(k.lat)),A(E,E,[m._pixelsPerMercatorPixel,m._pixelsPerMercatorPixel,1]),Float32Array.from(E)}pointCoordinate(m,x,k,E){return kDe(m,x,k,!0)||new mr(0,0)}pointCoordinate3D(m,x,k){const E=this.pointCoordinate(m,x,k,0);return[E.x,E.y,E.z]}isPointAboveHorizon(m,x){return!kDe(m,x.x,x.y,!1)}farthestPixelDistance(m){const x=function(E,P){const O=E.cameraToCenterDistance,U=E._centerAltitude*P,H=E._camera,X=E._camera.forward(),oe=he([],ge([],X,-O),[0,0,U]),ue=E.worldSize/(2*Math.PI),me=[0,0,-ue],_e=E.width/E.height,Se=Math.tan(E.fovAboveCenter),Pe=ge([],H.up(),Se),$e=ge([],H.right(),Se*_e),Ke=Ie([],he([],he([],X,Pe),$e)),lt=[];let nt;if(new oi(oe,Ke).closestPointOnSphere(me,ue,lt)){const pt=he([],lt,me),_t=Be([],pt,oe);nt=Math.cos(E.fovAboveCenter)*J(_t)}else{const pt=Be([],oe,me),_t=Be([],me,oe);Ie(_t,_t);const jt=J(pt)-ue;nt=Math.sqrt(jt*(jt+2*ue));const Yt=Math.acos(nt/(ue+jt))-Math.acos(Fe(X,_t));nt*=Math.cos(Yt)}return 1.01*nt}(m,this.pixelsPerMeter(m.center.lat,m.worldSize)),k=Yj(m.zoom);if(k>0){const E=rFe(m,Ns(1,m.center.lat)*m.worldSize),P=m.worldSize/(2*Math.PI),O=Math.max(m.width,m.height)/m.worldSize*Math.PI;return zr(x,E+P*(1-Math.cos(O)),Math.pow(k,10))}return x}upVector(m,x,k){return nO(x,k,m,1)}upVectorScale(m){return{metersToTile:mq(fq(b_(m)))}}}function dFe(w){const m=w.parallels,x=!!m&&Math.abs(m[0]+m[1])<.01;switch(w.name){case"mercator":return new iFe(w);case"equirectangular":return new n5t(w);case"naturalEarth":return new a5t(w);case"equalEarth":return new s5t(w);case"winkelTripel":return new i5t(w);case"albers":return x?new cFe(w):new t5t(w);case"lambertConformalConic":return x?new cFe(w):new r5t(w);case"globe":return new o5t(w)}throw new Error(`Invalid projection name: ${w.name}`)}class l5t{constructor(m,x){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=x,this.appearances=m;const k=m.map(E=>function(P){if(!P.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const O=P.condition.expression;return{featureDependent:!$y(O),stateDependent:!Uy(O),zoomDependent:!bm(O,["zoom"]),pitchDependent:!bm(O,["pitch"]),brightnessDependent:!bm(O,["brightness","measure-light"]),worldviewDependent:!bm(O,["worldview"])}}(E));this.anyFeatureDependent=k.some(E=>E.featureDependent),this.anyStateDependent=k.some(E=>E.stateDependent)}update(m,x){const k=this.lastParams,E=!k||k.zoom!==m.zoom||k.pitch!==(m.pitch||0)||k.brightness!==(m.brightness||0)||k.worldview!==m.worldview;this.lastParams={zoom:m.zoom,pitch:m.pitch||0,brightness:m.brightness||0,worldview:m.worldview};const P=x&&this.anyStateDependent;if(!E&&!P&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!P){const O=this.evaluateAllFeatures(m);return O===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=O,{kind:"all-features",appearanceIndex:O})}return{kind:"per-feature"}}evaluateAllFeatures(m){for(let x=0;x{for(let E=0;EO-U),P=new Map;for(const O of E){const U=k.get(O);P.set(O,new Po(U))}return x&&(this.cachedBatchIndices=E,this.cachedBatchSegments=P),{batchIndices:E,batchSegments:P}}snapshotSymbolVertexData(m,x){const k=m*X6;return this.layoutVertexArray.uint16.slice(k,k+x*X6)}restoreSymbolVertexData(m,x){this.layoutVertexArray.uint16.set(x,m*X6)}updateSymbolVertexData(m,x,k,E,P,O,U,H,X,oe,ue,me,_e){const Se=this.layoutVertexArray.uint16,Pe=m*X6;Se[Pe]=x,Se[Pe+1]=k,Se[Pe+2]=E,Se[Pe+3]=P,Se[Pe+4]=O,Se[Pe+5]=U,Se[Pe+6]=H,Se[Pe+7]=X,Se[Pe+8]=oe,Se[Pe+9]=ue,Se[Pe+10]=me,Se[Pe+11]=_e}upload(m,x,k,E,P,O){this.isEmpty()||(k&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,u3t.members,!!O),this.indexBuffer=m.createIndexBuffer(this.indexArray,x),this.dynamicLayoutVertexBuffer=m.createVertexBuffer(this.dynamicLayoutVertexArray,m3t.members,!0),this.opacityVertexBuffer=m.createVertexBuffer(this.opacityVertexArray,d5t,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=m.createVertexBuffer(this.iconTransitioningVertexArray,g3t.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=m.createVertexBuffer(this.globeExtVertexArray,h3t.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||P)&&(this.zOffsetVertexBuffer=m.createVertexBuffer(this.zOffsetVertexArray,p3t.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=m.createVertexBuffer(this.orientationVertexArray,x3t.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=m.createVertexBuffer(this.featureIdArray,f3t.members,!1))),(k||E)&&(this.programConfigurations.upload(m),this.uboBinder&&this.uboBinder.upload(m)))}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())}}Kn(F_e,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class z_e{constructor(m,x,k){this.layoutVertexArray=new m,this.layoutAttributes=x,this.indexArray=new k,this.segments=new Po,this.collisionVertexArray=new UC,this.collisionVertexArrayExt=new C1}upload(m){this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=m.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=m.createVertexBuffer(this.collisionVertexArray,y3t.members,!0),this.collisionVertexBufferExt=m.createVertexBuffer(this.collisionVertexArrayExt,v3t.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}Kn(z_e,"CollisionBuffers");class M1{constructor(m){this.collisionBoxArray=m.collisionBoxArray,this.zoom=m.zoom,this.overscaling=m.overscaling,this.layers=m.layers,this.layerIds=this.layers.map(O=>O.fqid),this.index=m.index,this.pixelRatio=m.pixelRatio,this.sourceLayerIndex=m.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=v([]),this.placementViewportMatrix=v([]);const x=this.layers[0]._unevaluatedLayout._values;this.worldview=m.worldview,this.localizable=m.localizable,this.maxUniformBufferBindings=m.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=m.maxUniformBlockSizeDwords,this.disableSymbolUBO=m.disableSymbolUBO,this.textSizeData=t3(this.zoom,x["text-size"],this.worldview,m.availableImages),this.iconSizeData=t3(this.zoom,x["icon-size"],this.worldview,m.availableImages);const k=this.layers[0].layout,E=k.get("symbol-sort-key"),P=k.get("symbol-z-order");this.lut=m.lut,this.canOverlap=k.get("text-allow-overlap")||k.get("icon-allow-overlap")||k.get("text-ignore-placement")||k.get("icon-ignore-placement"),this.sortFeaturesByKey=P!=="viewport-y"&&E.constantOr(1)!==void 0,this.sortFeaturesByY=(P==="viewport-y"||P==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=k.get("text-writing-mode").map(O=>Mx[O]),this.stateDependentLayerIds=this.layers.filter(O=>O.isStateDependent()).map(O=>O.id),this.sourceID=m.sourceID,this.projection=m.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(m){const x=this.layers[0].getAppearances();if(!x||x.length===0)return!1;const k=Array.isArray(m)?m:[m];return x.some(E=>k.some(P=>E.hasLayoutProperty(P)))}getAppearanceFeatureData(m){return this.featureAppearanceData.get(m)}createArrays(){this.text=new F_e(new Ue(this.layers,{zoom:this.zoom,lut:this.lut},m=>m.startsWith("text")||m.startsWith("symbol"))),this.icon=new F_e(new Ue(this.layers,{zoom:this.zoom,lut:this.lut},m=>m.startsWith("icon")||m.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new b_e(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new b_e(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new oq,this.lineVertexArray=new HC,this.symbolInstances=new iq}calculateGlyphDependencies(m,x,k,E,P){for(const O of m){const U=O.codePointAt(0);if(U===void 0)break;if(x[U]=!0,E&&P&&U<=65535){const H=jO[O];H&&(x[H.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(m,x,k,E,P,O,U){if(!m.hasLayoutProperty("icon-size"))return U*O;let H=1;const X=m.getUnevaluatedLayoutProperty("icon-size"),oe=t3(this.zoom,X,this.worldview,P),ue=K6(oe,x);if(oe.kind!=="constant"&&oe.kind!=="camera"||(H=ue.uSize),oe.kind==="composite"){const{minZoom:me,maxZoom:_e}=oe,Se=X.possiblyEvaluate(new La(me,{worldview:this.worldview}),E),Pe=X.possiblyEvaluate(new La(_e,{worldview:this.worldview}),E),$e=Se.evaluate(k,{},E,P);H=$e+(Pe.evaluate(k,{},E,P)-$e)*ue.uSizeT}return oe.kind==="source"&&(H=X.possiblyEvaluate(new La(this.zoom,{worldview:this.worldview}),E).evaluate(k,{},E,P)),H*O}updateFootprints(m,x){}updateReplacement(m,x){if(x.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=x.updateTime;const k=x.getReplacementRegionsForTile(m.toUnwrapped(),!0);return!kq(this.activeReplacements,k)&&(this.activeReplacements=k,!0)}getResolvedImageFromTokens(m){return typeof m=="string"?Hd.build(m):m}populate(m,x,k,E){const P=this.layers[0],O=P.layout,U=this.projection.name==="globe",H=O.get("text-font"),X=O.get("text-field"),oe=O.get("icon-image"),[ue,me]=O.get("icon-size-scale-range"),_e=Xe(x.scaleFactor||1,ue,me),[Se,Pe]=O.get("text-size-scale-range"),$e=Xe(x.scaleFactor||1,Se,Pe),Ke=(X.value.kind!=="constant"||X.value.value instanceof Vd&&!X.value.value.isEmpty()||X.value.value.toString().length>0)&&(H.value.kind!=="constant"||H.value.value.length>0),lt=oe.value.kind!=="constant"||!!oe.value.value||Object.keys(oe.parameters).length>0,nt=this.hasAnyAppearanceLayoutProperty("icon-image"),pt=O.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!Ke&&!lt&&!nt)return;const _t=x.iconDependencies,jt=x.glyphDependencies,Yt=x.availableImages,zt=new La(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),Wt=$t=>{const Ut=$t.id.toString();_t.has(Ut)?_t.get(Ut).push($t):_t.set(Ut,[$t])};for(const $t of m){const{feature:Ut,id:Bs,index:qs,sourceLayerIndex:Qs}=$t,sn=P._featureFilter.needGeometry,Xs=Wa(Ut,sn);if(!P._featureFilter.filter(zt,Xs,k))continue;if(sn||(Xs.geometry=Gr(Ut,k,E)),U&&Ut.type!==1&&k.z<=5){const Fn=Xs.geometry,On=.98078528056,En=(rr,pr)=>Fe(nO(rr.x,rr.y,k,1),nO(pr.x,pr.y,k,1)){if(!Fn.getLayoutProperty("icon-image"))return;const On=this.getCombinedIconPrimary(Fn,en,Xs,k,Yt,Tn,_e);On&&Wt(On)}),xn){const Fn=H.evaluate(Xs,{},k).join(","),On=O.get("text-rotation-alignment")==="map"&&O.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(Mx.vertical)>=0;for(const En of xn.sections)if(En.image){const rr=En.image.getPrimary().scaleSelf(this.pixelRatio*$e),pr=rr.id.toString(),Vr=_t.get(pr)||[];Vr.push(rr),_t.set(pr,Vr)}else{const rr=Vh(xn.toString()),pr=En.fontStack||Fn,Vr=jt[pr]=jt[pr]||{};this.calculateGlyphDependencies(En.text,Vr,On,this.allowVerticalPlacement,rr)}}}if(O.get("symbol-placement")==="line"&&(this.features=function($t){const Ut={},Bs={},qs=[];let Qs=0;function sn(en){qs.push($t[en]),Qs++}function Xs(en,on,yn){const Tn=Bs[en];return delete Bs[en],Bs[on]=Tn,qs[Tn].geometry[0].pop(),qs[Tn].geometry[0]=qs[Tn].geometry[0].concat(yn[0]),Tn}function xn(en,on,yn){const Tn=Ut[on];return delete Ut[on],Ut[en]=Tn,qs[Tn].geometry[0].shift(),qs[Tn].geometry[0]=yn[0].concat(qs[Tn].geometry[0]),Tn}function Os(en,on,yn){const Tn=yn?on[0][on[0].length-1]:on[0][0];return`${en}:${Tn.x}:${Tn.y}`}for(let en=0;en<$t.length;en++){const on=$t[en],yn=on.geometry,Tn=on.text?on.text.toString():null;if(!Tn){sn(en);continue}const or=Os(Tn,yn),Fn=Os(Tn,yn,!0);if(or in Bs&&Fn in Ut&&Bs[or]!==Ut[Fn]){const On=xn(or,Fn,yn),En=Xs(or,Fn,qs[On].geometry);delete Ut[or],delete Bs[Fn],Bs[Os(Tn,qs[En].geometry,!0)]=En,qs[On].geometry=null}else or in Bs?Xs(or,Fn,yn):Fn in Ut?xn(or,Fn,yn):(sn(en),Ut[or]=Qs-1,Bs[Fn]=Qs-1)}return qs.filter(en=>en.geometry)}(this.features)),O.get("symbol-elevation-reference")==="hd-road-markup"){if(this.elevationType="road",x.elevationFeatures){!this.elevationFeatures&&x.elevationFeatures.length>0&&(this.elevationFeatures=[],this.elevationFeatureIdToIndex=new Map);for(const $t of x.elevationFeatures)this.elevationFeatureIdToIndex.set($t.id,this.elevationFeatures.length),this.elevationFeatures.push($t)}}else O.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort(($t,Ut)=>$t.sortKey-Ut.sortKey)}getCombinedIconPrimary(m,x,k,E,P,O,U){let H,X;if(m.hasLayoutProperty("icon-image")){const oe=x.getAppearanceValueAndResolveTokens(m,"icon-image",k,E,P);H=this.getResolvedImageFromTokens(oe)}else{const oe=x.getValueAndResolveTokens("icon-image",k,E,P);H=this.getResolvedImageFromTokens(oe)}if(H){const oe=m.hasLayoutProperty("icon-size")?m.getUnevaluatedLayoutProperty("icon-size"):x._unevaluatedLayout._values["icon-size"];X=TO(H,t3(this.zoom,oe,this.worldview,P),oe,E,this.zoom,O,this.pixelRatio,U,this.worldview,P).iconPrimary}return X}updateSymbolInstanceIconVertices(m,x,k,E,P,O){const{canonical:U,availableImages:H,globalProperties:X,layer:oe,iconScaleFactor:ue,featureState:me,layoutIconOffset:_e,layoutIconSize:Se,layoutIconRotate:Pe}=O;if(m.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(x.activeAppearanceIndex===k)return{vertexOffsetDelta:m.numIconVertices,hasChanges:!1};const $e=k>=0?oe.appearances[k]:null;if($e){const Ke=this.getCombinedIconPrimary($e,oe,E,U,H,{sortKey:void 0,text:void 0,icon:null,index:m.featureIndex,sourceLayerIndex:m.featureIndex,geometry:[],properties:x.properties,type:"Point",id:x.id},ue);if(!Ke)return{vertexOffsetDelta:0,hasChanges:!1};const lt=Ke.toString(),nt=this.iconAtlasPositions&&this.iconAtlasPositions.get(lt);if(nt){const{appearanceIconOffset:pt,appearanceIconRotate:_t}=QOe($e,oe,E,U,_e,Pe,Se,ue);let jt=Vq(nt,void 0,pt,oe.layout.get("icon-anchor").evaluate(E,me,U));const Yt=nt.sdf,zt=oe.layout.get("icon-text-fit").constantOr("none");zt!=="none"&&x.textShaping&&x.iconTextFitPadding&&x.fontScale&&(jt=k_e(jt,x.textShaping,zt,x.iconTextFitPadding,pt,x.fontScale));const Wt=this.calculateEffectiveAppearanceIconSize($e,X.zoom,E,U,H,ue,Se),$t=0,Ut=1+(Math.min(s3,Math.round(Wt*Xj))<<1),Bs=I_e(jt,_t,Yt,zt!=="none",ue);x.isUsingAppearanceIconVertexData||(x.isUsingAppearanceIconVertexData=!0,x.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(P,m.numIconVertices));const qs=Math.floor(m.numIconVertices/4),Qs=Math.min(Bs.length,qs);let sn=P;for(let xn=0;xn0||m.numVerticalGlyphVertices>0;if(!pt)return{vertexOffsetDelta:pt?m.numHorizontalGlyphVertices+m.numVerticalGlyphVertices:0,hasChanges:!1};if(x.activeAppearanceIndex===k)return{vertexOffsetDelta:m.numHorizontalGlyphVertices+m.numVerticalGlyphVertices,hasChanges:!1};const _t=k>=0?H.appearances[k]:null;if(_t&&x.textShaping){const{appearanceTextOffset:jt,appearanceTextRotate:Yt,appearanceTextSize:zt}=XOe(_t,H,E,U,me,Se,_e);x.fontScale=sFe(zt,x.textScaleFactor);const Wt=_t.getUnevaluatedLayoutProperty("text-size");let $t=this.textSizeData,Ut=Ke,Bs=lt;_t.hasLayoutProperty("text-size")&&($t=t3(this.zoom,Wt,this.worldview,nt),Ut=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Bs=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const qs=x.textShaping.bottom-me[1],Qs=x.textShaping.left-me[0],sn=x.textShaping.right-me[0];x.textShaping.top=jt[1]+(x.textShaping.top-me[1]),x.textShaping.bottom=jt[1]+qs,x.textShaping.left=jt[0]+Qs,x.textShaping.right=jt[0]+sn;const Xs=YOe(0,x.textShaping,jt,H,!1,E,oe,this.allowVerticalPlacement,Yt),xn=zt&&$t.kind==="composite"?Wt.possiblyEvaluate(new La(Ut,{}),U).evaluate(E,ue,U):Pe,Os=zt&&$t.kind==="composite"?Wt.possiblyEvaluate(new La(Bs,{}),U).evaluate(E,ue,U):$e,en=R_e(_t.name,$t,zt,X,xn,Os),on=Array.isArray(en)?en[1]:zt,yn=0,Tn=1+(Math.min(s3,Math.round(on*Xj))<<1);x.isUsingAppearanceTextVertexData||(x.isUsingAppearanceTextVertexData=!0,x.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(P,m.numHorizontalGlyphVertices+m.numVerticalGlyphVertices));for(let or=0;or0){const X=new Set(Object.keys(m).map(oe=>{const ue=Number(oe);return!isNaN(ue)&&Number.isSafeInteger(ue)&&String(ue)===oe?ue:oe}));this.text.uboBinder&&this.text.uboBinder.updateFeatures(X,P[0],x,H,k,m,U),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(X,P[0],x,H,k,m,U)}}}updateRoadElevation(m){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let x=!1;const k=dn(m),E=1/k;let P=!1,O=!1;for(let U=0;U0||me>0,$e=_e>0,Ke=this.elevationFeatures[H.elevationFeatureIndex];if(Ke){const lt=new Ls(H.tileAnchorX,H.tileAnchorY),nt=.075+Ke.pointElevation(lt);H.zOffset!==nt&&(x=!0,H.zOffset=nt),nt!==0&&(this.hasAnyZOffset=!0);const pt=Ke.computeSlopeNormal(lt,E),_t=Jt(bt(),ne(0,0,1),pt);it(X,X,_t),it(oe,oe,_t),X[2]*=k,oe[2]*=k,X[0]===1&&X[1]===0&&X[2]===0&&oe[0]===0&&oe[1]===1&&oe[2]===0||(P=P||Pe,O=O||$e)}if(Pe&&(tV(this.text.orientationVertexArray,ue,X,oe),tV(this.text.orientationVertexArray,me,X,oe)),$e){const{placedIconSymbolIndex:lt,verticalPlacedIconSymbolIndex:nt}=H;lt>=0&&tV(this.icon.orientationVertexArray,_e,X,oe),nt>=0&&tV(this.icon.orientationVertexArray,Se,X,oe)}}P||(this.text.orientationVertexArray=void 0),O||(this.icon.orientationVertexArray=void 0),x&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const m=(P,O,U)=>{k+=O,k>P.length&&P.resize(k);for(let H=-O;H<0;H++)P.emplace(H+k,U)},x=(P,O,U)=>{E+=O,E>P.length&&P.resize(E);for(let H=-O;H<0;H++)P.emplace(H+E,U)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let k=0,E=0;for(let P=0;P0;if((U>0||H>0)&&(m(this.text.zOffsetVertexArray,U,oe),m(this.text.zOffsetVertexArray,H,oe)),ue){const{placedIconSymbolIndex:me,verticalPlacedIconSymbolIndex:_e}=O;me>=0&&x(this.icon.zOffsetVertexArray,X,oe),_e>=0&&x(this.icon.zOffsetVertexArray,O.numVerticalIconVertices,oe)}}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(m,x,k,E,P){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(m),this.iconCollisionBox.upload(m)),this.text.upload(m,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(O=>O.appearances&&O.appearances.length>0)),this.icon.upload(m,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(m,x,k,E,P,O=!1){const U={hasLayoutChanges:!1,hasUboChanges:!1};if(!m||!k||!this.featureAppearanceData)return U;const H=x||{},X=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,oe=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!X&&!oe)return U;const ue=this.layers[0],me=ue.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===ue.appearancesVersion||(this.featureAppearances=new l5t(ue.appearances,ue.appearancesVersion));const _e=this.featureAppearances.update(E,O);if(_e.kind==="no-changes")return U;let Se=1,Pe=0,$e=!1,Ke=!1;if(X){const[jt,Yt]=me.get("icon-size-scale-range");Se=Xe(1,jt,Yt)}let lt=1,nt=0,pt=!1;if(oe){const[jt,Yt]=me.get("text-size-scale-range");lt=Xe(1,jt,Yt)}const _t=new Map;if(P&&k)for(const jt of k){const Yt=P.getImage(jt,ue.scope);if(Yt){const zt=new np(jt.toString());_t.set(zt.toString(),Yt)}}for(let jt=0;jtsn.isActive({globals:E,feature:Ut,canonical:m,featureState:$t})):-1;Bs=Qs>=0?Qs:-1}const qs=zt.activeAppearanceIndex!==Bs;if(oe){const Qs=me.get("text-size"),sn=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Xs=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,xn={canonical:m,layer:ue,featureState:$t,availableImages:k,textScaleFactor:lt,imageMap:_t,layoutTextOffset:me.get("text-offset").evaluate(Ut,$t,m).map(en=>en*Zd),layoutTextSize:Qs.evaluate(Ut,$t,m),layoutTextRotate:me.get("text-rotate").evaluate(Ut,$t,m),layoutMinZoomSize:Qs.evaluate(Ut,{zoom:sn},m),layoutMaxZoomSize:Qs.evaluate(Ut,{zoom:Xs},m),layoutTextSizeMinZoom:sn,layoutTextSizeMaxZoom:Xs},Os=this.updateSymbolInstanceTextVertices(Yt,zt,Bs,Ut,nt,xn);nt+=Os.vertexOffsetDelta,pt=pt||Os.hasChanges}if(X){const Qs={canonical:m,layer:ue,featureState:$t,availableImages:k,globalProperties:E,iconScaleFactor:Se,layoutIconOffset:me.get("icon-offset").evaluate(Ut,$t,m),layoutIconSize:me.get("icon-size").evaluate(Ut,$t,m,k),layoutIconRotate:me.get("icon-rotate").evaluate(Ut,$t,m)},sn=this.updateSymbolInstanceIconVertices(Yt,zt,Bs,Ut,Pe,Qs);Pe+=sn.vertexOffsetDelta,$e=$e||sn.hasChanges}if(qs){const Qs=Yt.featureIndex,sn=E?E.brightness:null,Xs=$t||{},xn=Bs>=0?ue.appearances[Bs]:null;this.text.uboBinder&&(this.text.uboBinder.layer=ue,Ke=this.text.uboBinder.updateFeaturePaintForAppearance(Qs,Ut,Xs,m,k,sn,xn)||Ke),this.icon.uboBinder&&(this.icon.uboBinder.layer=ue,Ke=this.icon.uboBinder.updateFeaturePaintForAppearance(Qs,Ut,Xs,m,k,sn,xn)||Ke)}zt.activeAppearanceIndex=Bs}return $e&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),pt&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:$e||pt,hasUboChanges:Ke}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=dFe(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(m,x){const k=this.lineVertexArray.length;if(m.segment!==void 0)for(const{x:E,y:P}of x)this.lineVertexArray.emplaceBack(E,P);return{lineStartIndex:k,lineLength:this.lineVertexArray.length-k}}addSymbols(m,x,k,E,P,O,U,H,X,oe,ue,me,_e,Se,Pe,$e,Ke,lt){const nt=m.indexArray,pt=m.layoutVertexArray,_t=m.globeExtVertexArray,jt=lt,Yt=m.uboBinder?m.uboBinder.getCurrentBatchIndex():void 0,zt=m.segments.prepareSegment(4*jt,pt,nt,this.canOverlap?O.sortKey:void 0,Yt),Wt=this.glyphOffsetArray.length,$t=zt.vertexLength,Ut=this.allowVerticalPlacement&&U===Mx.vertical?Math.PI/2:0,Bs=O.text&&O.text.sections;let qs=pt.length,Qs=-1;for(let xn=0;xn=0)){const xn=4*sn;for(let Os=0;Os=0?x.rightJustifiedTextSymbolIndex:x.centerJustifiedTextSymbolIndex>=0?x.centerJustifiedTextSymbolIndex:x.leftJustifiedTextSymbolIndex>=0?x.leftJustifiedTextSymbolIndex:x.verticalPlacedTextSymbolIndex>=0?x.verticalPlacedTextSymbolIndex:E),O=S_e(this.textSizeData,m,P)/Zd;return this.tilePixelRatio*O}getSymbolInstanceIconSize(m,x,k){const E=this.icon.placedSymbolArray.get(k),P=S_e(this.iconSizeData,m,E);return this.tilePixelRatio*P}_commitDebugCollisionVertexUpdate(m,x,k,E){m.emplaceBack(x,-k,-k,E),m.emplaceBack(x,k,-k,E),m.emplaceBack(x,k,k,E),m.emplaceBack(x,-k,k,E)}_updateTextDebugCollisionBoxes(m,x,k,E,P,O,U){for(let H=E;H0}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(m,x){const k=m.placedSymbolArray.get(x),E=k.vertexStartIndex+4*k.numGlyphs;for(let P=k.vertexStartIndex;PE[U]-E[H]||P[H]-P[U]),O}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let m=0;mthis.symbolInstances.get(x).zOffset-this.symbolInstances.get(m).zOffset)}addToSortKeyRanges(m,x){const k=this.sortKeyRanges[this.sortKeyRanges.length-1];k&&k.sortKey===x?k.symbolInstanceEnd=m+1:this.sortKeyRanges.push({sortKey:x,symbolInstanceStart:m,symbolInstanceEnd:m+1})}sortFeatures(m){if(this.sortFeaturesByY&&this.sortedAngle!==m)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesWithinSegments();else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(m),this.sortedAngle=m,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const x of this.symbolInstanceIndexes){const k=this.symbolInstances.get(x);this.featureSortOrder.push(k.featureIndex);const{rightJustifiedTextSymbolIndex:E,centerJustifiedTextSymbolIndex:P,leftJustifiedTextSymbolIndex:O,verticalPlacedTextSymbolIndex:U,placedIconSymbolIndex:H,verticalPlacedIconSymbolIndex:X}=k;E>=0&&this.addIndicesForPlacedSymbol(this.text,E),P>=0&&P!==E&&this.addIndicesForPlacedSymbol(this.text,P),O>=0&&O!==P&&O!==E&&this.addIndicesForPlacedSymbol(this.text,O),U>=0&&this.addIndicesForPlacedSymbol(this.text,U),H>=0&&this.addIndicesForPlacedSymbol(this.icon,H),X>=0&&this.addIndicesForPlacedSymbol(this.icon,X)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}getOrCreateSortedSymbolsByBatch(m,x){const k=(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 P of E){const O=this.symbolInstances.get(P.index);P.rotatedY=0|Math.round(m*O.tileAnchorX+x*O.tileAnchorY)}else{this.symbolsByBatch=new Map;for(let E=0;EP.rotatedY-O.rotatedY||O.featureIndex-P.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(m,x){for(const k of m){const E=k.batchIndex;if(E===void 0)continue;const P=x.get(E);if(!P){k.primitiveOffset=this.text.indexArray.length,k.primitiveLength=0;continue}k.primitiveOffset=this.text.indexArray.length;const O=this.text.indexArray.length;for(const{index:U}of P){const H=this.symbolInstances.get(U),{rightJustifiedTextSymbolIndex:X,centerJustifiedTextSymbolIndex:oe,leftJustifiedTextSymbolIndex:ue,verticalPlacedTextSymbolIndex:me}=H;X>=0&&this.addIndicesForPlacedSymbol(this.text,X),oe>=0&&oe!==X&&this.addIndicesForPlacedSymbol(this.text,oe),ue>=0&&ue!==oe&&ue!==X&&this.addIndicesForPlacedSymbol(this.text,ue),me>=0&&this.addIndicesForPlacedSymbol(this.text,me)}k.primitiveLength=this.text.indexArray.length-O}}rebuildIconSegmentIndices(m,x){for(const k of m){const E=k.batchIndex;if(E===void 0)continue;const P=x.get(E);if(!P){k.primitiveOffset=this.icon.indexArray.length,k.primitiveLength=0;continue}k.primitiveOffset=this.icon.indexArray.length;const O=this.icon.indexArray.length;for(const{index:U}of P){const H=this.symbolInstances.get(U),{placedIconSymbolIndex:X,verticalPlacedIconSymbolIndex:oe}=H;X>=0&&this.addIndicesForPlacedSymbol(this.icon,X),oe>=0&&this.addIndicesForPlacedSymbol(this.icon,oe)}k.primitiveLength=this.icon.indexArray.length-O}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const m=Math.sin(this.sortedAngle),x=Math.cos(this.sortedAngle),k=this.getOrCreateSortedSymbolsByBatch(m,x),E=Array.from(k.keys()).sort((P,O)=>P-O);for(const P of E){const O=k.get(P);for(const{index:U}of O){const H=this.symbolInstances.get(U);this.featureSortOrder.push(H.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),k),this.rebuildIconSegmentIndices(this.icon.segments.get(),k),this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}getElevationFeatureForText(m){const x=this.symbolInstances.get(this.text.symbolInstanceIndices[m]).elevationFeatureIndex;let k;return this.elevationFeatures&&xk in w?String(w[k]):"")}let hFe,mFe,B_e;Kn(M1,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),M1.addDynamicAttributes=Q6;class pFe{constructor(m){this.type=m.property.overrides?m.property.overrides.runtimeType:If,this.defaultValue=m}evaluate(m){if(m.formattedSection){const x=this.defaultValue.property.overrides;if(x&&x.hasOverride(m.formattedSection))return x.getOverride(m.formattedSection)}return m.feature&&m.featureState?this.defaultValue.evaluate(m.feature,m.featureState):this.defaultValue.property.specification.default}eachChild(m){this.defaultValue.isConstant()||m(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}Kn(pFe,"FormatSectionOverride",{omit:["defaultValue"]});const $_e=()=>B_e||(B_e={layout:hFe||(hFe=new Wo({"symbol-placement":new kn(fs.layout_symbol["symbol-placement"]),"symbol-spacing":new kn(fs.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new kn(fs.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new jn(fs.layout_symbol["symbol-sort-key"]),"symbol-z-order":new kn(fs.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new kn(fs.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new kn(fs.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new kn(fs.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new kn(fs.layout_symbol["icon-ignore-placement"]),"icon-optional":new kn(fs.layout_symbol["icon-optional"]),"icon-rotation-alignment":new kn(fs.layout_symbol["icon-rotation-alignment"]),"icon-size":new jn(fs.layout_symbol["icon-size"]),"icon-size-scale-range":new kn(fs.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new jn(fs.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new jn(fs.layout_symbol["icon-text-fit-padding"]),"icon-image":new jn(fs.layout_symbol["icon-image"]),"icon-image-use-theme":new kn({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new jn(fs.layout_symbol["icon-rotate"]),"icon-padding":new kn(fs.layout_symbol["icon-padding"]),"icon-keep-upright":new kn(fs.layout_symbol["icon-keep-upright"]),"icon-offset":new jn(fs.layout_symbol["icon-offset"]),"icon-anchor":new jn(fs.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new kn(fs.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new kn(fs.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new kn(fs.layout_symbol["text-rotation-alignment"]),"text-field":new jn(fs.layout_symbol["text-field"]),"text-font":new jn(fs.layout_symbol["text-font"]),"text-size":new jn(fs.layout_symbol["text-size"]),"text-size-scale-range":new kn(fs.layout_symbol["text-size-scale-range"]),"text-max-width":new jn(fs.layout_symbol["text-max-width"]),"text-line-height":new jn(fs.layout_symbol["text-line-height"]),"text-letter-spacing":new jn(fs.layout_symbol["text-letter-spacing"]),"text-justify":new jn(fs.layout_symbol["text-justify"]),"text-radial-offset":new jn(fs.layout_symbol["text-radial-offset"]),"text-variable-anchor":new kn(fs.layout_symbol["text-variable-anchor"]),"text-anchor":new jn(fs.layout_symbol["text-anchor"]),"text-max-angle":new kn(fs.layout_symbol["text-max-angle"]),"text-writing-mode":new kn(fs.layout_symbol["text-writing-mode"]),"text-rotate":new jn(fs.layout_symbol["text-rotate"]),"text-padding":new kn(fs.layout_symbol["text-padding"]),"text-keep-upright":new kn(fs.layout_symbol["text-keep-upright"]),"text-transform":new jn(fs.layout_symbol["text-transform"]),"text-offset":new jn(fs.layout_symbol["text-offset"]),"text-allow-overlap":new kn(fs.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new kn(fs.layout_symbol["text-ignore-placement"]),"text-optional":new kn(fs.layout_symbol["text-optional"]),visibility:new kn(fs.layout_symbol.visibility)})),paint:mFe||(mFe=new Wo({"icon-opacity":new jn(fs.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new jn(fs.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new jn(fs.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new jn(fs.paint_symbol["text-emissive-strength"]),"icon-color":new jn(fs.paint_symbol["icon-color"]),"icon-halo-color":new jn(fs.paint_symbol["icon-halo-color"]),"icon-halo-width":new jn(fs.paint_symbol["icon-halo-width"]),"icon-halo-blur":new jn(fs.paint_symbol["icon-halo-blur"]),"icon-translate":new kn(fs.paint_symbol["icon-translate"]),"icon-translate-anchor":new kn(fs.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new kn(fs.paint_symbol["icon-image-cross-fade"]),"text-opacity":new jn(fs.paint_symbol["text-opacity"]),"text-occlusion-opacity":new jn(fs.paint_symbol["text-occlusion-opacity"]),"text-color":new jn(fs.paint_symbol["text-color"],{runtimeType:zh,getOverride:w=>w.textColor,hasOverride:w=>!!w.textColor}),"text-halo-color":new jn(fs.paint_symbol["text-halo-color"]),"text-halo-width":new jn(fs.paint_symbol["text-halo-width"]),"text-halo-blur":new jn(fs.paint_symbol["text-halo-blur"]),"text-translate":new kn(fs.paint_symbol["text-translate"]),"text-translate-anchor":new kn(fs.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new kn(fs.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new kn(fs.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new kn(fs.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new kn(fs.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new jn(fs.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"})}))},B_e);class sV extends lo{constructor(m,x,k,E){super(m,$_e(),x,k,E,m.layout?m.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=v([]),this.hasOcclusionOpacityProperties=m.paint!==void 0&&("icon-occlusion-opacity"in m.paint||"text-occlusion-opacity"in m.paint)}_handleSpecialPaintPropertyUpdate(m){m!=="icon-occlusion-opacity"&&m!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(m,x){super.recalculate(m,x),this.appearances&&this.appearances.forEach(E=>{E.recalculate(m,x,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 k=this.layout.get("text-writing-mode");if(k){const E=[];for(const P of k)E.indexOf(P)<0&&E.push(P);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(m,x,k,E){return this._saturation===m&&this._contrast===x&&this._brightnessMin===k&&this._brightnessMax===E||(this._colorAdjustmentMatrix=function(P,O,U,H){P=_i(P),O=Za(O);const X=g(),oe=P/3,ue=1-2*oe,me=[ue,oe,oe,0,oe,ue,oe,0,oe,oe,ue,0,0,0,0,1],_e=.5-.5*O,Se=H-U;return b(X,[Se,0,0,0,0,Se,0,0,0,0,Se,0,U,U,U,1],[O,0,0,0,0,O,0,0,0,0,O,0,_e,_e,_e,1]),b(X,X,me),X}(m,x,k,E),this._saturation=m,this._contrast=x,this._brightnessMin=k,this._brightnessMax=E),this._colorAdjustmentMatrix}getValueAndResolveTokens(m,x,k,E){const P=this.layout.get(m).evaluate(x,{},k,E),O=this._unevaluatedLayout._values[m];return O.isDataDriven()||Hy(O.value)||!P?P:uFe(x.properties,P)}getAppearanceValueAndResolveTokens(m,x,k,E,P){const O=m.getLayoutProperty(x);if(!O)return;const U=O.evaluate(k,{},E,P),H=m.getUnevaluatedLayoutProperties()._values[x];return H.isDataDriven()||Hy(H.value)||!U||typeof U!="string"?U:uFe(k.properties,U)}createBucket(m){return new M1(m)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const m of $_e().paint.overridableProperties){if(!sV.hasPaintOverride(this.layout,m))continue;const x=this.paint.get(m),k=new pFe(x),E=new w1(k,x.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let P=null;P=x.value.kind==="constant"||x.value.kind==="source"?new v0("source",E):new jx("composite",E,x.value.zoomStops,x.value.interpolationType),this.paint._values[m]=new k1(x.property,P,x.parameters)}}_handleOverridablePaintPropertyUpdate(m,x,k){return!(!this.layout||x.isDataDriven()||k.isDataDriven())&&sV.hasPaintOverride(this.layout,m)}static hasPaintOverride(m,x){const k=m.get("text-field"),E=$_e().paint.properties[x];let P=!1;const O=U=>{for(const H of U)if(E.overrides&&E.overrides.hasOverride(H))return void(P=!0)};if(k.value.kind==="constant"&&k.value.value instanceof Vd)O(k.value.value.sections);else if(k.value.kind==="source"){const U=X=>{P||(X instanceof ar&&Ml(X.value)===Dy?O(X.value.sections):X instanceof ym?O(X.sections):X.eachChild(U))},H=k.value;H._styleExpression&&U(H._styleExpression.expression)}return P}getProgramIds(){return["symbol"]}getDefaultProgramParams(m,x,k){return{config:new Le(this,{zoom:x,lut:k}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let fFe,xFe,gFe,yFe;var nV=cn([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function rV(w,m,x,k,E,P,O,U){const H=[w,m,1,x,k,1,E,P,1],X=[O,U,1],oe=p([],H),[ue,me,_e]=Ne(X,X,oe);return f(H,H,[ue,0,0,0,me,0,0,0,_e])}function vFe(w,m,x,k,E,P,O,U){const H=function(X,oe,ue,me,_e,Se,Pe,$e){const Ke=rV(0,0,1,0,1,1,0,1),lt=rV(X,oe,ue,me,_e,Se,Pe,$e);return f(lt,lt,p([],Ke))}(w,m,x,k,E,P,O,U);return[H[2]/H[8]/$n,H[5]/H[8]/$n]}function aV(w){return[w[0],Math.min(Math.max(w[1],-85.051129),Ys)]}class bFe extends Rp{constructor(m,x,k,E){super(),this.id=m,this.dispatcher=k,this.coordinates=x.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=x,this._dirty=!1}load(m,x){if(this._loaded=x||!1,this.fire(new zc("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return m&&(this.coordinates=m),this._loaded=!0,void this._finishLoading();this._imageRequest=fx(this.map._requestManager.transformRequest(this.url,u0.Image),(k,E)=>{this._imageRequest=null,this._loaded=!0,k?this.fire(new tp(k)):E&&(this.image=E,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,m&&(this.coordinates=m),this._finishLoading())})}loaded(){return this._loaded}updateImage(m){return m.url?(this._imageRequest&&m.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=m.url,this.load(m.coordinates,this._loaded),this):this}setTexture(m){if(!(m.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new bO(this.map.painter.context,m.handle),this.width=m.dimensions[0],this.height=m.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new zc("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(m){this.map=m,this.load()}onRemove(m){this._imageRequest&&(this._imageRequest.cancel(),this._imageRequest=null),!this.texture||this.texture instanceof bO||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(m){if(this.coordinates=m,this._boundsArray=void 0,this._unsupportedCoords=!1,!m.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let x=m[0][1],k=m[0][1];for(const P of m)P[1]>k&&(k=P[1]),P[1]Ys?this.onNorthPole=!0:E<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const P=m.map(mr.fromLngLat);this.tileID=function(O){let U=1/0,H=1/0,X=-1/0,oe=-1/0;for(const Pe of O)U=Math.min(U,Pe.x),H=Math.min(H,Pe.y),X=Math.max(X,Pe.x),oe=Math.max(oe,Pe.y);const ue=Math.max(X-U,oe-H),me=Math.max(0,Math.floor(-Math.log2(ue))),_e=Math.pow(2,me);let Se=Math.floor((U+X)/2*_e);return Se>1&&(Se-=1),new ZC(me,Se,Math.floor((H+oe)/2*_e))}(P),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new zc("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof bO||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(m){for(const $e in this.tiles){const Ke=this.tiles[$e];Ke.state!=="loaded"&&(Ke.state="loaded",Ke.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const x=n3(new ZC(0,0,0),this.map.transform.projection),k=[x.projection.project(this.coordinates[0][0],this.coordinates[0][1]),x.projection.project(this.coordinates[1][0],this.coordinates[1][1]),x.projection.project(this.coordinates[2][0],this.coordinates[2][1]),x.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function($e){const Ke=$e[1].x-$e[0].x,lt=$e[1].y-$e[0].y,nt=$e[2].x-$e[1].x,pt=$e[2].y-$e[1].y,_t=$e[3].x-$e[2].x,jt=$e[3].y-$e[2].y,Yt=$e[0].x-$e[3].x,zt=$e[0].y-$e[3].y,Wt=Ke*pt-nt*lt,$t=nt*jt-_t*pt,Ut=_t*zt-Yt*jt,Bs=Yt*lt-Ke*zt;return Wt>0&&$t>0&&Ut>0&&Bs>0||Wt<0&&$t<0&&Ut<0&&Bs<0}(k))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const E=n3(this.tileID,this.map.transform.projection),[P,O,U,H]=this.coordinates.map($e=>{const Ke=E.projection.project($e[0],$e[1]);return aFe(E,Ke)._round()});this.perspectiveTransform=vFe(P.x,P.y,O.x,O.y,U.x,U.y,H.x,H.y);const X=this._boundsArray=new ri;X.emplaceBack(P.x,P.y,0,0),X.emplaceBack(O.x,O.y,$n,0),X.emplaceBack(H.x,H.y,0,$n),X.emplaceBack(U.x,U.y,$n,$n),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=m.createVertexBuffer(X,nV.members),this.boundsSegments=Po.simpleSegment(0,0,4,2);const oe=[],ue=function($e){return[aV($e[0]),aV($e[1]),aV($e[2]),aV($e[3])]}(this.coordinates),[me,_e,Se,Pe]=function($e){let Ke=$e[0][0],lt=Ke,nt=$e[0][1],pt=nt;for(let _t=1;_t<$e.length;_t++)$e[_t][0]lt&&(lt=$e[_t][0]),$e[_t][1]pt&&(pt=$e[_t][1]);return[Ke,nt,lt-Ke,pt-nt]}(ue);{const $e=new ri,[Ke,lt,nt,pt]=function(Xs){let xn=Xs[0].x,Os=xn,en=Xs[0].y,on=en;for(let yn=1;ynOs&&(Os=Xs[yn].x),Xs[yn].yon&&(on=Xs[yn].y);return[xn,en,Os-xn,on-en]}(k),_t=Xs=>[(Xs.x-Ke)/nt,(Xs.y-lt)/pt],[jt,Yt,zt,Wt]=k.map(_t),$t=function(Xs,xn,Os,en,on,yn,Tn,or){const Fn=rV(0,0,1,0,1,1,0,1);return f(Fn,Fn,p([],rV(Xs,xn,Os,en,on,yn,Tn,or)))}(jt[0],jt[1],Yt[0],Yt[1],zt[0],zt[1],Wt[0],Wt[1]);this.elevatedGlobePerspectiveTransform=vFe(jt[0],jt[1],Yt[0],Yt[1],zt[0],zt[1],Wt[0],Wt[1]);const Ut=(Xs,xn)=>{oe.push(Xs.lng);const Os=Math.round((Xs.lng-me)/Se*$n),en=Math.round((Xs.lat-_e)/Pe*$n),on=_t(xn),yn=Ne([],[on[0],on[1],1],$t),Tn=Math.round(yn[0]/yn[2]*$n),or=Math.round(yn[1]/yn[2]*$n);$e.emplaceBack(Os,en,Tn,or)},Bs=k[3].x-k[0].x,qs=k[3].y-k[0].y,Qs=k[2].x-k[1].x,sn=k[2].y-k[1].y;for(let Xs=0;Xs<65;Xs++){const xn=Xs/64,Os=[k[0].x+xn*Bs,k[0].y+xn*qs],en=[k[1].x+xn*Qs,k[1].y+xn*sn],on=en[0]-Os[0],yn=en[1]-Os[1];for(let Tn=0;Tn<65;Tn++){const or=Tn/64,Fn={x:Os[0]+on*or,y:Os[1]+yn*or};Ut(x.projection.unproject(Fn.x,Fn.y),Fn)}}this.elevatedGlobeVertexBuffer=m.createVertexBuffer($e,nV.members)}{this.maxLongitudeTriangleSize=0;let $e=[],Ke=new sc;const lt=(nt,pt,_t)=>{Ke.emplaceBack(nt,pt,_t);const jt=oe[nt],Yt=oe[pt],zt=oe[_t],Wt=Math.min(Math.min(jt,Yt),zt),$t=Math.max(Math.max(jt,Yt),zt)-Wt;$t>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=$t),$e.push(Wt+$t/2)};for(let nt=0;nt<64;nt++)for(let pt=0;pt<64;pt++){const _t=65*nt+pt,jt=_t+1,Yt=_t+65,zt=Yt+1;lt(_t,Yt,jt),lt(jt,Yt,zt)}[$e,Ke]=function(nt,pt){const _t=Array.from({length:nt.length},(zt,Wt)=>Wt);_t.sort((zt,Wt)=>nt[zt]-nt[Wt]);const jt=[],Yt=new sc;for(let zt=0;zt<_t.length;zt++){const Wt=_t[zt];jt.push(nt[Wt]);const $t=3*Wt,Ut=$t+1;Yt.emplaceBack(pt.uint16[$t],pt.uint16[Ut],pt.uint16[Ut+1])}return[jt,Yt]}($e,Ke),this.elevatedGlobeTrianglesCenterLongitudes=$e,this.elevatedGlobeIndexBuffer=m.createIndexBuffer(Ke)}this.elevatedGlobeSegments=Po.simpleSegment(0,0,4225,8192),this.elevatedGlobeGridMatrix=new Float32Array([0,Se/$n,0,Pe/$n,0,0,_e,me,0])}prepare(){const m=Object.keys(this.tiles).length!==0;if(this.tileID&&!m)return;const x=this.map.painter.context,k=x.gl;!this._dirty||this.texture instanceof bO||(this.texture?this.texture.update(this.image):(this.texture=new j_(x,this.image,k.RGBA8),this.texture.bind(k.LINEAR,k.CLAMP_TO_EDGE)),this._dirty=!1),m&&this._prepareData(x)}loadTile(m,x){this.tileID&&this.tileID.equals(m.tileID.canonical)?(this.tiles[String(m.tileID.wrap)]=m,m.buckets={},x(null)):(m.state="errored",x(null))}serialize(){return{type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return!1}getSegmentsForLongitude(m){const x=this.elevatedGlobeSegments;if(!this.elevatedGlobeTrianglesCenterLongitudes||!x)return null;const k=this.elevatedGlobeTrianglesCenterLongitudes;let E=(P=m+180)+360*Math.round((k[0]-P)/360);var P;const O=new Po,U=(ue,me)=>{O.segments.push({vertexOffset:0,primitiveOffset:ue,vertexLength:x.segments[0].vertexLength,primitiveLength:me,sortKey:void 0,vaos:{}})},H=.51*this.maxLongitudeTriangleSize;if(Math.abs(k[0]-E)<=H){const ue=Bi(k,0,k.length,E+H);return ue===k.length||U(ue,zi(k,ue+1,k.length,E+360-H)-ue),O}E0}}let wFe,jFe,NFe,kFe,SFe,CFe,TFe;class EFe extends lo{constructor(m,x,k,E){super(m,{layout:wFe||(wFe=new Wo({visibility:new kn(fs["layout_raster-particle"].visibility)})),paint:jFe||(jFe=new Wo({"raster-particle-array-band":new kn(fs["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new kn(fs["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new Gp(fs["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new kn(fs["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new kn(fs["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new kn(fs["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new kn(fs["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new kn(fs["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"})}))},x,k,E),this._updateColorRamp(),this.lastInvalidatedAt=qd.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(m){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(m){return!1}_handleSpecialPaintPropertyUpdate(m){m!=="raster-particle-color"&&m!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),m==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const m=this._transitionablePaint._values["raster-particle-color"].value.expression,x=this._transitionablePaint._values["raster-particle-max-speed"].value.expression.evaluate({zoom:0});this.colorRamp=aO({expression:m,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:x}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=qd.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class m5t extends lo{constructor(m,x){super(m,{},x,null),this.implementation=m,m.slot&&(this.slot=m.slot)}is3D(m){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(m){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(m){this.implementation.onAdd&&this.implementation.onAdd(m,m.painter.context.gl)}onRemove(m){this.implementation.onRemove&&this.implementation.onRemove(m,m.painter.context.gl)}}function q_e(w,m,x){const k=[0,0,1],E=vt([]);return Zt(E,E,x?-js(w)+Math.PI:js(w)),Bt(E,E,-js(m)),it(k,k,E),Ie(k,k)}class iV{constructor(m,x,k,E){this.message=(m?`${m}: `:"")+k,E&&(this.identifier=E),x!=null&&x.__line__&&(this.line=x.__line__)}}function V_e(w,m){const x=w.indexOf("://")===-1;try{return new URL(w,x&&m?"http://example.com":void 0),!0}catch{return!1}}class AFe{constructor(m,x){this.feature=m,this.instancedDataOffset=x,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class MFe{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new ZR,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(m){const x=16*m,k=this.instancedDataArray.float32;let E=Math.floor(k[x+2]);const P=1.05*(k[x+2]-E);return E/=100,[k[x]%1*1.05,k[x+1]%1*1.05,P,E]}tileCoordinatesForInstance(m){const x=16*m,k=this.instancedDataArray.float32;let E=k[x+0];return E=E>$n?E-$n:E,new Ls(Math.trunc(E),Math.trunc(k[x+1]))}translationForInstance(m){const x=16*m,k=this.instancedDataArray.float32;return[k[x+4],k[x+5],k[x+6]]}rotationScaleForInstance(m){const x=16*m,k=this.instancedDataArray.float32;return[k[x+7],k[x+8],k[x+9],k[x+10],k[x+11],k[x+12],k[x+13],k[x+14],k[x+15]]}transformForInstance(m){const x=16*m,k=this.instancedDataArray.float32;return[k[x+7],k[x+8],k[x+9],k[x+4],k[x+10],k[x+11],k[x+12],k[x+5],k[x+13],k[x+14],k[x+15],k[x+6],0,0,0,1]}}class H_e{constructor(m){this.zoom=m.zoom,this.canonical=m.canonical,this.overscaledZ=this.canonical.z+Math.log2(m.overscaling),this.layers=m.layers,this.layerIds=this.layers.map(x=>x.fqid),this.projection=m.projection,this.index=m.index,this.worldview=m.worldview,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.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=m.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(m,x){}updateAppearances(m,x,k,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,E){this.tileToMeter=dn(k);const P=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const O=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?x.elevationFeatures:void 0;for(const{feature:U,id:H,index:X,sourceLayerIndex:oe}of m){const ue=H??(U.properties&&U.properties.hasOwnProperty("id")?U.properties.id:void 0),me=Wa(U,P);if(!this.layers[0]._featureFilter.filter(new La(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),me,k))continue;const _e={id:ue,sourceLayerIndex:oe,index:X,geometry:P?me.geometry:Gr(U,k,E),properties:U.properties,type:U.type,patterns:{}},Se=this.addFeature(_e,_e.geometry,me,O,k);Se&&x.featureIndex.insert(U,_e.geometry,X,oe,this.index,this.instancesPerModel[Se].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const m=this.layers[0].modelManager,x=this.layers[0].scope;let k=0;for(const E of this.modelUris){const P=m.getModel(E,x);if(!P)continue;const O=this.instancesPerModel[E];if(O){const U=.5*Me(P.aabb.max,P.aabb.min)*O.maxScale+O.maxXYTranslationDistance,H=Math.min($n,Math.max(U/this.tileToMeter,256));k=Math.max(H,k)}}return k}update(m,x,k,E){for(const P in this.instancesPerModel){const O=this.instancesPerModel[P];for(const U in m)O.idToFeaturesIndex.hasOwnProperty(U)&&(this.evaluate(O.features[O.idToFeaturesIndex[U]],m[U],O,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let m=!1;for(const x in this.instancesPerModel){const k=this.instancesPerModel[x];for(const E of k.features){const P=this.layers[0],O=E.feature,U=this.canonical,H=P.paint.get("model-rotation").evaluate(O,{},U),X=P.paint.get("model-scale").evaluate(O,{},U),oe=P.paint.get("model-translation").evaluate(O,{},U);Ge(E.rotation,H)&&Ge(E.scale,X)&&Ge(E.translation,oe)||(this.evaluate(E,E.featureStates,k,!0),m=!0)}}return m}updateReplacement(m,x,k,E){if(x.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=x.updateTime;const P=x.getReplacementRegionsForTile(m.toUnwrapped(),!0);if(kq(this.activeReplacements,P))return!1;this.activeReplacements=P;let O=!1;for(const U in this.instancesPerModel){const H=this.instancesPerModel[U],X=H.instancedDataArray;for(const oe of H.features){const ue=oe.instancedDataOffset,me=oe.instancedDataCount;for(let _e=0;_e$n;Pe=$e?Pe-$n:Pe;const Ke=Math.floor(Pe),lt=Math.floor(X.float32[Se+1]);let nt=!1;for(const pt of this.activeReplacements)if(!hRe(pt,k,Sq.Model,E)&&!(pt.min.x>Ke||Ke>pt.max.x||pt.min.y>lt||lt>pt.max.y)&&(nt=gRe(xRe(Ke,lt,m.canonical,pt.footprintTileId.canonical),pt.footprint),nt))break;X.float32[Se]=nt?Pe+$n:Pe,O=O||nt!==$e}}}return O}isEmpty(){for(const m in this.instancesPerModel)if(this.instancesPerModel[m].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(m){if(!this.uploaded)for(const x in this.instancesPerModel){const k=this.instancesPerModel[x];k.instancedDataArray.length<0||k.instancedDataArray.length===0||(k.instancedDataBuffer?k.instancedDataBuffer.updateData(k.instancedDataArray):k.instancedDataBuffer=m.createVertexBuffer(k.instancedDataArray,ICt.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(m){for(const k in this.instancesPerModel){const E=this.instancesPerModel[k];E.instancedDataArray.length!==0&&E.instancedDataBuffer&&E.instancedDataBuffer.destroy()}const x=this.layers[0].modelManager;if(m&&x&&this.modelUris&&this.modelsRequested)for(const k of this.modelUris)x.removeModel(k,"",!0)}addFeature(m,x,k,E,P){const O=this.layers[0],U=O.layout.get("model-id"),H=O.layout.get("model-allow-density-reduction"),X=U.evaluate(k,{},this.canonical);if(!X)return nr(`modelId is not evaluated for layer ${O.id} and it is not going to get rendered.`),X;(V_e(X,!1)||this.styleDefinedModelURLs[X]!==void 0)&&(this.modelUris.includes(X)||this.modelUris.push(X)),this.instancesPerModel[X]||(this.instancesPerModel[X]=new MFe);const oe=this.instancesPerModel[X],ue=oe.instancedDataArray,me=new AFe(k,ue.length);let _e;E&&(_e=Bo.getElevationFeature(m,E));for(const Se of x)for(const Pe of Se){if(Pe.x<0||Pe.x>=$n||Pe.y<0||Pe.y>=$n)continue;if(this.lookupDim!==0&&H){const Ke=(this.lookupDim-1)/$n,lt=this.lookupDim*(Pe.y*Ke|0)+Pe.x*Ke|0;if(this.lookup){if(this.lookup[lt]!==0)continue;this.lookup[lt]=1}}this.instanceCount++;const $e=ue.length;if(ue.resize($e+1),E){oe.instancesRoadElevation||(oe.instancesRoadElevation=[]);const Ke=_e?_e.pointElevation(new Ls(Pe.x,Pe.y)):0;oe.instancesRoadElevation.push(Ke)}oe.instancesEvaluatedElevation.push(0),ue.float32[16*$e]=Pe.x,ue.float32[16*$e+1]=Pe.y}return me.instancedDataCount=oe.instancedDataArray.length-me.instancedDataOffset,me.instancedDataCount>0&&(m.id&&(oe.idToFeaturesIndex[m.id]=oe.features.length),oe.features.push(me),this.evaluate(me,{},oe,!1)),X}getModelUris(){return this.modelUris}evaluate(m,x,k,E){const P=this.layers[0],O=m.feature,U=this.canonical,H=m.rotation=P.paint.get("model-rotation").evaluate(O,x,U),X=m.scale=P.paint.get("model-scale").evaluate(O,x,U),oe=m.translation=P.paint.get("model-translation").evaluate(O,x,U),ue=Object.assign({},P.paint.get("model-color").evaluate(O,x,U));ue.a=P.paint.get("model-color-mix-intensity").evaluate(O,x,U);const me=[];this.maxVerticalOffset0?Math.sqrt(_e):0;k.maxScale=Math.max(Math.max(k.maxScale,X[0]),Math.max(X[1],X[2])),k.maxXYTranslationDistance=Math.max(k.maxXYTranslationDistance,Se),this.maxScale=Math.max(Math.max(this.maxScale,X[0]),Math.max(X[1],X[2])),tOe(me,H,X);const Pe=Math.round(100*ue.a)+ue.b/1.05;for(let $e=0;$e10?this.tileToMeter:dn(U,_t)),nt[lt+4]=oe[0],nt[lt+5]=oe[1],nt[lt+6]=oe[2]+(k.instancesRoadElevation?k.instancesRoadElevation[Ke]:0)+pt,nt[lt+7]=me[0],nt[lt+8]=me[1],nt[lt+9]=me[2],nt[lt+10]=me[4],nt[lt+11]=me[5],nt[lt+12]=me[6],nt[lt+13]=me[8],nt[lt+14]=me[9],nt[lt+15]=me[10],k.instancesEvaluatedElevation[Ke]=oe[2]}}}Kn(H_e,"ModelBucket",{omit:["layers"]}),Kn(MFe,"PerModelAttributes"),Kn(AFe,"ModelFeature");class J6{constructor(m,x,k){this._demTile=m,this._dem=this._demTile.dem,this._scale=x,this._offset=k}static create(m,x,k){const E=k||m.findDEMTileFor(x);if(!E||!E.dem)return;const P=E.dem,O=E.tileID,U=1<X.fqid),this.stateDependentLayerIds=this.layers.filter(X=>X.isStateDependent()).map(X=>X.id),this.modelTraits|=H6.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,E&&(this.modelTraits|=H6.HasMapboxMeshFeatures),P&&(this.modelTraits|=H6.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=O,this.worldview=H,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const X of x)this.nodesInfo.push(new DFe(X)),PFe(X,U.featureIndexArray.length,U.grid),U.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,U.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(m,x){for(const k of this.getNodesInfo()){const E=k.node;E.footprint&&x.push({footprint:E.footprint,id:m})}}updateAppearances(m,x,k,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(m){const x=Object.keys(m).length!==0;if(x&&!this.stateDependentLayers.length)return;const k=x?this.stateDependentLayers:this.layers;if(!fi(m,this.states))for(const E of k)this.evaluate(E,m);this.states=structuredClone(m)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(m){if(!this.needsUpload)return;const x=this.getNodesInfo();for(const k of x){const E=k.node;this.uploaded?this.updatePbrBuffer(E):c_e(E,m,!0)}for(const k of x)zq(k.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(m){let x=!1;if(!m.meshes)return x;for(const k of m.meshes)k.pbrBuffer&&(k.pbrBuffer.updateData(k.featureArray),x=!0);return x}needsReEvaluation(m,x,k){const E=m.transform.projectionOptions,P=m.style.getBrightness(),O=this.brightness!==P;if(!this.uploaded||this.dirty||E.name!==this.projection.name||RO(k.paint.get("model-color").value,O)||RO(k.paint.get("model-color-mix-intensity").value,O)||RO(k.paint.get("model-roughness").value,O)||RO(k.paint.get("model-emissive-strength").value,O)||RO(k.paint.get("model-height-based-emissive-strength-multiplier").value,O)){this.projection=E,this.brightness=P;const U=this.getNodesInfo();for(const H of U)H.state=null;return!0}return!1}evaluateTransform(m,x){if(m.transform.zoom===this.zoom)return;this.zoom=m.transform.zoom;const k=this.getNodesInfo(),E=this.id.canonical;for(const P of k){const O=P.feature;P.evaluatedTranslation=x.paint.get("model-translation").evaluate(O,{},E),P.evaluatedScale=x.paint.get("model-scale").evaluate(O,{},E)}}evaluate(m,x){const k=this.getNodesInfo();for(const E of k){if(!E.node.meshes)continue;const P=E.feature,O=x&&x[P.id];if(fi(O,E.state))continue;E.state=structuredClone(O);const U=E.node.meshes&&E.node.meshes[0].featureData,H=E.evaluatedColor[2],X=E.evaluatedRMEA[2],oe=this.id.canonical;if(E.hasTranslucentParts=!1,U){for(let ue=0;ue=jt)continue;const xn=G_e[Xs],Os=Math.abs(xn);Os>Ut&&($t=xn,Ut=Os,Bs=sn,qs=Qs)}if(Ut>.1){const Qs=1-(jt+.5*Math.abs(Bs*qs))/Se;let sn=x._dem.get(zt,Yt)+$t*Qs;const Xs=x._dem.get(zt+Bs,Yt+qs),xn=x._dem.get(zt-Bs,Yt-qs,!0);(sn-Xs)*(sn-xn)>0&&(sn=(Xs+xn)/2),G_e[Wt]=x._dem.set(zt,Yt,sn),r3[Wt]=jt}}}}}U&&(x._demTile.needsDEMTextureUpload=!0,x._dem._timestamp=qd.now())}setFilter(m){this.filter=m?rk(m):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(m=>this.filter.filter(new La(this.id.overscaledZ,{worldview:this.worldview}),m.feature,this.id.canonical)):this.nodesInfo}destroy(){const m=this.getNodesInfo();for(const x of m)zq(x.node),d_e(x.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(m,x){if(x.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=x.updateTime;const k=x.getReplacementRegionsForTile(m.toUnwrapped());for(const E of this.getNodesInfo()){const P=E.node.footprint;E.hiddenByReplacement=!!P&&!k.find(O=>O.footprint===P)}}getHeightAtTileCoord(m,x){const k=[],E=[0,0,0],P=v([]);for(const O of this.getNodesInfo()){const U=O.node.meshes[0],H=U.transformedAabb;if(mH.max[0]||x>H.max[1])continue;if(O.node.hidden===!0)return{height:1/0,maxHeight:O.feature.properties.height,hidden:!1,verticalScale:O.evaluatedScale[2]};j(P,O.node.globalMatrix),E[0]=m,E[1]=x,Ze(E,E,P);const X=(E[0]-U.aabb.min[0])/(U.aabb.max[0]-U.aabb.min[0])*JC|0,oe=Math.min(63,(E[1]-U.aabb.min[1])/(U.aabb.max[1]-U.aabb.min[1])*JC|0)*JC+Math.min(63,X),ue=U.heightmap[oe];if(!(ue<0&&O.node.footprint))return O.hiddenByReplacement?void 0:{height:ue,maxHeight:O.feature.properties.height,hidden:!1,verticalScale:O.evaluatedScale[2]};if(O.node.footprint.grid.query(new Ls(m,x),new Ls(m,x),k),k.length>0)return{height:void 0,maxHeight:O.feature.properties.height,hidden:O.hiddenByReplacement,verticalScale:O.evaluatedScale[2]}}}}function RO(w,m){return w instanceof v0&&!w.isLightConstant&&m}function p5t(w,m,x,k,E,P,O,U){let H=(61440&m|(61440&m)>>4)>>8,X=(3840&m|(3840&m)>>4)>>4,oe=240&m|(240&m)>>4;x[3]>0&&(H=zr(H,255*x[0],x[3]),X=zr(X,255*x[1],x[3]),oe=zr(oe,255*x[2],x[3]));const ue=H<<8|X,me=oe<<8|Math.floor(255*k[3]),_e=function(jt){const Yt=Xe(jt,0,2);return Math.min(Math.round(.5*Yt*255),255)}(k[2])<<8|15*k[0]<<4|15*k[1],Se=Xe(E[0],0,1),Pe=Xe(E[1],0,1),$e=Xe(E[2],0,1),Ke=Xe(E[3],0,1);let lt,nt,pt,_t;if(Se!==Pe&&O!==P&&Pe!==Se){const jt=O-P;nt=1/(jt*(Pe-Se)),pt=-(P+jt*Se)/(jt*(Pe-Se));const Yt=Xe(E[4],-1,1);_t=Math.pow(10,Yt),lt=255*$e<<8|255*Ke}else lt=65535,nt=0,pt=1,_t=1;if(w.emplaceBack(ue,me,_e,lt,nt,pt,_t),U){const jt=U.length;U.clear();for(let Yt=0;Yt>16&65535,oe=P?H>>16&65535:65535&H,ue=(15&oe)<8?15&oe:0,me=w.evaluatedRMEA[ue],_e=w.evaluatedColor[ue],Se=w.emissionHeightBasedParams[ue];let Pe;if(U&&ue===2&&k.lights&&(Pe=new P6,Pe.resize(10*k.lights.length)),p5t(O.featureArray,X,_e,me,Se,O.aabb.min[2],O.aabb.max[2],Pe),Pe&&U){U=!1;const $e=k.meshes[k.lightMeshIndex];$e.featureArray=Pe,$e.featureArray._trim()}}O.featureArray._trim(),E++}}Kn(oV,"Tiled3dModelBucket",{omit:["layers"]}),Kn(DFe,"Tiled3dModelFeature");const x5t=["id","tile","layer","source","sourceLayer","state"];class a3{constructor(m,x,k,E,P){this.type="Feature",this._vectorTileFeature=m,this._z=x,this._x=k,this._y=E,this.properties=m?m.properties:{},this.id=P}clone(){const m=new a3(this._vectorTileFeature,this._z,this._x,this._y,this.id);return this.state&&(m.state=Object.assign({},this.state)),this.layer&&(m.layer=Object.assign({},this.layer)),this.source&&(m.source=this.source),this.sourceLayer&&(m.sourceLayer=this.sourceLayer),m}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(m){this._geometry=m}toJSON(){const m={type:"Feature",state:void 0,geometry:this.geometry,properties:this.properties};for(const x of x5t)this[x]!==void 0&&(m[x]=this[x]);return m}}class i3 extends Rp{constructor(m,x,k,E){super(),this.id=m,this.type="model",this.models=[],this._options=x,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}loadGLTFFromURI(m,x){return QRe(this.map._requestManager.transformRequest(m,u0.Model).url,x)}async loadModel(m,x,k){try{const E=await this.loadGLTFFromURI(x.uri,k);if(k.aborted)return;const P=this._modelsInfo.get(m);if(!P)return;const O=h_e(E),U=P.modelSpec,H=new sOe(m,U.uri,U.position,U.orientation,O);i3.applyModelSpecification(H,U),H.computeBoundsAndApplyParent(),this.models.push(H),P.model=H}catch(E){if(E instanceof Error&&E.name==="AbortError")return;const P=E instanceof Error?E.message:"Unknown error";this.fire(new tp(new Error(`Could not load model ${m} from ${x.uri}: ${P}`)))}}async load(){this._abortController||(this._abortController=new AbortController);const m=this._abortController.signal,x=[];for(const k in this._options.models){const E=this._options.models[k],P=this._modelsInfo.get(k);if(P&&P.model){P.modelSpec=E;const O=P.model;O.position=E.position!=null?new ns(E.position[0],E.position[1]):new ns(0,0),O.orientation=E.orientation!=null?E.orientation:[0,0,0],i3.applyModelSpecification(O,E),O.computeBoundsAndApplyParent(),this.models.push(O)}else P?P.modelSpec=E:(this._modelsInfo.set(k,{modelSpec:E,model:null}),x.push(this.loadModel(k,E,m)))}x.length!==0?(await Promise.allSettled(x),m.aborted||this.fire(new zc("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new zc("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(m,x){x.nodeOverrides&&i3.convertNodeOverrides(m,x.nodeOverrides),x.materialOverrides&&i3.convertMaterialOverrides(m,x.materialOverrides),x.nodeOverrideNames&&(m.nodeOverrideNames=[...x.nodeOverrideNames]),x.materialOverrideNames&&(m.materialOverrideNames=[...x.materialOverrideNames]),x.featureProperties&&(m.featureProperties=x.featureProperties)}static convertNodeOverrides(m,x){if(Array.isArray(x)&&x.every(k=>typeof k=="string")){m.nodeOverrideNames=[];for(const k of x)m.nodeOverrideNames.push(k)}else Object.entries(x).forEach(([k,E])=>{const P={orientation:[0,0,0]};if(E.hasOwnProperty("orientation")){const O=E.orientation;O&&(P.orientation=O)}m.nodeOverrides.set(k,P)})}static convertMaterialOverrides(m,x){if(Array.isArray(x)&&x.every(k=>typeof k=="string")){m.materialOverrideNames=[];for(const k of x)m.materialOverrideNames.push(k)}else Object.entries(x).forEach(([k,E])=>{const P={color:new Gn(1,1,1),colorMix:0,emissionStrength:0,opacity:1},O=E["model-color"];O!==void 0&&(P.color.r=O[0],P.color.g=O[1],P.color.b=O[2]);const U=E["model-color-mix-intensity"];U!==void 0&&(P.colorMix=U);const H=E["model-emissive-strength"];H!==void 0&&(P.emissionStrength=H);const X=E["model-opacity"];X!==void 0&&(P.opacity=X),m.materialOverrides.set(k,P)})}onAdd(m){this.map=m,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const m of this._modelsInfo.values())if(m.model==null)return!1;return!0}getModels(){return this.models}loadTile(m,x){}serialize(){return this._options}setProperty(m,x){return!1}reload(){this.cancelModelRequests();const m=yt(this.id,this.scope);this.map.style.clearSource(m),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(m){this.cancelModelRequests()}setModels(m){this.models=[];const x=new Map;for(const k in m){const E=m[k],P=this._modelsInfo.get(k);P&&P.modelSpec.uri===E.uri&&x.set(k,P)}if(this._modelsInfo.size!==x.size){this.cancelModelRequests();for(const[k,E]of x)E.model||x.delete(k)}this._modelsInfo=x,this._options.models=m,this.load()}}function W_e(w,m,x,k){const E=1<H>=_t.vertexArrayOffset&&H<_t.vertexArrayOffset+_t.vertexCount);if(pt&&pt.flags&Tq)return!1;if(_e){const _t=Pe.centroidVertexArray,jt=H+1;jt<_t.length&&(me[0]=_t.geta_centroid_pos0(jt),me[1]=_t.geta_centroid_pos1(jt))}}if(me[0]===0&&me[1]===1)return!1;P.projection.name==="globe"&&(k=CRe([k],[new Ls(0,0),new Ls($n,$n)],w.tileID.canonical).map(pt=>pt.polygon).flat());const $e=_e?U:null,[Ke,lt]=RRe(P,k,ue,oe,X,O,$e,me,Se,P.center.lat,w.tileID.canonical),nt=w.queryGeometry;return DRe(Ke,lt,nt.isPointQuery()?nt.screenBounds:nt.screenGeometry)}},building:class extends lo{constructor(w,m,x,k){super(w,{layout:cOe||(cOe=new Wo({visibility:new kn(fs.layout_building.visibility),"building-facade":new jn(fs.layout_building["building-facade"]),"building-facade-floors":new jn(fs.layout_building["building-facade-floors"]),"building-facade-unit-width":new jn(fs.layout_building["building-facade-unit-width"]),"building-facade-window":new jn(fs.layout_building["building-facade-window"]),"building-roof-shape":new jn(fs.layout_building["building-roof-shape"]),"building-height":new jn(fs.layout_building["building-height"]),"building-base":new jn(fs.layout_building["building-base"]),"building-flood-light-wall-radius":new jn(fs.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new jn(fs.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new jn(fs.layout_building["building-flip-roof-orientation"])})),paint:dOe||(dOe=new Wo({"building-opacity":new kn(fs.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new kn(fs.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new kn(fs.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new kn(fs.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new kn(fs.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new kn(fs.paint_building["building-vertical-scale"]),"building-cast-shadows":new kn(fs.paint_building["building-cast-shadows"]),"building-color":new jn(fs.paint_building["building-color"]),"building-emissive-strength":new jn(fs.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new kn(fs.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new kn(fs.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new kn(fs.paint_building["building-front-cutoff"]),"building-flood-light-color":new kn(fs.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new kn(fs.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new kn(fs.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"})}))},m,x,k),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(w){return new lOe(w)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(w){return!0}queryRadius(w){return 0}queryIntersectsFeature(w,m,x,k,E,P,O,U,H,X){let oe=this.layout.get("building-height").evaluate(m,x);const ue=this.layout.get("building-base").evaluate(m,x),me=w.tile.getBucket(this).getFootprint(m);if(me){if(me.hiddenFlags!==0)return!1;oe=me.height}const[_e,Se]=RRe(P,k,ue,oe,new Ls(0,0),O,null,[0,0],1,P.center.lat,w.tileID.canonical),Pe=w.queryGeometry;return DRe(_e,Se,Pe.isPointQuery()?Pe.screenBounds:Pe.screenGeometry)}},line:class extends lo{constructor(w,m,x,k){const E=bOe();super(w,E,m,x,k),E.layout&&(this.layout=new Kd(E.layout)),this.gradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1}_handleSpecialPaintPropertyUpdate(w){if(w==="line-gradient"){const m=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=m._styleExpression&&m._styleExpression.expression instanceof Nj,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(w,m){super.recalculate(w,m),this.paint._values["line-floorwidth"]=(()=>{if(wO)return wO;const x=bOe();return wO=new d3t(x.paint.properties["line-width"].specification),wO.useIntegerZoom=!0,wO})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,w)}createBucket(w){return new $q(w)}getProgramIds(){const w=[this.paint.get("line-pattern").constantOr(1)?"linePattern":"line"];return this.paint.get("line-blend-mode")!=="default"&&w.push("lineBlendComposite"),w}getDefaultProgramParams(w,m,x){if(w==="lineBlendComposite")return{};const k=yOe(this);return{config:new Le(this,{zoom:m,lut:x}),defines:k,overrideFog:!1}}queryRadius(w){const m=w,x=_Oe(dk("line-width",this,m),dk("line-gap-width",this,m)),k=dk("line-offset",this,m);return x/2+Math.abs(k)+uq(this.paint.get("line-translate"))}queryIntersectsFeature(w,m,x,k,E,P){if(w.queryGeometry.isAboveHorizon)return!1;const O=vDe(w.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),P.angle,w.pixelToTileUnitsFactor),U=w.pixelToTileUnitsFactor/2*_Oe(this.paint.get("line-width").evaluate(m,x),this.paint.get("line-gap-width").evaluate(m,x)),H=this.paint.get("line-offset").evaluate(m,x);return H&&(k=function(X,oe){const ue=[],me=new Ls(0,0);for(let _e=0;_e=3){for(let Se=0;Se<_e.length;Se++)if(Kp(X,_e[Se]))return!0}if(Uf(X,_e,ue))return!0}return!1}(O,k,U)}isTileClipped(){return this.hasNonElevatedBuckets}isDraped(w){return!this.hasElevatedBuckets||this.layout&&this.layout.get("line-elevation-reference")==="hd-road-markup"}hasElevation(){return this.layout&&this.layout.get("line-elevation-reference")!=="none"}hasOffscreenPass(){return this.paint.get("line-blend-mode")!=="default"&&this.paint.get("line-opacity").constantOr(1)!==0&&this.paint.get("line-width").constantOr(1)!==0&&this.visibility!=="none"}resize(){this._destroyLineBlendFbo()}_clear(){this._destroyLineBlendFbo()}_destroyLineBlendFbo(){this.lineBlendFbo&&(this.lineBlendFbo.destroy(),this.lineBlendFbo=null),this.lineBlendStencil=null,this.lineBlendDrapeFbo&&(this.lineBlendDrapeFbo.destroy(),this.lineBlendDrapeFbo=null),this.lineBlendDrapeStencil=null}},symbol:sV,background:class extends lo{constructor(w,m,x,k){super(w,{layout:fFe||(fFe=new Wo({visibility:new kn(fs.layout_background.visibility)})),paint:xFe||(xFe=new Wo({"background-pitch-alignment":new kn(fs.paint_background["background-pitch-alignment"]),"background-color":new kn(fs.paint_background["background-color"]),"background-pattern":new kn(fs.paint_background["background-pattern"]),"background-opacity":new kn(fs.paint_background["background-opacity"]),"background-emissive-strength":new kn(fs.paint_background["background-emissive-strength"]),"background-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"})}))},m,x,k)}getProgramIds(){return[this.paint.get("background-pattern")?"backgroundPattern":"background"]}getDefaultProgramParams(w,m,x){return{overrideFog:!1}}is3D(w){return this.paint.get("background-pitch-alignment")==="viewport"}},raster:_Fe,"raster-particle":EFe,sky:class extends lo{constructor(w,m,x,k){super(w,{layout:NFe||(NFe=new Wo({visibility:new kn(fs.layout_sky.visibility)})),paint:kFe||(kFe=new Wo({"sky-type":new kn(fs.paint_sky["sky-type"]),"sky-atmosphere-sun":new kn(fs.paint_sky["sky-atmosphere-sun"]),"sky-atmosphere-sun-intensity":new kn(fs.paint_sky["sky-atmosphere-sun-intensity"]),"sky-gradient-center":new kn(fs.paint_sky["sky-gradient-center"]),"sky-gradient-radius":new kn(fs.paint_sky["sky-gradient-radius"]),"sky-gradient":new Gp(fs.paint_sky["sky-gradient"]),"sky-atmosphere-halo-color":new kn(fs.paint_sky["sky-atmosphere-halo-color"]),"sky-atmosphere-color":new kn(fs.paint_sky["sky-atmosphere-color"]),"sky-opacity":new kn(fs.paint_sky["sky-opacity"]),"sky-gradient-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"}),"sky-atmosphere-halo-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"}),"sky-atmosphere-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"})}))},m,x,k),this._updateColorRamp()}_clear(){this.skyboxFbo&&(this.skyboxFbo.destroy(),this.skyboxFbo=null),this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null),this._skyboxInvalidated=!0}_handleSpecialPaintPropertyUpdate(w){w==="sky-gradient"?this._updateColorRamp():w!=="sky-atmosphere-sun"&&w!=="sky-atmosphere-halo-color"&&w!=="sky-atmosphere-color"&&w!=="sky-atmosphere-sun-intensity"||(this._skyboxInvalidated=!0)}_updateColorRamp(){this.colorRamp=aO({expression:this._transitionablePaint._values["sky-gradient"].value.expression,evaluationKey:"skyRadialProgress"}),this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null)}needsSkyboxCapture(w){if(this._skyboxInvalidated||!this.skyboxTexture||!this.skyboxGeometry)return!0;if(!this.paint.get("sky-atmosphere-sun")){const m=w.style.light.properties.get("position");return this._lightPosition.azimuthal!==m.azimuthal||this._lightPosition.polar!==m.polar}return!1}getCenter(w,m){if(this.paint.get("sky-type")==="atmosphere"){const k=this.paint.get("sky-atmosphere-sun"),E=!k,P=w.style.light,O=P.properties.get("position");return E&&P.properties.get("anchor")==="viewport"&&nr("The sun direction is attached to a light with viewport anchor, lighting may behave unexpectedly."),E?q_e(O.azimuthal,90-O.polar,m):q_e(k[0],90-k[1],m)}const x=this.paint.get("sky-gradient-center");return q_e(x[0],90-x[1],m)}isSky(){return!0}markSkyboxValid(w){this._skyboxInvalidated=!1,this._lightPosition=w.style.light.properties.get("position")}hasOffscreenPass(){return!0}getProgramIds(){const w=this.paint.get("sky-type");return w==="atmosphere"?["skyboxCapture","skybox"]:w==="gradient"?["skyboxGradient"]:null}},slot:class extends lo{constructor(w,m,x,k){super(w,{paint:SFe||(SFe=new Wo({}))},m,null)}},model:class extends lo{constructor(w,m,x,k){super(w,{layout:CFe||(CFe=new Wo({visibility:new kn(fs.layout_model.visibility),"model-id":new jn(fs.layout_model["model-id"]),"model-allow-density-reduction":new kn(fs.layout_model["model-allow-density-reduction"])})),paint:TFe||(TFe=new Wo({"model-opacity":new jn(fs.paint_model["model-opacity"]),"model-rotation":new jn(fs.paint_model["model-rotation"]),"model-scale":new jn(fs.paint_model["model-scale"]),"model-translation":new jn(fs.paint_model["model-translation"]),"model-color":new jn(fs.paint_model["model-color"]),"model-color-mix-intensity":new jn(fs.paint_model["model-color-mix-intensity"]),"model-type":new kn(fs.paint_model["model-type"]),"model-cast-shadows":new kn(fs.paint_model["model-cast-shadows"]),"model-receive-shadows":new kn(fs.paint_model["model-receive-shadows"]),"model-ambient-occlusion-intensity":new kn(fs.paint_model["model-ambient-occlusion-intensity"]),"model-emissive-strength":new jn(fs.paint_model["model-emissive-strength"]),"model-roughness":new jn(fs.paint_model["model-roughness"]),"model-height-based-emissive-strength-multiplier":new jn(fs.paint_model["model-height-based-emissive-strength-multiplier"]),"model-cutoff-fade-range":new kn(fs.paint_model["model-cutoff-fade-range"]),"model-front-cutoff":new kn(fs.paint_model["model-front-cutoff"]),"model-elevation-reference":new kn(fs.paint_model["model-elevation-reference"]),"model-ignore-line-cutout":new kn(fs.paint_model["model-ignore-line-cutout"]),"model-color-use-theme":new jn({type:"string",default:"default","property-type":"data-driven"})}))},m,x,k),this.layer=w,this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(w){return new H_e(w)}getProgramIds(){return["model"]}is3D(w){return!0}hasShadowPass(){return!0}canCastShadows(){return!0}hasLightBeamPass(){return!0}cutoffRange(){return this.paint.get("model-cutoff-fade-range")}queryRadius(w){return w instanceof oV?8191:0}queryRenderedFeatures(w,m,x){const k=m.getSource();if(!(k&&k instanceof i3))return{};const E=k,P={};P[this.id]=[];const O=P[this.id];let U=0;for(const H of E.models){const X=m.getFeatureState(this.sourceLayer,H.id),oe={type:"Unknown",id:H.id,properties:H.featureProperties},ue=this.paint.get("model-rotation").evaluate(oe,X),me=this.paint.get("model-scale").evaluate(oe,X),_e=this.paint.get("model-translation").evaluate(oe,X),Se=this.paint.get("model-elevation-reference");let Pe=[];Fq(Pe,H,x,H.position,ue,me,_e,Se==="ground",Se==="ground",!1),x.projection.name==="globe"&&(Pe=Oq(Pe,x));const $e=b([],x.projMatrix,Pe),Ke=l_e(w.isPointQuery()?w.screenBounds:w.screenGeometry,x,$e,H.aabb);if(Ke!=null){const lt=new a3(void 0,0,0,0,H.id);lt.layer=this.layer,lt.properties=structuredClone(H.featureProperties),lt.properties.layer=this.id,lt.properties.uri=H.uri,lt.properties.orientation=H.orientation,lt.sourceLayer=this.sourceLayer,lt.geometry={type:"Point",coordinates:[H.position.lng,H.position.lat]},lt.state=X,lt.source=this.source,O.push({featureIndex:U,feature:lt,intersectionZ:Ke})}++U}return P}queryIntersectsFeature(w,m,x,k,E,P,O,U,H,X){if(!this.modelManager)return!1;const oe=this.modelManager,ue=w.tile.getBucket(this);if(!(ue&&ue instanceof H_e))return!1;for(const me in ue.instancesPerModel){const _e=ue.instancesPerModel[me],Se=m.id!==void 0?m.id:m.properties&&m.properties.hasOwnProperty("id")?m.properties.id:void 0;if(_e.idToFeaturesIndex.hasOwnProperty(Se)){const Pe=_e.features[_e.idToFeaturesIndex[Se]],$e=oe.getModel(me,X||this.scope);if(!$e)return!1;let Ke=[];const lt=new ns(0,0),nt=ue.canonical;let pt=Number.MAX_VALUE;for(let _t=0;_t{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 RFe{constructor(m){this._stringToNumber={},this._numberToString=[];for(let x=0;x=0&&me[3]>=0&&X.insert(H,me[0],me[1],me[2],me[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new Vi(new Uq(this.rawTileData)).layers,this.sourceLayerCoder=new RFe(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const m in this.vtLayers)this.vtFeatures[m]=[]}return this.vtLayers}query(m,x){const{tilespaceGeometry:k,transform:E,tileTransform:P,pixelPosMatrix:O,availableImages:U,worldview:H}=x;this.loadVTLayers(),this.serializedLayersCache.clear();const X=x.queryRadius?x.queryRadius:0,oe=k.bufferedTilespaceBounds,ue=this.grid.query(oe.min.x,oe.min.y,oe.max.x,oe.max.y,(Pe,$e,Ke,lt)=>g_(k.bufferedTilespaceGeometry,Pe-X,$e-X,Ke+X,lt+X));ue.sort(b5t);let me=null;E.elevation&&ue.length>0&&(me=J6.create(E.elevation,this.tileID));const _e={};let Se;for(let Pe=0;Pe(lt||(lt=Gr(nt,this.tileID.canonical,P)),pt.queryIntersectsFeature(k,nt,_t,lt,this.z,E,O,me,jt,x.scope)))}return _e}loadMatchingFeature(m,x,k,E,P,O){const{featureIndex:U,bucketIndex:H,sourceLayerIndex:X,layoutVertexArrayOffset:oe}=x,ue=this.bucketLayerIDs[H],me=k.layers,_e=Object.keys(me);if(_e.length&&!jr(_e,ue))return;const Se=k.sourceCache,Pe=this.sourceLayerCoder.decode(X),$e=this.vtLayers[Pe].feature(U),Ke=this.getId($e,Pe);for(let lt=0;lt`${U.key}: ${U.message}`).join(", ");return void nr(`Failed to create expression for promoteId: ${O}`)}this.promoteIdExpression=P.value}k=this.promoteIdExpression.evaluate({zoom:0},m)}else k=m.properties[E];typeof k=="boolean"&&(k=Number(k))}return k}}function FFe(w,m,x,k,E){return ln(w,(P,O)=>{const U=m instanceof Kd?m.get(O):null;return U&&U.evaluate?U.evaluate(x,k,void 0,E):U})}function b5t(w,m){return m-w}function zFe(w,m){const x={};if(!m)return x;for(const k of w){const E=k.layerIds.map(P=>m.getLayer(P)).filter(Boolean);if(E.length!==0){k.layers=E,k.stateDependentLayerIds&&(k.stateDependentLayers=k.stateDependentLayerIds.map(P=>E.filter(O=>O.id===P)[0]));for(const P of E)x[P.fqid]=k}}return x}Kn(OFe,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const Xy=32,N_=33,gk=new Uint16Array(8184);for(let w=0;w<2046;w++){let m=w+2,x=0,k=0,E=0,P=0,O=0,U=0;for(1&m?E=P=O=Xy:x=k=U=Xy;(m>>=1)>1;){const X=x+E>>1,oe=k+P>>1;1&m?(E=x,P=k,x=O,k=U):(x=E,k=P,E=O,P=U),O=X,U=oe}const H=4*w;gk[H+0]=x,gk[H+1]=k,gk[H+2]=E,gk[H+3]=P}const k_=new Uint16Array(2178),yk=new Uint8Array(1089),lV=new Uint16Array(1089);function BFe(w){return w===0?-.03125:w===32?.03125:0}const $Fe={Other:0,Symbol:1,FillExtrusion:2},UFe={type:2,extent:$n,loadGeometry:()=>[[new Ls(0,0),new Ls(8193,0),new Ls(8193,8193),new Ls(0,8193),new Ls(0,0)]]};class _5t{constructor(){this.tasks={},this.taskQueue=[],ks(["process"],this),this.invoker=new v5t(this.process),this.nextId=0}add(m,x){const k=this.nextId++,E=function({type:P,renderSourceType:O,zoom:U}){U=U||0;const H=O===$Fe.Symbol;return P==="message"?0:P!=="maybePrepare"||H?P!=="parseTile"||H?P==="parseTile"&&H?300-U:P==="maybePrepare"&&H?400-U:500:200-U:100-U}(x);if(E===0){try{m()}finally{}return null}return this.tasks[k]={fn:m,metadata:x,priority:E,id:k},this.taskQueue.push(k),this.invoker.trigger(),{cancel:()=>{delete this.tasks[k]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(k=>!!this.tasks[k]),!this.taskQueue.length)return;const m=this.pick();if(m===null)return;const x=this.tasks[m];if(delete this.tasks[m],this.taskQueue.length&&this.invoker.trigger(),!x)return;x.fn()}finally{}}pick(){let m=null,x=1/0;for(let E=0;E>16&255)/255,(w>>8&255)/255,(255&w)/255,1)}function P5t(w,m,x){w===1?(m.rgb_color=uV(x.readVarint()),m.paint="rgb_color"):w===2?(m.linear_gradient_idx=x.readVarint(),m.paint="linear_gradient_idx"):w===3?(m.radial_gradient_idx=x.readVarint(),m.paint="radial_gradient_idx"):w===5?x.readPackedFloat(m.dasharray):w===6?m.dashoffset=x.readFloat():w===7?m.miterlimit=x.readFloat():w===8?m.opacity=x.readVarint():w===9?m.width=x.readFloat():w===10?m.linecap=x.readVarint():w===11&&(m.linejoin=x.readVarint())}function L5t(w,m,x){w===1?m.transform=dV(x,x.readVarint()+x.pos):w===2?m.spread_method=x.readVarint():w===3?m.stops.push(HFe(x,x.readVarint()+x.pos)):w===4?m.x1=x.readFloat():w===5?m.y1=x.readFloat():w===6?m.x2=x.readFloat():w===7&&(m.y2=x.readFloat())}function HFe(w,m){return w.readFields(D5t,{offset:0,opacity:255,rgb_color:K_e},m)}function D5t(w,m,x){w===1?m.offset=x.readFloat():w===2?m.opacity=x.readVarint():w===3&&(m.rgb_color=uV(x.readVarint()))}function R5t(w,m,x){w===1?m.transform=dV(x,x.readVarint()+x.pos):w===2?m.spread_method=x.readVarint():w===3?m.stops.push(HFe(x,x.readVarint()+x.pos)):w===4?m.cx=x.readFloat():w===5?m.cy=x.readFloat():w===6?m.r=x.readFloat():w===7?m.fx=x.readFloat():w===8?m.fy=x.readFloat():w===9&&(m.fr=x.readFloat())}function O5t(w,m,x){w===1?m.transform=dV(x,x.readVarint()+x.pos):w===2?m.clip_path_idx=x.readVarint():w===3&&m.children.push(cV(x,x.readVarint()+x.pos))}function F5t(w,m,x){w===1?m.left=m.top=x.readFloat():w===2?m.width=m.height=x.readFloat():w===3?m.top=x.readFloat():w===4?m.height=x.readFloat():w===5?m.mask_type=x.readVarint():w===6?m.mask_idx=x.readVarint():w===7&&m.children.push(cV(x,x.readVarint()+x.pos))}class z5t{static calculate(m={},x=[]){const k=new Map,E=new Map;if(Object.keys(m).length===0)return k;x.forEach(P=>{E.set(P.name,P.rgb_color||new Gn(0,0,0))});for(const[P,O]of Object.entries(m))E.has(P)?k.set(E.get(P).toString(),O):console.warn(`Ignoring unknown image variable "${P}"`);return k}}function eI(w,m=255,x){const k=m/255,E=w.toString(),P=x.has(E)?x.get(E).clone():w.clone();return P.a*=k,P.toString()}function OO(w,m){if(!Gu()){const x=document.createElement("canvas");return x.width=w,x.height=m,x}return new OffscreenCanvas(w,m)}let Y_e,FO=null;function Z_e(w,m,x,k,E){for(const P of k.children)GFe(w,m,x,P,E)}function GFe(w,m,x,k,E){k.group?(w.save(),function(P,O,U,H,X){const oe=H.mask_idx!=null?U.masks[H.mask_idx]:null,ue=H.clip_path_idx!=null?U.clip_paths[H.clip_path_idx]:null;if(H.transform&&(O=tI(H.transform).preMultiplySelf(O)),!function(Se,Pe,$e){return Se.opacity!==255||Pe||$e}(H,ue!=null,oe!=null))return void Z_e(P,O,U,H,X);const me=OO(P.canvas.width,P.canvas.height),_e=me.getContext("2d");Z_e(_e,O,U,H,X),ue&&JFe(_e,O,U,ue),oe&&e7e(_e,O,U,oe,X),P.globalAlpha=H.opacity/255,P.drawImage(me,0,0)}(w,m,x,k.group,E),w.restore()):k.path&&(w.save(),function(P,O,U,H,X){P.setTransform(O),H.paint_order===1?(WFe(P,U,H,X),YFe(P,U,H,X)):(YFe(P,U,H,X),WFe(P,U,H,X))}(w,m,x,k.path,E),w.restore())}function WFe(w,m,x,k){const E=x.fill;if(!E)return;const P=E.opacity/255;switch(w.save(),w.beginPath(),t7e(x,w),E.paint){case"rgb_color":w.fillStyle=eI(E.rgb_color,E.opacity,k);break;case"linear_gradient_idx":{const O=m.linear_gradients[E.linear_gradient_idx];O.transform&&w.setTransform(tI(O.transform).preMultiplySelf(w.getTransform())),w.fillStyle=ZFe(w,O,P,k);break}case"radial_gradient_idx":{const O=m.radial_gradients[E.radial_gradient_idx];O.transform&&w.setTransform(tI(O.transform).preMultiplySelf(w.getTransform())),w.fillStyle=QFe(w,O,P,k)}}w.fill(KFe(x)),w.restore()}function KFe(w){return w.rule===1?"nonzero":w.rule===2?"evenodd":void 0}function YFe(w,m,x,k){const E=x.stroke;if(!E)return;const P=s7e(x);w.lineWidth=E.width,w.miterLimit=E.miterlimit,w.setLineDash(E.dasharray),w.lineDashOffset=E.dashoffset;const O=E.opacity/255;switch(E.paint){case"rgb_color":w.strokeStyle=eI(E.rgb_color,E.opacity,k);break;case"linear_gradient_idx":w.strokeStyle=ZFe(w,m.linear_gradients[E.linear_gradient_idx],O,k,!0);break;case"radial_gradient_idx":w.strokeStyle=QFe(w,m.radial_gradients[E.radial_gradient_idx],O,k,!0)}switch(E.linejoin){case 2:case 1:w.lineJoin="miter";break;case 3:w.lineJoin="round";break;case 4:w.lineJoin="bevel"}switch(E.linecap){case 1:w.lineCap="butt";break;case 2:w.lineCap="round";break;case 3:w.lineCap="square"}w.stroke(P)}function ZFe(w,m,x,k,E=!1){if(m.stops.length===1){const me=m.stops[0];return eI(me.rgb_color,me.opacity*x,k)}const{x1:P,y1:O,x2:U,y2:H}=m;let X=new DOMPoint(P,O),oe=new DOMPoint(U,H);if(E){const me=tI(m.transform);X=me.transformPoint(X),oe=me.transformPoint(oe)}const ue=w.createLinearGradient(X.x,X.y,oe.x,oe.y);for(const me of m.stops)ue.addColorStop(me.offset,eI(me.rgb_color,me.opacity*x,k));return ue}function QFe(w,m,x,k,E=!1){if(m.stops.length===1){const Ke=m.stops[0];return eI(Ke.rgb_color,Ke.opacity*x,k)}const P=tI(m.transform),{fx:O,fy:U,fr:H,cx:X,cy:oe,r:ue}=m;let me=new DOMPoint(O,U),_e=new DOMPoint(X,oe),Se=H,Pe=ue;if(E){me=P.transformPoint(me),_e=P.transformPoint(_e);const Ke=(P.a+P.d)/2;Se=H*Ke,Pe=m.r*Ke}const $e=w.createRadialGradient(me.x,me.y,Se,_e.x,_e.y,Pe);for(const Ke of m.stops)$e.addColorStop(Ke.offset,eI(Ke.rgb_color,Ke.opacity*x,k));return $e}function XFe(w,m,x,k){const E=k.transform?tI(k.transform).preMultiplySelf(m):m,P=OO(w.canvas.width,w.canvas.height),O=P.getContext("2d");for(const H of k.children)if(H.group)XFe(O,E,x,H.group);else if(H.path){const X=H.path,oe=new Path2D;oe.addPath(s7e(X),E),O.fill(oe,KFe(X))}const U=k.clip_path_idx!=null?x.clip_paths[k.clip_path_idx]:null;U&&JFe(O,E,x,U),w.globalCompositeOperation="source-over",w.drawImage(P,0,0)}function JFe(w,m,x,k){const E=OO(w.canvas.width,w.canvas.height);XFe(E.getContext("2d"),m,x,k),w.globalCompositeOperation="destination-in",w.drawImage(E,0,0)}function e7e(w,m,x,k,E){if(k.children.length===0)return;const P=k.mask_idx!=null?x.masks[k.mask_idx]:null;P&&e7e(w,m,x,P,E);const O=w.canvas.width,U=w.canvas.height,H=OO(O,U),X=H.getContext("2d"),oe=k.width,ue=k.height,me=k.left,_e=k.top,Se=new Path2D,Pe=new Path2D;Pe.rect(me,_e,oe,ue),Se.addPath(Pe,m),X.clip(Se);for(const lt of k.children)GFe(X,m,x,lt,E);const $e=X.getImageData(0,0,O,U),Ke=$e.data;if(k.mask_type===1)for(let lt=0;ltm[O])return null}else{const U=1/k[O];let H=(w[O]-x[O])*U,X=(m[O]-x[O])*U;if(H>X){const oe=H;H=X,X=oe}if(H>E&&(E=H),XP)return null}return E}function a7e(w,m,x,k,E,P,O,U,H,X,oe){const ue=k-w,me=E-m,_e=P-x,Se=O-w,Pe=U-m,$e=H-x,Ke=oe[1]*$e-oe[2]*Pe,lt=oe[2]*Se-oe[0]*$e,nt=oe[0]*Pe-oe[1]*Se,pt=ue*Ke+me*lt+_e*nt;if(Math.abs(pt)<1e-15)return null;const _t=1/pt,jt=X[0]-w,Yt=X[1]-m,zt=X[2]-x,Wt=(jt*Ke+Yt*lt+zt*nt)*_t;if(Wt<0||Wt>1)return null;const $t=Yt*_e-zt*me,Ut=zt*ue-jt*_e,Bs=jt*me-Yt*ue,qs=(oe[0]*$t+oe[1]*Ut+oe[2]*Bs)*_t;return qs<0||Wt+qs>1?null:(Se*$t+Pe*Ut+$e*Bs)*_t}function i7e(w,m,x){return(w-m)/(x-m)}function o7e(w,m,x,k,E,P,O,U,H){const X=1<{const lt=$e?1:0,nt=(_e+1)*Pe-lt,pt=Se*Pe,_t=(Se+1)*Pe-lt;Ke[0]=_e*Pe,Ke[1]=pt,Ke[2]=nt,Ke[3]=_t};let ue=new n7e(H);const me=[];for(let _e=0;_e=1;H/=2){const _e=U[U.length-1];ue=new n7e(H);for(let Se=0;Se0;){const{idx:Se,t:Pe,nodex:$e,nodey:Ke,depth:lt}=_e.pop();if(this.leaves[Se]){o7e($e,Ke,lt,m,x,k,E,ue,me);const pt=1<=Xs[2])return Pe}continue}let nt=0;for(let pt=0;pt=X[oe[zt]]&&(oe.splice(zt,0,pt),Yt=!0);Yt||(oe[nt]=pt),nt++}}for(let pt=0;pt=this.dim+1||x<-1||x>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(x+1)*this.stride+(m+1)}static pack(m,x){const k=[0,0,0,0],E=mV.getUnpackVector(x);let P=Math.floor((m+E[3])/E[2]);return k[2]=P%256,P=Math.floor(P/256),k[1]=P%256,P=Math.floor(P/256),k[0]=P,k}getPixels(){return new VDe({width:this.stride,height:this.stride},this.pixels)}backfillBorder(m,x,k){if(this.dim!==m.dim)throw new Error("dem dimension mismatch");let E=x*this.dim,P=x*this.dim+this.dim,O=k*this.dim,U=k*this.dim+this.dim;switch(x){case-1:E=P-1;break;case 1:P=E+1}switch(k){case-1:O=U-1;break;case 1:U=O+1}const H=-x*this.dim,X=-k*this.dim;for(let oe=O;oe=1;k--){const E=k===1?1:0,P=k===2?1:0;for(let O=0;O>>1^-(1&w[m]);return w}function J5t(w,m){switch(m){case"uint32":return w;case"uint16":for(let x=0;x>4|(61440&k)>>8|(240&E)<<4|61440&E,w[x+1]=15&k|(3840&k)>>4|(15&E)<<8|(3840&E)<<4}return w;case"uint8":for(let x=0;x>6|(192&E)>>4|(192&P)>>2|192&O,w[x+1]=(48&k)>>4|(48&E)>>2|48&P|(48&O)<<2,w[x+2]=(12&k)>>2|12&E|(12&P)<<2|(12&O)<<4,w[x+3]=3&k|(3&E)<<2|(3&P)<<4|(3&O)<<6}return w;default:throw new Error(`Invalid pixel format, "${m}"`)}}Kn(mV,"DEMData"),Kn(l7e,"DemMinMaxQuadTree",{omit:["dem"]});var S0=Uint8Array,zO=Uint16Array,eTt=Int32Array,d7e=new S0([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]),u7e=new S0([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]),tTt=new S0([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),h7e=function(w,m){for(var x=new zO(31),k=0;k<31;++k)x[k]=m+=1<>1|(21845&Td)<<1;f7e[Td]=((65280&(sI=(61680&(sI=(52428&sI)>>2|(13107&sI)<<2))>>4|(3855&sI)<<4))>>8|(255&sI)<<8)>>1}var BO=function(w,m,x){for(var k=w.length,E=0,P=new zO(m);E>H]=X;return O},$O=new S0(288);for(Td=0;Td<144;++Td)$O[Td]=8;for(Td=144;Td<256;++Td)$O[Td]=9;for(Td=256;Td<280;++Td)$O[Td]=7;for(Td=280;Td<288;++Td)$O[Td]=8;var x7e=new S0(32);for(Td=0;Td<32;++Td)x7e[Td]=5;var rTt=BO($O,9),aTt=BO(x7e,5),X_e=function(w){for(var m=w[0],x=1;xm&&(m=w[x]);return m},I1=function(w,m,x){var k=m/8|0;return(w[k]|w[k+1]<<8)>>(7&m)&x},J_e=function(w,m){var x=m/8|0;return(w[x]|w[x+1]<<8|w[x+2]<<16)>>(7&m)},iTt=function(w){return(w+7)/8|0},oTt=["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"],P1=function(w,m,x){var k=new Error(m||oTt[w]);if(k.code=w,Error.captureStackTrace&&Error.captureStackTrace(k,P1),!x)throw k;return k},lTt=new S0(0),cTt=typeof TextDecoder<"u"&&new TextDecoder;try{cTt.decode(lTt,{stream:!0})}catch{}const dTt={gzip_data:"gzip"};class Jy extends Error{constructor(m){super(m),this.name="MRTError"}}const uTt={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},g7e={uint32:1,uint16:2,uint8:4},hTt={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let ewe;class pV{constructor(m=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=m}getLayer(m){const x=this.layers[m];if(!x)throw new Jy(`Layer '${m}' not found`);return x}getHeaderLength(m){const x=new Uint8Array(m),k=new DataView(m);if(x[0]!==13)throw new Jy("File is not a valid MRT.");return k.getUint32(1,!0)}parseHeader(m){const x=new Uint8Array(m),k=this.getHeaderLength(m);if(x.length= ${k} but got buffer of length ${x.length}`);const E=new ewe(x.subarray(0,k)).readFields(q5t,{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 Jy(`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 P of E.layers)this.layers[P.name]=new y7e(P,{cacheSize:this._cacheSize});return this}createDecodingTask(m){const x=[],k=this.getLayer(m.layerName);for(let E of m.blockIndices){const P=k.dataIndex[E],O=P.firstByte-m.firstByte,U=P.lastByte-m.firstByte;if(k._blocksInProgress.has(E))continue;const H={layerName:k.name,firstByte:O,lastByte:U,pixelFormat:k.pixelFormat,blockIndex:E,blockShape:[P.bands.length].concat(k.bandShape),buffer:k.buffer,codec:P.codec.codec,filters:P.filters.map(X=>X.filter)};k._blocksInProgress.add(E),x.push(H)}return new v7e(x,()=>{x.forEach(E=>k._blocksInProgress.delete(E.blockIndex))},(E,P)=>{if(x.forEach(O=>k._blocksInProgress.delete(O.blockIndex)),E)throw E;P.forEach(O=>{this.getLayer(O.layerName).processDecodedData(O)})})}}class y7e{constructor({version:m,name:x,units:k,tileSize:E,pixelFormat:P,buffer:O,dataIndex:U},H){if(this.version=m,this.version!==1)throw new Jy(`Cannot parse raster layer encoded with MRT version ${m}`);this.name=x,this.units=k,this.tileSize=E,this.buffer=O,this.pixelFormat=uTt[P],this.dataIndex=U,this.bandShape=[E+2*O,E+2*O,g7e[this.pixelFormat]],this._decodedBlocks=new hV(H?H.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return g7e[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:m})=>m).flat()}processDecodedData(m){const x=m.blockIndex.toString();this._decodedBlocks.get(x)||this._decodedBlocks.put(x,m.data)}getBlockForBand(m){let x=0;switch(typeof m){case"string":for(const[k,E]of this.dataIndex.entries()){for(const[P,O]of E.bands.entries())if(O===m)return{bandIndex:x+P,blockIndex:k,blockBandIndex:P};x+=E.bands.length}break;case"number":for(const[k,E]of this.dataIndex.entries()){if(m>=x&&mthis.cacheSize)throw new Jy(`Number of blocks to decode (${P.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:x,lastByte:k,blockIndices:E}}hasBand(m){const{blockIndex:x}=this.getBlockForBand(m);return x>=0}hasDataForBand(m){const{blockIndex:x}=this.getBlockForBand(m);return x>=0&&!!this._decodedBlocks.get(x.toString())}getBandView(m){const{blockIndex:x,blockBandIndex:k}=this.getBlockForBand(m);if(x<0)throw new Jy(`Band not found: ${JSON.stringify(m)}`);const E=this._decodedBlocks.get(x.toString());if(!E)throw new Jy(`Data for band ${JSON.stringify(m)} of layer "${this.name}" not decoded.`);const P=this.dataIndex[x],O=this.bandShape.reduce((X,oe)=>X*oe,1),U=k*O,H=E.subarray(U,U+O);return{data:H,bytes:new Uint8Array(H.buffer).subarray(H.byteOffset,H.byteOffset+H.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:P.offset,scale:P.scale}}}pV.setPbf=function(w){ewe=w};class v7e{constructor(m,x,k){this.tasks=m,this._onCancel=x,this._onComplete=k,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(m,x){this._finalized||(this._onComplete(m,x),this._finalized=!0)}}pV.performDecoding=function(w,m){const x=new Uint8Array(w);return Promise.all(m.tasks.map(k=>{const{layerName:E,firstByte:P,lastByte:O,pixelFormat:U,blockShape:H,blockIndex:X,filters:oe,codec:ue}=k,me=x.subarray(P,O+1),_e=new Uint32Array(H[0]*H[1]*H[2]);let Se;if(ue!=="gzip_data")throw new Jy(`Unhandled codec: ${ue}`);return Se=function(Pe,$e){if(!globalThis.DecompressionStream&&$e==="gzip_data")return Promise.resolve((_t=function(zt){zt[0]==31&&zt[1]==139&&zt[2]==8||P1(6,"invalid gzip data");var Wt=zt[3],$t=10;4&Wt&&($t+=2+(zt[10]|zt[11]<<8));for(var Ut=(Wt>>3&1)+(Wt>>4&1);Ut>0;Ut-=!zt[$t++]);return $t+(2&Wt)}(Ke=Pe),_t+8>Ke.length&&P1(6,"invalid gzip data"),function(zt,Wt,$t,Ut){var Bs=zt.length;if(!Bs||Wt.f&&!Wt.l)return $t||new S0(0);var qs=!$t,Qs=qs||Wt.i!=2,sn=Wt.i;qs&&($t=new S0(3*Bs));var Xs=function(Fl){var km=$t.length;if(Fl>km){var _u=new S0(Math.max(2*km,Fl));_u.set($t),$t=_u}},xn=Wt.f||0,Os=Wt.p||0,en=Wt.b||0,on=Wt.l,yn=Wt.d,Tn=Wt.m,or=Wt.n,Fn=8*Bs;do{if(!on){xn=I1(zt,Os,1);var On=I1(zt,Os+1,3);if(Os+=3,!On){var En=zt[(Ji=iTt(Os)+4)-4]|zt[Ji-3]<<8,rr=Ji+En;if(rr>Bs){sn&&P1(0);break}Qs&&Xs(en+En),$t.set(zt.subarray(Ji,rr),en),Wt.b=en+=En,Wt.p=Os=8*rr,Wt.f=xn;continue}if(On==1)on=rTt,yn=aTt,Tn=9,or=5;else if(On==2){var pr=I1(zt,Os,31)+257,Vr=I1(zt,Os+10,15)+4,kr=pr+I1(zt,Os+5,31)+1;Os+=14;for(var Ea=new S0(kr),Ni=new S0(19),Aa=0;Aa>4)<16)Ea[Aa++]=Ji;else{var Ro=0,Il=0;for(Ji==16?(Il=3+I1(zt,Os,3),Os+=2,Ro=Ea[Aa-1]):Ji==17?(Il=3+I1(zt,Os,7),Os+=3):Ji==18&&(Il=11+I1(zt,Os,127),Os+=7);Il--;)Ea[Aa++]=Ro}}var Qd=Ea.subarray(0,pr),Pl=Ea.subarray(pr);Tn=X_e(Qd),or=X_e(Pl),on=BO(Qd,Tn),yn=BO(Pl,or)}else P1(1);if(Os>Fn){sn&&P1(0);break}}Qs&&Xs(en+131072);for(var nc=(1<>4;if((Os+=15&Ro)>Fn){sn&&P1(0);break}if(Ro||P1(2),jh<256)$t[en++]=jh;else{if(jh==256){rc=Os,on=null;break}var Xd=jh-254;jh>264&&(Xd=I1(zt,Os,(1<<(fc=d7e[Aa=jh-257]))-1)+p7e[Aa],Os+=fc);var Ja=yn[J_e(zt,Os)&Uc],up=Ja>>4;if(Ja||P1(3),Os+=15&Ja,Pl=nTt[up],up>3){var fc=u7e[up];Pl+=J_e(zt,Os)&(1<Fn){sn&&P1(0);break}Qs&&Xs(en+131072);var bu=en+Xd;if(enFl.length)&&(_u=Fl.length),new S0(Fl.subarray(0,_u))}($t,0,en):$t.subarray(0,en)}(Ke.subarray(_t,-8),{i:2},new S0(((nt=Ke)[(pt=nt.length)-4]|nt[pt-3]<<8|nt[pt-2]<<16|nt[pt-1]<<24)>>>0),lt)));var Ke,lt,nt,pt,_t;const jt=dTt[$e];if(!jt)throw new Error(`Unhandled codec: ${$e}`);const Yt=new globalThis.DecompressionStream(jt);return new Response(new Blob([Pe]).stream().pipeThrough(Yt)).arrayBuffer().then(zt=>new Uint8Array(zt))}(me,ue).then(Pe=>(function($e,Ke){$e.readFields(Y5t,Ke)}(new ewe(Pe),_e),new hTt[U](_e.buffer))),Se.then(Pe=>{for(let $e=oe.length-1;$e>=0;$e--)switch(oe[$e]){case"delta_filter":Q5t(Pe,H);break;case"zigzag_filter":X5t(Pe);break;case"bitshuffle_filter":J5t(Pe,U);break;default:throw new Jy(`Unhandled filter "${oe[$e]}"`)}return{layerName:E,blockIndex:X,data:Pe}}).catch(Pe=>{throw Pe})}))},Kn(v7e,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),Kn(pV,"MapboxRasterTile"),Kn(y7e,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const b7e=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class twe{static from(m){if(!(m instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[x,k]=new Uint8Array(m,0,2);if(x!==219)throw new Error("Data does not appear to be in a KDBush format.");const E=k>>4;if(E!==1)throw new Error(`Got v${E} data when expected v1.`);const P=b7e[15&k];if(!P)throw new Error("Unrecognized array type.");const[O]=new Uint16Array(m,2,1),[U]=new Uint32Array(m,4,1);return new twe(U,O,P,m)}constructor(m,x=64,k=Float64Array,E){if(isNaN(m)||m<0)throw new Error(`Unpexpected numItems value: ${m}.`);this.numItems=+m,this.nodeSize=Math.min(Math.max(+x,2),65535),this.ArrayType=k,this.IndexArrayType=m<65536?Uint16Array:Uint32Array;const P=b7e.indexOf(this.ArrayType),O=2*m*this.ArrayType.BYTES_PER_ELEMENT,U=m*this.IndexArrayType.BYTES_PER_ELEMENT,H=(8-U%8)%8;if(P<0)throw new Error(`Unexpected typed array class: ${k}.`);E&&E instanceof ArrayBuffer?(this.data=E,this.ids=new this.IndexArrayType(this.data,8,m),this.coords=new this.ArrayType(this.data,8+U+H,2*m),this._pos=2*m,this._finished=!0):(this.data=new ArrayBuffer(8+O+U+H),this.ids=new this.IndexArrayType(this.data,8,m),this.coords=new this.ArrayType(this.data,8+U+H,2*m),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+P]),new Uint16Array(this.data,2,1)[0]=x,new Uint32Array(this.data,4,1)[0]=m)}add(m,x){const k=this._pos>>1;return this.ids[k]=k,this.coords[this._pos++]=m,this.coords[this._pos++]=x,k}finish(){const m=this._pos>>1;if(m!==this.numItems)throw new Error(`Added ${m} items when expected ${this.numItems}.`);return swe(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(m,x,k,E){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:P,coords:O,nodeSize:U}=this,H=[0,P.length-1,0],X=[];for(;H.length;){const oe=H.pop()||0,ue=H.pop()||0,me=H.pop()||0;if(ue-me<=U){for(let $e=me;$e<=ue;$e++){const Ke=O[2*$e],lt=O[2*$e+1];Ke>=m&&Ke<=k&<>=x&<<=E&&X.push(P[$e])}continue}const _e=me+ue>>1,Se=O[2*_e],Pe=O[2*_e+1];Se>=m&&Se<=k&&Pe>=x&&Pe<=E&&X.push(P[_e]),(oe===0?m<=Se:x<=Pe)&&(H.push(me),H.push(_e-1),H.push(1-oe)),(oe===0?k>=Se:E>=Pe)&&(H.push(_e+1),H.push(ue),H.push(1-oe))}return X}within(m,x,k){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:E,coords:P,nodeSize:O}=this,U=[0,E.length-1,0],H=[],X=k*k;for(;U.length;){const oe=U.pop()||0,ue=U.pop()||0,me=U.pop()||0;if(ue-me<=O){for(let $e=me;$e<=ue;$e++)w7e(P[2*$e],P[2*$e+1],m,x)<=X&&H.push(E[$e]);continue}const _e=me+ue>>1,Se=P[2*_e],Pe=P[2*_e+1];w7e(Se,Pe,m,x)<=X&&H.push(E[_e]),(oe===0?m-k<=Se:x-k<=Pe)&&(U.push(me),U.push(_e-1),U.push(1-oe)),(oe===0?m+k>=Se:x+k>=Pe)&&(U.push(_e+1),U.push(ue),U.push(1-oe))}return H}}function swe(w,m,x,k,E,P){if(E-k<=x)return;const O=k+E>>1;_7e(w,m,O,k,E,P),swe(w,m,x,k,O-1,1-P),swe(w,m,x,O+1,E,1-P)}function _7e(w,m,x,k,E,P){for(;E>k;){if(E-k>600){const X=E-k+1,oe=x-k+1,ue=Math.log(X),me=.5*Math.exp(2*ue/3),_e=.5*Math.sqrt(ue*me*(X-me)/X)*(oe-X/2<0?-1:1);_7e(w,m,x,Math.max(k,Math.floor(x-oe*me/X+_e)),Math.min(E,Math.floor(x+(X-oe)*me/X+_e)),P)}const O=m[2*x+P];let U=k,H=E;for(UO(w,m,k,x),m[2*E+P]>O&&UO(w,m,k,E);UO;)H--}m[2*k+P]===O?UO(w,m,k,H):(H++,UO(w,m,H,E)),H<=x&&(k=H+1),x<=H&&(E=H-1)}}function UO(w,m,x,k){nwe(w,x,k),nwe(m,2*x,2*k),nwe(m,2*x+1,2*k+1)}function nwe(w,m,x){const k=w[m];w[m]=w[x],w[x]=k}function w7e(w,m,x,k){const E=w-x,P=m-k;return E*E+P*P}o.$=Uy,o.A=class{constructor(w,m,x){this.target=w,this.parent=m,this.mapId=x,this.callbacks={},this.cancelCallbacks={},ks(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new _5t}send(w,m,x,k,E=!1,P){const O=Math.round(1e18*Math.random()).toString(36).substring(0,10);x&&(x.metadata=P,this.callbacks[O]=x);const U=new Set;return this.target.postMessage({id:O,type:w,hasCallback:!!x,targetMapId:k,mustQueue:E,sourceMapId:this.mapId,data:mc(m,U)},U),{cancel:()=>{x&&delete this.callbacks[O],this.target.postMessage({id:O,type:"",targetMapId:k,sourceMapId:this.mapId})}}}receive(w){const m=w.data;if(!m)return;const x=m.id;if(x&&(!m.targetMapId||this.mapId===m.targetMapId))if(m.type===""){const k=this.cancelCallbacks[x];delete this.cancelCallbacks[x],k&&k.cancel()}else if(m.mustQueue||Hn(self)){const k=this.callbacks[x],E=this.scheduler.add(()=>this.processTask(x,m),k&&k.metadata||{type:"message"});E&&(this.cancelCallbacks[x]=E)}else this.processTask(x,m)}processTask(w,m){if(delete this.cancelCallbacks[w],m.type===""){const x=this.callbacks[w];delete this.callbacks[w],x&&(m.error?x(tc(m.error)):x(null,tc(m.data)))}else{const x=new Set,k=m.hasCallback?(P,O)=>{this.target.postMessage({id:w,type:"",sourceMapId:this.mapId,error:P?mc(P):null,data:mc(O,x)},x)}:()=>{},E=tc(m.data);if(this.parent[m.type])this.parent[m.type](m.sourceMapId,E,k);else if(this.parent.getWorkerSource){const P=m.type.split("."),{source:O,scope:U}=E;this.parent.getWorkerSource(m.sourceMapId,{type:P[0],source:O,scope:U,uid:0})[P[1]](E,k)}else k(new Error(`Could not find function ${m.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},o.B=tp,o.C=zc,o.D=np,o.E=Rp,o.F=yt,o.G=2,o.H=kO,o.I=Lt,o.J=BOe,o.K=dj,o.L=$j,o.M=Oy,o.N=Yb,o.O=lp,o.P=Ls,o.Q=Up,o.R=u0,o.S=YN,o.T=j_,o.U=Hy,o.V=iV,o.W=f_,o.X=wx,o.Y=Pj,o.Z=bm,o._=$y,o.a=function(w){return ga.API_CDN_URL_REGEX.test(w)},o.a$=Uq,o.a0=Bc,o.a1=h0,o.a2=i1,o.a3=Dr,o.a4=Uj,o.a5=class extends iV{},o.a6=ZN,o.a7=KN,o.a8=fs,o.a9=function(w){const m=w.value;return m?i1(m)?V_e(m,!0)?[]:[new iV(w.key,m,`invalid url "${m}"`)]:[new iV(w.key,m,`string expected, "${Oy(m)}" found`)]:[]},o.aA=pOe,o.aB=function(w){let m=1/0,x=1/0,k=-1/0,E=-1/0;for(const P of w)m=Math.min(m,P.x),x=Math.min(x,P.y),k=Math.max(k,P.x),E=Math.max(E,P.y);return{min:new Ls(m,x),max:new Ls(k,E)}},o.aC=Xe,o.aD=b,o.aE=dt,o.aF=Tt,o.aG=Kp,o.aH=an,o.aI=ir,o.aJ=function(w,m){const x={};for(let k=0;k=0?m.slice(x+1):""}catch{return""}},o.aN=class{constructor(w){this.entries={},this.scheduler=w}request(w,m,x,k){const E=this.entries[w]=this.entries[w]||{callbacks:[]};if(E.result){const[P,O]=E.result;return this.scheduler?this.scheduler.add(()=>{k(P,O)},m):k(P,O),()=>{}}return E.callbacks.push(k),E.cancel||(E.cancel=x((P,O)=>{E.result=[P,O];for(const U of E.callbacks)this.scheduler?this.scheduler.add(()=>{U(P,O)},m):U(P,O);setTimeout(()=>delete this.entries[w],3e3)})),()=>{E.result||(E.callbacks=E.callbacks.filter(P=>P!==k),E.callbacks.length||(E.cancel(),delete this.entries[w]))}}},o.aO=function(w,m,x){const k=JSON.stringify(w.request);return w.data&&(this.deduped.entries[k]={result:[null,w.data]}),this.deduped.request(k,{type:"parseTile",renderSourceType:w.renderSourceType,zoom:w.tileZoom},E=>{const P=Py(w.request,(O,U,H)=>{O?Af(O)?E(null,null):E(O):U&&E(null,{rawData:U,vectorTile:x?void 0:new Vi(new Uq(U)),responseHeaders:new Map(H.entries())})});return()=>{P.cancel(),E(null,null)}},m)},o.aP=function(w){return w?{cacheControl:w.get("cache-control"),expires:w.get("expires")}:{cacheControl:void 0,expires:void 0}},o.aQ=function(w){qb++,qb>My&&(w.getActor().send("enforceCacheSizeLimit",Ay),qb=0)},o.aR=dp,o.aS=_Fe,o.aT=EFe,o.aU=ns,o.aV=bFe,o.aW=function(w,m){const x=document.createElement("video");x.muted=!0,x.onloadstart=function(){m(null,x)};for(let k=0;k{}}},o.aX=bO,o.aY=i3,o.aZ=ks,o.a_=pV,o.aa=tk,o.ab=Wo,o.ac=kn,o.ad=class{constructor(w){this.specification=w}possiblyEvaluate(w,m){return sr(w.expression.evaluate(m))}interpolate(w,m,x){return{x:zr(w.x,m.x,x),y:zr(w.y,m.y,x),z:zr(w.z,m.z,x),azimuthal:zr(w.azimuthal,m.azimuthal,x),polar:zr(w.polar,m.polar,x)}}},o.ae=La,o.af=jx,o.ag=mr,o.ah=Ze,o.ai=J,o.aj=ot,o.ak=Kd,o.al=Yj,o.am=zr,o.an=$n,o.ao=Cd,o.ap=js,o.aq=Gn,o.ar=class{constructor(w){this.specification=w}possiblyEvaluate(w,m){return function([x,k]){const E=sr([1,x,k]);return{x:E.x,y:E.y,z:E.z}}(w.expression.evaluate(m))}interpolate(w,m,x){return{x:zr(w.x,m.x,x),y:zr(w.y,m.y,x),z:zr(w.z,m.z,x)}}},o.as=function(w,m,x=0,k=!0){const E=new Ls(x,x),P=w.sub(E),O=m.add(E),U=[P,new Ls(O.x,P.y),O,new Ls(P.x,O.y)];return k&&U.push(P.clone()),U},o.at=function(w,m){const x=[];for(let k=0;kthis.buckets[ue].layers.some(me=>O.has(me.fqid))),H=Object.keys(this.buckets).some(ue=>this.buckets[ue].layers.some(me=>me.hasTransition&&me.hasTransition())),X=this._firstPrepareComplete&&P!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(m));const oe=this._lastUpdatedBrightness!==k;this._lastAvailableImagesCount=P,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||k||this._hasAppearances||U||H||X)&&(!(this._hasAppearances||U||H||X)&&this._lastUpdatedBrightness&&k&&Math.abs(this._lastUpdatedBrightness-k)<.001||(this.updateBuckets(m,oe,void 0,X||U||H,O,E),this._lastUpdatedBrightness=k))}evaluateQueryRenderedFeaturePadding(){let w=0;for(const m in this.buckets){const x=this.buckets[m];x.evaluateQueryRenderedFeaturePadding&&(w=Math.max(w,x.evaluateQueryRenderedFeaturePadding()))}return w}queryRenderedFeatures(w,m,x,k,E,P,O){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const U=this.evaluateQueryRenderedFeaturePadding(),H=function(X,oe){const ue=M([],[.5*X.width,.5*-X.height,1]);return S(ue,ue,[1,-1,0]),b(ue,ue,X.calculateProjMatrix(oe.toUnwrapped())),Float32Array.from(ue)}(E,this.tileID);return this.latestFeatureIndex.query(w,{tilespaceGeometry:m,pixelPosMatrix:H,transform:k,availableImages:x,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:U,scope:O})}querySourceFeatures(w,m){const x=this.latestFeatureIndex;if(!x||!x.rawTileData)return;const k=x.loadVTLayers(),E=m?m.sourceLayer:"",P=k._geojsonTileLayer||k[E];if(!P)return;const O=rk(m&&m.filter),{z:U,x:H,y:X}=this.tileID.canonical,oe={z:U,x:H,y:X};for(let ue=0;uex)k=!1;else if(m)if(this.expirationTimex.appearances&&x.appearances.length>0))return!0;return!1}updateBuckets(w,m,x,k,E,P){if(!this.latestFeatureIndex||!w.style)return;const O=P||w.style.listImages(),U=w.style.getBrightness(),H=E||new Set;for(const X in this.buckets){if(!w.style.hasLayer(X))continue;const oe=this.buckets[X],ue=oe.layers[0],me=ue.sourceLayer||"_geojsonTileLayer",_e=w.style.getLayerSourceCache(ue),Se=oe.layers.some(_t=>H.has(_t.fqid)),Pe=(k||Se)&&oe instanceof M1?w.style.getOwnLayer(X):void 0;let $e=x&&x[me]||{};_e&&!x&&($e=_e._state.getState(me,void 0));const Ke=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},lt=Object.keys($e).length>0&&!m;oe.hasAppearances=oe.layers.some(_t=>_t.appearances&&_t.appearances.length>0);const nt=lt?oe.stateDependentLayers:oe.layers;if(lt&&oe.stateDependentLayers.length!==0||m||Se||k){const _t=this.latestFeatureIndex.loadVTLayers()[me];if(oe.update($e,_t,O,Ke,nt,m,U,this.tileID.canonical),(k||Se)&&!m&&oe instanceof M1&&Pe&&Pe.type==="symbol"){const jt=oe;jt.text&&jt.text.uboBinder&&jt.text.uboBinder.updateDynamicExpressions(Pe,_t,this.tileID.canonical,O,$e,U),jt.icon&&jt.icon.uboBinder&&jt.icon.uboBinder.updateDynamicExpressions(Pe,_t,this.tileID.canonical,O,$e,U)}if(oe instanceof M1){const jt=oe,Yt=w.context;jt.text&&jt.text.uboBinder&&jt.text.uboBinder.upload(Yt),jt.icon&&jt.icon.uboBinder&&jt.icon.uboBinder.upload(Yt)}}if(lt&&oe.stateDependentLayers.length!==0||m||oe.hasAppearances){const _t={zoom:w.transform.zoom,pitch:w.transform.pitch,brightness:w.style.getBrightness()||0,worldview:w.worldview},jt=oe.updateAppearances(this.tileID.canonical,$e,O,_t,w.imageManager,lt&&oe.stateDependentLayers.length!==0);if(jt&&jt.hasUboChanges){const Yt=w.context;oe instanceof M1&&oe.text&&oe.text.uboBinder&&oe.text.uboBinder.upload(Yt),oe instanceof M1&&oe.icon&&oe.icon.uboBinder&&oe.icon.uboBinder.upload(Yt)}}(oe instanceof $q||oe instanceof wq)&&w._terrain&&w._terrain.enabled&&_e&&oe.uploadPending()&&w._terrain._clearRenderCacheForTile(_e.id,this.tileID);const pt=w&&w.style&&w.style.getOwnLayer(X);pt&&(this.queryPadding=Math.max(this.queryPadding,pt.queryRadius(oe)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;Pe--){const $e=4*Pe,Ke=gk[$e+0],lt=gk[$e+1],nt=gk[$e+2],pt=gk[$e+3],_t=Ke+nt>>1,jt=lt+pt>>1,Yt=_t+jt-lt,zt=jt+Ke-_t,Wt=lt*N_+Ke,$t=pt*N_+nt,Ut=jt*N_+_t,Bs=Math.hypot((k_[2*Wt+0]+k_[2*$t+0])/2-k_[2*Ut+0],(k_[2*Wt+1]+k_[2*$t+1])/2-k_[2*Ut+1])>=16;yk[Ut]=yk[Ut]||(Bs?1:0),Pe<1022&&(yk[Ut]=yk[Ut]||yk[(lt+zt>>1)*N_+(Ke+Yt>>1)]||yk[(pt+zt>>1)*N_+(nt+Yt>>1)])}const oe=new ri,ue=new sc;let me=0;function _e(Pe,$e){const Ke=$e*N_+Pe;return lV[Ke]===0&&(oe.emplaceBack(k_[2*Ke+0],k_[2*Ke+1],Pe*$n/Xy,$e*$n/Xy),lV[Ke]=++me),lV[Ke]-1}function Se(Pe,$e,Ke,lt,nt,pt){const _t=Pe+Ke>>1,jt=$e+lt>>1;if(Math.abs(Pe-nt)+Math.abs($e-pt)>1&&yk[jt*N_+_t])Se(nt,pt,Pe,$e,_t,jt),Se(Ke,lt,nt,pt,_t,jt);else{const Yt=_e(Pe,$e),zt=_e(Ke,lt),Wt=_e(nt,pt);ue.emplaceBack(Yt,zt,Wt)}}return Se(0,0,Xy,Xy,Xy,0),Se(Xy,Xy,0,0,0,Xy),{vertices:oe,indices:ue}}(this.tileID.canonical,m);k=P.vertices,E=P.indices}else{k=new ri,E=new sc;for(const{x:O,y:U}of x)k.emplaceBack(O,U,0,0);const P=B6(k.int16.subarray(0,4*k.length),void 0,4);for(let O=0;O0&&(O=j(new Float64Array(16),m.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(w,k,m,E,O,P),this._makeGlobeTileDebugTextBuffer(w,k,m,E,O,P)}_globePoint(w,m,x,k,E,P,O){let U=nO(w,m,x);if(P){const H=1<.5?me=-1:ue<-.5&&(me=1);let _e=(w/$n+x.x)/H+me,Se=(m/$n+x.y)/H;_e=(_e-X)*k._pixelsPerMercatorPixel+X,Se=(Se-oe)*k._pixelsPerMercatorPixel+oe;const Pe=[_e*k.worldSize,Se*k.worldSize,0];Ze(Pe,Pe,P),U=Kj(U,Pe,O)}return Ze(U,U,E)}_makeGlobeTileDebugBorderBuffer(w,m,x,k,E,P){const O=new Ha,U=new Hj,H=new $i,X=(ue,me,_e,Se,Pe)=>{const $e=(_e-ue)/(Pe-1),Ke=(Se-me)/(Pe-1),lt=O.length;for(let nt=0;ntX*ue+me;for(let ue=0;ue1)return!1;const x=m.getSource().maxzoom,k=1<1)return m;const E=k.getSource().maxzoom,P=1<{const U=this.getAtTileOffset(w,E,P,O),H=k.upVector(w.canonical,E.x,E.y);return ge(H,H,U*k.upVectorScale(w.canonical,m,x).metersToTile),H}}getForTilePoints(w,m,x,k){if(this.isUsingMockSource())return!1;const E=J6.create(this,w,k);return!!E&&(m.forEach(P=>{P[2]=this.exaggeration()*E.getElevationAt(P[0],P[1],x)}),!0)}getMinMaxForTile(w){if(this.isUsingMockSource())return null;const m=this.findDEMTileFor(w);if(!m||!m.dem)return null;const x=m.dem.tree,k=m.tileID,E=1<0&&(k+=(w[E]-0)*(w[E]-0)),m[E]<0&&(k+=(0-m[E])*(0-m[E]));return k},o.cL=function(w){return w*w*w*w*w},o.cM=Ps,o.cN=45,o.cO=O6,o.cP=function(w,m,x){const k=Math.sqrt(w*w+m*m+x*x),E=k>0?Math.acos(x/k)*Jn:0;let P=w!==0||m!==0?Math.atan2(-m,-w)*Jn+90:0;return P<0&&(P+=360),[k,P,E]},o.cQ=ne,o.cR=sr,o.cS=dn,o.cT=he,o.cU=so,o.cV=ce,o.cW=function(w){return[Math.pow(w[0],1/2.2),Math.pow(w[1],1/2.2),Math.pow(w[2],1/2.2)]},o.cX=QRe,o.cY=h_e,o.cZ=sOe,o.c_=V_e,o.ca=2,o.cb=7,o.cc=6,o.cd=be,o.ce=Y,o.cf=K,o.cg=0,o.ch=1,o.ci=4,o.cj=5,o.ck=z6,o.cl=$f,o.cm=JRe,o.cn=ZC,o.co=TDe,o.cp=function(w,m,x,k,E,P,O,U,H){if(H.name==="globe")return TDe(w,m,new ZC(x,k,E),!1);const X=n3({z:x,x:k,y:E},H);return new so([(P+X.x/X.scale)*m,m*(X.y/X.scale),O],[(P+X.x2/X.scale)*m,m*(X.y2/X.scale),U])},o.cq=function(w,m,x){return w[0]=Math.min(m[0],x[0]),w[1]=Math.min(m[1],x[1]),w[2]=Math.min(m[2],x[2]),w[3]=Math.min(m[3],x[3]),w},o.cr=function(w,m,x){return w[0]=Math.max(m[0],x[0]),w[1]=Math.max(m[1],x[1]),w[2]=Math.max(m[2],x[2]),w[3]=Math.max(m[3],x[3]),w},o.cs=function(w){const m=Math.round((w+45+360)%360/90)%4;return wr[m]},o.ct=Ys,o.cu=tt,o.cv=6,o.cw=function(w){const m=v(new Float64Array(16));b(m,w.pixelMatrix,w.globeMatrix);const x=[0,Ft,0],k=[0,Qt,0];return Ze(x,x,m),Ze(k,k,m),[x[0]>0&&x[0]<=w.width&&x[1]>0&&x[1]<=w.height&&!Pbe(w,new ns(w.center.lat,90)),k[0]>0&&k[0]<=w.width&&k[1]>0&&k[1]<=w.height&&!Pbe(w,new ns(w.center.lat,-90))]},o.cx=function(w,m){const{scale:x}=w.tileTransform,k=x*$n/(w.tileSize*Math.pow(2,m.zoom-w.tileID.overscaledZ+w.tileID.canonical.z));return function(E,P,O){var U=P[1],H=P[2],X=P[3],oe=O[0],ue=O[1];return E[0]=P[0]*oe,E[1]=U*oe,E[2]=H*ue,E[3]=X*ue,E}(new Float32Array(4),m.inverseAdjustmentMatrix,[k,k])},o.cy=Dq,o.cz=W,o.d=function(w){return ga.API_TILEJSON_REGEX.test(w)},o.d$=_4t,o.d0=Rl,o.d1=class{static calculate(w,m,x){const k=new Set,E=new Map,P=new Set,O=new Set;for(const H of Object.values(w))for(const[X,oe]of Object.entries(H.floors)){P.add(X),oe.isDefault&&O.add(X),oe.conflicts&&E.set(X,oe.conflicts);const ue=X===m,me=oe.connections&&m&&oe.connections.has(m);(ue||me)&&k.add(X)}const U=H=>{const X=E.get(H)||new Set;for(const oe of k)if((E.get(oe)||new Set).has(H)||X.has(oe))return!0;return!1};if(x)for(const H of x)P.has(H)&&(U(H)||k.add(H));for(const H of O)k.has(H)||U(H)||k.add(H);return k}},o.d2=Gq,o.d3=M_e,o.d4=Qa,o.d5=function(){return{API_URL:ga.API_URL,DRACO_URL:ga.DRACO_URL,MESHOPT_URL:ga.MESHOPT_URL,MESHOPT_SIMD_URL:ga.MESHOPT_SIMD_URL,BUILDING_GEN_URL:ga.BUILDING_GEN_URL}},o.d6=S6,o.d7=oj,o.d8=Sd,o.d9=Un,o.dA=mq,o.dB=Ha,o.dC=sc,o.dD=function(w,m){return[Math.pow(w[0],2.2)*m,Math.pow(w[1],2.2)*m,Math.pow(w[2],2.2)*m]},o.dE=h,o.dF=function(w,m){var x=Math.sin(m),k=Math.cos(m);return w[0]=k,w[1]=x,w[2]=0,w[3]=-x,w[4]=k,w[5]=0,w[6]=0,w[7]=0,w[8]=1,w},o.dG=Ne,o.dH=ADe,o.dI=Za,o.dJ=_i,o.dK=U_e,o.dL=function(w,m){const x=[0,0,0];return Ze(x,x,rO(b_(m.canonical))),Ze(x,x,w),x},o.dM=w=>({u_matrix:new y(w),u_texsize:new wg(w),u_pixels_to_tile_units:new $(w),u_device_pixel_ratio:new ud(w),u_width_scale:new ud(w),u_floor_width_scale:new ud(w),u_image:new KC(w),u_units_to_pixels:new wg(w),u_tile_units_to_pixels:new ud(w),u_alpha_discard_threshold:new ud(w),u_trim_offset:new wg(w),u_trim_fade_range:new wg(w),u_trim_gradient_mix_range:new wg(w),u_trim_color:new O6(w),u_zbias_factor:new ud(w),u_tile_to_meter:new ud(w),u_ground_shadow_factor:new YC(w),u_pattern_transition:new ud(w)}),o.dN=w=>({u_matrix:new y(w),u_pixels_to_tile_units:new $(w),u_device_pixel_ratio:new ud(w),u_width_scale:new ud(w),u_floor_width_scale:new ud(w),u_units_to_pixels:new wg(w),u_dash_image:new KC(w),u_gradient_image:new KC(w),u_image_height:new ud(w),u_texsize:new wg(w),u_tile_units_to_pixels:new ud(w),u_alpha_discard_threshold:new ud(w),u_trim_offset:new wg(w),u_trim_fade_range:new wg(w),u_trim_gradient_mix_range:new wg(w),u_trim_color:new O6(w),u_zbias_factor:new ud(w),u_tile_to_meter:new ud(w),u_ground_shadow_factor:new YC(w)}),o.dO=w=>({u_camera_to_center_distance:new ud(w),u_extrude_scale:new $(w),u_device_pixel_ratio:new ud(w),u_matrix:new y(w),u_inv_rot_matrix:new y(w),u_merc_center:new wg(w),u_tile_id:new YC(w),u_zoom_transition:new ud(w),u_up_dir:new YC(w),u_emissive_strength:new ud(w)}),o.dP=HR,o.dQ=b3t,o.dR=class{constructor(w,m,x,k){this.context=w,this.format=k,this.size=x,this.texture=w.gl.createTexture();const[E,P,O]=this.size,{gl:U}=w;U.bindTexture(U.TEXTURE_3D,this.texture),w.pixelStoreUnpackFlipY.set(!1),w.pixelStoreUnpack.set(1),w.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in m&&m.data&&U.texImage3D(U.TEXTURE_3D,0,this.format,E,P,O,0,a_e(this.format),i_e(this.format),m.data)}bind(w,m){const{context:x}=this,{gl:k}=x;k.bindTexture(k.TEXTURE_3D,this.texture),w!==this.minFilter&&(k.texParameteri(k.TEXTURE_3D,k.TEXTURE_MAG_FILTER,w),k.texParameteri(k.TEXTURE_3D,k.TEXTURE_MIN_FILTER,w),this.minFilter=w),m!==this.wrapS&&(k.texParameteri(k.TEXTURE_3D,k.TEXTURE_WRAP_S,m),k.texParameteri(k.TEXTURE_3D,k.TEXTURE_WRAP_T,m),this.wrapS=m)}destroy(){const{gl:w}=this.context;w.deleteTexture(this.texture),this.texture=null}},o.dS=LDe,o.dT=(w,m,x,k,E,P)=>{const O=w.transform,U=O.projection.name==="globe";let H;if(P.paint.get("circle-pitch-alignment")==="map")if(U){const oe=ADe(O.zoom,m.canonical)*O._pixelsPerMercatorPixel;H=Float32Array.from([oe,0,0,oe])}else H=O.calculatePixelsToTileUnitsMatrix(x);else H=new Float32Array([O.pixelsToGLUnits[0],0,0,O.pixelsToGLUnits[1]]);const X={u_camera_to_center_distance:w.transform.getCameraToCenterDistance(O.projection),u_matrix:w.translatePosMatrix(m.projMatrix,x,P.paint.get("circle-translate"),P.paint.get("circle-translate-anchor")),u_device_pixel_ratio:qd.devicePixelRatio,u_extrude_scale:H,u_inv_rot_matrix:C4t,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:P.paint.get("circle-emissive-strength")};if(U){X.u_inv_rot_matrix=k,X.u_merc_center=E,X.u_tile_id=[m.canonical.x,m.canonical.y,1<{const oe=w.transform,ue=oe.pitch<15?fOe(.07,.7,Xe((14-oe.zoom)/5,0,1)):.07,me=x.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:gOe(w,m,x,k),u_texsize:m.imageAtlasTexture?m.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:oe.calculatePixelsToTileUnitsMatrix(m),u_device_pixel_ratio:E,u_width_scale:P,u_floor_width_scale:O,u_image:0,u_tile_units_to_pixels:xOe(m,oe),u_units_to_pixels:[1/oe.pixelsToGLUnits[0],1/oe.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:U,u_trim_fade_range:x.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:x.paint.get("line-trim-color").toPremultipliedRenderColor(me?null:x.lut).toArray01(),u_zbias_factor:ue,u_tile_to_meter:dn(m.tileID.canonical,0),u_ground_shadow_factor:H,u_pattern_transition:X}},o.dX=(w,m,x,k,E,P,O,U,H,X)=>{const oe=w.transform,ue=oe.calculatePixelsToTileUnitsMatrix(m),me=x.paint.get("line-trim-color-use-theme").constantOr("default")==="none",_e=oe.pitch<15?fOe(.07,.7,Xe((14-oe.zoom)/5,0,1)):.07;return{u_matrix:gOe(w,m,x,k),u_pixels_to_tile_units:ue,u_device_pixel_ratio:P,u_width_scale:O,u_floor_width_scale:U,u_units_to_pixels:[1/oe.pixelsToGLUnits[0],1/oe.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:E,u_texsize:vOe(x)&&m.lineAtlasTexture?m.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:xOe(m,w.transform),u_alpha_discard_threshold:0,u_trim_offset:H,u_trim_fade_range:x.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:x.paint.get("line-trim-color").toPremultipliedRenderColor(me?null:x.lut).toArray01(),u_zbias_factor:_e,u_tile_to_meter:dn(m.tileID.canonical,0),u_ground_shadow_factor:X}},o.dY=rs,o.dZ=aO,o.d_=Us,o.da=function(w){const m=w.indexOf(et);return m>=0?w.slice(0,m):w},o.db=function(w){return w.indexOf(et)>=0},o.dc=function(w){const m=w.lastIndexOf(et);return m>=0?w.slice(m+1):""},o.dd=function(w){const m=[],x=w.id;return x===void 0&&m.push({message:`layers.${x}: missing required property "id"`}),w.render===void 0&&m.push({message:`layers.${x}: missing required method "render"`}),w.renderingMode&&w.renderingMode!=="2d"&&w.renderingMode!=="3d"&&m.push({message:`layers.${x}: property "renderingMode" must be either "2d" or "3d"`}),m},o.de=function(w,m,x,k){return w.type==="custom"?new m5t(w,m):new y5t[w.type](w,m,x,k)},o.df=Gs,o.dg=rk,o.dh=ps,o.di=class extends a3{constructor(w,m){super(w._vectorTileFeature,w._z,w._x,w._y,w.id),w.state&&(this.state=Object.assign({},w.state)),this.target=m.target,this.namespace=m.namespace,m.properties&&(this.properties=m.properties),this.target&&("featuresetId"in this.target&&!this.target.importId||"layerId"in this.target)&&(this.source=w.source,this.sourceLayer=w.sourceLayer,this.layer=w.layer)}toJSON(){const w=super.toJSON();return w.target=this.target,w.namespace=this.namespace,w}},o.dj=ek,o.dk=function(w){return w({pluginStatus:Wd,pluginURL:Hp}),ek.on("pluginStateChange",w),w},o.dl=Tbe,o.dm=class extends _g{constructor(w){super(w),this.current=C}set(w,m,x){if(this.fetchUniformLocation(w,m)){for(let k=0;k<9;k++)if(x[k]!==this.current[k]){this.current=x,this.gl.uniformMatrix3fv(this.location,!1,x);break}}}},o.dn=$r,o.dp=function(w,m,x){const k=Yj(x.zoom),E=w.style.map._antialias,P=w.terrain&&w.terrain.exaggeration()>0;return k===0&&!E&&!P},o.dq=function(w){const m=w.pixelsPerMeter,x=m/Ns(1,w.center.lat),k=v(new Float64Array(16));return S(k,k,[w.point.x,w.point.y,0]),A(k,k,[x,x,m]),Float32Array.from(k)},o.dr=pq,o.ds=function(w){const m=80.051129;w=Xe(w,-80.051129,m)/m*90;const x=Math.pow(Math.abs(Math.sin(js(w))),3);return Math.round(x*(es.length-1))},o.dt=function(w,m,x,k){const E=m.getNorth(),P=m.getSouth(),O=m.getWest(),U=m.getEast(),H=1<0){const Se=180/k;f(_e,_e,[Se/X+1,0,0,0,Se/oe+1,0,-.5*Se/ue,.5*Se/me,1])}return _e[2]=H,_e[5]=w.x,_e[8]=w.y,_e},o.du=rO,o.dv=b_,o.dw=function(w,m,x){const k=v(new Float64Array(16)),E=(m/(1<0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(w,m=!1){const x=pRe(new Ls(0,0),new Ls($n,$n),w),k=[];if(m&&!Kbe(x,this._globalClipBounds))return k;for(const E of this._activeRegions){if(E.hiddenByOverlap||!Kbe(x,E))continue;const P=cCt(E.min,E.max,w);k.push({min:P.min,max:P.max,sourceId:this._sourceIds[E.priority],footprint:E.footprint,footprintTileId:E.tileId,order:E.order,clipMask:E.clipMask,clipScope:E.clipScope})}return k}setSources(w){this._setSources(w.map(m=>({getSourceId:()=>m.cache.id,getFootprints:()=>{const x=[];for(const k of m.cache.getVisibleCoordinates()){const E=m.cache.getTile(k).buckets[m.layer];E&&E.updateFootprints(k.toUnwrapped(),x)}return x},getOrder:()=>m.order,getClipMask:()=>m.clipMask,getClipScope:()=>m.clipScope})))}_addSource(w){const m=w.getFootprints();if(m.length===0)return;const x=w.getOrder(),k=w.getClipMask(),E=w.getClipScope();for(const P of m){if(!P.footprint)continue;const O=pRe(P.footprint.min,P.footprint.max,P.id);this._activeRegions.push({min:O.min,max:O.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:P.id,footprint:P.footprint,order:x,clipMask:k,clipScope:E})}this._sourceIds.push(w.getSourceId())}_computeReplacement(){this._activeRegions.sort((m,x)=>m.priority-x.priority||Nq(m.min,x.min)||Nq(m.max,x.max)||m.order-x.order||m.clipMask-x.clipMask||function(k,E){const P=(O,U)=>O+U;return k.length-E.length||k.reduce(P,"").localeCompare(E.reduce(P,""))}(m.clipScope,x.clipScope));let w=this._activeRegions.length!==this._prevRegions.length;if(!w){let m=0;for(;!w&&m!==this._activeRegions.length;){const x=this._activeRegions[m],k=this._prevRegions[m];w=x.priority!==k.priority||!mRe(x,k)||x.order!==k.order||x.clipMask!==k.clipMask||!fi(x.clipScope,k.clipScope),this._activeRegions[m].hiddenByOverlap=k.hiddenByOverlap,++m}}if(w){++this._updateTime;for(const x of this._activeRegions)x.order!==mO&&(this._globalClipBounds.min.x=Math.min(this._globalClipBounds.min.x,x.min.x),this._globalClipBounds.min.y=Math.min(this._globalClipBounds.min.y,x.min.y),this._globalClipBounds.max.x=Math.max(this._globalClipBounds.max.x,x.max.x),this._globalClipBounds.max.y=Math.max(this._globalClipBounds.max.y,x.max.y));const m=x=>{const k=this._activeRegions;if(x>=k.length)return x;const E=k[x].priority;for(;x1){let x=0,k=m(x);for(;x!==k;){let E=x;const P=x;for(;E!==k;){const O=this._activeRegions[E];O.hiddenByOverlap=!1;for(let U=0;U=0;m--)this._addSource(w[m]);this._computeReplacement()}},o.eH=ri,o.eI=nV,o.eJ=Hj,o.eK=mO,o.eL=class{constructor(w){this._createGrid(w),this._createPoles(w)}destroy(){this._poleIndexBuffer.destroy(),this._gridBuffer.destroy(),this._gridIndexBuffer.destroy(),this._poleNorthVertexBuffer.destroy(),this._poleSouthVertexBuffer.destroy();for(const w of this._poleSegments)w.destroy();for(const w of this._gridSegments)w.withSkirts.destroy(),w.withoutSkirts.destroy()}_fillGridMeshWithLods(w,m){const x=new Ha,k=new sc,E=[],P=w+1+2,O=m[0]+1,U=m[0]+1+(1+m.length),H=(X,oe,ue)=>{let me=X===P-1?X-2:X===0?X:X-1;return me+=ue?24575:0,[me,oe]};for(let X=0;X>>=0,w=Math.imul(2747636419^w,2654435769)>>>0,w=Math.imul(w^w>>>16,2654435769)>>>0,(w=Math.imul(w^w>>>16,2654435769)>>>0)/4294967296},o.ec=SDe,o.ed=Mbe,o.ee=vg,o.ef=L,o.eg=function(w,m){return w[0]=m[0],w[1]=m[1],w[2]=m[2],w[3]=m[4],w[4]=m[5],w[5]=m[6],w[6]=m[8],w[7]=m[9],w[8]=m[10],w},o.eh=qj,o.ei=qC,o.ej=function(w,m,x,k,E){return Xe((w-m)/(x-m)*(E-k)+k,k,E)},o.ek=Zt,o.el=function(w,m){var x=m[0],k=m[1],E=m[2],P=m[3],O=m[4],U=m[5],H=m[6],X=m[7],oe=m[8],ue=oe*O-U*X,me=-oe*P+U*H,_e=X*P-O*H,Se=x*ue+k*me+E*_e;return Se?(w[0]=ue*(Se=1/Se),w[1]=(-oe*k+E*X)*Se,w[2]=(U*k-E*O)*Se,w[3]=me*Se,w[4]=(oe*x-E*H)*Se,w[5]=(-U*x+E*P)*Se,w[6]=_e*Se,w[7]=(-X*x+k*H)*Se,w[8]=(O*x-k*P)*Se,w):null},o.em=TC,o.en=2,o.eo=De,o.ep=bt,o.eq=z,o.er=function(w,m){var x=new d(3);z(x,m);var k=1/x[0],E=1/x[1],P=1/x[2],O=m[0]*k,U=m[1]*E,H=m[2]*P,X=m[4]*k,oe=m[5]*E,ue=m[6]*P,me=m[8]*k,_e=m[9]*E,Se=m[10]*P,Pe=O+oe+Se,$e=0;return Pe>0?($e=2*Math.sqrt(Pe+1),w[3]=.25*$e,w[0]=(ue-_e)/$e,w[1]=(me-H)/$e,w[2]=(U-X)/$e):O>oe&&O>Se?($e=2*Math.sqrt(1+O-oe-Se),w[3]=(ue-_e)/$e,w[0]=.25*$e,w[1]=(U+X)/$e,w[2]=(me+H)/$e):oe>Se?($e=2*Math.sqrt(1+oe-O-Se),w[3]=(me-H)/$e,w[0]=(U+X)/$e,w[1]=.25*$e,w[2]=(ue+_e)/$e):($e=2*Math.sqrt(1+Se-O-oe),w[3]=(U-X)/$e,w[0]=(me+H)/$e,w[1]=(ue+_e)/$e,w[2]=.25*$e),w},o.es=function(w,m){var x=2*Math.acos(m[3]),k=Math.sin(x/2);return k>c?(w[0]=m[0]/k,w[1]=m[1]/k,w[2]=m[2]/k):(w[0]=1,w[1]=0,w[2]=0),x},o.et=W_e,o.eu=Fq,o.ev=Oq,o.ew=[1,1,1],o.ex=J6,o.ey=function(w,m,x,k){var E=m[0],P=m[1],O=m[2],U=m[3];return w[0]=E+k*(x[0]-E),w[1]=P+k*(x[1]-P),w[2]=O+k*(x[2]-O),w[3]=U+k*(x[3]-U),w},o.ez=H6,o.f=zo,o.f0=IDe,o.f1=function(w){const m=[0,0,0],x=v(new Float64Array(16));return b(x,w.pixelMatrix,w.globeMatrix),Ze(m,m,x),new Ls(m[0],m[1])},o.f2=k0,o.f3=function(w,m,x=!1){if(Wd===jm.deferred||Wd===jm.loading||Wd===jm.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");Hp=qd.resolveURL(w),Wd=jm.deferred,Bf=m,JN(),x||C6()},o.f4=Yi,o.f5=Ta,o.f6=wn,o.f7=function(w){const m=mx();if(!m)return;const x=m.delete(fm);w&&x.then(()=>w()).catch(w)},o.f8=Kn,o.f9=uk,o.fA=va,o.fB=function(w){let m=0;if(new Uint32Array(w,0,1)[0]!==GRe){const x=new Uint32Array(w,0,7),[,,k,E,P,O]=x;m=x.byteLength+E+P+O+P,(k!==w.byteLength||m>=w.byteLength)&&nr("Invalid b3dm header information.")}return ZRe(w,m)},o.fC=function(w,m){const x=h_e(w);for(const k of x){for(const E of k.meshes)BCt(E);k.lights&&(k.lightMeshIndex=k.meshes.length,k.meshes.push($Ct(k.lights,m)))}return x},o.fD=oV,o.fE=Hn,o.fF=Nm,o.fG=jm,o.fH=function(w){fo(),yh!=null&&yh.then(m=>{m.keys().then(x=>{for(let k=0;knr(E.message))}).catch(x=>nr(x.message))}).catch(m=>nr(m.message))},o.fa=2,o.fb=mg,o.fc=n3,o.fd=QR,o.fe=RFe,o.ff=OFe,o.fg=uOe,o.fh=za,o.fi="hd_road_elevation",o.fj=Bo,o.fk=ln,o.fl=wq,o.fm=Zj,o.fn=E_e,o.fo=1,o.fp=M1,o.fq=function(w,m,x,k,E,P,O,U=1,H,X,oe,ue){w.createArrays(),w.tilePixelRatio=$n/(512*w.overscaling),w.compareText={},w.iconsNeedLinear=!1;const me=w.layers[0].layout,_e=w.layers[0]._unevaluatedLayout._values,Se={};Se.scaleFactor=U,Se.textSizeScaleRange=me.get("text-size-scale-range"),Se.iconSizeScaleRange=me.get("icon-size-scale-range");const[Pe,$e]=Se.textSizeScaleRange,[Ke,lt]=Se.iconSizeScaleRange;Se.textScaleFactor=Xe(Se.scaleFactor,Pe,$e),Se.iconScaleFactor=Xe(Se.scaleFactor,Ke,lt);const nt=_e["text-size"],pt=_e["icon-size"];if(w.textSizeData.kind==="composite"){const{minZoom:$t,maxZoom:Ut}=w.textSizeData;Se.compositeTextSizes=[nt.possiblyEvaluate(new La($t,{worldview:oe}),P),nt.possiblyEvaluate(new La(Ut,{worldview:oe}),P)]}if(w.iconSizeData.kind==="composite"){const{minZoom:$t,maxZoom:Ut}=w.iconSizeData;Se.compositeIconSizes=[pt.possiblyEvaluate(new La($t,{worldview:oe}),P,ue),pt.possiblyEvaluate(new La(Ut,{worldview:oe}),P,ue)]}Se.layoutTextSize=nt.possiblyEvaluate(new La(O+1,{worldview:oe}),P),Se.layoutIconSize=pt.possiblyEvaluate(new La(O+1,{worldview:oe}),P,ue),Se.textMaxSize=nt.possiblyEvaluate(new La(18,{worldview:oe}),P);const _t=me.get("symbol-placement"),jt=me.get("text-rotation-alignment")==="map"&&_t!=="point",Yt=me.get("text-size");let zt=!1;const Wt=[];for(const $t of w.features){const Ut=me.get("text-font").evaluate($t,{},P).join(","),Bs=Yt.evaluate($t,{},P)*Se.textScaleFactor,qs=Se.layoutTextSize.evaluate($t,{},P)*Se.textScaleFactor,Qs=Se.layoutIconSize.evaluate($t,{},P,ue)*Se.iconScaleFactor,sn={horizontal:{},vertical:void 0},Xs=$t.text;let xn,Os=[0,0];if(Xs){const Ka=Xs.toString(),Ol=me.get("text-letter-spacing").evaluate($t,{},P)*Zd,Ji=me.get("text-line-height").evaluate($t,{},P)*Zd,Di=N6(Ka)?Ol:0,Ro=me.get("text-anchor").evaluate($t,{},P),Il=me.get("text-variable-anchor");if(!Il){const rc=me.get("text-radial-offset").evaluate($t,{},P);if(rc)Os=ZOe(Ro,[rc*Zd,P_e]);else{const jh=me.get("text-offset").evaluate($t,{},P);Os=[jh[0]*Zd,jh[1]*Zd]}}let Qd=jt?"center":me.get("text-justify").evaluate($t,{},P);const Pl=_t==="point",nc=Pl?me.get("text-max-width").evaluate($t,{},P)*Zd:1/0,Uc=rc=>{w.allowVerticalPlacement&&Vh(Ka)&&(sn.vertical=w_e(Xs,m,x,E,Ut,nc,Ji,Ro,rc,Di,Os,Mx.vertical,!0,qs,Bs,H,Se.textScaleFactor))};if(!jt&&Il){const rc=Qd==="auto"?Il.map(Xd=>L_e(Xd)):[Qd];let jh=!1;for(let Xd=0;Xd=0||!Vh(Ka)){const rc=w_e(Xs,m,x,E,Ut,nc,Ji,Ro,Qd,Di,Os,Mx.horizontal,!1,qs,Bs,H,Se.textScaleFactor);rc&&(sn.horizontal[Qd]=rc)}Uc(Pl?"left":Qd)}}let en,on,yn,Tn,or,Fn,On=!1;const En=me.get("icon-text-fit").evaluate($t,{},P);if($t.icon&&$t.icon.hasPrimary()){const Ka=TO($t.icon,w.iconSizeData,_e["icon-size"],P,w.zoom,$t,H,Se.iconScaleFactor,oe,ue);en=Ka.iconPrimary,yn=Ka.iconSecondary;const Ol=en.toString();if(on=k.get(Ol),on&&(or=me.get("icon-offset").evaluate($t,{},P),Fn=me.get("icon-anchor").evaluate($t,{},P),xn=Vq(E.get(Ol),yn?E.get(yn.toString()):void 0,or,Fn),On=on.sdf,w.sdfIcons===void 0?w.sdfIcons=on.sdf:w.sdfIcons!==on.sdf&&nr("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(on.pixelRatio!==w.pixelRatio||me.get("icon-rotate").constantOr(1)!==0)&&(w.iconsNeedLinear=!0)),yn){const Ji=yn.toString();Tn=k.get(Ji)}}zt=zt||!(!$t.icon||!$t.icon.hasSecondary());const rr=Qq(sn.horizontal)||sn.vertical;w.iconsInText||(w.iconsInText=!!rr&&rr.iconsInText);const pr=qs*Se.textScaleFactor/Zd,{defaultShapedIcon:Vr,verticallyShapedIcon:kr}=Q3t(w,xn,me,$t,P,sn,pr,or,En);En!=="none"&&xn&&(IOe(xn)||POe(xn))&&(Zq(0,on,en,xn,Vr,En,X,k,E),Zq(0,Tn,yn,xn,Vr,En,X,k,E),kr&&(Zq(0,on,en,xn,kr,En,X,k,E),Zq(0,Tn,yn,xn,kr,En,X,k,E))),xn=Vr;const{iconBBox:Ea,iconVerticalBBox:Ni,textBBox:Aa,textVerticalBBox:Ci}=G3t(w,xn,kr,me,$t,P,Qs,or,Se,E,Fn,sn,qs,Os,ue);Wt.push({feature:$t,shapedTextOrientations:sn,shapedText:rr,shapedIcon:xn,iconPrimary:en,iconSecondary:yn,iconOffset:or,iconAnchor:Fn,verticallyShapedIcon:kr,layoutTextSize:qs,layoutIconSize:Qs,textOffset:Os,isSDFIcon:On,iconTextFit:En,iconCollisionBounds:Ea,iconVerticalCollisionBounds:Ni,textCollisionBounds:Aa,textVerticalCollisionBounds:Ci})}return{featureData:Wt,sizes:Se,hasAnySecondaryIcon:zt,textAlongLine:jt,symbolPlacement:_t}},o.fr=A_e,o.fs=T_e,o.ft=UOe,o.fu=qOe,o.fv=function(w,m,x,k,E,P,O,U,H,X){w.iconAtlasPositions=X.iconPositions;const{featureData:oe,hasAnySecondaryIcon:ue,sizes:me,textAlongLine:_e,symbolPlacement:Se}=m;for(const Pe of oe){const{shapedIcon:$e,verticallyShapedIcon:Ke,feature:lt,shapedTextOrientations:nt,shapedText:pt,layoutTextSize:_t,textOffset:jt,isSDFIcon:Yt,iconPrimary:zt,iconSecondary:Wt,iconTextFit:$t,iconOffset:Ut,iconCollisionBounds:Bs,iconVerticalCollisionBounds:qs,textCollisionBounds:Qs}=Pe;eFe($e,X.iconPositions,zt,Wt),eFe(Ke,X.iconPositions,zt,Wt),Z3t(nt,X.iconPositions),Y3t(zt,Wt,X.iconPositions),(pt||$e)&&X3t(w,lt,nt,$e,Ke,H,me,_t,0,jt,Yt,k,E,O,U,ue,$t,Ut,_e,Se,Bs,qs,Qs)}x&&w.generateCollisionDebugBuffers(P,w.collisionBoxArray,me.textScaleFactor)},o.fw=$q,o.fx=Vi,o.fy=function(w){return w<=1?1:Math.pow(2,Math.floor(Math.log2(w)))},o.fz=mV,o.g=ga,o.h=function(w,m){return Iy(Object.assign(w,{method:"GET"}),m)},o.i=function(w){return ga.API_STYLE_REGEX.test(w)&&!rl(w)},o.j=function(w){return btoa(encodeURIComponent(w).replace(/%([0-9A-F]{2})/g,(m,x)=>String.fromCharCode(+("0x"+x))))},o.k=xm,o.l=function(w){return decodeURIComponent(atob(w).split("").map(m=>"%"+("00"+m.charCodeAt(0).toString(16)).slice(-2)).join(""))},o.m=function(w,m){return Iy(Object.assign(w,{type:"json"}),m)},o.n=fx,o.o=qd,o.p=function(w,m){return Iy(Object.assign(w,{method:"POST"}),m)},o.q=Gh,o.r=xs,o.s=function(w){try{const m=self[w];return m.setItem("_mapbox_test_",1),m.removeItem("_mapbox_test_"),!0}catch{return!1}},o.t=Rt,o.u=function(){return function w(m){return m?(m^Math.random()*(16>>m/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,w)}()},o.v=function(w){return!!w&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(w)},o.w=nr,o.x=class{constructor(w){this.cache=new Map,this.textures=new Map,this.textureAccessTimes=new Map,this.textureMemoryUsed=0,this.maxTextureMemory=1024*(w&&w.maxTextureMemoryMB?w.maxTextureMemoryMB:256)*1024,this.finalizationRegistry=new FinalizationRegistry(m=>{this.cache.delete(m),this.clearExpiredTextures()})}calculateTextureMemory(w){return w.image?Math.ceil(w.image.width*w.image.height*4*(w.patternPositions.size>0?1.33:1)):0}evictTexture(w){const m=this.textures.get(w);if(m){const x=this.calculateTextureMemory(w);m.destroy(),this.textures.delete(w),this.textureAccessTimes.delete(w),this.textureMemoryUsed-=x}}evictTexturesIfNeeded(w){for(;this.textureMemoryUsed+w>this.maxTextureMemory&&this.textures.size>0;){let m=null,x=1/0;for(const[k]of this.textures.entries()){const E=this.textureAccessTimes.get(k)||0;Ethis._layers[Un.id]),xs=qt[0];if(xs.visibility==="none")continue;const rs=xs.source||"";let ks=this.familiesBySource[rs];ks||(ks=this.familiesBySource[rs]=Object.create(null));const ln=xs.sourceLayer||"_geojsonTileLayer";let Gs=ks[ln];Gs||(Gs=ks[ln]=[]),Gs.push(qt)}}}const g=1*c.fa;class _{constructor(Oe){const Xe={},ot=[];for(const xs in Oe){const rs=Oe[xs],ks=Xe[xs]={};for(const ln in rs.glyphs){const Gs=rs.glyphs[+ln];if(!Gs||Gs.bitmap.width===0||Gs.bitmap.height===0)continue;const Un=Gs.metrics.localGlyph?g:1,jr={x:0,y:0,w:Gs.bitmap.width+2*Un,h:Gs.bitmap.height+2*Un};ot.push(jr),ks[ln]=jr}}const{w:Nt,h:Rt}=c.J(ot),qt=new c.f9({width:Nt||1,height:Rt||1});for(const xs in Oe){const rs=Oe[xs];for(const ks in rs.glyphs){const ln=rs.glyphs[+ks];if(!ln||ln.bitmap.width===0||ln.bitmap.height===0)continue;const Gs=Xe[xs][ks],Un=ln.metrics.localGlyph?g:1;c.f9.copy(ln.bitmap,qt,{x:0,y:0},{x:Gs.x+Un,y:Gs.y+Un},ln.bitmap)}}this.image=qt,this.positions=Xe}}function v(ss,Oe,Xe){ss[Oe]?Xe&&(ss[Oe].center=Xe):ss[Oe]={floorIds:new Set,center:Xe||[0,0],floors:{}}}function j(ss,Oe,Xe,ot){for(const Nt of Oe)v(ss,Nt),ss[Nt].floors[Xe]=ot,ss[Nt].floorIds.add(Xe)}function b(ss){return{id:ss.properties.id.toString(),center:[ss.properties.center_lon||0,ss.properties.center_lat||0]}}function S(ss,Oe){const Xe=ss.properties.id.toString(),ot=!!ss.properties.is_default&&ss.properties.is_default,Nt=ss.properties.connected_floor_ids?new Set(ss.properties.connected_floor_ids.toString().split(";")):new Set,Rt=ss.properties.conflicted_floor_ids?new Set(ss.properties.conflicted_floor_ids.toString().split(";")):new Set,qt=ss.properties.structure_ids?new Set(ss.properties.structure_ids.toString().split(";")):new Set,xs=ss.properties.name.toString(),rs=ss.properties.z_index,ks=function(ln,Gs){const Un=ln.loadGeometry();if(!Un||Un.length===0)return;const jr=Un.map(Sr=>Sr.map(nr=>c.fb(nr,Gs,ln.extent)));return jr.length===0?void 0:{type:"Polygon",coordinates:[jr[0]]}}(ss,Oe);return{id:Xe,isDefault:ot,connections:Nt,conflicts:Rt,buildings:qt,name:xs,zIndex:rs,geometry:ks}}function A(ss,Oe){return Oe.every(Xe=>ss.properties&&ss.properties[Xe]!=null)}function T(ss){return A(ss,["type","id","name"])&&ss.properties.type==="structure"}function L(ss){return A(ss,["type","id","name","z_index"])&&ss.properties.type==="floor"}c.f8(_,"GlyphAtlas");class D{constructor(Oe){this.tileID=new c.aR(Oe.tileID.overscaledZ,Oe.tileID.wrap,Oe.tileID.canonical.z,Oe.tileID.canonical.x,Oe.tileID.canonical.y),this.tileZoom=Oe.tileZoom,this.uid=Oe.uid,this.zoom=Oe.zoom,this.lut=Oe.lut,this.canonical=Oe.tileID.canonical,this.pixelRatio=Oe.pixelRatio,this.tileSize=Oe.tileSize,this.source=Oe.source,this.scope=Oe.scope,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=Oe.showCollisionBoxes,this.collectResourceTiming=!!Oe.request&&Oe.request.collectResourceTiming,this.promoteId=Oe.promoteId,this.renderSourceType=Oe.renderSourceType,this.tileTransform=c.fc(Oe.tileID.canonical,Oe.projection),this.projection=Oe.projection,this.worldview=Oe.worldview,this.localizableLayerIds=Oe.localizableLayerIds,this.brightness=Oe.brightness,this.extraShadowCaster=!!Oe.extraShadowCaster,this.tessellationStep=Oe.tessellationStep,this.scaleFactor=Oe.scaleFactor,this.worldview=Oe.worldview,this.indoor=Oe.indoor}parse(Oe,Xe,ot,Nt,Rt,qt){this.status="parsing",this.data=Oe,this.collisionBoxArray=new c.fd;const xs=new c.fe(Object.keys(Oe.layers).sort()),rs=new c.ff(this.tileID,this.promoteId);rs.bucketLayerIDs=[];const ks={},ln=new c.fg(256,256),Gs={featureIndex:rs,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:ln,availableImages:ot,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(Gs.activeFloors=function(nr,Ot,fn,sr){const Hn=Ot.indoorState.activeFloorsVisible;if(!Ot.sourceLayers)return Hn?Ot.indoorState.activeFloors:void 0;const ta=function(Mr,zi){if(!Mr)return c.w("No source layers defined in indoor specification"),zi;if(Mr.size===0)return zi;const Bi=Mr.difference(zi);for(const Za of Bi)c.w(`Missing source layer required in indoor specification: ${Za}`);return zi.intersection(zi)}(Ot.sourceLayers,new Set(Object.keys(nr.layers))),Zr=Ot.indoorState,ur=function(Mr,zi,Bi,Za,_i){const qi={};for(const ga of zi){const wn=Mr.layers[ga];if(wn)for(let Ta=0;Ta=Za.maxzoom||Za.visibility==="none")continue;M(Bi,this.zoom,Gs.brightness,ot,this.worldview,Gs.activeFloors);const _i=ks[Za.id]=Za.createBucket({index:rs.bucketLayerIDs.length,layers:Bi,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:Zr,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:Nt,worldview:this.worldview,localizable:Mr,availableImages:ot,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});rs.bucketLayerIDs.push(Bi.map(ga=>c.F(ga.id,ga.scope)));let qi=_i.prepare?_i.prepare():null;qi!=null?(qi=qi.then(()=>_i.populate(ur,Gs,this.tileID.canonical,this.tileTransform)),Un.push(qi)):_i.populate(ur,Gs,this.tileID.canonical,this.tileTransform)}}const Sr=()=>{ln.trim();const nr=!(!Gs.elevationFeatures||!Gs.elevationFeatures.some(Za=>Za.heightRange.min<0));let Ot,fn,sr,Hn,ta,Zr,ur;const Mr={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},zi=()=>{if(Ot)return this.status="done",qt(Ot);if(this.extraShadowCaster)this.status="done",qt(null,{buckets:Object.values(ks).filter(Za=>!Za.isEmpty()),featureIndex:rs,collisionBoxArray:null,hasTunnelGeometry:nr,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:Gs.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(fn&&sr&&Hn&&ur){const _i=new _(fn),qi=new Map;for(const[Ta,Yi]of sr.entries()){const{imagePosition:zo}=c.fn(Ta,Yi,c.fo);qi.set(Ta,zo)}const ga={};for(const Ta in ks){const Yi=ks[Ta];Yi instanceof c.fp&&(M(Yi.layers,this.zoom,Gs.brightness,ot,this.worldview,Gs.activeFloors),ga[Ta]=c.fq(Yi,fn,_i.positions,sr,qi,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,ta,this.worldview,ot))}const wn={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(Rt,sr,ta,()=>{wn.iconsPending=!1,Bi(ga,_i,wn,void 0,ur)}),this.rasterizeIfNeeded(Rt,Hn,Zr,()=>{wn.patternsPending=!1,Bi(ga,_i,wn,void 0,ur)})}},Bi=(Za,_i,qi,ga,wn)=>{if(qi.iconsPending||qi.patternsPending)return;const Ta=sr.size>0||Hn.size>0,Yi=Object.keys(Za).length>0;if(!Ta&&!Yi)return this.status="done",void qt(null,{buckets:Object.values(ks).filter(rl=>!rl.isEmpty()),featureIndex:rs,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:nr,glyphAtlasImage:_i.image,lineAtlas:ln,imageAtlas:null,brightness:Gs.brightness});const zo=(rl,po)=>{for(const uc in ks){const hc=ks[uc];if(uc in Za)c.fv(hc,Za[uc],this.showCollisionBoxes,ot,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,sr,po);else if(hc.hasPattern&&(hc instanceof c.fw||hc instanceof c.fl||hc instanceof c.e0)){M(hc.layers,this.zoom,Gs.brightness,ot,this.worldview,Gs.activeFloors);const Tf=Object.fromEntries(po.patternPositions);hc.addFeatures(Gs,this.tileID.canonical,Tf,ot,this.tileTransform,this.brightness)}}this.status="done",qt(null,{buckets:Object.values(ks).filter(uc=>!uc.isEmpty()),featureIndex:rs,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:nr,glyphAtlasImage:_i.image,lineAtlas:ln,imageAtlas:rl,brightness:Gs.brightness})};if(Ta){const rl=new Map,po=c.fr(sr,rl),uc=c.fr(Hn,rl),hc=new c.fs(po,uc,wn,this.lut,rl);Rt.send("checkAtlasCache",{descriptor:hc,scope:this.scope},(Tf,Hu)=>{let pm,Gu;if(Tf&&c.w(`[Worker] Error checking atlas cache: ${Tf.message}`),Hu)pm=new c.ft(Hu.sourceHash),Gu=Hu;else{const qd=new c.fu(sr,Hn,this.lut,wn);pm=qd,Gu=qd}zo(pm,Gu)})}else zo(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const Za=c.fk(Gs.glyphDependencies,ga=>Object.keys(ga).map(Number));Object.keys(Za).length?Rt.send("getGlyphs",{uid:this.uid,stacks:Za},(ga,wn)=>{Ot||(Ot=ga,fn=wn,zi())},void 0,!1,Mr):fn={},ur=new Map;const _i=Array.from(Gs.iconDependencies.keys()).map(ga=>c.I.parse(ga));_i.length?Rt.send("getImages",{images:_i,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(ga,wn)=>{if(!Ot){Ot=ga,sr=new Map,ta=this.updateImageMapAndGetImageTaskQueue(sr,wn.images,Gs.iconDependencies);for(const[Ta,Yi]of wn.versions.entries())ur.set(Ta,Yi);zi()}},void 0,!1,Mr):(sr=new Map,ta=new Map);const qi=Array.from(Gs.patternDependencies.keys()).map(ga=>c.I.parse(ga));qi.length?Rt.send("getImages",{images:qi,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(ga,wn)=>{if(!Ot){Ot=ga,Hn=new Map,Zr=this.updateImageMapAndGetImageTaskQueue(Hn,wn.images,Gs.patternDependencies);for(const[Ta,Yi]of wn.versions.entries())ur.set(Ta,Yi);zi()}},void 0,!1,Mr):(Hn=new Map,Zr=new Map)}if(Gs.elevationFeatures&&Gs.elevationFeatures.length>0){const Za=[];for(const qi of Object.values(ks))if(qi instanceof c.fl){const ga=qi.getUnevaluatedPortalGraph();ga&&Za.push(ga)}const _i=c.fm.evaluate(Za);for(const qi of Object.values(ks))if(qi instanceof c.fl){const ga=Oe.layers[xs.decode(qi.sourceLayerIndex)];qi.setEvaluatedPortalGraph(_i,ga,this.tileID.canonical,Gs.availableImages,Gs.brightness)}}zi()};Un.length>0?Promise.allSettled(Un).then(Sr).catch(qt):Sr()}updateParameters(Oe){this.scaleFactor=Oe.scaleFactor,this.showCollisionBoxes=Oe.showCollisionBoxes,this.projection=Oe.projection,this.brightness=Oe.brightness,this.tileTransform=c.fc(Oe.tileID.canonical,Oe.projection),this.extraShadowCaster=Oe.extraShadowCaster,this.lut=Oe.lut,this.worldview=Oe.worldview,this.indoor=Oe.indoor}rasterizeIfNeeded(Oe,Xe,ot,Nt){Array.from(Xe.values()).some(Rt=>Rt.usvg)?this.rasterize(Oe,Xe,ot,Nt):Nt()}updateImageMapAndGetImageTaskQueue(Oe,Xe,ot){const Nt=new Map;for(const Rt of Xe.keys()){const qt=ot.get(Rt)||[];for(const xs of qt){const rs=xs.toString(),ks=Xe.get(xs.id.toString());ks.usvg?Nt.has(rs)||(Nt.set(rs,xs),Oe.set(rs,Object.assign({},ks))):Oe.set(rs,ks)}}return Nt}rasterize(Oe,Xe,ot,Nt){this.rasterizeTask=Oe.send("rasterizeImages",{scope:this.scope,tasks:ot},(Rt,qt)=>{if(!Rt)for(const[xs,rs]of qt.entries()){const ks=Object.assign(Xe.get(xs),{data:rs});Xe.set(xs,ks)}Nt()})}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function M(ss,Oe,Xe,ot,Nt,Rt){const qt=new c.ae(Oe,{brightness:Xe,worldview:Nt,activeFloors:Rt});for(const xs of ss)xs.recalculate(qt,ot)}class F extends c.E{constructor({actor:Oe,layerIndex:Xe,availableImages:ot,availableModels:Nt,isSpriteLoaded:Rt,tileProvider:qt,brightness:xs,maxUniformBufferBindings:rs,maxUniformBlockSizeDwords:ks,disableSymbolUBO:ln}){super(),this.actor=Oe,this.layerIndex=Xe,this.availableImages=ot,this.availableModels=Nt,this.loadVectorData=c.aO,this.tileProvider=qt,this.loading={},this.loaded={},this.deduped=new c.aN(Oe.scheduler),this.isSpriteLoaded=Rt,this.scheduler=Oe.scheduler,this.brightness=xs,this.maxUniformBufferBindings=rs,this.maxUniformBlockSizeDwords=ks,this.disableSymbolUBO=ln}loadTileData(Oe,Xe){if(!this.tileProvider)return this.loadVectorData(Oe,Xe);const ot=new AbortController,{z:Nt,x:Rt,y:qt}=Oe.tileID.canonical;return this.tileProvider.loadTile({z:Nt,x:Rt,y:qt},{request:Oe.request,signal:ot.signal}).then(xs=>{if(ot.signal.aborted)return;if(xs==null){const ks=new Error("Tile not found");return ks.status=404,Xe(ks)}if(xs.data===null)return Xe(null,null);const rs=new Map;xs.expires&&rs.set("expires",xs.expires),xs.cacheControl&&rs.set("cache-control",xs.cacheControl),Xe(null,{rawData:xs.data,responseHeaders:rs})}).catch(xs=>{ot.signal.aborted||Xe(xs instanceof Error?xs:new Error(String(xs)))}),()=>ot.abort()}loadTile(Oe,Xe){const ot=Oe.uid,Nt=Oe&&Oe.request,Rt=Nt&&Nt.collectResourceTiming,qt=this.loading[ot]=new D(Oe);qt.maxUniformBufferBindings=this.maxUniformBufferBindings,qt.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,qt.disableSymbolUBO=this.disableSymbolUBO,qt.abort=this.loadTileData(Oe,(xs,rs)=>{const ks=!this.loading[ot];if(delete this.loading[ot],qt.cancelRasterize(),ks||xs||!rs)return qt.status="done",ks||(this.loaded[ot]=qt),Xe(xs);const ln=rs.rawData,Gs={},Un=c.aP(rs.responseHeaders);Un&&Un.expires&&(Gs.expires=Un.expires),Un&&Un.cacheControl&&(Gs.cacheControl=Un.cacheControl),qt.vectorTile=rs.vectorTile||new c.fx(new c.a$(ln));const jr=()=>{qt.parse(qt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(Sr,nr)=>{if(Sr||!nr)return Xe(Sr);const Ot={};if(Rt){const fn=d(Nt);fn.length>0&&(Ot.resourceTiming=JSON.parse(JSON.stringify(fn)))}Xe(null,Object.assign({rawTileData:ln.slice(0),responseHeaders:rs.responseHeaders},nr,Gs,Ot))})};this.isSpriteLoaded?jr():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(jr,{type:"parseTile",renderSourceType:Oe.renderSourceType,zoom:Oe.tileZoom}):jr()}),this.loaded=this.loaded||{},this.loaded[ot]=qt})}reloadTile(Oe,Xe){const ot=this.loaded,Nt=Oe.uid;if(ot&&ot[Nt]){const Rt=ot[Nt];Rt.updateParameters(Oe);const qt=(xs,rs)=>{const ks=Rt.reloadCallback;ks&&(delete Rt.reloadCallback,Rt.parse(Rt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,ks)),Xe(xs,rs)};Rt.status==="parsing"?Rt.reloadCallback=qt:Rt.status==="done"&&(Rt.vectorTile?Rt.parse(Rt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,qt):qt())}else Xe(null,void 0)}abortTile(Oe,Xe){const ot=Oe.uid,Nt=this.loading[ot];Nt&&(Nt.abort&&Nt.abort(),delete this.loading[ot]),Xe()}removeTile(Oe,Xe){const ot=this.loaded,Nt=Oe.uid;ot&&ot[Nt]&&delete ot[Nt],Xe()}}class z{constructor(Oe){this.loading={}}loadTile(Oe,Xe){const ot=Oe.uid,{cancel:Nt}=c.b1(Oe.request,(Rt,qt,xs)=>{const rs=!this.loading[ot];if(delete this.loading[ot],rs||Rt||!qt)return Xe(Rt);this.decodeTile(ot,qt,Oe.encoding).then(ks=>{const{expires:ln,cacheControl:Gs}=c.aP(xs);Xe(null,Object.assign(ks,{expires:ln,cacheControl:Gs}))}).catch(ks=>Xe(ks))});this.loading[ot]={cancel:Nt}}async decodeTile(Oe,Xe,ot){const Nt=await createImageBitmap(new Blob([new Uint8Array(Xe)],{type:"image/png"})),Rt=1-(Nt.width-c.fy(Nt.width))/2,qt=Rt<1,xs=this.getImageData(Nt,Rt);return Nt.close(),{dem:new c.fz(Oe,xs,ot,qt),borderReady:qt}}reloadTile(Oe,Xe){Xe(null,null)}abortTile(Oe,Xe){const ot=Oe.uid,Nt=this.loading[ot];Nt&&(Nt.cancel(),delete this.loading[ot]),Xe()}removeTile(Oe,Xe){Xe()}getImageData(Oe,Xe){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(Oe.width,Oe.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=Oe.width,this.offscreenCanvas.height=Oe.height,this.offscreenCanvasContext.drawImage(Oe,0,0,Oe.width,Oe.height);const ot=this.offscreenCanvasContext.getImageData(-Xe,-Xe,Oe.width+2*Xe,Oe.height+2*Xe);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),ot}}c.a_.setPbf(c.a$);class V{constructor(Oe){this._mrt=new c.a_(Oe.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=Oe.uid,this.tileID=Oe.tileID,this.source=Oe.source}parse(Oe,Xe){const ot=this._mrt;this.status="parsing",this._entireBuffer=Oe;try{ot.parseHeader(Oe),this._isHeaderLoaded=!0;const Nt=[];for(const Rt in ot.layers){const qt=ot.getLayer(Rt),xs=qt.getDataRange(qt.getBandList()),rs=ot.createDecodingTask(xs),ks=Oe.slice(xs.firstByte,xs.lastByte+1),ln=c.a_.performDecoding(ks,rs).then(Gs=>rs.complete(null,Gs)).catch(Gs=>rs.complete(Gs,null));Nt.push(ln)}Promise.allSettled(Nt).then(()=>Xe(null,ot)).catch(Rt=>Xe(Rt))}catch(Nt){Xe(Nt)}}}class W{constructor({actor:Oe}){this.actor=Oe,this.loading={},this.loaded={}}loadTile(Oe,Xe){const ot=Oe.uid,Nt=Oe.request,Rt=this.loading[ot]=new V(Oe),{cancel:qt}=c.b1(Nt,(xs,rs,ks)=>{const ln=!this.loading[ot];if(delete this.loading[ot],ln||xs||!rs)return Rt.status="done",ln||(this.loaded[ot]=Rt),Xe(xs);Rt.parse(rs,(Gs,Un)=>{if(Gs||!Un)return Xe(Gs);Xe(null,Un,ks)}),this.loaded[ot]=Rt});Rt.abort=qt}reloadTile(Oe,Xe){Xe(null,void 0)}abortTile(Oe,Xe){const ot=Oe.uid,Nt=this.loading[ot];Nt&&(Nt.abort&&Nt.abort(),delete this.loading[ot]),Xe()}removeTile(Oe,Xe){const ot=Oe.uid;this.loaded[ot]&&delete this.loaded[ot],Xe()}decodeRasterArray(Oe,Xe){c.a_.performDecoding(Oe.buffer,Oe.task).then(ot=>Xe(null,ot)).catch(ot=>Xe(ot))}}const Y=c.fA.prototype.toGeoJSON;class K{constructor(Oe){this._feature=Oe,this.extent=c.an,this.type=Oe.type,this.properties=Oe.tags,"id"in Oe&&!isNaN(Oe.id)&&(this.id=parseInt(Oe.id,10))}loadGeometry(){if(this._feature.type===1){const Oe=[];for(const Xe of this._feature.geometry)Oe.push([new c.P(Xe[0],Xe[1])]);return Oe}{const Oe=[];for(const Xe of this._feature.geometry){const ot=[];for(const Nt of Xe)ot.push(new c.P(Nt[0],Nt[1]));Oe.push(ot)}return Oe}}toGeoJSON(Oe,Xe,ot){return Y.call(this,Oe,Xe,ot)}}class J{constructor(Oe,Xe){this.name=Oe,this.extent=c.an,this.length=Xe.length,this._jsonFeatures=Xe}feature(Oe){return new K(this._jsonFeatures[Oe])}}class ne{constructor(Oe){this.layers={},this.extent=c.an;for(const Xe of Object.keys(Oe))this.layers[Xe]=new J(Xe,Oe[Xe])}}const ie=64/4096;class he{constructor(){this.features=new Map}clear(){this.features.clear()}load(Oe=[],Xe){for(const ot of Oe){const Nt=ot.id;if(Nt==null)continue;let Rt=this.features.get(Nt);Rt&&this.updateCache(Rt,Xe),ot.geometry?(Rt=pe(ot),this.updateCache(Rt,Xe),this.features.set(Nt,Rt)):this.features.delete(Nt),this.updateCache(Rt,Xe)}}updateCache(Oe,Xe){for(const{canonical:ot,uid:Nt}of Object.values(Xe)){const{z:Rt,x:qt,y:xs}=ot;ce(Oe,Math.pow(2,Rt),qt,xs)&&delete Xe[Nt]}}getTile(Oe,Xe,ot){const Nt=Math.pow(2,Oe),Rt=[];for(const qt of this.features.values())ce(qt,Nt,Xe,ot)&&Rt.push(Te(qt,Nt,Xe,ot));return{features:Rt}}getFeatures(){return[...this.features.values()]}}function ce({minX:ss,minY:Oe,maxX:Xe,maxY:ot},Nt,Rt,qt){return ss<(Rt+1+ie)/Nt&&Oe<(qt+1+ie)/Nt&&Xe>(Rt-ie)/Nt&&ot>(qt-ie)/Nt}function pe(ss){const{id:Oe,geometry:Xe,properties:ot}=ss;if(!Xe)return;if(Xe.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:Nt,coordinates:Rt}=Xe,qt={id:Oe,type:1,geometry:[],tags:ot,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},xs=qt.geometry;if(Nt==="Point")le(Rt,xs,qt);else if(Nt==="MultiPoint")for(const rs of Rt)le(rs,xs,qt);else if(Nt==="LineString")qt.type=2,ve(Rt,xs,qt);else if(Nt==="MultiLineString")qt.type=2,ge(Rt,xs,qt);else if(Nt==="Polygon")qt.type=3,ge(Rt,xs,qt,!0);else{if(Nt!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");qt.type=3;for(const rs of Rt)ge(rs,xs,qt,!0)}return qt}function le([ss,Oe],Xe,ot){const Nt=c.aH(ss);let Rt=c.aL(Oe);Rt=Rt<0?0:Rt>1?1:Rt,Xe.push(Nt,Rt),ot.minX=Math.min(ot.minX,Nt),ot.minY=Math.min(ot.minY,Rt),ot.maxX=Math.max(ot.maxX,Nt),ot.maxY=Math.max(ot.maxY,Rt)}function ve(ss,Oe,Xe,ot=!1,Nt=!1){const Rt=[];for(const qt of ss)le(qt,Rt,Xe);Oe.push(Rt),ot&&function(qt,xs){let rs=0;for(let ks=0,ln=qt.length,Gs=ln-2;ks0===xs)for(let ks=0,ln=qt.length;ks=qt&&Gs>=qt||(ks>=qt?(ln+=Math.round(Sr*((qt-ks)/jr)),ks=qt):Gs>=qt&&(Un=ln+Math.round(Sr*((qt-ks)/jr)),Gs=qt),ln>=qt&&Un>=qt||(ln>=qt?(ks+=Math.round(jr*((qt-ln)/Sr)),ln=qt):Un>=qt&&(Gs=ks+Math.round(jr*((qt-ln)/Sr)),Un=qt),xs&&ks===xs[xs.length-1][0]&&ln===xs[xs.length-1][1]||(xs=[[ks,ln]],Nt.push(xs)),xs.push([Gs,Un])))))}}function Ce(ss,Oe,Xe,ot,Nt){const Rt=(Xe-ie)/Oe,qt=(ot-ie)/Oe,xs=(Xe+1+ie)/Oe,rs=(ot+1+ie)/Oe;function ks(Un,jr){let Sr=0;return Unxs&&(Sr|=2),jrrs&&(Sr|=8),Sr}let ln=[];for(let Un=1;Un<=8;Un*=2){let jr=ss[ss.length-2],Sr=ss[ss.length-1],nr=!(ks(jr,Sr)&Un);for(let Ot=0;Ot>31}function be(ss,Oe){const{geometry:Xe,type:ot}=ss;let Nt=0,Rt=0;if(ot===1){Oe.writeVarint(Fe(1,Xe.length));for(const qt of Xe){const xs=qt[0]-Nt,rs=qt[1]-Rt;Oe.writeVarint(qe(xs)),Oe.writeVarint(qe(rs)),Nt+=xs,Rt+=rs}}else for(const qt of Xe){if(qt.length===0)continue;Oe.writeVarint(Fe(1,1));const xs=qt.length-(ot===3?1:0);for(let rs=0;rsss},it=Math.fround||(je=new Float32Array(1),ss=>(je[0]=+ss,je[0]));var je;class Ge{constructor(Oe){this.options=Object.assign(Object.create(Ne),Oe),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(Oe){const{log:Xe,minZoom:ot,maxZoom:Nt}=this.options;Xe&&console.time("total time");const Rt=`prepare ${Oe.length} points`;Xe&&console.time(Rt),this.points=Oe;const qt=[];for(let rs=0;rs=ot;rs--){const ks=+Date.now();xs=this.trees[rs]=this._createTree(this._cluster(xs,rs)),Xe&&console.log("z%d: %d clusters in %dms",rs,xs.numItems,+Date.now()-ks)}return Xe&&console.timeEnd("total time"),this}getClusters(Oe,Xe){let ot=((Oe[0]+180)%360+360)%360-180;const Nt=Math.max(-90,Math.min(90,Oe[1]));let Rt=Oe[2]===180?180:((Oe[2]+180)%360+360)%360-180;const qt=Math.max(-90,Math.min(90,Oe[3]));if(Oe[2]-Oe[0]>=360)ot=-180,Rt=180;else if(ot>Rt){const Gs=this.getClusters([ot,Nt,180,qt],Xe),Un=this.getClusters([-180,Nt,Rt,qt],Xe);return Gs.concat(Un)}const xs=this.trees[this._limitZoom(Xe)],rs=xs.range(We(ot),rt(qt),We(Rt),rt(Nt)),ks=xs.data,ln=[];for(const Gs of rs){const Un=this.stride*Gs;ln.push(ks[Un+5]>1?Be(ks,Un,this.clusterProps):this.points[ks[Un+3]])}return ln}getChildren(Oe){const Xe=this._getOriginId(Oe),ot=this._getOriginZoom(Oe),Nt="No cluster with the specified id.",Rt=this.trees[ot];if(!Rt)throw new Error(Nt);const qt=Rt.data;if(Xe*this.stride>=qt.length)throw new Error(Nt);const xs=this.options.radius/(this.options.extent*Math.pow(2,ot-1)),rs=Rt.within(qt[Xe*this.stride],qt[Xe*this.stride+1],xs),ks=[];for(const ln of rs){const Gs=ln*this.stride;qt[Gs+4]===Oe&&ks.push(qt[Gs+5]>1?Be(qt,Gs,this.clusterProps):this.points[qt[Gs+3]])}if(ks.length===0)throw new Error(Nt);return ks}getLeaves(Oe,Xe,ot){const Nt=[];return this._appendLeaves(Nt,Oe,Xe=Xe||10,ot=ot||0,0),Nt}getTile(Oe,Xe,ot){const Nt=this.trees[this._limitZoom(Oe)],Rt=Math.pow(2,Oe),{extent:qt,radius:xs}=this.options,rs=xs/qt,ks=(ot-rs)/Rt,ln=(ot+1+rs)/Rt,Gs={features:[]};return this._addTileFeatures(Nt.range((Xe-rs)/Rt,ks,(Xe+1+rs)/Rt,ln),Nt.data,Xe,ot,Rt,Gs),Xe===0&&this._addTileFeatures(Nt.range(1-rs/Rt,ks,1,ln),Nt.data,Rt,ot,Rt,Gs),Xe===Rt-1&&this._addTileFeatures(Nt.range(0,ks,rs/Rt,ln),Nt.data,-1,ot,Rt,Gs),Gs.features.length?Gs:null}getClusterExpansionZoom(Oe){let Xe=this._getOriginZoom(Oe)-1;for(;Xe<=this.options.maxZoom;){const ot=this.getChildren(Oe);if(Xe++,ot.length!==1)break;Oe=ot[0].properties.cluster_id}return Xe}_appendLeaves(Oe,Xe,ot,Nt,Rt){const qt=this.getChildren(Xe);for(const xs of qt){const rs=xs.properties;if(rs&&rs.cluster?Rt+rs.point_count<=Nt?Rt+=rs.point_count:Rt=this._appendLeaves(Oe,rs.cluster_id,ot,Nt,Rt):Rt1;let ln,Gs,Un;if(ks)ln=Ye(Xe,rs,this.clusterProps),Gs=Xe[rs],Un=Xe[rs+1];else{const nr=this.points[Xe[rs+3]];ln=nr.properties;const[Ot,fn]=nr.geometry.coordinates;Gs=We(Ot),Un=rt(fn)}const jr={type:1,geometry:[[Math.round(this.options.extent*(Gs*Rt-ot)),Math.round(this.options.extent*(Un*Rt-Nt))]],tags:ln};let Sr;Sr=ks||this.options.generateId?Xe[rs+3]:this.points[Xe[rs+3]].id,Sr!==void 0&&(jr.id=Sr),qt.features.push(jr)}}_limitZoom(Oe){return Math.max(this.options.minZoom,Math.min(Math.floor(+Oe),this.options.maxZoom+1))}_cluster(Oe,Xe){const{radius:ot,extent:Nt,reduce:Rt,minPoints:qt}=this.options,xs=ot/(Nt*Math.pow(2,Xe)),rs=Oe.data,ks=[],ln=this.stride;for(let Gs=0;GsXe&&(Ot+=rs[sr+5])}if(Ot>nr&&Ot>=qt){let fn,sr=Un*nr,Hn=jr*nr,ta=-1;const Zr=(Gs/ln<<5)+(Xe+1)+this.points.length;for(const ur of Sr){const Mr=ur*ln;if(rs[Mr+2]<=Xe)continue;rs[Mr+2]=Xe;const zi=rs[Mr+5];sr+=rs[Mr]*zi,Hn+=rs[Mr+1]*zi,rs[Mr+4]=Zr,Rt&&(fn||(fn=this._map(rs,Gs,!0),ta=this.clusterProps.length,this.clusterProps.push(fn)),Rt(fn,this._map(rs,Mr)))}rs[Gs+4]=Zr,ks.push(sr/Ot,Hn/Ot,1/0,Zr,-1,Ot),Rt&&ks.push(ta)}else{for(let fn=0;fn1)for(const fn of Sr){const sr=fn*ln;if(!(rs[sr+2]<=Xe)){rs[sr+2]=Xe;for(let Hn=0;Hn>5}_getOriginZoom(Oe){return(Oe-this.points.length)%32}_map(Oe,Xe,ot){if(Oe[Xe+5]>1){const qt=this.clusterProps[Oe[Xe+6]];return ot?Object.assign({},qt):qt}const Nt=this.points[Oe[Xe+3]].properties,Rt=this.options.map(Nt);return ot&&Rt===Nt?Object.assign({},Rt):Rt}}function Be(ss,Oe,Xe){return{type:"Feature",id:ss[Oe+3],properties:Ye(ss,Oe,Xe),geometry:{type:"Point",coordinates:[(ot=ss[Oe],360*(ot-.5)),tt(ss[Oe+1])]}};var ot}function Ye(ss,Oe,Xe){const ot=ss[Oe+5],Nt=ot>=1e4?`${Math.round(ot/1e3)}k`:ot>=1e3?Math.round(ot/100)/10+"k":ot,Rt=ss[Oe+6],qt=Rt===-1?{}:Object.assign({},Xe[Rt]);return Object.assign(qt,{cluster:!0,cluster_id:ss[Oe+3],point_count:ot,point_count_abbreviated:Nt})}function We(ss){return ss/360+.5}function rt(ss){const Oe=Math.sin(ss*Math.PI/180),Xe=.5-.25*Math.log((1+Oe)/(1-Oe))/Math.PI;return Xe<0?0:Xe>1?1:Xe}function tt(ss){const Oe=(180-360*ss)*Math.PI/180;return 360*Math.atan(Math.exp(Oe))/Math.PI-90}function at(ss,Oe,Xe,ot){let Nt=ot;const Rt=Oe+(Xe-Oe>>1);let qt,xs=Xe-Oe;const rs=ss[Oe],ks=ss[Oe+1],ln=ss[Xe],Gs=ss[Xe+1];for(let Un=Oe+3;UnNt)qt=Un,Nt=jr;else if(jr===Nt){const Sr=Math.abs(Un-Rt);Srot&&(qt-Oe>3&&at(ss,Oe,qt,ot),ss[qt+2]=Nt,Xe-qt>3&&at(ss,qt,Xe,ot))}function He(ss,Oe,Xe,ot,Nt,Rt){let qt=Nt-Xe,xs=Rt-ot;if(qt!==0||xs!==0){const rs=((ss-Xe)*qt+(Oe-ot)*xs)/(qt*qt+xs*xs);rs>1?(Xe=Nt,ot=Rt):rs>0&&(Xe+=qt*rs,ot+=xs*rs)}return qt=ss-Xe,xs=Oe-ot,qt*qt+xs*xs}function dt(ss,Oe,Xe,ot){const Nt={id:ss??null,type:Oe,geometry:Xe,tags:ot,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(Oe==="Point"||Oe==="MultiPoint"||Oe==="LineString")bt(Nt,Xe);else if(Oe==="Polygon")bt(Nt,Xe[0]);else if(Oe==="MultiLineString")for(const Rt of Xe)bt(Nt,Rt);else if(Oe==="MultiPolygon")for(const Rt of Xe)bt(Nt,Rt[0]);return Nt}function bt(ss,Oe){for(let Xe=0;Xe0&&(qt+=ot?(Nt*ln-ks*Rt)/2:Math.sqrt(Math.pow(ks-Nt,2)+Math.pow(ln-Rt,2))),Nt=ks,Rt=ln}const xs=Oe.length-3;Oe[2]=1,at(Oe,0,xs,Xe),Oe[xs+2]=1,Oe.size=Math.abs(qt),Oe.start=0,Oe.end=Oe.size}function Fs(ss,Oe,Xe,ot){for(let Nt=0;Nt1?1:Xe}function Pt(ss,Oe,Xe,ot,Nt,Rt,qt,xs){if(ot/=Oe,Rt>=(Xe/=Oe)&&qt=ot)return null;const rs=[];for(const ks of ss){const ln=ks.geometry;let Gs=ks.type;const Un=Nt===0?ks.minX:ks.minY,jr=Nt===0?ks.maxX:ks.maxY;if(Un>=Xe&&jr=ot)continue;let Sr=[];if(Gs==="Point"||Gs==="MultiPoint")Jt(ln,Sr,Xe,ot,Nt);else if(Gs==="LineString")ft(ln,Sr,Xe,ot,Nt,!1,xs.lineMetrics);else if(Gs==="MultiLineString")Ms(ln,Sr,Xe,ot,Nt,!1);else if(Gs==="Polygon")Ms(ln,Sr,Xe,ot,Nt,!0);else if(Gs==="MultiPolygon")for(const nr of ln){const Ot=[];Ms(nr,Ot,Xe,ot,Nt,!0),Ot.length&&Sr.push(Ot)}if(Sr.length){if(xs.lineMetrics&&Gs==="LineString"){for(const nr of Sr)rs.push(dt(ks.id,Gs,nr,ks.tags));continue}Gs!=="LineString"&&Gs!=="MultiLineString"||(Sr.length===1?(Gs="LineString",Sr=Sr[0]):Gs="MultiLineString"),Gs!=="Point"&&Gs!=="MultiPoint"||(Gs=Sr.length===3?"Point":"MultiPoint"),rs.push(dt(ks.id,Gs,Sr,ks.tags))}}return rs.length?rs:null}function Jt(ss,Oe,Xe,ot,Nt){for(let Rt=0;Rt=Xe&&qt<=ot&&Xt(Oe,ss[Rt],ss[Rt+1],ss[Rt+2])}}function ft(ss,Oe,Xe,ot,Nt,Rt,qt){let xs=Vt(ss);const rs=Nt===0?Js:Cs;let ks,ln,Gs=ss.start;for(let Ot=0;OtXe&&(ln=rs(xs,fn,sr,ta,Zr,Xe),qt&&(xs.start=Gs+ks*ln)):ur>ot?Mr=Xe&&(ln=rs(xs,fn,sr,ta,Zr,Xe),zi=!0),Mr>ot&&ur<=ot&&(ln=rs(xs,fn,sr,ta,Zr,ot),zi=!0),!Rt&&zi&&(qt&&(xs.end=Gs+ks*ln),Oe.push(xs),xs=Vt(ss)),qt&&(Gs+=ks)}let Un=ss.length-3;const jr=ss[Un],Sr=ss[Un+1],nr=Nt===0?jr:Sr;nr>=Xe&&nr<=ot&&Xt(xs,jr,Sr,ss[Un+2]),Un=xs.length-3,Rt&&Un>=3&&(xs[Un]!==xs[0]||xs[Un+1]!==xs[1])&&Xt(xs,xs[0],xs[1],xs[2]),xs.length&&Oe.push(xs)}function Vt(ss){const Oe=[];return Oe.size=ss.size,Oe.start=ss.start,Oe.end=ss.end,Oe}function Ms(ss,Oe,Xe,ot,Nt,Rt){for(const qt of ss)ft(qt,Oe,Xe,ot,Nt,Rt,!1)}function Xt(ss,Oe,Xe,ot){ss.push(Oe,Xe,ot)}function Js(ss,Oe,Xe,ot,Nt,Rt){const qt=(Rt-Oe)/(ot-Oe);return Xt(ss,Rt,Xe+(Nt-Xe)*qt,1),qt}function Cs(ss,Oe,Xe,ot,Nt,Rt){const qt=(Rt-Xe)/(Nt-Xe);return Xt(ss,Oe+(ot-Oe)*qt,Rt,1),qt}function As(ss,Oe){const Xe=[];for(let ot=0;ot0&&Oe.size<(Nt?qt:ot))return void(Xe.numPoints+=Oe.length/3);const xs=[];for(let rs=0;rsqt)&&(Xe.numSimplified++,xs.push(Oe[rs],Oe[rs+1])),Xe.numPoints++;Nt&&function(rs,ks){let ln=0;for(let Gs=0,Un=rs.length,jr=Un-2;Gs0===ks)for(let Gs=0,Un=rs.length;Gs24)throw new Error("maxZoom should be in the 0-24 range");if(Xe.promoteId&&Xe.generateId)throw new Error("promoteId and generateId cannot be used together.");let Nt=function(Rt,qt){const xs=[];if(Rt.type==="FeatureCollection")for(let rs=0;rs1&&console.time("creation"),jr=this.tiles[Un]=gn(Oe,Xe,ot,Nt,ks),this.tileCoords.push({z:Xe,x:ot,y:Nt}),ln)){ln>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",Xe,ot,Nt,jr.numFeatures,jr.numPoints,jr.numSimplified),console.timeEnd("creation"));const zi=`z${Xe}`;this.stats[zi]=(this.stats[zi]||0)+1,this.total++}if(jr.source=Oe,Rt==null){if(Xe===ks.indexMaxZoom||jr.numPoints<=ks.indexMaxPoints)continue}else{if(Xe===ks.maxZoom||Xe===Rt)continue;if(Rt!=null){const zi=Rt-Xe;if(ot!==qt>>zi||Nt!==xs>>zi)continue}}if(jr.source=null,Oe.length===0)continue;ln>1&&console.time("clipping");const Sr=.5*ks.buffer/ks.extent,nr=.5-Sr,Ot=.5+Sr,fn=1+Sr;let sr=null,Hn=null,ta=null,Zr=null,ur=Pt(Oe,Gs,ot-Sr,ot+Ot,0,jr.minX,jr.maxX,ks),Mr=Pt(Oe,Gs,ot+nr,ot+fn,0,jr.minX,jr.maxX,ks);Oe=null,ur&&(sr=Pt(ur,Gs,Nt-Sr,Nt+Ot,1,jr.minY,jr.maxY,ks),Hn=Pt(ur,Gs,Nt+nr,Nt+fn,1,jr.minY,jr.maxY,ks),ur=null),Mr&&(ta=Pt(Mr,Gs,Nt-Sr,Nt+Ot,1,jr.minY,jr.maxY,ks),Zr=Pt(Mr,Gs,Nt+nr,Nt+fn,1,jr.minY,jr.maxY,ks),Mr=null),ln>1&&console.timeEnd("clipping"),rs.push(sr||[],Xe+1,2*ot,2*Nt),rs.push(Hn||[],Xe+1,2*ot,2*Nt+1),rs.push(ta||[],Xe+1,2*ot+1,2*Nt),rs.push(Zr||[],Xe+1,2*ot+1,2*Nt+1)}}getTile(Oe,Xe,ot){Oe=+Oe,Xe=+Xe,ot=+ot;const Nt=this.options,{extent:Rt,debug:qt}=Nt;if(Oe<0||Oe>24)return null;const xs=1<1&&console.log("drilling down to z%d-%d-%d",Oe,Xe,ot);let ks,ln=Oe,Gs=Xe,Un=ot;for(;!ks&&ln>0;)ln--,Gs>>=1,Un>>=1,ks=this.tiles[Ls(ln,Gs,Un)];return ks&&ks.source?(qt>1&&(console.log("found parent tile z%d-%d-%d",ln,Gs,Un),console.time("drilling down")),this.splitTile(ks.source,ln,Gs,Un,Oe,Xe,ot),qt>1&&console.timeEnd("drilling down"),this.tiles[rs]?tn(this.tiles[rs],Rt):null):null}}function Ls(ss,Oe,Xe){return 32*((1<ks.tags&&"3d_elevation_id"in ks.tags&&"source"in ks.tags&&ks.tags.source==="elevation",Rt=ot.features.filter(ks=>Nt(ks));let qt={_geojsonTileLayer:ot.features};Rt.length>0&&(qt={_geojsonTileLayer:ot.features.filter(ks=>!Nt(ks)),hd_road_elevation:Rt});const xs=new ne(qt),rs=function(ks){const ln=new c.a$;for(const Gs of Object.keys(ks))ln.writeMessage(3,Ae,{name:Gs,features:ks[Gs]});return ln.finish()}(qt).buffer;Oe(null,{vectorTile:xs,rawData:rs})}class Lr extends F{constructor(Oe){super(Oe),this.loadVectorData=fi,this._dynamicIndex=new he}loadData(Oe,Xe){const ot=Oe&&Oe.request,Nt=ot&&ot.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(Oe,(Rt,qt)=>{if(Rt||!qt)return Xe(Rt);if(typeof qt!="object")return Xe(new Error(`Input data given to '${Oe.source}' is not a valid GeoJSON object.`));{try{if(Oe.filter){const rs=c.X(Oe.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(rs.result==="error")throw new Error(rs.value.map(ks=>`${ks.key}: ${ks.message}`).join(", "));qt.features=qt.features.filter(ks=>rs.value.evaluate({zoom:0},ks))}Oe.dynamic?(qt.type==="Feature"&&(qt={type:"FeatureCollection",features:[qt]}),Oe.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(qt.features,this.loaded),Oe.cluster&&(qt.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=Oe.cluster?new Ge(function({superclusterOptions:rs,clusterProperties:ks}){if(!ks||!rs)return rs;const ln={},Gs={},Un={accumulated:null,zoom:0},jr={properties:null},Sr=Object.keys(ks);for(const nr of Sr){const[Ot,fn]=ks[nr],sr=c.X(fn),Hn=c.X(typeof Ot=="string"?[Ot,["accumulated"],["get",nr]]:Ot);ln[nr]=sr.value,Gs[nr]=Hn.value}return rs.map=nr=>{jr.properties=nr;const Ot={};for(const fn of Sr)Ot[fn]=ln[fn].evaluate(Un,jr);return Ot},rs.reduce=(nr,Ot)=>{jr.properties=Ot;for(const fn of Sr)Un.accumulated=nr[fn],nr[fn]=Gs[fn].evaluate(Un,jr)},rs}(Oe)).load(qt.features):Oe.dynamic?this._dynamicIndex:function(rs,ks){return new vi(rs,ks)}(qt,Oe.geojsonVtOptions)}catch(rs){return Xe(rs)}const xs={};if(Nt){const rs=d(ot);rs&&(xs.resourceTiming={},xs.resourceTiming[Oe.source]=JSON.parse(JSON.stringify(rs)))}Xe(null,xs)}})}reloadTile(Oe,Xe){const ot=this.loaded;return ot&&ot[Oe.uid]?Oe.partial?Xe(null,void 0):super.reloadTile(Oe,Xe):this.loadTile(Oe,Xe)}loadGeoJSON(Oe,Xe){if(Oe.request)c.m(Oe.request,Xe);else{if(typeof Oe.data!="string")return Xe(new Error(`Input data given to '${Oe.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return Xe(null,JSON.parse(Oe.data))}catch{return Xe(new Error(`Input data given to '${Oe.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(Oe,Xe){try{Xe(null,this._geoJSONIndex.getClusterExpansionZoom(Oe.clusterId))}catch(ot){Xe(ot)}}getClusterChildren(Oe,Xe){try{Xe(null,this._geoJSONIndex.getChildren(Oe.clusterId))}catch(ot){Xe(ot)}}getClusterLeaves(Oe,Xe){try{Xe(null,this._geoJSONIndex.getLeaves(Oe.clusterId,Oe.limit,Oe.offset))}catch(ot){Xe(ot)}}}class Jn{constructor(Oe,Xe,ot){this.tileID=new c.aR(Oe.tileID.overscaledZ,Oe.tileID.wrap,Oe.tileID.canonical.z,Oe.tileID.canonical.x,Oe.tileID.canonical.y),this.tileZoom=Oe.tileZoom,this.uid=Oe.uid,this.zoom=Oe.zoom,this.canonical=Oe.tileID.canonical,this.pixelRatio=Oe.pixelRatio,this.tileSize=Oe.tileSize,this.source=Oe.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=Oe.projection,this.brightness=Xe,this.worldview=ot}parse(Oe,Xe,ot,Nt){this.status="parsing";const Rt=new c.aR(ot.tileID.overscaledZ,ot.tileID.wrap,ot.tileID.canonical.z,ot.tileID.canonical.x,ot.tileID.canonical.y),qt=[],xs=Xe.familiesBySource[ot.source],rs=new c.ff(Rt,ot.promoteId);rs.bucketLayerIDs=[],rs.is3DTile=!0,c.fB(Oe).then(ks=>{const ln=ks.json.extensionsUsed&&ks.json.extensionsUsed.includes("MAPBOX_mesh_features")||ks.json.asset.extras&&ks.json.asset.extras.MAPBOX_mesh_features,Gs=ks.json.extensionsUsed&&ks.json.extensionsUsed.includes("EXT_meshopt_compression"),Un=new c.ae(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const jr in xs)for(const Sr of xs[jr]){const nr=Sr[0];rs.bucketLayerIDs.push(Sr.map(sr=>c.F(sr.id,sr.scope))),nr.recalculate(Un,[]);const Ot=c.fC(ks,1/c.cS(ot.tileID.canonical)),fn=new c.fD(Sr,Ot,Rt,ln,Gs,this.brightness,rs,this.worldview);ln||(fn.needsUpload=!0),qt.push(fn),fn.evaluate(nr)}this.status="done",Nt(null,{buckets:qt,featureIndex:rs,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(ks=>Nt(new Error(ks.message)))}}class js{constructor({actor:Oe,layerIndex:Xe,availableImages:ot,availableModels:Nt,brightness:Rt,worldview:qt}){this.actor=Oe,this.layerIndex=Xe,this.availableImages=ot,this.availableModels=Nt,this.brightness=Rt,this.loading={},this.loaded={},this.worldview=qt}loadTile(Oe,Xe){const ot=Oe.uid,Nt=this.loading[ot]=new Jn(Oe,this.brightness,this.worldview);c.b1(Oe.request,(Rt,qt)=>{const xs=!this.loading[ot];return delete this.loading[ot],xs||Rt?(Nt.status="done",xs||(this.loaded[ot]=Nt),Xe(Rt)):qt&&qt.byteLength!==0?void Nt.parse(qt,this.layerIndex,Oe,(rs,ks)=>{Nt.status="done",this.loaded=this.loaded||{},this.loaded[ot]=Nt,rs||!ks?Xe(rs):Xe(null,ks)}):(Nt.status="done",this.loaded[ot]=Nt,Xe())})}reloadTile(Oe,Xe){const ot=this.loaded,Nt=Oe.uid;if(ot&&ot[Nt]){const Rt=ot[Nt];Rt.projection=Oe.projection,Rt.brightness=Oe.brightness;const qt=(xs,rs)=>{Rt.reloadCallback&&(delete Rt.reloadCallback,this.loadTile(Oe,Xe)),Xe(xs,rs)};Rt.status==="parsing"?Rt.reloadCallback=qt:Rt.status==="done"&&this.loadTile(Oe,Xe)}}abortTile(Oe,Xe){const ot=Oe.uid;this.loading[ot]&&delete this.loading[ot],Xe()}removeTile(Oe,Xe){const ot=this.loaded,Nt=Oe.uid;ot&&ot[Nt]&&delete ot[Nt],Xe()}}const Dn=new Map,wr=new Map;class $r{constructor(Oe){this.self=Oe,this.actor=new c.A(Oe,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:F,geojson:Lr,"raster-dem":z,"raster-array":W,"batched-model":js},this.workerSources={},this.self.registerWorkerSource=(Xe,ot)=>{if(this.workerSourceTypes[Xe])throw new Error(`Worker source with name "${Xe}" already registered.`);this.workerSourceTypes[Xe]=ot},this.self.registerRTLTextPlugin=Xe=>{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=Xe.applyArabicShaping,c.fF.processBidirectionalText=Xe.processBidirectionalText,c.fF.processStyledBidirectionalText=Xe.processStyledBidirectionalText;for(const ot of this.rtlPluginParsingListeners)ot(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(Oe,Xe,ot){delete this.layerIndexes[Oe],delete this.availableImages[Oe],delete this.availableModels[Oe],delete this.workerSources[Oe],ot()}checkIfReady(Oe,Xe,ot){ot()}setReferrer(Oe,Xe){this.referrer=Xe}spriteLoaded(Oe,Xe){this.isSpriteLoaded[Oe]||(this.isSpriteLoaded[Oe]={});const{scope:ot,isLoaded:Nt}=Xe;if(this.isSpriteLoaded[Oe][ot]=Nt,this.workerSources[Oe]&&this.workerSources[Oe][ot])for(const Rt in this.workerSources[Oe][ot]){const qt=this.workerSources[Oe][ot][Rt];for(const xs in qt){const rs=qt[xs];rs instanceof F&&(rs.isSpriteLoaded=Nt,rs.fire(new c.C("isSpriteLoaded")))}}}setImages(Oe,Xe,ot){this.availableImages[Oe]||(this.availableImages[Oe]={});const{scope:Nt,images:Rt}=Xe;if(this.availableImages[Oe][Nt]=Rt,this.workerSources[Oe]&&this.workerSources[Oe][Nt]){for(const qt in this.workerSources[Oe][Nt]){const xs=this.workerSources[Oe][Nt][qt];for(const rs in xs)xs[rs].availableImages=Rt}ot()}else ot()}setModels(Oe,{scope:Xe,models:ot},Nt){if(this.availableModels[Oe]||(this.availableModels[Oe]={}),this.availableModels[Oe][Xe]=ot,this.workerSources[Oe]&&this.workerSources[Oe][Xe]){for(const Rt in this.workerSources[Oe][Xe]){const qt=this.workerSources[Oe][Xe][Rt];for(const xs in qt)qt[xs].availableModels=ot}Nt()}else Nt()}setProjection(Oe,Xe){this.projections[Oe]=c.c0(Xe)}setBrightness(Oe,Xe,ot){this.brightness=Xe,ot()}setContextParams(Oe,Xe,ot){this.maxUniformBufferBindings=Xe.maxBindingPoints,this.maxUniformBlockSizeDwords=Xe.maxUniformBlockSizeDwords,this.disableSymbolUBO=Xe.disableSymbolUBO,ot()}setWorldview(Oe,Xe,ot){this.worldview=Xe,ot()}setLayers(Oe,Xe,ot){this.getLayerIndex(Oe,Xe.scope).replace(Xe.layers,Xe.options),ot()}updateLayers(Oe,Xe,ot){this.getLayerIndex(Oe,Xe.scope).update(Xe.layers,Xe.removedIds,Xe.options),ot()}loadTile(Oe,Xe,ot){Xe.projection=this.projections[Oe]||this.defaultProjection,this.getWorkerSource(Oe,Xe).loadTile(Xe,ot)}decodeRasterArray(Oe,Xe,ot){this.getWorkerSource(Oe,Xe).decodeRasterArray(Xe,ot)}reloadTile(Oe,Xe,ot){Xe.projection=this.projections[Oe]||this.defaultProjection,this.getWorkerSource(Oe,Xe).reloadTile(Xe,ot)}abortTile(Oe,Xe,ot){this.getWorkerSource(Oe,Xe).abortTile(Xe,ot)}removeTile(Oe,Xe,ot){this.getWorkerSource(Oe,Xe).removeTile(Xe,ot)}removeSource(Oe,Xe,ot){if(!(this.workerSources[Oe]&&this.workerSources[Oe][Xe.scope]&&this.workerSources[Oe][Xe.scope][Xe.type]&&this.workerSources[Oe][Xe.scope][Xe.type][Xe.source]))return;const Nt=this.workerSources[Oe][Xe.scope][Xe.type][Xe.source];delete this.workerSources[Oe][Xe.scope][Xe.type][Xe.source],Nt.removeSource!==void 0?Nt.removeSource(Xe,ot):ot()}loadTileProvider(Oe,Xe,ot){(async function(Nt,Rt){const qt=wr.get(Nt);if(qt)return qt;const xs=Dn.get(Nt);if(xs!==void 0)return xs;const rs=import(Rt).then(ks=>{const ln=ks.default;if(typeof ln!="function")throw new Error(`TileProvider "${Nt}" module must default-export a class`);if(typeof ln.prototype.loadTile!="function")throw new Error(`TileProvider "${Nt}" class must have a loadTile method`);return wr.set(Nt,ln),ln}).finally(()=>{Dn.delete(Nt)});return Dn.set(Nt,rs),rs})(Xe.name,Xe.url).then(Nt=>{const Rt=new Nt(Xe.options);return this.getWorkerSource(Oe,{type:Xe.type,source:Xe.source,scope:Xe.scope},Rt),Rt.load&&Xe.request?Rt.load({request:Xe.request}):null}).then(Nt=>ot(null,Nt)).catch(Nt=>ot(Nt instanceof Error?Nt:new Error(typeof Nt=="string"?Nt:"Unknown error")))}loadWorkerSource(Oe,Xe,ot){try{this.self.importScripts(Xe.url),ot()}catch(Nt){ot(Nt)}}syncRTLPluginState(Oe,Xe,ot){if(c.fF.isParsed())ot(null,!0);else if(c.fF.isParsing())this.rtlPluginParsingListeners.push(ot);else try{c.fF.setState(Xe);const Nt=c.fF.getPluginURL();!c.fF.isLoaded()||c.fF.isParsed()||c.fF.isParsing()||Nt==null||(c.fF.setState({pluginStatus:c.fG.parsing,pluginURL:c.fF.getPluginURL()}),this.self.importScripts(Nt),c.fF.isParsed()?ot(null,!0):this.rtlPluginParsingListeners.push(ot))}catch(Nt){ot(Nt)}}setConfig(Oe,Xe){Object.assign(c.g,Xe)}getAvailableImages(Oe,Xe){this.availableImages[Oe]||(this.availableImages[Oe]={});let ot=this.availableImages[Oe][Xe];return ot||(ot=[]),ot}getAvailableModels(Oe,Xe){this.availableModels[Oe]||(this.availableModels[Oe]={});let ot=this.availableModels[Oe][Xe];return ot||(ot={}),ot}getLayerIndex(Oe,Xe){this.layerIndexes[Oe]||(this.layerIndexes[Oe]={});let ot=this.layerIndexes[Oe][Xe];return ot||(ot=this.layerIndexes[Oe][Xe]=new f,ot.scope=Xe),ot}getWorkerSource(Oe,Xe,ot){const{type:Nt,source:Rt,scope:qt}=Xe,xs=this.workerSources;if(xs[Oe]||(xs[Oe]={}),xs[Oe][qt]||(xs[Oe][qt]={}),xs[Oe][qt][Nt]||(xs[Oe][qt][Nt]={}),this.isSpriteLoaded[Oe]||(this.isSpriteLoaded[Oe]={}),!xs[Oe][qt][Nt][Rt]){const rs={send:(ln,Gs,Un,jr,Sr,nr)=>this.actor.send(ln,Gs,Un,Oe,Sr,nr),scheduler:this.actor.scheduler},ks=this.workerSourceTypes[Nt];if(!ks)throw new Error(`Unknown worker source type "${Nt}".`);xs[Oe][qt][Nt][Rt]=new ks({actor:rs,layerIndex:this.getLayerIndex(Oe,qt),availableImages:this.getAvailableImages(Oe,qt),availableModels:this.getAvailableModels(Oe,qt),isSpriteLoaded:this.isSpriteLoaded[Oe][qt],tileProvider:ot,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return xs[Oe][qt][Nt][Rt]}rasterizeImagesWorker(Oe,Xe,ot){const Nt=new Map;for(const[Rt,{image:qt,imageVariant:xs}]of Xe.tasks.entries()){const rs=this.imageRasterizer.rasterize(xs,qt,Xe.scope,Oe);Nt.set(Rt,rs)}ot(void 0,Nt)}removeRasterizedImages(Oe,Xe,ot){this.imageRasterizer.removeImagesFromCacheByIds(Xe.imageIds,Xe.scope,Oe),ot()}enforceCacheSizeLimit(Oe,Xe){c.fH(Xe)}getWorkerPerformanceMetrics(Oe,Xe,ot){ot(void 0,void 0)}}return c.fE(self)&&(self.worker=new $r(self)),$r}),i(["./shared"],function(o){var c="3.22.0";const d={create:"create",load:"load",fullLoad:"fullLoad"},u={mark(I){performance.mark(I)},measure(I,y,C){performance.measure(I,y,C)}};function h(I){const y=I.name.split("?")[0];return o.a(y)&&y.includes("mapbox-gl.js")?"javascript":o.a(y)&&y.includes("mapbox-gl.css")?"css":o.b(y)?"fontRange":o.c(y)?"sprite":o.i(y)?"style":o.d(y)?"tilejson":"other"}var p,f={},g=function(){if(p)return f;function I(R){return!y(R)}function y(R){return typeof window>"u"||typeof document>"u"?"not a browser":function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var G,Z,te=new Blob([""],{type:"text/javascript"}),de=URL.createObjectURL(te);try{Z=new Worker(de),G=!0}catch{G=!1}return Z&&Z.terminate(),URL.revokeObjectURL(de),G}()?function(){var G=document.createElement("canvas");G.width=G.height=1;var Z=G.getContext("2d");if(!Z)return!1;var te=Z.getImageData(0,0,1,1);return te&&te.width===G.width}()?(C[$=R&&R.failIfMajorPerformanceCaveat]===void 0&&(C[$]=function(G){var Z,te=function(de){var xe=document.createElement("canvas"),we=Object.create(I.webGLContextAttributes);return we.failIfMajorPerformanceCaveat=de,xe.getContext("webgl2",we)}(G);if(!te)return!1;try{Z=te.createShader(te.VERTEX_SHADER)}catch{return!1}return!(!Z||te.isContextLost())&&(te.shaderSource(Z,"void main() {}"),te.compileShader(Z),te.getShaderParameter(Z,te.COMPILE_STATUS)===!0)}($)),C[$]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var $}p=1,f.supported=I,f.notSupportedReason=y;var C={};return I.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},f}();function _(I,y,C){const R=document.createElement(I);return y!=null&&(R.className=y),C&&C.appendChild(R),R}function v(I,y,C){const R=document.createElementNS("http://www.w3.org/2000/svg",I);for(const $ of Object.keys(y))R.setAttributeNS(null,$,String(y[$]));return C&&C.appendChild(R),R}const j=typeof document<"u"?document.documentElement&&document.documentElement.style:null,b=j&&j.userSelect!==void 0?"userSelect":"WebkitUserSelect";let S;function A(){j&&b&&(S=j[b],j[b]="none")}function T(){j&&b&&(j[b]=S)}function L(I){I.preventDefault(),I.stopPropagation(),window.removeEventListener("click",L,!0)}function D(){window.addEventListener("click",L,!0),window.setTimeout(()=>{window.removeEventListener("click",L,!0)},0)}function M(I,y){const C=I.getBoundingClientRect();return V(I,C,y)}function F(I,y){const C=I.getBoundingClientRect(),R=[];for(let $=0;$this._skuTokenExpiresAt}transformRequest(y,C){return this._transformRequestFn&&this._transformRequestFn(y,C)||{url:y}}normalizeStyleURL(y,C){if(!o.e(y))return y;const R=ne(y);return R.params.push(`sdk=js-${c}`),R.path=`/styles/v1${R.path}`,this._makeAPIURL(R,this._customAccessToken||C)}normalizeGlyphsURL(y,C){if(!o.e(y))return y;const R=ne(y);return R.path=`/fonts/v1${R.path}`,this._makeAPIURL(R,this._customAccessToken||C)}normalizeModelURL(y,C){if(!o.e(y))return y;const R=ne(y);return R.path=`/models/v1${R.path}`,this._makeAPIURL(R,this._customAccessToken||C)}normalizeSourceURL(y,C,R,$){if(!o.e(y))return y;const G=ne(y);return G.path=`/v4/${G.authority}.json`,G.params.push("secure"),R&&G.params.push(`language=${R}`),$&&G.params.push(`worldview=${$}`),this._makeAPIURL(G,this._customAccessToken||C)}normalizeIconsetURL(y,C){const R=ne(y);return o.e(y)?(R.path=`/styles/v1${R.path}/iconset.pbf`,this._makeAPIURL(R,this._customAccessToken||C)):ie(R)}normalizeSpriteURL(y,C,R,$){const G=ne(y);return o.e(y)?(G.path=`/styles/v1${G.path}/sprite${C}${R}`,this._makeAPIURL(G,this._customAccessToken||$)):(G.path+=`${C}${R}`,ie(G))}normalizeTileURL(y,C,R){if(this._isSkuTokenExpired()&&this._createSkuToken(),y&&!o.e(y))return y;const $=ne(y);$.path=$.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${C||R&&$.authority!=="raster"&&R===512?"@2x":""}${o.k.supported?".webp":"$1"}`),$.authority==="raster"?$.path=`/${o.g.RASTER_URL_PREFIX}${$.path}`:$.authority==="rasterarrays"?$.path=`/${o.g.RASTERARRAYS_URL_PREFIX}${$.path}`:$.authority==="3dtiles"?$.path=`/${o.g.TILES3D_URL_PREFIX}${$.path}`:($.path=$.path.replace(/^.+\/v4\//,"/"),$.path=`/${o.g.TILE_URL_VERSION}${$.path}`);const G=this._customAccessToken||function(Z){for(const te of Z){const de=te.match(/^access_token=(.*)$/);if(de)return de[1]}return null}($.params)||o.g.ACCESS_TOKEN;return o.g.REQUIRE_ACCESS_TOKEN&&G&&this._skuToken&&$.params.push(`sku=${this._skuToken}`),this._makeAPIURL($,G)}canonicalizeTileURL(y,C){const R=ne(y);if(!R.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!R.path.match(/\.[\w]+$/))return y;let $="mapbox://";R.path.match(/^\/raster\/v1\//)?$+=`raster/${R.path.replace(`/${o.g.RASTER_URL_PREFIX}/`,"")}`:R.path.match(/^\/rasterarrays\/v1\//)?$+=`rasterarrays/${R.path.replace(`/${o.g.RASTERARRAYS_URL_PREFIX}/`,"")}`:$+=`tiles/${R.path.replace(`/${o.g.TILE_URL_VERSION}/`,"")}`;let G=R.params;return C&&(G=G.filter(Z=>!Z.match(/^access_token=/))),G.length&&($+=`?${G.join("&")}`),$}canonicalizeTileset(y,C){const R=!!C&&o.e(C),$=[];for(const G of y.tiles||[])o.f(G)?$.push(this.canonicalizeTileURL(G,R)):$.push(G);return $}_makeAPIURL(y,C){const R="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",$=ne(o.g.API_URL);if(y.protocol=$.protocol,y.authority=$.authority,y.protocol==="http"){const G=y.params.indexOf("secure");G>=0&&y.params.splice(G,1)}if($.path!=="/"&&(y.path=`${$.path}${y.path}`),!o.g.REQUIRE_ACCESS_TOKEN)return ie(y);if(C=C||o.g.ACCESS_TOKEN,!this._silenceAuthErrors){if(!C)throw new Error(`An API access token is required to use Mapbox GL. ${R}`);if(C[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${R}`)}return y.params=y.params.filter(G=>G.indexOf("access_token")===-1),y.params.push(`access_token=${C||""}`),ie(y)}}const J=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function ne(I){const y=I.match(J);if(!y)throw new Error("Unable to parse URL object");return{protocol:y[1],authority:y[2],path:y[3]||"/",params:y[4]?y[4].split("&"):[]}}function ie(I){const y=I.params.length?`?${I.params.join("&")}`:"";return`${I.protocol}://${I.authority}${I.path}${y}`}const he="mapbox.eventData";function ce(I){if(!I)return null;const y=I.split(".");if(!y||y.length!==3)return null;try{return JSON.parse(o.l(y[1]))}catch{return null}}function pe(I){return!(!o.g.EVENTS_URL||!I&&!o.g.ACCESS_TOKEN)}class le{constructor(y){this.type=y,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(y){const C=ce(o.g.ACCESS_TOKEN);let R="";return R=C&&C.u?o.j(C.u):o.g.ACCESS_TOKEN||"",y?`${he}.${y}:${R}`:`${he}:${R}`}fetchEventData(){const y=o.s("localStorage"),C=this.getStorageKey(),R=this.getStorageKey("uuid"),$=this.getStorageKey("uuidTimestamp");if(y)try{const G=localStorage.getItem(C);G&&(this.eventData=JSON.parse(G));const Z=localStorage.getItem(R);Z&&(this.anonId=Z);const te=localStorage.getItem($);te&&(this.anonIdTimestamp=Number(te));const de=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(C,JSON.stringify(this.eventData)),Z&&localStorage.setItem($,Z.toString())}catch{o.w("Unable to write to LocalStorage")}}processRequests(y){}postEvent(y,C,R,$){if(!o.g.EVENTS_URL)return;const G=ne(o.g.EVENTS_URL);G.params.push(`access_token=${$||o.g.ACCESS_TOKEN||""}`);const Z={event:this.type,created:new Date(y).toISOString()},te=C?Object.assign(Z,C):Z,de={url:ie(G),headers:{"Content-Type":"text/plain"},body:JSON.stringify([te])};this.pendingRequest=o.p(de,xe=>{this.pendingRequest=null,R(xe),this.saveEventData(),this.processRequests($)})}queueRequest(y,C){this.queue.push(y),this.processRequests(C)}}class ve extends le{constructor(y){super("metrics"),y&&(this.data=y)}postMetricsEvent(y){if(!pe(y))return;this.anonId||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID();const C=Object.assign({},this.data,{sessionId:this.anonId});this.queueRequest({timestamp:Date.now(),payload:C},y)}processRequests(y){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:C,payload:R}=this.queue.shift();this.postEvent(C,R,()=>{},y)}}const ge=new class extends le{constructor(I){super("appUserTurnstile"),this._customAccessToken=I}postTurnstileEvent(I,y){pe(y)&&Array.isArray(I)&&I.some(C=>o.e(C)||o.f(C))&&this.queueRequest(Date.now(),y)}processRequests(I){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const y=ce(o.g.ACCESS_TOKEN),C=y?y.u:o.g.ACCESS_TOKEN;let R=C!==this.eventData.tokenU;o.v(this.anonId)||(this.refreshUUID(),R=!0);const $=this.queue.shift();if(this.eventData.lastSuccess){const G=new Date(this.eventData.lastSuccess),Z=new Date($),te=($-this.eventData.lastSuccess)/864e5;R=R||te>=1||te<-1||G.getDate()!==Z.getDate()}else R=!0;R?this.postEvent($,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:W,"enabled.telemetry":!1,userId:this.anonId},G=>{G||(this.eventData.lastSuccess=$,this.eventData.tokenU=C)},I):this.processRequests()}},Te=ge.postTurnstileEvent.bind(ge),Me=new class extends le{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(I,y,C,R){this.skuToken=y,this.errorCb=R,o.g.EVENTS_URL&&(C||o.g.ACCESS_TOKEN?this.queueRequest({id:I,timestamp:Date.now()},C):this.errorCb(new Error(Y)))}processRequests(I){if(this.pendingRequest||this.queue.length===0)return;const{id:y,timestamp:C}=this.queue.shift();y&&this.success[y]||(this.anonId&&this.anonIdTimestamp||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID(),this.postEvent(C,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:W,skuToken:this.skuToken,userId:this.anonId},R=>{R?this.errorCb(R):y&&(this.success[y]=!0)},I))}remove(){this.errorCb=null}},Ce=Me.postMapLoadEvent.bind(Me),Ae=new class extends le{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(I){let y=this.mapInstanceIdMap.get(I);return y||(y=o.u(),this.mapInstanceIdMap.set(I,y)),y}getEventId(I){const y=this.eventIdPerMapInstanceMap.get(I)||0;return this.eventIdPerMapInstanceMap.set(I,y+1),y}postStyleLoadEvent(I,y){const{map:C,style:R,importedStyles:$}=y;if(!pe(I))return;const G=this.getMapInstanceId(C),Z={mapInstanceId:G,eventId:this.getEventId(G),style:R};$.length&&(Z.importedStyles=$),this.queueRequest({timestamp:Date.now(),payload:Z},I)}processRequests(I){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:y,payload:C}=this.queue.shift();this.postEvent(y,C,()=>{},I)}},De=Ae.postStyleLoadEvent.bind(Ae),Ie=new ve({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Fe=Ie.postMetricsEvent.bind(Ie),qe=new ve({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),be=qe.postMetricsEvent.bind(qe),Ze=new class extends le{constructor(){super("gljs.performance")}postPerformanceEvent(I,y){pe(I)&&this.queueRequest({timestamp:Date.now(),performanceData:y},I)}processRequests(I){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:y,performanceData:C}=this.queue.shift(),R=function($){const G=performance.getEntriesByType("resource"),Z=performance.getEntriesByType("mark"),te=function(Ue){const st={};if(Ue){for(const Je in Ue)if(Je!=="other")for(const mt of Ue[Je]){const ht=`${Je}ResolveRangeMin`,kt=`${Je}ResolveRangeMax`,Tt=`${Je}RequestCount`,xt=`${Je}RequestCachedCount`;st[ht]=Math.min(st[ht]||1/0,mt.startTime),st[kt]=Math.max(st[kt]||-1/0,mt.responseEnd);const es=Ft=>{st[Ft]===void 0&&(st[Ft]=0),++st[Ft]};mt.transferSize!==void 0&&mt.transferSize===0&&es(xt),es(Tt)}}return st}(function(Ue,st){const Je={};if(Ue)for(const mt of Ue){const ht=st(mt);Je[ht]===void 0&&(Je[ht]=[]),Je[ht].push(mt)}return Je}(G,h)),de=window.devicePixelRatio,xe=navigator.connection||navigator.mozConnection||navigator.webkitConnection,we=xe?xe.effectiveType:void 0,Re={counters:[],metadata:[],attributes:[]},Le=(Ue,st,Je)=>{Je!=null&&Ue.push({name:st,value:Je.toString()})};for(const Ue in te)Le(Re.counters,Ue,te[Ue]);if($.interactionRange[0]!==1/0&&$.interactionRange[1]!==-1/0&&(Le(Re.counters,"interactionRangeMin",$.interactionRange[0]),Le(Re.counters,"interactionRangeMax",$.interactionRange[1])),Z)for(const Ue of Object.values(d)){const st=Z.find(Je=>Je.name===Ue);st&&Le(Re.counters,Ue,st.startTime)}return Le(Re.counters,"visibilityHidden",$.visibilityHidden),Le(Re.attributes,"style",function(Ue){if(Ue)for(const st of Ue){const Je=st.name.split("?")[0];if(o.i(Je)){const mt=Je.split("/").slice(-2);if(mt.length===2)return`mapbox://styles/${mt[0]}/${mt[1]}`}}}(G)),Le(Re.attributes,"terrainEnabled",$.terrainEnabled?"true":"false"),Le(Re.attributes,"fogEnabled",$.fogEnabled?"true":"false"),Le(Re.attributes,"projection",$.projection),Le(Re.attributes,"zoom",$.zoom),Le(Re.metadata,"devicePixelRatio",de),Le(Re.metadata,"connectionEffectiveType",we),Le(Re.metadata,"navigatorUserAgent",navigator.userAgent),Le(Re.metadata,"screenWidth",window.screen.width),Le(Re.metadata,"screenHeight",window.screen.height),Le(Re.metadata,"windowWidth",window.innerWidth),Le(Re.metadata,"windowHeight",window.innerHeight),Le(Re.metadata,"mapWidth",$.width/de),Le(Re.metadata,"mapHeight",$.height/de),Le(Re.metadata,"webglRenderer",$.renderer),Le(Re.metadata,"webglVendor",$.vendor),Le(Re.metadata,"sdkVersion",c),Le(Re.metadata,"sdkIdentifier","mapbox-gl-js"),Re}(C);for(const $ of R.metadata);for(const $ of R.counters);for(const $ of R.attributes);this.postEvent(y,R,()=>{},I)}},Ne=Ze.postPerformanceEvent.bind(Ze),it=new class extends le{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(I,y,C,R){if(!o.g.API_URL||!o.g.SESSION_PATH)return;const $=ne(o.g.API_URL+o.g.SESSION_PATH);$.params.push(`sku=${y||""}`),$.params.push(`access_token=${R||o.g.ACCESS_TOKEN||""}`);const G={url:ie($),headers:{"Content-Type":"text/plain"}};this.pendingRequest=o.h(G,Z=>{this.pendingRequest=null,C(Z),this.saveEventData(),this.processRequests(R)})}getSessionAPI(I,y,C,R){this.skuToken=y,this.errorCb=R,o.g.EVENTS_URL&&o.g.SESSION_PATH&&o.g.API_URL&&(C||o.g.ACCESS_TOKEN?this.queueRequest({id:I,timestamp:Date.now()},C):this.errorCb(new Error(Y)))}processRequests(I){if(this.pendingRequest||this.queue.length===0)return;const{id:y,timestamp:C}=this.queue.shift();y&&this.success[y]||this.getSession(C,this.skuToken,R=>{R?this.errorCb(R):y&&(this.success[y]=!0)},I)}remove(){this.errorCb=null}},je=it.getSessionAPI.bind(it),Ge=new Set;function Be(I,y){y?Ge.add(I):Ge.delete(I)}class Ye{constructor(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps=new Set,this._updatedImages={}}isDirty(){return this._changed}setDirty(){this._changed=!0}getUpdatedSourceCaches(){return this._updatedSourceCaches}updateSourceCache(y,C){this._updatedSourceCaches[y]=C,this.setDirty()}discardSourceCacheUpdate(y){delete this._updatedSourceCaches[y]}updateLayer(y){const C=y.scope;this._updatedLayers[C]=this._updatedLayers[C]||new Set,this._updatedLayers[C].add(y.id),this.setDirty()}removeLayer(y){const C=y.scope;this._removedLayers[C]=this._removedLayers[C]||{},this._updatedLayers[C]=this._updatedLayers[C]||new Set,this._removedLayers[C][y.id]=y,this._updatedLayers[C].delete(y.id),this._updatedPaintProps.delete(y.fqid),this.setDirty()}getRemovedLayer(y){return this._removedLayers[y.scope]?this._removedLayers[y.scope][y.id]:null}discardLayerRemoval(y){this._removedLayers[y.scope]&&delete this._removedLayers[y.scope][y.id]}getLayerUpdatesByScope(){const y={};for(const C in this._updatedLayers)y[C]=y[C]||{},y[C].updatedIds=Array.from(this._updatedLayers[C].values());for(const C in this._removedLayers)y[C]=y[C]||{},y[C].removedIds=Object.keys(this._removedLayers[C]);return y}getUpdatedPaintProperties(){return this._updatedPaintProps}updatePaintProperties(y){this._updatedPaintProps.add(y.fqid),this.setDirty()}getUpdatedImages(y){return this._updatedImages[y]?Array.from(this._updatedImages[y].values()):[]}updateImage(y,C){this._updatedImages[C]=this._updatedImages[C]||new Set,this._updatedImages[C].add(o.I.toString(y)),this.setDirty()}resetUpdatedImages(y){this._updatedImages[y]&&this._updatedImages[y].clear()}reset(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps.clear(),this._updatedImages={}}}function We(I){const{userImage:y}=I;return!!(y&&y.render&&y.render())&&(I.data.replace(new Uint8Array(y.data.buffer)),!0)}const rt={workerUrl:"",workerClass:null,workerParams:void 0};function tt(I){return rt.workerClass!=null?new rt.workerClass:new self.Worker(rt.workerUrl,Object.assign({name:I},rt.workerParams))}const at="mapboxgl_preloaded_worker_pool";class He{constructor(y){this.active={},this.name=y}acquire(y,C=He.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{C.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[at]}numActive(){return Object.keys(this.active).length}}He.workerCount=2;class dt{constructor(y,C,R="Worker",$=He.workerCount){this.workerPool=y,this.actors=[],this.currentActor=0,this.id=o.r();const G=this.workerPool.acquire(this.id,$);for(let Z=0;Z{this.ready=!0})}broadcast(y,C,R){o.t(this.actors,($,G)=>{$.send(y,C,G)},R=R||function(){})}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(y=>{y.remove()}),this.actors=[],this.workerPool.release(this.id)}}let bt,vt;function Bt(){return bt||(bt=new He),bt}dt.Actor=o.A;class Zt extends o.E{constructor(y){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=y,y!=="raster"&&o.y()&&(this.imageRasterizerDispatcher=new dt((vt||(vt=new He("ImageRasterizer")),vt),this,"Image Rasterizer Worker",1))}addScope(y){this.loaded.set(y,!1),this.imageProviders.set(y,new Map),this.images.set(y,new Map),this.updatedImages.set(y,new Set),this.callbackDispatchedThisFrame.set(y,new Set),this.imageVersions.set(y,new Map),this.patterns.set(y,new Map),this.atlasImage.set(y,new o.q({width:1,height:1}))}removeScope(y){this.loaded.delete(y),this.imageProviders.delete(y),this.images.delete(y),this.updatedImages.delete(y),this.callbackDispatchedThisFrame.delete(y),this.imageVersions.delete(y),this.patterns.delete(y),this.atlasImage.delete(y);const C=this.atlasTexture.get(y);C&&(C.destroy(),this.atlasTexture.delete(y))}addImageProvider(y,C){this.imageProviders.has(C)||this.imageProviders.set(C,new Map),this.imageProviders.get(C).set(y.id,y)}removeImageProvider(y,C){this.imageProviders.has(C)&&this.imageProviders.get(C).delete(y)}getPendingImageProviders(){const y=[];for(const C of this.imageProviders.values())for(const R of C.values())R.hasPendingRequests()&&y.push(R);return y}get imageRasterizer(){return this._imageRasterizer||(this._imageRasterizer=new o.z),this._imageRasterizer}isLoaded(){for(const y of this.loaded.keys())if(!this.loaded.get(y))return!1;return!0}setLoaded(y,C){if(this.loaded.get(C)!==y&&(this.loaded.set(C,y),y)){for(const{ids:R,callback:$}of this.requestors)this._notify(R,C,$);this.requestors=[]}}hasImage(y,C){return!!this.getImage(y,C)}getImage(y,C){return this.images.get(C).get(y.toString())}addImage(y,C,R){if(this._validate(y,R)){this.images.get(C).set(y.toString(),R);const $=this.imageVersions.get(C),G=$.get(y.toString())||0;$.set(y.toString(),G+1)}}_validate(y,C){let R=!0;return this._validateStretch(C.stretchX,C.data&&C.data.width)||(this.fire(new o.B(new Error(`Image "${y.name}" has invalid "stretchX" value`))),R=!1),this._validateStretch(C.stretchY,C.data&&C.data.height)||(this.fire(new o.B(new Error(`Image "${y.name}" has invalid "stretchY" value`))),R=!1),this._validateContent(C.content,C)||(this.fire(new o.B(new Error(`Image "${y.name}" has invalid "content" value`))),R=!1),R}_validateStretch(y,C){if(!y)return!0;let R=0;for(const $ of y){if($[0]o.I.from(C))}getImageVersions(y){const C=this.imageVersions.get(y);if(C)return C}getImages(y,C,R){const $=[],G=[],Z=this.imageProviders.get(C);for(const we of y){if(!we.iconsetId){$.push(we);continue}const Re=Z.get(we.iconsetId);Re&&(this.getImage(we,C)?G.push(we):Re.addPendingRequest(we))}if($.length===0)return void this._notify(G,C,R);let te=!0;const de=!!this.loaded.get(C),xe=this.images.get(C);if(!de)for(const we of $)xe.has(we.toString())||(te=!1);de||te?this._notify($,C,R):this.requestors.push({ids:$,scope:C,callback:R})}rasterizeImages(y,C){const R=new Map,{tasks:$,scope:G}=y;for(const[Z,te]of $.entries()){const de=this.getImage(te.id,G);de&&R.set(Z,{image:de,imageVariant:te})}this._rasterizeImages(G,R,C)}_rasterizeImages(y,C,R){if(o.y())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:C,scope:y},R);else{const $=new Map;for(const[G,{image:Z,imageVariant:te}]of C.entries())$.set(G,this.imageRasterizer.rasterize(te,Z,y,0));R(void 0,$)}}getUpdatedImages(y){return this.updatedImages.get(y)||new Set}_notify(y,C,R){const $=this.images.get(C),G=new Map;for(const Z of y){if(!$.get(Z.toString())){if(Z.iconsetId)continue;this.fire(new o.C("styleimagemissing",{id:Z.name}))}const te=$.get(Z.toString());if(!te){o.w(`Image "${Z.name}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);continue}const de={data:te.usvg?null:te.data.clone(),pixelRatio:te.pixelRatio,sdf:te.sdf,usvg:te.usvg,stretchX:te.stretchX,stretchY:te.stretchY,content:te.content,hasRenderCallback:!!(te.userImage&&te.userImage.render)};te.usvg&&Object.assign(de,{width:te.icon.usvg_tree.width,height:te.icon.usvg_tree.height}),G.set(o.I.toString(Z),de)}R(null,{images:G,versions:this.getImageVersions(C)})}getPixelSize(y){const{width:C,height:R}=this.atlasImage.get(y);return{width:C,height:R}}getPattern(y,C,R){const $=y.toString(),G=this.patterns.get(C),Z=G.get($),te=this.getImage(y,C);if(!te)return null;if(Z){if(Z.position.version===te.version)return Z.position;Z.position.version=te.version}else{if(te.usvg&&!te.data){const de=this.getPatternInFlightId($,C);if(this.patternsInFlight.has(de))return null;this.patternsInFlight.add(de);const xe=new o.D(y).scaleSelf(o.o.devicePixelRatio),we=new Map([[xe.toString(),{image:te,imageVariant:xe}]]);return this._rasterizeImages(C,we,(Re,Le)=>this.storePatternImage(xe,C,te,R,Le)),null}this.storePattern(y,C,te)}return this._updatePatternAtlas(C,R),G.get($).position}getPatternInFlightId(y,C){return o.F(y,C)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(y,C,R,$,G){const Z=y.toString(),te=G?G.get(Z):void 0;te&&(R.data=te,this.storePattern(y.id,C,R),this._updatePatternAtlas(C,$),this.patternsInFlight.delete(this.getPatternInFlightId(y.id.toString(),C)))}storePattern(y,C,R){const $={w:R.data.width+2*o.G,h:R.data.height+2*o.G,x:0,y:0},G=new o.H($,R,o.G);this.patterns.get(C).set(y.toString(),{bin:$,position:G})}destroyAtlasTextures(){for(const y of this.atlasTexture.values())y&&y.destroy();this.atlasTexture.clear()}bind(y,C){const R=y.gl;let $=this.atlasTexture.get(C);$?this.dirty&&($.update(this.atlasImage.get(C)),this.dirty=!1):($=new o.T(y,this.atlasImage.get(C),R.RGBA8),this.atlasTexture.set(C,$)),$.bind(R.LINEAR,R.CLAMP_TO_EDGE)}_updatePatternAtlas(y,C){const R=this.patterns.get(y),$=Array.from(R.values()).map(({bin:xe})=>xe),{w:G,h:Z}=o.J($),te=this.atlasImage.get(y);te.resize({width:G||1,height:Z||1});const de=this.images.get(y);for(const[xe,{bin:we,position:Re}]of R.entries()){let Le=Re.padding;const Ue=we.x+Le,st=we.y+Le,Je=de.get(xe).data,mt=Je.width,ht=Je.height;Le=Le>1?Le-1:Le,o.q.copy(Je,te,{x:0,y:0},{x:Ue,y:st},{width:mt,height:ht},C),o.q.copy(Je,te,{x:0,y:ht-Le},{x:Ue,y:st-Le},{width:mt,height:Le},C),o.q.copy(Je,te,{x:0,y:0},{x:Ue,y:st+ht},{width:mt,height:Le},C),o.q.copy(Je,te,{x:mt-Le,y:0},{x:Ue-Le,y:st},{width:Le,height:ht},C),o.q.copy(Je,te,{x:0,y:0},{x:Ue+mt,y:st},{width:Le,height:ht},C),o.q.copy(Je,te,{x:mt-Le,y:ht-Le},{x:Ue-Le,y:st-Le},{width:Le,height:Le},C),o.q.copy(Je,te,{x:0,y:ht-Le},{x:Ue+mt,y:st-Le},{width:Le,height:Le},C),o.q.copy(Je,te,{x:0,y:0},{x:Ue+mt,y:st+ht},{width:Le,height:Le},C),o.q.copy(Je,te,{x:mt-Le,y:0},{x:Ue-Le,y:st+ht},{width:Le,height:Le},C)}this.dirty=!0}beginFrame(){for(const y of this.images.keys())this.callbackDispatchedThisFrame.set(y,new Set)}dispatchRenderCallbacks(y,C){const R=this.images.get(C);for(const $ of y){if(this.callbackDispatchedThisFrame.get(C).has($.toString()))continue;this.callbackDispatchedThisFrame.get(C).add($.toString());const G=R.get($.toString());We(G)&&this.updateImage($,C,G)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function Fs(I){const y=I.value,C=I.valueSpec,R=I.style,$=I.styleSpec,G=I.key,Z=I.arrayElementValidator||Lr;if(!Array.isArray(y))return[new o.V(G,y,`array expected, ${o.M(y)} found`)];if(C.length&&y.length!==C.length)return[new o.V(G,y,`array length ${C.length} expected, length ${y.length} found`)];if(C["min-length"]&&y.length$)return[new o.V(y,C,`${C} is greater than the maximum value ${$}`)]}return[]}function ms(I){const y=I.key,C=I.value;if(!o.K(C))return[new o.V(y,C,`object expected, ${o.M(C)} found`)];const R=I.valueSpec,$=o.L(C.type);let G,Z,te,de={};const xe=$!=="categorical"&&C.property===void 0,we=!xe,Re=function(Je){const mt=Je.stops;return Array.isArray(mt)&&Array.isArray(mt[0])&&o.K(mt[0][0])}(C),Le=Jn({key:I.key,value:I.value,valueSpec:I.styleSpec.function,style:I.style,styleSpec:I.styleSpec,objectElementValidators:{stops:function(Je){if($==="identity")return[new o.V(Je.key,Je.value,'identity function may not have a "stops" property')];let mt=[];const ht=Je.value;return mt=mt.concat(Fs({key:Je.key,value:ht,valueSpec:Je.valueSpec,style:Je.style,styleSpec:Je.styleSpec,arrayElementValidator:Ue})),Array.isArray(ht)&&ht.length===0&&mt.push(new o.V(Je.key,ht,"array must have at least one stop")),mt},default:function(Je){return Lr({key:Je.key,value:Je.value,valueSpec:R,style:Je.style,styleSpec:Je.styleSpec})}}});return $==="identity"&&xe&&Le.push(new o.V(I.key,I.value,'missing required property "property"')),$==="identity"||C.stops||Le.push(new o.V(I.key,I.value,'missing required property "stops"')),$==="exponential"&&R.expression&&!o.O(R)&&Le.push(new o.V(I.key,I.value,"exponential functions not supported")),I.styleSpec.$version>=8&&(we&&!o.Q(R)?Le.push(new o.V(I.key,I.value,"property functions not supported")):xe&&!o.S(R)&&Le.push(new o.V(I.key,I.value,"zoom functions not supported"))),$!=="categorical"&&!Re||C.property!==void 0||Le.push(new o.V(I.key,I.value,'"property" property is required')),Le;function Ue(Je){let mt=[];const ht=Je.value,kt=Je.key;if(!Array.isArray(ht))return[new o.V(kt,ht,`array expected, ${o.M(ht)} found`)];if(ht.length!==2)return[new o.V(kt,ht,`array length 2 expected, length ${ht.length} found`)];if(Re){if(!o.K(ht[0]))return[new o.V(kt,ht,`object expected, ${o.M(ht[0])} found`)];const Tt=ht[0];if(Tt.zoom===void 0)return[new o.V(kt,ht,"object stop key must have zoom")];if(Tt.value===void 0)return[new o.V(kt,ht,"object stop key must have value")];const xt=o.L(Tt.zoom);if(typeof xt!="number")return[new o.V(kt,Tt.zoom,"stop zoom values must be numbers")];if(te&&te>xt)return[new o.V(kt,Tt.zoom,"stop zoom values must appear in ascending order")];xt!==te&&(te=xt,Z=void 0,de={}),mt=mt.concat(Jn({key:`${kt}[0]`,value:ht[0],valueSpec:{zoom:{}},style:Je.style,styleSpec:Je.styleSpec,objectElementValidators:{zoom:Rs,value:st}}))}else mt=mt.concat(st({key:`${kt}[0]`,value:ht[0],style:Je.style,styleSpec:Je.styleSpec},ht));return o.U(o.W(ht[1]))?mt.concat([new o.V(`${kt}[1]`,ht[1],"expressions are not allowed in function stops.")]):mt.concat(Lr({key:`${kt}[1]`,value:ht[1],valueSpec:R,style:Je.style,styleSpec:Je.styleSpec}))}function st(Je,mt){const ht=o.M(Je.value),kt=o.L(Je.value),Tt=Je.value!==null?Je.value:mt;if(G){if(ht!==G)return[new o.V(Je.key,Tt,`${ht} stop domain type must match previous stop domain type ${G}`)]}else G=ht;if(ht!=="number"&&ht!=="string"&&ht!=="boolean"&&typeof kt!="number"&&typeof kt!="string"&&typeof kt!="boolean")return[new o.V(Je.key,Tt,"stop domain value must be a number, string, or boolean")];if(ht!=="number"&&$!=="categorical"){let xt=`number expected, ${ht} found`;return o.Q(R)&&$===void 0&&(xt+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new o.V(Je.key,Tt,xt)]}return $!=="categorical"||ht!=="number"||typeof kt=="number"&&isFinite(kt)&&Math.floor(kt)===kt?$!=="categorical"&&ht==="number"&&typeof kt=="number"&&typeof Z=="number"&&Z!==void 0&&ktnew o.V(`${I.key}${R.key}`,I.value,R.message));const C=y.value.expression||y.value._styleExpression.expression;if(I.expressionContext==="property"&&I.propertyKey==="text-font"&&!C.outputDefined())return[new o.V(I.key,I.value,`Invalid data expression for "${I.propertyKey}". Output values must be contained as literals within the expression.`)];if(I.expressionContext==="property"&&I.propertyType==="layout"&&!o.$(C))return[new o.V(I.key,I.value,'"feature-state" data expressions are not supported with layout properties.')];if(I.expressionContext==="filter")return Jt(C,I);if(I.expressionContext==="appearance")return ft(C,I);if(I.expressionContext&&I.expressionContext.indexOf("cluster")===0){if(!o.Z(C,["zoom","feature-state"]))return[new o.V(I.key,I.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(I.expressionContext==="cluster-initial"&&!o._(C))return[new o.V(I.key,I.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function Jt(I,y){const C=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(y.valueSpec&&y.valueSpec.expression)for(const $ of y.valueSpec.expression.parameters)C.delete($);if(C.size===0)return[];const R=[];return I instanceof o.a0&&C.has(I.name)?[new o.V(y.key,y.value,`["${I.name}"] expression is not supported in a filter for a ${y.object.type} layer with id: ${y.object.id}`)]:(I.eachChild($=>{R.push(...Jt($,y))}),R)}function ft(I,y){const C=new Set;if(y.valueSpec&&y.valueSpec.expression)for(const $ of y.valueSpec.expression.parameters)C.add($);if(C.size===0)return[];const R=[];return I instanceof o.a0&&!C.has(I.name)?[new o.V(y.key,y.value,`["${I.name}"] is not an allowed parameter`)]:(I.eachChild($=>{R.push(...ft($,y))}),R)}function Vt(I){const y=I.key,C=I.value,R=I.valueSpec,$=[];return Array.isArray(R.values)?R.values.indexOf(o.L(C))===-1&&$.push(new o.V(y,C,`expected one of [${R.values.join(", ")}], ${JSON.stringify(C)} found`)):Object.keys(R.values).indexOf(o.L(C))===-1&&$.push(new o.V(y,C,`expected one of [${Object.keys(R.values).join(", ")}], ${JSON.stringify(C)} found`)),$}function Ms(I){return o.a4(o.W(I.value))?Pt(Object.assign({},I,{expressionContext:"filter",valueSpec:I.styleSpec[`filter_${I.layerType||"fill"}`]})):Xt(I)}function Xt(I){const y=I.value,C=I.key;if(!Array.isArray(y))return[new o.V(C,y,`array expected, ${o.M(y)} found`)];if(y.length<1)return[new o.V(C,y,"filter array must have at least 1 element")];const R=I.styleSpec;let $=Vt({key:`${C}[0]`,value:y[0],valueSpec:R.filter_operator});const G=()=>{y.length>=2&&(o.a2(y[1])||$.push(new o.V(`${C}[1]`,y[1],`string expected, ${o.M(y[1])} found`)));for(let Z=2;Z":case">=":y.length>=2&&o.L(y[1])==="$type"&&$.push(new o.V(C,y,`"$type" cannot be use with operator "${y[0]}"`)),y.length!==3&&$.push(new o.V(C,y,`filter array for operator "${y[0]}" must have 3 elements`)),G();break;case"==":case"!=":y.length!==3&&$.push(new o.V(C,y,`filter array for operator "${y[0]}" must have 3 elements`)),G();break;case"in":case"!in":G();break;case"any":case"all":case"none":for(let Z=1;Z{xe in C&&y.push(new o.V(R,C[xe],`"${xe}" is prohibited for ref layers`))}),$.layers.forEach(xe=>{o.L(xe.id)===te&&(de=xe)}),de?de.ref?y.push(new o.V(R,C.ref,"ref cannot reference another ref layer")):Z=o.L(de.type):typeof te=="string"&&y.push(new o.V(R,C.ref,`ref layer "${te}" not found`))}else if(Z!=="background"&&Z!=="sky"&&Z!=="slot")if(C.source)if(o.a2(C.source)){const de=$.sources&&$.sources[C.source],xe=de&&o.L(de.type);de?xe==="vector"&&Z==="raster"?y.push(new o.V(R,C.source,`layer "${C.id}" requires a raster source`)):xe==="raster"&&Z!=="raster"?y.push(new o.V(R,C.source,`layer "${C.id}" requires a vector source`)):xe!=="vector"||C["source-layer"]?xe==="raster-dem"&&Z!=="hillshade"?y.push(new o.V(R,C.source,"raster-dem source can only be used with layer type 'hillshade'.")):xe!=="raster-array"||["raster","raster-particle"].includes(Z)?Z==="line"&&C.paint&&(C.paint["line-gradient"]||C.paint["line-trim-offset"])&&xe==="geojson"&&!de.lineMetrics?y.push(new o.V(R,C,`layer "${C.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):Z==="raster-particle"&&xe!=="raster-array"&&y.push(new o.V(R,C.source,`layer "${C.id}" requires a 'raster-array' source.`)):y.push(new o.V(R,C.source,"raster-array source can only be used with layer type 'raster'.")):y.push(new o.V(R,C,`layer "${C.id}" must specify a "source-layer"`)):y.push(new o.V(R,C.source,`source "${C.source}" not found`))}else y.push(new o.V(`${R}.source`,C.source,'"source" must be a string'));else y.push(new o.V(R,C,'missing required property "source"'));return y=y.concat(Jn({key:R,value:C,valueSpec:G.layer,style:I.style,styleSpec:I.styleSpec,objectElementValidators:{"*":()=>[],type:()=>Lr({key:`${R}.type`,value:C.type,valueSpec:G.layer.type,style:I.style,styleSpec:I.styleSpec,object:C,objectKey:"type"}),filter:de=>Ms(Object.assign({layerType:Z},de)),layout:de=>Jn({layer:C,key:de.key,value:de.value,valueSpec:{},style:de.style,styleSpec:de.styleSpec,objectElementValidators:{"*":xe=>As(Object.assign({layerType:Z},xe))}}),paint:de=>Jn({layer:C,key:de.key,value:de.value,valueSpec:{},style:de.style,styleSpec:de.styleSpec,objectElementValidators:{"*":xe=>Cs(Object.assign({layerType:Z,layer:C},xe))}}),appearances(de){const xe=Fs({key:de.key,value:de.value,valueSpec:de.valueSpec,style:de.style,styleSpec:de.styleSpec,arrayElementValidator:Le=>function(Ue){const{key:st,layer:Je,layerType:mt}=Ue,ht=o.L(Ue.value),kt=o.L(ht.name),Tt=o.L(ht.condition),xt=Jn({key:st,value:ht,valueSpec:Ue.styleSpec.appearance,style:Ue.style,styleSpec:Ue.styleSpec,objectElementValidators:{condition:es=>function(Ft){const Qt=[];return Qt.push(...Pt({key:Ft.key,value:Ft.object.condition,valueSpec:o.a8.appearance.condition,expressionContext:"appearance"})),Qt}(Object.assign({layer:Je,layerType:mt},es)),properties:es=>function(Ft){const Qt=[],{styleSpec:At,layer:Dt,layerType:Gt}=Ft,gs=At[`paint_${Gt}`],ns=At[`layout_${Gt}`],$s=Ft.object[Ft.objectKey];for(const Ps in $s){const an=Ps in gs?"paint":Ps in ns?"layout":void 0;if(!an){Qt.push(new o.V(Ft.key,Ps,`unknown property "${Ps}" for layer type "${Gt}"`));continue}const mn=Object.assign({},Ft,{key:`${Ft.key}.${Ps}`,object:$s,objectKey:Ps,layer:Dt,layerType:Gt,value:$s[Ps],valueSpec:an==="paint"?gs[Ps]:ns[Ps]});Qt.push(...Js(mn,an))}return Qt}(Object.assign({layer:Je,layerType:mt},es))}});return kt!=="hidden"&&Tt===void 0&&xt.push(new o.V(Ue.key,"name",'Appearance with name different than "hidden" must have a condition')),xt}(Object.assign({layerType:Z,layer:C},Le))}),we=Array.isArray(de.value)?de.value:[],Re=new Set;return we.forEach((Le,Ue)=>{const st=o.L(Le.name);if(st)if(Re.has(st)){const Je=o.L(C.id);xe.push(new o.V(de.key,st,`Duplicated appearance name "${st}" for layer "${Je}"`))}else Re.add(st)}),xe}}})),y}function tn({key:I,value:y}){return o.a2(y)?[]:[new o.V(I,y,`string expected, ${o.M(y)} found`)]}const er={promoteId:function I({key:y,value:C}){if(o.a2(C))return tn({key:y,value:C});if(Array.isArray(C)){const $=[],G=o.W(C),Z=o.X(G);return Z.result==="error"?(Z.value.forEach(te=>{$.push(new o.V(`${y}${te.key}`,null,`${te.message}`))}),$):(o.Z(Z.value.expression,["zoom","heatmap-density","line-progress","raster-value","sky-radial-progress","accumulated","is-supported-script","pitch","distance-from-center","measure-light","raster-particle-speed"])||$.push(new o.V(`${y}`,null,"promoteId expression should be only feature dependent")),$)}if(!o.K(C))return[new o.V(y,C,`string, expression or object expected, "${o.M(C)}" found`)];const R=[];for(const $ in C)R.push(...I({key:`${y}.${$}`,value:C[$]}));return R}};function gn(I){const y=I.value,C=I.key,R=I.styleSpec,$=I.style;if(!o.K(y))return[new o.V(C,y,`object expected, ${o.M(y)} found`)];if(!("type"in y))return[new o.V(C,y,'"type" is required')];const G=o.L(y.type);let Z=[];switch(["vector","raster","raster-dem","raster-array"].includes(G)&&("url"in y||"tiles"in y||Z.push(new o.a5(C,y,'Either "url" or "tiles" is required.'))),G){case"vector":case"raster":case"raster-dem":case"raster-array":return Z=Z.concat(Jn({key:C,value:y,valueSpec:R[`source_${G.replace("-","_")}`],style:I.style,styleSpec:R,objectElementValidators:er})),Z;case"geojson":if(Z=Jn({key:C,value:y,valueSpec:R.source_geojson,style:$,styleSpec:R,objectElementValidators:er}),"cluster"in y&&"clusterProperties"in y){if(!o.K(y.clusterProperties))return[new o.V(`${C}.clusterProperties`,y,`object expected, ${o.M(y)} found`)];for(const te in y.clusterProperties){const de=y.clusterProperties[te];if(!Array.isArray(de))return[new o.V(`${C}.clusterProperties.${te}`,de,"array expected")];const[xe,we]=de,Re=typeof xe=="string"?[xe,["accumulated"],["get",te]]:xe;Z.push(...Pt({key:`${C}.${te}.map`,value:we,expressionContext:"cluster-map"})),Z.push(...Pt({key:`${C}.${te}.reduce`,value:Re,expressionContext:"cluster-reduce"}))}}return Z;case"video":return Jn({key:C,value:y,valueSpec:R.source_video,style:$,styleSpec:R});case"image":return Jn({key:C,value:y,valueSpec:R.source_image,style:$,styleSpec:R});case"canvas":return[new o.V(C,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Vt({key:`${C}.type`,value:y.type,valueSpec:{values:In(R)}})}}function In(I){return I.source.reduce((y,C)=>{const R=I[C];return R.type.type==="enum"&&(y=y.concat(Object.keys(R.type.values||{}))),y},[])}function Zn(I){const y=I.value,C=I.styleSpec,R=C.light,$=I.style;if(y===void 0)return[];if(!o.K(y))return[new o.V("light",y,`object expected, ${o.M(y)} found`)];let G=[];for(const Z in y){const te=Z.match(/^(.*)-transition$/),de=Z.match(/^(.*)-use-theme$/);G=G.concat(de&&R[de[1]]?Lr({key:Z,value:y[Z],valueSpec:{type:"string"},style:$,styleSpec:C}):te&&R[te[1]]&&R[te[1]].transition?Lr({key:Z,value:y[Z],valueSpec:C.transition,style:$,styleSpec:C}):R[Z]?Lr({key:Z,value:y[Z],valueSpec:R[Z],style:$,styleSpec:C}):[new o.V(Z,y[Z],`unknown property "${Z}"`)])}return G}function ea(I){const y=I.value;if(!y)return[];const C=I.key;if(!o.K(y))return[new o.V(C,y,`object expected, ${o.M(y)} found`)];let R=[];const $=I.styleSpec,G=$["light-3d"],Z=I.style,te=I.style.lights;for(const we of["type","id"])if(!(we in y))return R=R.concat([new o.V(C,y,`missing property "${we}"`)]),R;if(!o.a2(y.type))return R=R.concat([new o.V(`${C}.type`,y.type,"string expected")]),R;if(te)for(let we=0;we[],array:Fs,boolean:function(I){const y=I.value,C=I.key;return o.a1(y)?[]:[new o.V(C,y,`boolean expected, ${o.M(y)} found`)]},number:Rs,color:function({key:I,value:y}){return o.a2(y)?o.a3.parseCSSColor(y)===null?[new o.V(I,y,`color expected, "${y}" found`)]:[]:[new o.V(I,y,`color expected, ${o.M(y)} found`)]},enum:Vt,filter:Ms,function:ms,layer:rn,object:Jn,source:gn,model:o.a9,light:Zn,"light-3d":ea,terrain:vi,fog:Ls,string:tn,formatted:function(I){return tn(I).length===0?[]:Pt(I)},resolvedImage:function(I){return tn(I).length===0?[]:Pt(I)},projection:function(I){const y=I.value,C=I.styleSpec,R=C.projection,$=I.style;if(o.K(y)){let G=[];for(const Z in y)G=G.concat(Lr({key:Z,value:y[Z],valueSpec:R[Z],style:$,styleSpec:C}));return G}return o.a2(y)?[]:[new o.V("projection",y,`object or string expected, ${o.M(y)} found`)]},import:function(I){const y=I.key,{value:C,styleSpec:R}=I;if(!o.K(C))return[new o.V(y,C,"import must be an object")];const{data:$,...G}=C;Object.defineProperty(G,"__line__",{value:C.__line__,enumerable:!1});let Z=Jn(Object.assign({},I,{value:G,valueSpec:R.import}));return o.L(G.id)===""&&Z.push(new o.V(`${I.key}.id`,G,"import id can't be an empty string")),$&&(Z=Z.concat(Dn($,R,{key:`${I.key}.data`}))),Z},iconset:function(I){const y=I.value,C=I.key,R=I.styleSpec,$=I.style;if(!o.K(y))return[new o.V(C,y,"object expected")];if(!y.type)return[new o.V(C,y,'"type" is required')];const G=o.L(y.type);let Z=[];if(Z=Z.concat(Jn({key:C,value:y,valueSpec:R[`iconset_${G}`],style:$,styleSpec:R})),function(te,de){return!(te!=="source"||!de.source)}(G,y)){const te=$.sources&&$.sources[y.source],de=te&&o.L(te.type);te?de!=="raster-array"&&Z.push(new o.V(C,y.source,`iconset cannot be used with a source of type ${String(de)}, it only be used with a "raster-array" source type`)):Z.push(new o.V(C,y.source,`source "${y.source}" not found`))}return Z}};function Lr(I,y=!1){const C=I.value,R=I.valueSpec,$=I.styleSpec;if(R.expression){if(o.a6(o.L(C)))return ms(I);if(o.U(o.W(C)))return Pt(I)}if(R.type&&fi[R.type]){const G=fi[R.type](I);return y===!0&&G.length>0&&Array.isArray(I.value)?Pt(I):G}return Jn(Object.assign({},I,{valueSpec:R.type?$[R.type]:R}))}function Jn(I){const y=I.key,C=I.value,R=I.valueSpec||{},$=I.objectElementValidators||{},G=I.style,Z=I.styleSpec;if(!o.K(C))return[new o.V(y,C,`object expected, ${o.M(C)} found`)];let te=[];for(const de in C){const xe=de.split(".")[0];let we;$[xe]?we=$[xe]:R[xe]?we=Lr:$["*"]?we=$["*"]:R["*"]&&(we=Lr),we?te=te.concat(we({key:(y&&`${y}.`)+de,value:C[de],valueSpec:R[xe]||R["*"],style:G,styleSpec:Z,object:C,objectKey:de},C)):te.push(new o.a5(y,C[de],`unknown property "${de}"`))}for(const de in R){if($[de])continue;const xe=R[de];xe.required&&xe.default===void 0&&C[de]===void 0&&te.push(new o.V(y,C,`missing required property "${de}"`))}return te}function js({key:I,value:y}){const C=tn({key:I,value:y});if(C.length)return C;const R=y;return R.indexOf("{fontstack}")===-1&&C.push(new o.V(I,y,'"glyphs" url must include a "{fontstack}" token')),R.indexOf("{range}")===-1&&C.push(new o.V(I,y,'"glyphs" url must include a "{range}" token')),C}function Dn(I,y=o.a8,C={}){return Jn({key:C.key||"",value:I,valueSpec:Object.assign(y.$root,{"*":{type:"*"}}),styleSpec:y,style:I,objectElementValidators:{glyphs:js}})}function wr(I,y=o.a8){return Gs(Dn(I,y))}const $r=I=>Gs(gn(I)),ss=I=>Gs(Zn(I)),Oe=I=>Gs(ea(I)),Xe=I=>Gs(vi(I)),ot=I=>Gs(Ls(I)),Nt=I=>Gs(function(y){const C=y.value,R=y.style,$=y.styleSpec,G=$.snow;if(C===void 0)return[];if(!o.K(C))return[new o.V("snow",C,`object expected, ${o.M(C)} found`)];let Z=[];for(const te in C){const de=te.match(/^(.*)-transition$/);Z=Z.concat(de&&G[de[1]]&&G[de[1]].transition?Lr({key:te,value:C[te],valueSpec:$.transition,style:R,styleSpec:$}):G[te]?Lr({key:te,value:C[te],valueSpec:G[te],style:R,styleSpec:$}):[new o.a5(te,C[te],`unknown property "${te}"`)])}return Z}(I)),Rt=I=>Gs(function(y){const C=y.value,R=y.style,$=y.styleSpec,G=$.rain;if(C===void 0)return[];if(!o.K(C))return[new o.V("rain",C,`object expected, ${o.M(C)} found`)];let Z=[];for(const te in C){const de=te.match(/^(.*)-transition$/);Z=Z.concat(de&&G[de[1]]&&G[de[1]].transition?Lr({key:te,value:C[te],valueSpec:$.transition,style:R,styleSpec:$}):G[te]?Lr({key:te,value:C[te],valueSpec:G[te],style:R,styleSpec:$}):[new o.a5(te,C[te],`unknown property "${te}"`)])}return Z}(I)),qt=I=>Gs(rn(I)),xs=I=>Gs(Ms(I)),rs=I=>Gs(Cs(I)),ks=I=>Gs(As(I)),ln=I=>Gs(o.a9(I));function Gs(I){return I.slice().sort((y,C)=>y.line&&C.line?y.line-C.line:0)}function Un(I,y){let C=!1;if(y&&y.length)for(const R of y)R instanceof o.a5?o.w(R.message):(I.fire(new o.B(new Error(R.message))),C=!0);return C}const jr=o.a8.light;let Sr;class nr extends o.E{constructor(y,C="flat"){super(),this._transitionable=new o.aa(Sr||(Sr=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(y,C),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(y,C,R={}){this._validate(ss,y,R)||(this._transitionable.setTransitionOrValue(y),this.id=C)}updateTransitions(y){this._transitioning=this._transitionable.transitioned(y,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(y){this.properties=this._transitioning.possiblyEvaluate(y)}_validate(y,C,R){return(!R||R.validate!==!1)&&Un(this,y.call(wr,Object.assign({value:C,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}const Ot=o.a8.terrain;let fn=class extends o.E{constructor(I,y,C,R,$){super(),this.scope=C,this._transitionable=new o.aa(new o.ab({source:new o.ac(Ot.source),exaggeration:new o.ac(Ot.exaggeration)}),C,R),this._transitionable.setTransitionOrValue(I,R),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=y,this.worldview=$}get(){return this._transitionable.serialize()}set(I,y){this._transitionable.setTransitionOrValue(I,y)}updateTransitions(I){this._transitioning=this._transitionable.transitioned(I,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(I){this.properties=this._transitioning.possiblyEvaluate(I)}getExaggeration(I){return this._transitioning.possiblyEvaluate(new o.ae(I,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const I=this._transitionable._values.exaggeration;if(!I)return null;const y=I.value.expression;if(!y)return null;let C=-1,R=-1,$=1;for(const G of y.zoomStops)$=y.evaluate(new o.ae(G,{worldview:this.worldview})),$>.01?(C=G,R=-1):R=G;return $<.01&&C>0&&R>C?[C,R]:null}isZoomDependent(){const I=this._transitionable._values.exaggeration;return I!=null&&I.value!=null&&I.value.expression!=null&&I.value.expression instanceof o.af}};const sr=.05;function Hn(I,y,C,R){const $=o.aj(45,65,C),[G,Z]=ta(I,R);let te=1-Math.min(1,Math.exp((y-G)/(Z-G)*-6));return te*=te*te,te=Math.min(1,1.00747*te),te*$*I.alpha}function ta(I,y){const C=.5/Math.tan(.5*y);return[I.range[0]+C,I.range[1]+C]}function Zr(I,y,C,R,$){const G=o.ah([],[y,C,R],$.mercatorFogMatrix);return Hn(I,o.ai(G),$.pitch,$._fov)}function ur(I,y,C,R,$,G,Z){const te=[[C,R,0],[$,R,0],[$,G,0],[C,G,0]];let de=Number.MAX_VALUE,xe=-Number.MAX_VALUE;for(const we of te){const Re=o.ah([],we,y),Le=o.ai(Re);de=Math.min(de,Le),xe=Math.max(xe,Le)}return[Hn(I,de,Z.pitch,Z._fov),Hn(I,xe,Z.pitch,Z._fov)]}const Mr=o.a8.fog;class zi extends o.E{constructor(y,C,R,$){super();const G=new o.ab({range:new o.ac(Mr.range),color:new o.ac(Mr.color),"color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"high-color":new o.ac(Mr["high-color"]),"high-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"space-color":new o.ac(Mr["space-color"]),"space-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new o.ac(Mr["horizon-blend"]),"star-intensity":new o.ac(Mr["star-intensity"]),"vertical-range":new o.ac(Mr["vertical-range"])});this._transitionable=new o.aa(G,R,new Map($)),this.set(y,$),this._transitioning=this._transitionable.untransitioned(),this._transform=C,this.properties=new o.ak(G),this.scope=R}get state(){const y=this._transform,C=y.projection.name==="globe",R=o.al(y.zoom),$=this.properties.get("range"),G=[.5,3];return{range:C?[o.am(G[0],$[0],R),o.am(G[1],$[1],R)]:$,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(y,C,R={}){if(this._validate(ot,y,R))return;const $=Object.assign({},y);for(const G of Object.keys(Mr))$[G]===void 0&&($[G]=Mr[G].default);this._options=$,this._transitionable.setTransitionOrValue(this._options,C)}getOpacity(y){if(!this._transform.projection.supportsFog)return 0;const C=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:o.aj(45,65,y))*C.a}getOpacityAtLatLng(y,C){return this._transform.projection.supportsFog?function(R,$,G){const Z=o.ag.fromLngLat($),te=G.elevation?G.elevation.getAtPointOrZero(Z):0;return Zr(R,Z.x,Z.y,te,G)}(this.state,y,C):0}getOpacityForTile(y){if(!this._transform.projection.supportsFog)return[1,1];const C=this._transform.calculateFogTileMatrix(y.toUnwrapped());return ur(this.state,C,0,0,o.an,o.an,this._transform)}getOpacityForBounds(y,C,R,$,G){return this._transform.projection.supportsFog?ur(this.state,y,C,R,$,G,this._transform):[1,1]}getFovAdjustedRange(y){return this._transform.projection.supportsFog?ta(this.state,y):[0,1]}isVisibleOnFrustum(y){if(!this._transform.projection.supportsFog)return!1;const C=[4,5,6,7];for(const R of C){const $=y.points[R];let G;if($[2]>=0)G=$;else{const Z=y.points[R-4];G=o.ao(Z,$,Z[2]/(Z[2]-$[2]))}if(Zr(this.state,G[0],G[1],0,this._transform)>=sr)return!0}return!1}updateConfig(y){this._transitionable.setTransitionOrValue(this._options,new Map(y))}updateTransitions(y){this._transitioning=this._transitionable.transitioned(y,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(y){this.properties=this._transitioning.possiblyEvaluate(y)}_validate(y,C,R){return(!R||R.validate!==!1)&&Un(this,y.call(wr,Object.assign({value:C,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}let Bi,Za,_i,qi=class extends o.E{constructor(I,y,C,R){super();const $=Bi||(Bi=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($,C,new Map(R)),this.set(I,R),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak($),this.scope=C}get state(){const I=this.properties.get("opacity"),y=this.properties.get("color"),C=this.properties.get("direction"),R=o.ap(C[0]),$=-Math.max(o.ap(C[1]),.01),G=[Math.cos(R)*Math.cos($),Math.sin(R)*Math.cos($),Math.sin($)],Z=this.properties.get("vignette"),te=this.properties.get("vignette-color");return te.a=Z,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(y.r,y.g,y.b,y.a*I),direction:G,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:te}}get(){return this._transitionable.serialize()}set(I,y,C={}){if(this._validate(Nt,I,C))return;const R=Object.assign({},I),$=o.a8.snow;for(const G of Object.keys($))R[G]===void 0&&(R[G]=$[G].default);this._options=R,this._transitionable.setTransitionOrValue(this._options,y)}updateConfig(I){this._transitionable.setTransitionOrValue(this._options,new Map(I))}updateTransitions(I){this._transitioning=this._transitionable.transitioned(I,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(I){this.properties=this._transitioning.possiblyEvaluate(I)}_validate(I,y,C){return(!C||C.validate!==!1)&&Un(this,I.call(wr,Object.assign({value:y,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}},ga=class extends o.E{constructor(I,y,C,R){super();const $=Za||(Za=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($,C,new Map(R)),this.set(I,R),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak($),this.scope=C}get state(){const I=this.properties.get("opacity"),y=this.properties.get("color"),C=this.properties.get("direction"),R=o.ap(C[0]),$=-Math.max(o.ap(C[1]),.01),G=[Math.cos(R)*Math.cos($),Math.sin(R)*Math.cos($),Math.sin($)],Z=this.properties.get("vignette-color");return Z.a=this.properties.get("vignette"),{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(y.r,y.g,y.b,y.a*I),direction:G,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:Z}}get(){return this._transitionable.serialize()}set(I,y,C={}){if(this._validate(Rt,I,C))return;const R=Object.assign({},I),$=o.a8.rain;for(const G of Object.keys($))R[G]===void 0&&(R[G]=$[G].default);this._options=R,this._transitionable.setTransitionOrValue(this._options,y)}updateConfig(I){this._transitionable.setTransitionOrValue(this._options,new Map(I))}updateTransitions(I){this._transitioning=this._transitionable.transitioned(I,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(I){this.properties=this._transitioning.possiblyEvaluate(I)}_validate(I,y,C){return(!C||C.validate!==!1)&&Un(this,I.call(wr,Object.assign({value:y,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}};class wn extends o.E{constructor(y,C,R,$){super(),this.scope=R,this._options=y,this.properties=new o.ak(C),this._transitionable=new o.aa(C,R,new Map($)),this._transitionable.setTransitionOrValue(y.properties),this._transitioning=this._transitionable.untransitioned()}updateConfig(y){this._transitionable.setTransitionOrValue(this._options.properties,new Map(y))}updateTransitions(y){this._transitioning=this._transitionable.transitioned(y,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(y){this.properties=this._transitioning.possiblyEvaluate(y)}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(y,C){this._options=y,this._transitionable.setTransitionOrValue(y.properties,C)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}const Ta=()=>_i||(_i=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 Yi;const zo=()=>Yi||(Yi=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 rl{constructor(y,C,R){this.screenBounds=y,this.cameraPoint=R.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=C,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,R)}static createFromScreenPoints(y,C){let R,$;if(y instanceof o.P||typeof y[0]=="number"){const G=o.P.convert(y);R=[G],$=C.isPointAboveHorizon(G)}else{const G=o.P.convert(y[0]),Z=o.P.convert(y[1]),te=G.add(Z)._div(2);R=[G,Z],$=o.as(G,Z).every(de=>C.isPointAboveHorizon(de))&&C.isPointAboveHorizon(te)}return new rl(R,$,C)}isPointQuery(){return this.screenBounds.length===1}bufferedScreenGeometry(y){return o.as(this.screenBounds[0],this.screenBounds.length===1?this.screenBounds[0]:this.screenBounds[1],y)}bufferedCameraGeometry(y){const C=this.screenBounds[0],R=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],$=o.as(C,R,0,!1);return this.cameraPoint.y>R.y&&(this.cameraPoint.x>C.x&&this.cameraPoint.x=R.x?$[2]=this.cameraPoint:this.cameraPoint.x<=C.x&&($[3]=this.cameraPoint)),o.at($,y)}bufferedCameraGeometryGlobe(y){const C=this.screenBounds[0],R=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],$=o.as(C,R,y),G=this.cameraPoint.clone(),Z=+(G.x>C.x)+ +(G.x>R.x);switch(3*(+(G.y>C.y)+ +(G.y>R.y))+Z){case 0:$[0]=G,$[4]=G.clone();break;case 1:$.splice(1,0,G);break;case 2:$[1]=G;break;case 3:$.splice(4,0,G);break;case 5:$.splice(2,0,G);break;case 6:$[3]=G;break;case 7:$.splice(3,0,G);break;case 8:$[2]=G}return $}containsTile(y,C,R,$=0){const G=Math.max(y.queryPadding,y.evaluateQueryRenderedFeaturePadding())/C._pixelsPerMercatorPixel+1,Z=R?this._bufferedCameraMercator(G,C):this._bufferedScreenMercator(G,C);let te=y.tileID.wrap+(Z.unwrapped?$:0);const de=Z.polygon.map(mt=>o.au(y.tileTransform,mt,te));if(!o.av(de,0,0,o.an,o.an))return;te=y.tileID.wrap+(this.screenGeometryMercator.unwrapped?$:0);const xe=this.screenGeometryMercator.polygon.map(mt=>o.aw(y.tileTransform,mt,te)),we=xe.map(mt=>new o.P(mt[0],mt[1])),Re=C.getFreeCameraOptions().position||new o.ag(0,0,0),Le=o.aw(y.tileTransform,Re,te),Ue=xe.map(mt=>{const ht=o.ax(mt,mt,Le);return o.ay(ht,ht),new o.az(Le,ht)}),st=o.aA(y,1,C.zoom)*C._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:we,tilespaceRays:Ue,bufferedTilespaceGeometry:de,bufferedTilespaceBounds:(Je=o.aB(de),Je.min.x=o.aC(Je.min.x,0,o.an),Je.min.y=o.aC(Je.min.y,0,o.an),Je.max.x=o.aC(Je.max.x,0,o.an),Je.max.y=o.aC(Je.max.y,0,o.an),Je),tile:y,tileID:y.tileID,pixelToTileUnitsFactor:st};var Je}_bufferedScreenMercator(y,C){const R=hc(y);if(this._screenRaycastCache[R])return this._screenRaycastCache[R];{let $;return $=C.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(y),C):{polygon:this.bufferedScreenGeometry(y).map(G=>C.pointCoordinate3D(G)),unwrapped:!0},this._screenRaycastCache[R]=$,$}}_bufferedCameraMercator(y,C){const R=hc(y);if(this._cameraRaycastCache[R])return this._cameraRaycastCache[R];{let $;return $=C.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(y),C):{polygon:this.bufferedCameraGeometry(y).map(G=>C.pointCoordinate3D(G)),unwrapped:!0},this._cameraRaycastCache[R]=$,$}}_projectAndResample(y,C){const R=function(G,Z){const te=o.aD([],Z.pixelMatrix,Z.globeMatrix),de=[0,-o.aF,0,1],xe=[0,o.aF,0,1],we=[0,0,0,1];o.aE(de,de,te),o.aE(xe,xe,te),o.aE(we,we,te);const Re=new o.P(de[0]/de[3],de[1]/de[3]),Le=new o.P(xe[0]/xe[3],xe[1]/xe[3]),Ue=o.aG(G,Re)&&de[3]1?po(G.slice(0,mt),Z):[],Tt=mtnew o.P(uc(Qt.x),Qt.y)),Tt=Tt.map(Qt=>new o.P(uc(Qt.x),Qt.y));const xt=[...kt];xt.length===0&&xt.push(Tt[Tt.length-1]);const es=o.am(xt[xt.length-1].y,(Tt.length===0?kt[0]:Tt[0]).y,ht);let Ft;return Ft=Ue?[new o.P(0,es),new o.P(0,0),new o.P(1,0),new o.P(1,es)]:[new o.P(1,es),new o.P(1,1),new o.P(0,1),new o.P(0,es)],xt.push(...Ft),Tt.length===0?xt.push(kt[0]):xt.push(...Tt),{polygon:xt.map(Qt=>new o.ag(Qt.x,Qt.y)),unwrapped:!1}}(y,C);if(R)return R;const $=function(G,Z){let te=!1,de=-1/0,xe=0;for(let Re=0;Rede&&(de=G[Re].x,xe=Re);for(let Re=0;Re.5&&(Ue.x{Re.x-=1}),{polygon:G,unwrapped:te}}(po(y,C).map(G=>new o.P(uc(G.x),G.y)),C);return{polygon:$.polygon.map(G=>new o.ag(G.x,G.y)),unwrapped:$.unwrapped}}}function po(I,y){return o.aI(I,C=>{const R=y.pointCoordinate3D(C);C.x=R.x,C.y=R.y},1/256)}function uc(I){return I<0?1+I%1:I%1}function hc(I){return 100*I|0}function Tf(I,y,C){try{y=function($){if(!$.variants)return $;if(!Array.isArray($.variants))throw new Error("variants must be an array");for(const G of $.variants){if(G==null||typeof G!="object"||G.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(G.capabilities))throw new Error("capabilities must be an array");if(G.capabilities.length===1&&G.capabilities[0]==="meshopt")return Object.assign($,G)}return $}(y)}catch($){return new Error("Failed to process TileJSON variants",{cause:$})}const R=o.aJ(Object.assign({},y,I),["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);return I.url&&y.tiles&&I.tiles&&(R.tiles=y.tiles),R.tiles=C.canonicalizeTileset(R,I.url),R}function Hu(I,y,C,R,$){const G=function(te,de){if(te)return $(te);if(de){I.url&&de.tiles&&I.tiles&&delete I.tiles;const xe=Tf(I,de,y);if(xe instanceof Error)return $(xe);$(null,xe)}},Z=function(te,de,xe){if(!te)return null;if(!de&&!xe)return te;xe=xe||te.worldview_default;const we=Object.values(te.language||{});if(we.length===0)return null;const Re=Object.values(te.worldview||{});if(Re.length===0)return null;const Le=we.every(st=>st===de),Ue=Re.every(st=>st===xe);return Le&&Ue?te:de in(te.language_options||{})||xe in(te.worldview_options||{})?null:te.language_options&&te.worldview_options?te:null}(I.data,C,R);return Z?o.o.frame(()=>G(null,Z)):I.url?o.m(y.transformRequest(y.normalizeSourceURL(I.url,null,C,R),o.R.Source),G):o.o.frame(()=>{const{data:te,...de}=I;G(null,de)})}function pm(I,y){const C=Math.pow(2,y.z),R=Math.floor(o.aH(I.getWest())*C),$=Math.floor(o.aL(I.getNorth())*C),G=Math.ceil(o.aH(I.getEast())*C),Z=Math.ceil(o.aL(I.getSouth())*C);return y.x>=R&&y.x=$&&y.ythis.maxzoom||y.z{this._tileJSONRequest=null,this._loaded=!0,Z?(C&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${C}`),R&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${R}`),this.fire(new o.B(Z))):te&&(this._setTileJSON(te),Te(te.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"}))),y&&y(Z)};this.provider=this._options.provider;const G=function(Z){if("provider"in Z&&!Z.provider)return null;let te=Z.provider;if(!te&&"url"in Z&&Z.url&&(te=o.aM(Z.url)),!te)return null;const de=o.g.TILE_PROVIDER_URLS[te];if(!de)return null;let xe;try{xe=new URL(de,o.g.API_URL).href}catch{return o.w(`TileProvider "${te}" has an invalid URL: "${de}"`),null}return{name:te,url:xe}}(this._options);if(this.provider&&!G)return this._loaded=!0,this.fire(new o.B(new Error(`TileProvider "${this.provider}" is not registered`))),void(y&&y());this._tileJSONRequest=G?this._loadWithProvider(G,$):Hu(this._options,this.map._requestManager,C,R,$)}_loadWithProvider(y,C){this.provider=y.name;const R=new AbortController,$=this._options.url&&!this._options.tiles?this.map._requestManager.transformRequest(this._options.url,o.R.Source):void 0,G=$?Object.assign({},this._options,{url:$.url}):this._options;return this.dispatcher.broadcast("loadTileProvider",{name:y.name,url:y.url,source:this.id,scope:this.scope,type:this.type,options:G,request:$},(Z,te)=>{if(R.signal.aborted)return;if(Z)return void C(Z);const de=te?te.find(xe=>xe!=null):null;if(de){const xe=Tf(this._options,de,this.map._requestManager);xe instanceof Error?C(xe):C(null,xe)}else C(null,{tiles:this._options.tiles})}),{cancel:()=>{R.abort()}}}_setTileJSON(y){if(Object.assign(this,y),this.hasWorldviews=!!y.worldview_options,y.worldview_default&&(this.worldviewDefault=y.worldview_default),y.vector_layers){this.vectorLayers=y.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const C of y.vector_layers)this.vectorLayerIds.push(C.id),y.worldview&&y.worldview[C.source]&&this.localizableLayerIds.add(C.id)}this.tileBounds=Gu.fromTileJSON(y)}loaded(){return this._loaded}hasTile(y){return!this.tileBounds||this.tileBounds.contains(y.canonical)}onAdd(y){this.map=y,this.load()}reload(){this.cancelTileJSONRequest();const y=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(y))}setTiles(y){return this._options.tiles=y,this.reload(),this}setUrl(y){return this.url=y,this._options.url=y,this.reload(),this}onRemove(y){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}loadTile(y,C){const R=y.tileID.canonical.url(this.tiles,this.scheme),$=this.map._requestManager.normalizeTileURL(R),G=this.map._requestManager.transformRequest($,o.R.Tile),Z=this.map.style?this.map.style.getLut(this.scope):null,te=Z?{image:Z.image.clone()}:null,de={request:G,data:void 0,uid:y.uid,tileID:y.tileID,tileZoom:y.tileZoom,zoom:y.tileID.overscaledZ,maxZoom:this.maxzoom,lut:te,tileSize:this.tileSize*y.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,renderSourceType:y.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:y.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(R)&&(de.localizableLayerIds=this.localizableLayerIds),de.request.collectResourceTiming=this._collectResourceTiming,y.actor&&y.state!=="expired")y.state==="loading"?y.reloadCallback=C:y.request=y.actor.send("reloadTile",de,xe.bind(this));else if(y.actor=this._tileWorkers[$]=this._tileWorkers[$]||this.dispatcher.getActor(),this.dispatcher.ready||this.provider)y.request=y.actor.send("loadTile",de,xe.bind(this),void 0,!0);else{const we=o.aO.call({deduped:this._deduped},de,(Re,Le)=>{if(Re||!Le)xe.call(this,Re);else{const Ue=o.aP(Le.responseHeaders);de.data={rawData:Le.rawData.slice(0),expires:Ue.expires,cacheControl:Ue.cacheControl},y.actor&&y.actor.send("loadTile",de,xe.bind(this),void 0,!0)}},!0);y.request={cancel:we}}function xe(we,Re){return delete y.request,y.aborted?C(null):we?C(we):(Re&&Re.resourceTiming&&(y.resourceTiming=Re.resourceTiming),this.map._refreshExpiredTiles&&Re&&y.setExpiryData(Re),y.loadVectorData(Re,this.map.painter),o.aQ(this.dispatcher),C(null,Re),void(y.reloadCallback&&(this.loadTile(y,y.reloadCallback),y.reloadCallback=null)))}}abortTile(y){y.request&&(y.request.cancel(),delete y.request),y.actor&&y.actor.send("abortTile",{uid:y.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(y,C){y.actor&&y.actor.send("removeTile",{uid:y.uid,type:this.type,source:this.id,scope:this.scope}),y.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}class a1 extends o.E{constructor(y,C,R,$){super(),this.id=y,this.dispatcher=R,this.setEventedParent($),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=Object.assign({type:"raster"},C),Object.assign(this,o.aJ(C,["url","scheme","tileSize"]))}load(y){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const C=this.map.getWorldview();this._tileJSONRequest=Hu(this._options,this.map._requestManager,null,C,(R,$)=>{this._tileJSONRequest=null,this._loaded=!0,R?this.fire(new o.B(R)):$&&(Object.assign(this,$),$.raster_layers&&(this.rasterLayers=$.raster_layers,this.rasterLayerIds=this.rasterLayers.map(G=>G.id)),this.tileBounds=Gu.fromTileJSON($),Te($.tiles),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),y&&y(R)})}loaded(){return this._loaded}onAdd(y){this.map=y,this.load()}reload(){this.cancelTileJSONRequest();const y=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(y))}setTiles(y){return this._options.tiles=y,this.reload(),this}setUrl(y){return this.url=y,this._options.url=y,this.reload(),this}onRemove(y){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}hasTile(y){return!this.tileBounds||this.tileBounds.contains(y.canonical)}loadTile(y,C){const R=o.o.devicePixelRatio>=2,$=this.map._requestManager.normalizeTileURL(y.tileID.canonical.url(this.tiles,this.scheme),R,this.tileSize);y.request=o.n(this.map._requestManager.transformRequest($,o.R.Tile),(G,Z,te)=>{if(delete y.request,y.aborted)return y.state="unloaded",C(null);if(G)return y.state="errored",C(G);if(!Z)return C(null);const de=o.aP(te);this.map._refreshExpiredTiles&&y.setExpiryData(de),y.setTexture(Z,this.map.painter),y.state="loaded",o.aQ(this.dispatcher),C(null)})}abortTile(y,C){y.request&&(y.request.cancel(),delete y.request),C&&C()}unloadTile(y,C){y.texture&&y.texture instanceof o.T?(y.destroy(!1),y.texture&&y.texture instanceof o.T&&this.map.painter.saveTileTexture(y.texture)):y.destroy(),C&&C()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function oj([I,y],C,R,{scaled:$=!0}={}){const{tileSize:G,buffer:Z}=R,{x:te,y:de,z:xe}=C;if(!isFinite(te)||!isFinite(de)||!isFinite(xe))throw new Error("Invalid MRT header");const we=2**xe,Re=we*o.aH(I),Le=we*o.aL(y);return function([Ue,st],Je,{scaled:mt=!0}={}){if(!Je)throw new Error("bandView is undefined");const{data:ht,tileSize:kt,buffer:Tt,offset:xt,scale:es,dimension:Ft}=Je;if(Ue<-Tt||Ue>kt+Tt||st<-Tt||st>kt+Tt)throw new Error(`Point (${Ue}, ${st}) out of bounds for tileSize=${kt}, buffer=${Tt}`);const Qt=(st+Tt)*(kt+2*Tt)+(Ue+Tt);if(new Uint32Array(ht.buffer)[Qt]===4294967295)return null;let At=[];At=mt?[]:new Je.data.constructor(Ft);for(let Dt=0;Dt{if(delete y.request,y.aborted)return y.state="unloaded",C(null);if(te)return te.name==="AbortError"?void 0:(y.state="errored",C(te));if(this.map._refreshExpiredTiles&&de){const we=o.aP(xe);y.setExpiryData(we)}if(this.partial&&y.state!=="expired")y.state="empty";else if(!this.partial){if(!de)return C(null);y.state="loaded",y._isHeaderLoaded=!0,y._mrt=de}C(null)};y.request=this.partial?y.fetchHeader(void 0,Z.bind(this)):y.actor.send("loadTile",G,Z.bind(this),void 0,!0)}abortTile(y){y.request&&(y.request.cancel(),delete y.request),y.actor&&y.actor.send("abortTile",{uid:y.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(y,C){const R=y.texturePerLayer;if(y.flushAllQueues(),R.size){y.destroy(!1);for(const $ of R.values())this.map.painter.saveTileTexture($)}else y.destroy()}prepareTile(y,C,R,$){y._isHeaderLoaded&&(y.state!=="empty"&&(y.state="reloading"),y.fetchBandForRender(C,R,$,(G,Z)=>{G?(y.state="errored",this.fire(new o.B(G))):Z&&(y._isHeaderLoaded=!0,y.setTexturePerLayer(R,Z,this.map.painter),y.state="loaded"),this.triggerRepaint(y)}))}getInitialBand(y){if(!this.rasterLayers)return 0;const C=this.rasterLayers.find(({id:G})=>G===y),R=C&&C.fields,$=R&&R.bands&&R.bands;return $?$[0]:0}getTextureDescriptor(y,C,R){if(!y)return;const $=C.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!$)return;let G=null;C instanceof o.aS?G=C.paint.get("raster-array-band"):C instanceof o.aT&&(G=C.paint.get("raster-particle-array-band"));const Z=G||this.getInitialBand($);if(Z==null)return;if(!y.textureDescriptorPerLayer.get(C.id))return void this.prepareTile(y,$,C.id,Z);if(y.updateNeeded(C.id,Z)&&!R)return;const te=y.textureDescriptorPerLayer.get(C.id);return Object.assign({},te,{texture:y.texturePerLayer.get(C.id)})}getImages(y,C){const R=new Map;for(const $ of y)for(const G of C){const[Z,te]=G.split("/"),de=$.getLayer(Z);if(!de||!de.hasBand(te)||!de.hasDataForBand(te))continue;const{bytes:xe,tileSize:we,buffer:Re}=de.getBandView(te),Le=we+2*Re,Ue={data:new o.q({width:Le,height:Le},xe),pixelRatio:2,sdf:!1,usvg:!1,version:0};R.set(G,Ue)}return R}queryRasterArrayValueByBandId(y,C,R){const $=C._mrt;return new Promise(G=>{const Z={},te=new Set;for(const[de,xe]of Object.entries($.layers)){if(R.layerName&&de!==R.layerName)continue;const we={};Z[de]=we;for(const{bands:Re}of xe.dataIndex)for(const Le of Re)R.bands&&!R.bands.includes(Le)||(te.add(o.F(de,Le)),C.fetchBand(de,null,Le,Ue=>{o.o.frame(()=>{we[Le]=Ue?null:oj([y.lng,y.lat],$,xe.getBandView(Le)),te.delete(o.F(de,Le)),te.size===0&&G(Z)})},!1))}te.size===0&&G(Z)})}_loadTileForQuery(y,C){if(this._loadTileLoaded[y.uid])return void C(null,y._mrt);if(this._loadTilePending[y.uid])return void this._loadTilePending[y.uid].push(C);this._loadTilePending[y.uid]=[C];const R=this.map._requestManager.normalizeTileURL(y.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),$=this.map._requestManager.transformRequest(R,o.R.Tile);y.actor.send("loadTile",{request:$,uid:y.uid,tileID:y.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(G,Z,te)=>{if(G)return this._loadTilePending[y.uid].forEach(de=>de(G,null)),void delete this._loadTilePending[y.uid];if(!Z)return this._loadTilePending[y.uid].forEach(de=>de(null,null)),void delete this._loadTilePending[y.uid];if(this.map._refreshExpiredTiles&&Z){const de=o.aP(te);y.setExpiryData(de)}y._mrt=Z,y._isHeaderLoaded=!0,y.state="loaded",this._loadTilePending[y.uid].forEach(de=>de(null,Z)),this._loadTileLoaded[y.uid]=!0,delete this._loadTilePending[y.uid]},void 0,!0)}queryRasterArrayValueByAllBands(y,C,R){return new Promise(($,G)=>{this._loadTileForQuery(C,(Z,te)=>{Z?G(Z):$(te?this.queryRasterArrayValueByBandId(y,C,R):null)})})}queryRasterArrayValue(y,C){const R=o.aU.convert(y),$=this.findLoadedParent(R);return $&&$._mrt?C.bands||!this.partial?this.queryRasterArrayValueByBandId(R,$,C):this.queryRasterArrayValueByAllBands(R,$,C):Promise.resolve(null)}findLoadedParent(y){const C=o.ag.fromLngLat(y,this.map.transform.tileSize),R=this.maxzoom+1,$=1<0&&(te[new o.aR(I.overscaledZ,$,y.z,R,y.y-1).key]={backfilled:!1},te[new o.aR(I.overscaledZ,I.wrap,y.z,y.x,y.y-1).key]={backfilled:!1},te[new o.aR(I.overscaledZ,Z,y.z,G,y.y-1).key]={backfilled:!1}),y.y+1{if(this._loaded=!0,this._pendingLoad=null,R)this.fire(new o.B(R));else{const G={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&$&&$.resourceTiming&&$.resourceTiming[this.id]&&(G.resourceTiming=$.resourceTiming[this.id]),I&&(this._partialReload=!0),this.fire(new o.C("data",G)),this._partialReload=!1,this._metadataFired=!0}this._coalesce&&(this._updateWorkerData(I),this._coalesce=!1)})}loaded(){return this._loaded}reload(){const I=o.F(this.id,this.scope);this.map.style.clearSource(I),this._updateWorkerData()}loadTile(I,y){const C=I.actor?"reloadTile":"loadTile";I.actor=this.actor;const R=this.map.style?this.map.style.getLut(this.scope):null,$=R?{image:R.image.clone()}:null,G=this._partialReload,Z={type:this.type,uid:I.uid,tileID:I.tileID,tileZoom:I.tileZoom,zoom:I.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:$,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:I.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:G,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};I.request=this.actor.send(C,Z,(te,de)=>G&&!de?(I.state="loaded",y(null)):(delete I.request,I.destroy(!1),I.aborted?y(null):te?y(te):(I.loadVectorData(de,this.map.painter,C==="reloadTile"),y(null))),void 0,C==="loadTile")}abortTile(I){I.request&&(I.request.cancel(),delete I.request),I.aborted=!0}unloadTile(I,y){this.actor.send("removeTile",{uid:I.uid,type:this.type,source:this.id,scope:this.scope}),I.destroy()}onRemove(I){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(I,y,C,R){super(I,y,C,R),this.roundZoom=!0,this.type="video",this.options=y}load(){this._loaded=!1;const I=this.options;this.urls=[];for(const y of I.urls)this.urls.push(this.map._requestManager.transformRequest(y,o.R.Source).url);o.aW(this.urls,(y,C)=>{this._loaded=!0,y?this.fire(new o.B(y)):C&&(this.video=C,this.video.loop=!0,this.video.setAttribute("playsinline",""),this.video.addEventListener("playing",()=>{this.map.triggerRepaint()}),this.map&&this.video.play(),this._finishLoading())})}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(I){if(this.video){const y=this.video.seekable;Iy.end(0)?this.fire(new o.B(new o.V(`sources.${this.id}`,null,`Playback for this video can be set only between the ${y.start(0)} and ${y.end(0)}-second mark.`))):this.video.currentTime=I}}getVideo(){return this.video}onAdd(I){this.map||(this.map=I,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 I=this.map.painter.context,y=I.gl;this.texture?this.video.paused||(this.texture.bind(y.LINEAR,y.CLAMP_TO_EDGE),y.texSubImage2D(y.TEXTURE_2D,0,0,0,y.RGBA,y.UNSIGNED_BYTE,this.video)):(this.texture=new o.T(I,this.video,y.RGBA8),this.texture.bind(y.LINEAR,y.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(I)}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(I,y,C,R){super(),this.type="batched-model",this.id=I,this.tileSize=512,this._options=y,this.tiles=this._options.tiles,this.maxzoom=y.maxzoom||19,this.minzoom=y.minzoom||0,this.roundZoom=!0,this.usedInConflation=!0,this.dispatcher=C,this.reparseOverscaled=!1,this.scheme="xyz",this._loaded=!1,this.setEventedParent(R)}onAdd(I){this.map=I,this.load()}reload(){this.cancelTileJSONRequest();const I=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(I))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(I){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const y=Array.isArray(this.map._language)?this.map._language.join():this.map._language,C=this.map.getWorldview();this._tileJSONRequest=Hu(this._options,this.map._requestManager,y,C,(R,$)=>{this._tileJSONRequest=null,this._loaded=!0,R?(y&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${y}`),C&&C.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${C}`),this.fire(new o.B(R))):$&&(Object.assign(this,$),$.bounds&&(this.tileBounds=new Gu($.bounds,this.minzoom,this.maxzoom)),Te($.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"}))),I&&I(R)})}hasTransition(){return!1}hasTile(I){return!this.tileBounds||this.tileBounds.contains(I.canonical)}loaded(){return this._loaded}loadTile(I,y){const C=this.map._requestManager.normalizeTileURL(I.tileID.canonical.url(this.tiles,this.scheme)),R={request:this.map._requestManager.transformRequest(C,o.R.Tile),data:void 0,uid:I.uid,tileID:I.tileID,tileZoom:I.tileZoom,zoom:I.tileID.overscaledZ,tileSize:this.tileSize*I.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:I.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:o.o.devicePixelRatio,promoteId:this.promoteId};if(I.actor&&I.state!=="expired")if(I.state==="loading")I.reloadCallback=y;else{if(I.buckets){const G=Object.values(I.buckets);for(const Z of G)Z.dirty=!0;return void(I.state="loaded")}I.request=I.actor.send("reloadTile",R,$.bind(this))}else I.actor=this.dispatcher.getActor(),I.request=I.actor.send("loadTile",R,$.bind(this),void 0,!0);function $(G,Z){return I.aborted?y(null):G&&G.status!==404?y(G):(this.map._refreshExpiredTiles&&Z&&I.setExpiryData(Z),I.loadModelData(Z,this.map.painter),I.state="loaded",void y(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends o.aV{constructor(I,y,C,R){super(I,y,C,R),y.coordinates?Array.isArray(y.coordinates)&&y.coordinates.length===4&&!y.coordinates.some($=>!Array.isArray($)||$.length!==2||$.some(G=>typeof G!="number"))||this.fire(new o.B(new o.V(`sources.${I}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new o.B(new o.V(`sources.${I}`,null,'missing required property "coordinates"'))),y.animate&&typeof y.animate!="boolean"&&this.fire(new o.B(new o.V(`sources.${I}`,null,'optional "animate" property must be a boolean value'))),y.canvas?typeof y.canvas=="string"||y.canvas instanceof HTMLCanvasElement||this.fire(new o.B(new o.V(`sources.${I}`,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.${I}`,null,'missing required property "canvas"'))),this.options=y,this.animate=y.animate===void 0||y.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(I){this.map=I,this.load(),this.canvas&&this.animate&&this.play()}onRemove(I){this.pause()}prepare(){let I=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,I=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,I=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const y=this.map.painter.context;this.texture?!I&&!this._playing||this.texture instanceof o.aX||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new o.T(y,this.canvas,y.gl.RGBA8,{premultiply:!0}),this._prepareData(y)}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const I of[this.canvas.width,this.canvas.height])if(isNaN(I)||I<=0)return!0;return!1}},custom:class extends o.E{constructor(I,y,C,R){super(),this.id=I,this.type="custom",this._dataType="raster",this._dispatcher=C,this._implementation=y,this.setEventedParent(R),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 Gu(this._implementation.bounds,this.minzoom,this.maxzoom));const $=y;$.update=this._update.bind(this),$.clearTiles=this._clearTiles.bind(this),$.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,o.aJ(y,["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(I){this.map=I,this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(I),this.load()}onRemove(I){this._implementation.onRemove&&this._implementation.onRemove(I)}hasTile(I){if(this._implementation.hasTile){const{x:y,y:C,z:R}=I.canonical;return this._implementation.hasTile({x:y,y:C,z:R})}return!this.tileBounds||this.tileBounds.contains(I.canonical)}loadTile(I,y){const{x:C,y:R,z:$}=I.tileID.canonical,G=new AbortController,Z=Promise.resolve(this._implementation.loadTile({x:C,y:R,z:$},{signal:G.signal})).then((function(te){return delete I.request,I.aborted?(I.state="unloaded",y(null)):te===void 0?(I.state="errored",y(null)):te===null?(this.loadTileData(I,{width:this.tileSize,height:this.tileSize,data:null}),I.state="loaded",y(null)):function(de){return de instanceof ImageData||de instanceof HTMLCanvasElement||de instanceof ImageBitmap||de instanceof HTMLImageElement}(te)?(this.loadTileData(I,te),I.state="loaded",void y(null)):(I.state="errored",y(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}).bind(this)).catch(te=>{te.name!=="AbortError"&&(I.state="errored",y(te))});Z.cancel=()=>G.abort(),I.request=Z}loadTileData(I,y){I.setTexture(y,this.map.painter)}unloadTile(I,y){if(I.texture&&I.texture instanceof o.T?(I.destroy(!1),I.texture&&I.texture instanceof o.T&&this.map.painter.saveTileTexture(I.texture)):I.destroy(),this._implementation.unloadTile){const{x:C,y:R,z:$}=I.tileID.canonical;this._implementation.unloadTile({x:C,y:R,z:$})}y&&y()}abortTile(I,y){I.request&&I.request.cancel&&(I.request.cancel(),delete I.request),y&&y()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(I=>({x:I.canonical.x,y:I.canonical.y,z:I.canonical.z}))}_clearTiles(){const I=o.F(this.id,this.scope);this.map.style.clearSource(I)}_update(){this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))}}},My=function(I,y,C,R){const $=new Ay[y.type](I,y,C,R);if($.id!==I)throw new Error(`Expected Source id to be ${I} instead of ${$.id}`);return o.aZ(["load","abort","unload","serialize","prepare"],$),$};function Ef(I,y,C=""){return`${C}:${y.id||""}:${y.layer.id}:${function(R){if("layerId"in R)return`layer:${R.layerId}`;{const{featuresetId:$,importId:G}=R;return`featureset:${$}${G?`:import:${G}`:""}`}}(I.target)}`}function yh(I,y,C,R=""){if(I.uniqueFeatureID){const $=Ef(I,y,R);if(C.has($))return!0;C.add($)}return!1}function mx(I,y,C,R,$=!1,G=void 0){const Z=y.sourceCache.transform,te=y.sourceCache.tilesIn(I,y.has3DLayers,$);te.sort(xm);const de=[];for(const xe of te){const we=xe.tile.queryRenderedFeatures(y,xe,C,R,Z,$,G);Object.keys(we).length&&de.push({wrappedTileID:xe.tile.tileID.wrapped().key,queryResults:we})}for(const xe in y.layers){const we=y.layers[xe];if(we.styleLayer){const Re=we.styleLayer.queryRenderedFeatures(I,y.sourceCache,R);Object.keys(Re).length&&de.push({wrappedTileID:0,queryResults:Re})}}return de.length===0?{}:function(xe){const we={},Re={};for(const Le of xe){const Ue=Le.queryResults,st=Le.wrappedTileID,Je=Re[st]=Re[st]||{};for(const mt in Ue){const ht=Ue[mt],kt=Je[mt]=Je[mt]||{},Tt=we[mt]=we[mt]||[];for(const xt of ht)kt[xt.featureIndex]||(kt[xt.featureIndex]=!0,Tt.push(xt))}}return we}(de)}function fo(I,y,C,R,$,G){const Z={},te=R.queryRenderedSymbols(I),de=[];for(const xe of Object.keys(te).map(Number))de.push($[xe]);de.sort(xm);for(const xe of de){const we=xe.featureIndex.lookupSymbolFeatures(te[xe.bucketInstanceId],xe.bucketIndex,xe.sourceLayerIndex,y,C,G);for(const Re in we){const Le=Z[Re]=Z[Re]||[],Ue=we[Re];Ue.sort((st,Je)=>{const mt=xe.featureSortOrder;if(mt){const ht=mt.indexOf(st.featureIndex);return mt.indexOf(Je.featureIndex)-ht}return Je.featureIndex-st.featureIndex});for(const st of Ue)Le.push(st)}}return Z}function qb(I,y){const C=I.getRenderableIds().map(G=>I.getTileByID(G)),R=[],$={};for(let G=0;G{if(G)C(G);else try{const de=R.getHeaderLength(Z);if(de>y)return void(this.request=this.fetchHeader(de,C));R.parseHeader(Z),this._isHeaderLoaded=!0;let xe=0;for(const we of Object.values(R.layers))xe=Math.max(xe,we.dataIndex[we.dataIndex.length-1].lastByte);Z.byteLength>=xe&&(this.entireBuffer=Z),C(null,this.entireBuffer||Z,te)}catch(de){C(de)}}),this.request}fetchBandForRender(y,C,R,$){this.fetchBand(y,C,R,G=>{if(G)return void $(G);this.updateTextureDescriptor(y,C,R);const Z=this.textureDescriptorPerLayer.get(C);$(null,Z?Z.img:null)})}fetchBand(y,C,R,$,G=!0){const Z=this._mrt;if(!this._isHeaderLoaded||!Z)return void $(new Error("Tile header is not ready"));const te=this.actor;if(!te)return void $(new Error("Can't fetch tile band without an actor"));let de;const xe=o.F(String(R),o.F(this.tileID.key,y));let we=this._taskQueue.get(xe);we?we.add($):(we=new Set,we.add($),this._taskQueue.set(xe,we));const Re=(Je,mt)=>{de.complete(Je,mt),Je?$(Je):(we.forEach(ht=>ht(null,mt)),this._taskQueue.delete(xe))},Le=(Je,mt)=>{if(Je)return $(Je);const ht=te.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:mt,task:de},Re,void 0,!0);if(C!==null){const kt=this._workQueuePerLayer.get(C)||[];kt.push(()=>{ht&&ht.cancel(),de.cancel()}),this._workQueuePerLayer.has(C)||this._workQueuePerLayer.set(C,kt)}};let Ue;try{Ue=Z.getLayer(y)}catch(Je){if(this.state==="reloading")return;throw Je}if(!Ue)return void $(new Error(`Unknown sourceLayer "${y}"`));if(Ue.hasDataForBand(R))return we.forEach(Je=>Je(null,null)),void this._taskQueue.delete(xe);const st=Ue.getDataRange([R]);if(de=Z.createDecodingTask(st),!de||de.tasks.length)if(C!==null&&this.flushQueues(C),this.entireBuffer)Le(null,this.entireBuffer.slice(st.firstByte,st.lastByte+1));else{const Je=Object.assign({},this.requestParams,{headers:{Range:`bytes=${st.firstByte}-${st.lastByte}`}}),mt=o.b1(Je,Le);if(C!==null){const ht=this._fetchQueuePerLayer.get(C)||[];ht.push(()=>{mt.cancel(),de.cancel()}),this._fetchQueuePerLayer.has(C)||this._fetchQueuePerLayer.set(C,ht)}}}updateNeeded(y,C){return(!this.textureDescriptorPerLayer.get(y)||this.textureDescriptorPerLayer.get(y).band!==C||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(y,C,R){if(!this._mrt)return;const $=this._mrt.getLayer(y);if(!$||!$.hasBand(R)||!$.hasDataForBand(R))return;const{bytes:G,tileSize:Z,buffer:te,offset:de,scale:xe}=$.getBandView(R),we=Z+2*te,Re=new o.q({width:we,height:we},G),Le=this.texturePerLayer.get(C);Le&&Le instanceof o.T&&Le.update(Re,{premultiply:!1}),this.textureDescriptorPerLayer.set(C,{layer:y,band:R,img:Re,buffer:te,offset:de,tileSize:Z,format:$.pixelFormat,mix:[xe,256*xe,65536*xe,16777216*xe]})}destroy(y=!1){if(super.destroy(y),delete this._mrt,!y)for(const C of this.texturePerLayer.values())C&&C instanceof o.T&&C.destroy();this.texturePerLayer.clear(),this.textureDescriptorPerLayer.clear(),this.fbo&&(this.fbo.destroy(),delete this.fbo),delete this.request,delete this.requestParams,this._isHeaderLoaded=!1}}class px{constructor(y,C){this.max=y,this.onRemove=C,this.reset()}reset(){for(const y in this.data)for(const C of this.data[y])C.timeout&&clearTimeout(C.timeout),this.onRemove(C.value);return this.data={},this.order=[],this}add(y,C,R){const $=y.wrapped().key;this.data[$]===void 0&&(this.data[$]=[]);const G={value:C,timeout:void 0};if(R!==void 0&&(G.timeout=setTimeout(()=>{this.remove(y,G)},R)),this.data[$].push(G),this.order.push($),this.order.length>this.max){const Z=this._getAndRemoveByKey(this.order[0]);Z&&this.onRemove(Z)}return this}has(y){return y.wrapped().key in this.data}getAndRemove(y){return this.has(y)?this._getAndRemoveByKey(y.wrapped().key):null}_getAndRemoveByKey(y){const C=this.data[y].shift();return C.timeout&&clearTimeout(C.timeout),this.data[y].length===0&&delete this.data[y],this.order.splice(this.order.indexOf(y),1),C.value}getByKey(y){const C=this.data[y];return C?C[0].value:null}get(y){return this.has(y)?this.data[y.wrapped().key][0].value:null}remove(y,C){if(!this.has(y))return this;const R=y.wrapped().key,$=C===void 0?0:this.data[R].indexOf(C),G=this.data[R][$];return this.data[R].splice($,1),G.timeout&&clearTimeout(G.timeout),this.data[R].length===0&&delete this.data[R],this.onRemove(G.value),this.order.splice(this.order.indexOf(R),1),this}setMaxSize(y){for(this.max=y;this.order.length>this.max;){const C=this._getAndRemoveByKey(this.order[0]);C&&this.onRemove(C)}return this}filter(y){const C=[];for(const R in this.data)for(const $ of this.data[R])y($.value)||C.push($);for(const R of C)this.remove(R.value.tileID,R)}}class Wu{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(y,C,R){const $=String(C);if(this.stateChanges[y]=this.stateChanges[y]||{},this.stateChanges[y][$]=this.stateChanges[y][$]||{},Object.assign(this.stateChanges[y][$],R),this.deletedStates[y]===null){this.deletedStates[y]={};for(const G in this.state[y])G!==$&&(this.deletedStates[y][G]=null)}else if(this.deletedStates[y]&&this.deletedStates[y][$]===null){this.deletedStates[y][$]={};for(const G in this.state[y][$])R[G]||(this.deletedStates[y][$][G]=null)}else for(const G in R)this.deletedStates[y]&&this.deletedStates[y][$]&&this.deletedStates[y][$][G]===null&&delete this.deletedStates[y][$][G]}removeFeatureState(y,C,R){if(this.deletedStates[y]===null)return;const $=String(C);if(this.deletedStates[y]=this.deletedStates[y]||{},R&&C!==void 0)this.deletedStates[y][$]!==null&&(this.deletedStates[y][$]=this.deletedStates[y][$]||{},this.deletedStates[y][$][R]=null);else if(C!==void 0)if(this.stateChanges[y]&&this.stateChanges[y][$])for(R in this.deletedStates[y][$]={},this.stateChanges[y][$])this.deletedStates[y][$][R]=null;else this.deletedStates[y][$]=null;else this.deletedStates[y]=null}getState(y,C){const R=this.state[y]||{},$=this.stateChanges[y]||{},G=this.deletedStates[y];if(G===null)return{};if(C!==void 0){const te=String(C),de=Object.assign({},R[te],$[te]);if(G){const xe=G[C];if(xe===null)return{};for(const we in xe)delete de[we]}return de}const Z=Object.assign({},R,$);if(G)for(const te in G)delete Z[te];return Z}initializeTileState(y,C){y.refreshFeatureState(C)}coalesceChanges(y,C){const R={};for(const $ in this.stateChanges){this.state[$]=this.state[$]||{};const G={};for(const Z in this.stateChanges[$])this.state[$][Z]||(this.state[$][Z]={}),Object.assign(this.state[$][Z],this.stateChanges[$][Z]),G[Z]=this.state[$][Z];R[$]=G}for(const $ in this.deletedStates){this.state[$]=this.state[$]||{};const G={};if(this.deletedStates[$]===null)for(const Z in this.state[$])G[Z]={},this.state[$][Z]={};else for(const Z in this.deletedStates[$]){if(this.deletedStates[$][Z]===null)this.state[$][Z]={};else if(this.state[$][Z])for(const te of Object.keys(this.deletedStates[$][Z]))delete this.state[$][Z][te];G[Z]=this.state[$][Z]}R[$]=R[$]||{},Object.assign(R[$],G)}if(this.stateChanges={},this.deletedStates={},Object.keys(R).length!==0)for(const $ in y)y[$].refreshFeatureState(C,R)}}class al extends o.E{constructor(y,C,R){super(),this.id=y,this._renderSourceType=R,this._maxzoomOverride=null,C.on("data",$=>{$.dataType==="source"&&$.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&$.dataType==="source"&&$.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),C.on("error",()=>{this._sourceErrored=!0}),this._source=C,this._tiles={},this._cache=new px(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=C.minTileCacheSize,this._maxTileCacheSize=C.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new Wu,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(y){this.map=y,this._minTileCacheSize=this._minTileCacheSize===void 0&&y?y._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&y?y._maxTileCacheSize:this._maxTileCacheSize}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;for(const y in this._tiles)if(!this._tiles[y].loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const y=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,y&&this.reload(),this.transform&&this.update(this.transform)}setMaxzoomOverride(y){this._maxzoomOverride=y}_loadTile(y,C){return y.renderSourceType=this._renderSourceType,y.isExtraShadowCaster=this._shadowCasterTiles[y.tileID.key],this._source.loadTile(y,C)}_unloadTile(y){if(this._source.unloadTile)return this._source.unloadTile(y)}_abortTile(y){if(this._source.abortTile)return this._source.abortTile(y)}serialize(){return this._source.serialize()}prepare(y){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const C in this._tiles){const R=this._tiles[C];R.upload(y,this.map?this.map.painter:void 0),R.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map(y=>y.tileID).sort(d0).map(y=>y.key)}getRenderableIds(y,C){const R=[];for(const $ in this._tiles)this._isIdRenderable(+$,y,C)&&R.push(this._tiles[$]);return y?R.sort(($,G)=>{const Z=$.tileID,te=G.tileID,de=new o.P(Z.canonical.x,Z.canonical.y)._rotate(this.transform.angle),xe=new o.P(te.canonical.x,te.canonical.y)._rotate(this.transform.angle);return Z.overscaledZ-te.overscaledZ||xe.y-de.y||xe.x-de.x}).map($=>$.tileID.key):R.map($=>$.tileID).sort(d0).map($=>$.key)}hasRenderableParent(y){const C=this.findLoadedParent(y,0);return!!C&&this._isIdRenderable(C.tileID.key)}_isIdRenderable(y,C,R){return this._tiles[y]&&this._tiles[y].hasData()&&!this._coveredTiles[y]&&(C||!this._tiles[y].holdingForFade())&&(R||!this._shadowCasterTiles[y])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const y in this._tiles)this._tiles[y].state!=="errored"&&this._reloadTile(+y,"reloading")}}_reloadTile(y,C){const R=this._tiles[y];R&&(R.state!=="loading"&&(R.state=C),this._loadTile(R,this._tileLoaded.bind(this,R,y,C)))}_tileLoaded(y,C,R,$,G){if($){if(y.state="errored",o.b2($)){if(this._source.fire(new o.C("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:y})),!(y.tileID.key in this._loadedParentTiles))return;if(this._source.type==="raster-dem"&&this.usedForTerrain&&this.map.painter.terrain){const te=this.map.painter.terrain;this.update(this.transform,te.getScaledDemTileSize(),!0),te.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new o.B($,{tile:y}));return}y.timeAdded=o.o.now(),R==="expired"&&(y.refreshedUponExpiration=!0),this._setTileReloadTimer(C,y),this._source.type==="raster-dem"&&y.dem&&this._backfillDEM(y),this._state.initializeTileState(y,this.map?this.map.painter:null);let Z=new Map;G&&G.responseHeaders&&(Z=G.responseHeaders),this._source.fire(new o.C("data",{dataType:"source",tile:y,coord:y.tileID,sourceCacheId:this.id,responseHeaders:Z}))}_hasTunnelGeometry(){for(const y in this._tiles){const C=this._tiles[y];if(C&&C.hasTunnelGeometry)return!0}return!1}_backfillDEM(y){const C=this.getRenderableIds();for(let $=0;$1||(Math.abs(Z)>1&&(Math.abs(Z+de)===1?Z+=de:Math.abs(Z-de)===1&&(Z-=de)),G.dem&&$.dem&&($.dem.backfillBorder(G.dem,Z,te),$.neighboringTiles&&$.neighboringTiles[xe]&&($.neighboringTiles[xe].backfilled=!0)))}}getTile(y){return this.getTileByID(y.key)}getTileByID(y){return this._tiles[y]}_retainLoadedChildren(y,C,R,$){for(const G in this._tiles){let Z=this._tiles[G];if($[G]||!Z.hasData()||Z.tileID.overscaledZ<=C||Z.tileID.overscaledZ>R)continue;let te=Z.tileID;for(;Z&&Z.tileID.overscaledZ>C+1;){const xe=Z.tileID.scaledTo(Z.tileID.overscaledZ-1);Z=this._tiles[xe.key],Z&&Z.hasData()&&(te=xe)}let de=te;for(;de.overscaledZ>C;)if(de=de.scaledTo(de.overscaledZ-1),y[de.key]){$[te.key]=te;break}}}findLoadedParent(y,C){if(y.key in this._loadedParentTiles){const R=this._loadedParentTiles[y.key];return R&&R.tileID.overscaledZ>=C?R:null}for(let R=y.overscaledZ-1;R>=C;R--){const $=y.scaledTo(R),G=this._getLoadedTile($);if(G)return G}}_getLoadedTile(y){const C=this._tiles[y.key];return C&&C.hasData()?C:this._cache.getByKey(this._source.reparseOverscaled?y.wrapped().key:y.canonical.key)}updateCacheSize(y,C){C=C||this._source.tileSize;const R=Math.ceil(y.width/C)+1,$=Math.ceil(y.height/C)+1,G=Math.floor(R*$*5),Z=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,G):G,te=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,Z):Z;this._cache.setMaxSize(te)}handleWrapJump(y){const C=Math.round((y-(this._prevLng===void 0?y:this._prevLng))/360);if(this._prevLng=y,C){const R={};for(const $ in this._tiles){const G=this._tiles[$];G.tileID=G.tileID.unwrapTo(G.tileID.wrap+C),R[G.tileID.key]=G}this._tiles=R;for(const $ in this._timers)clearTimeout(this._timers[$]),delete this._timers[$];for(const $ in this._tiles)this._setTileReloadTimer(+$,this._tiles[$])}}update(y,C,R,$,G){if(this.transform=y,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!R)return;this.updateCacheSize(y,C),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const Z=this._source.type==="batched-model";let te,de=this._source.maxzoom;this._maxzoomOverride!==null&&(de=Math.min(de,this._maxzoomOverride));const xe=this.map&&this.map.painter?this.map.painter._terrain:null;if(xe&&xe.sourceCache===this&&xe.attenuationRange()){const Ue=xe.attenuationRange()[0],st=Math.floor(Ue)-Math.log2(xe.getDemUpscale());de>st&&(de=st)}const we=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)te=y.getVisibleUnwrappedCoordinates(this._source.tileID).map(Ue=>new o.aR(Ue.canonical.z,Ue.wrap,Ue.canonical.z,Ue.canonical.x,Ue.canonical.y));else if(this.tileCoverLift!==0){const Ue=y.clone();Ue.tileCoverLift=this.tileCoverLift,te=Ue.coveringTiles({tileSize:C||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:de,roundZoom:this._source.roundZoom&&!R,reparseOverscaled:we,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:Z}),this._source.minzoom<=1&&y.projection.name==="globe"&&(te.push(new o.aR(1,0,1,0,0)),te.push(new o.aR(1,0,1,1,0)),te.push(new o.aR(1,0,1,0,1)),te.push(new o.aR(1,0,1,1,1)))}else if(te=y.coveringTiles({tileSize:C||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:de,roundZoom:this._source.roundZoom&&!R,reparseOverscaled:we,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:Z}),this._source.hasTile){const Ue=this._source.hasTile.bind(this._source);te=te.filter(st=>Ue(st))}}else te=[];if(te.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const Ue=y.coveringZoomLevel({tileSize:C||this._source.tileSize,roundZoom:this._source.roundZoom&&!R}),st=Math.min(Ue,de);if(Z){const Je=y.extendTileCover(te,st);for(const mt of Je)te.push(mt)}else if(G){const Je=this.transform.getFrustum(st),mt=y.extendTileCoverToNearPlane(te,Je,st);for(const ht of mt)te.push(ht);if(st>=18&&this._hasTunnelGeometry()){const ht=y.extendTileCoverForTunnels(te,Je,st,20);for(const kt of ht)te.push(kt)}}else if(this.castsShadows&&$){const Je=y.extendTileCover(te,st,$,16);for(const mt of Je)this._shadowCasterTiles[mt.key]=!0,te.push(mt)}}const Re=this._updateRetainedTiles(te);if(this._supportsFading&&te.length!==0){const Ue={},st={},Je=o.o.now(),mt=Object.keys(Re);for(const kt of mt){const Tt=Re[kt],xt=this._tiles[kt];if(!xt||xt.fadeEndTime!==void 0&&xt.fadeEndTime<=Je)continue;const es=this.findLoadedParent(Tt,Math.max(Tt.overscaledZ-al.maxOverzooming,this._source.minzoom));es&&(this._addTile(es.tileID),Ue[es.tileID.key]=es.tileID),st[kt]=Tt}const ht=te[te.length-1].overscaledZ;for(const kt in this._tiles){const Tt=this._tiles[kt];if(Re[kt]||!Tt.hasData())continue;let xt=Tt.tileID;for(;xt.overscaledZ>ht;){xt=xt.scaledTo(xt.overscaledZ-1);const es=this._tiles[xt.key];if(es&&es.hasData()&&st[xt.key]){Re[kt]=Tt.tileID;break}}}for(const kt in Ue)Re[kt]||(this._coveredTiles[kt]=!0,Re[kt]=Ue[kt])}for(const Ue in Re)this._tiles[Ue].clearFadeHold();const Le=o.b3(this._tiles,Re);for(const Ue of Le){const st=this._tiles[Ue];st.hasSymbolBuckets&&!st.holdingForFade()?st.setHoldDuration(this.map._fadeDuration):st.hasSymbolBuckets&&!st.symbolFadeFinished()||this._removeTile(+Ue)}this._updateLoadedParentTileCache(),this._renderSourceType===o.b4.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const y in this._tiles)this._tiles[y].holdingForFade()&&this._removeTile(+y)}_updateRetainedTiles(y){const C={};if(y.length===0)return C;const R={},$=y.reduce((xe,we)=>Math.min(xe,we.overscaledZ),1/0),G=y[0].overscaledZ,Z=Math.max(G-al.maxOverzooming,this._source.minzoom),te=Math.max(G+al.maxUnderzooming,this._source.minzoom),de={};for(const xe of y){const we=this._addTile(xe);C[xe.key]=xe,we.hasData()||$=this._source.maxzoom){const Le=xe.children(this._source.maxzoom)[0],Ue=this.getTile(Le);if(Ue&&Ue.hasData()){C[Le.key]=Le;continue}}else{const Le=xe.children(this._source.maxzoom);if(C[Le[0].key]&&C[Le[1].key]&&C[Le[2].key]&&C[Le[3].key])continue}let Re=we.wasRequested();for(let Le=xe.overscaledZ-1;Le>=Z;--Le){const Ue=xe.scaledTo(Le);if(R[Ue.key]||(R[Ue.key]=!0,we=this.getTile(Ue),!we&&Re&&(we=this._addTile(Ue)),we&&(C[Ue.key]=Ue,Re=we.wasRequested(),we.hasData())))break}}return C}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const y in this._tiles){const C=[];let R,$=this._tiles[y].tileID;for(;$.overscaledZ>0;){if($.key in this._loadedParentTiles){R=this._loadedParentTiles[$.key];break}C.push($.key);const G=$.scaledTo($.overscaledZ-1);if(R=this._getLoadedTile(G),R)break;$=G}for(const G of C)this._loadedParentTiles[G]=R}}_addTile(y){let C=this._tiles[y.key];if(C)return C.isExtraShadowCaster!==!0||this._shadowCasterTiles[y.key]||this._reloadTile(y.key,"reloading"),C;C=this._cache.getAndRemove(y),C&&(this._setTileReloadTimer(y.key,C),C.tileID=y,this._state.initializeTileState(C,this.map?this.map.painter:null),this._cacheTimers[y.key]&&(clearTimeout(this._cacheTimers[y.key]),delete this._cacheTimers[y.key],this._setTileReloadTimer(y.key,C)));const R=!!C;if(!R){const $=this.map?this.map.painter:null,G=this._source.tileSize*y.overscaleFactor();C=this._source.type==="raster-array"?new Fh(y,G,this.transform.tileZoom,$,this._isRaster):new o.b0(y,G,this.transform.tileZoom,$,this._isRaster,this._source.worldview),this._loadTile(C,this._tileLoaded.bind(this,C,y.key,C.state))}return C.uses++,this._tiles[y.key]=C,R||this._source.fire(new o.C("dataloading",{tile:C,coord:C.tileID,dataType:"source"})),C}_setTileReloadTimer(y,C){y in this._timers&&(clearTimeout(this._timers[y]),delete this._timers[y]);const R=C.getExpiryTimeout();R&&(this._timers[y]=setTimeout(()=>{this._reloadTile(y,"expired"),delete this._timers[y]},R))}_removeTile(y){const C=this._tiles[y];C&&(C.uses--,delete this._tiles[y],this._timers[y]&&(clearTimeout(this._timers[y]),delete this._timers[y]),C.uses>0||(C.hasData()&&C.state!=="reloading"||C.state==="empty"?this._cache.add(C.tileID,C,C.getExpiryTimeout()):(C.aborted=!0,this._abortTile(C),this._unloadTile(C))))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const y in this._tiles)this._removeTile(+y);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(y,C,R){const $=[],G=this.transform;if(!G)return $;const Z=G.projection.name==="globe",te=o.aH(G.center.lng);for(const de in this._tiles){const xe=this._tiles[de];if(R&&xe.clearQueryDebugViz(),xe.holdingForFade())continue;let we;if(Z){const Re=xe.tileID.canonical;if(Re.z===0){const Le=[Math.abs(o.aC(te,...xu(Re,-1))-te),Math.abs(o.aC(te,...xu(Re,1))-te)];we=[0,2*Le.indexOf(Math.min(...Le))-1]}else{const Le=[Math.abs(o.aC(te,...xu(Re,-1))-te),Math.abs(o.aC(te,...xu(Re,0))-te),Math.abs(o.aC(te,...xu(Re,1))-te)];we=[Le.indexOf(Math.min(...Le))-1]}}else we=[0];for(const Re of we){const Le=y.containsTile(xe,G,C,Re);Le&&$.push(Le)}}return $}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(y){return this._getRenderableCoordinates(y)}_getRenderableCoordinates(y,C){const R=this.getRenderableIds(y,C).map(G=>this._tiles[G].tileID),$=this.transform.projection.name==="globe";for(const G of R)G.projMatrix=this.transform.calculateProjMatrix(G.toUnwrapped()),G.expandedProjMatrix=$?this.transform.calculateProjMatrix(G.toUnwrapped(),!1,!0):G.projMatrix;return R}sortCoordinatesByDistance(y){const C=y.slice(),R=this.transform._camera.position,$=this.transform._camera.forward(),G={};for(const Z of C){const te=1/(1<G[Z.key]-G[te.key]),C}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const y=o.o.now();for(const C in this._tiles){const R=this._tiles[C];if(R.fadeEndTime!==void 0&&R.fadeEndTime>=y)return!0}}return!1}setFeatureState(y,C,R){this._state.updateState(y=y||"_geojsonTileLayer",C,R)}removeFeatureState(y,C,R){this._state.removeFeatureState(y=y||"_geojsonTileLayer",C,R)}getFeatureState(y,C){return this._state.getState(y=y||"_geojsonTileLayer",C)}setDependencies(y,C,R){const $=this._tiles[y];$&&$.setDependencies(C,R)}reloadTilesForDependencies(y,C){for(const R in this._tiles)this._tiles[R].hasDependency(y,C)&&this._reloadTile(+R,"reloading");this._cache.filter(R=>!R.hasDependency(y,C))}_preloadTiles(y,C){if(!this._sourceLoaded){const de=()=>{this._sourceLoaded&&(this._source.off("data",de),this._preloadTiles(y,C))};return void this._source.on("data",de)}const R=new Map,$=Array.isArray(y)?y:[y],G=this.map.painter.terrain,Z=this.usedForTerrain&&G?G.getScaledDemTileSize():this._source.tileSize;for(const de of $){const xe=de.coveringTiles({tileSize:Z,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const we of xe)R.set(we.key,we);this.usedForTerrain&&de.updateElevation(!1)}const te=Array.from(R.values());o.t(te,(de,xe)=>{const we=new o.b0(de,this._source.tileSize*de.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(we,Re=>{this._source.type==="raster-dem"&&we.dem&&this._backfillDEM(we),xe(Re,we)})},C)}}function d0(I,y){const C=Math.abs(2*I.wrap)-+(I.wrap<0),R=Math.abs(2*y.wrap)-+(y.wrap<0);return I.overscaledZ-y.overscaledZ||R-C||y.canonical.y-I.canonical.y||y.canonical.x-I.canonical.x}function xu(I,y){const C=1<0:R.type==="building"?$=!R.isHidden(y)&&R.paint.get("building-opacity")>0:R.type==="model"&&($=!R.isHidden(y)&&R.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!$&&C.visible,C.visible=$}}updateZOffset(y,C){this.currentBuildingBuckets=[];for(const $ of this.layers){const G=$.layer,Z=this.style.getLayerSourceCache(G);let te=1;G.type==="fill-extrusion"?te=$.visible?G.paint.get("fill-extrusion-vertical-scale"):0:G.type==="building"&&(te=$.visible?G.paint.get("building-vertical-scale"):0);let de=Z?Z.getTile(C):null;if(!de&&Z)for(const xe in Z._tiles){const we=Z._tiles[xe];if(C.canonical.isChildOf(we.tileID.canonical)){de=we;break}}this.currentBuildingBuckets.push({bucket:de?de.getBucket(G):null,tileID:de?de.tileID:C,verticalScale:te})}y.hasAnyZOffset=!1;let R=!1;for(let $=0;${R in y&&(C[R]=y[R])}),C}function Af(I){I=I.slice();const y=Object.create(null);for(const C of I)y[C.id]=C;for(let C=0;C0?($-Z)/te:0;return this.points[G].mult(1-de).add(this.points[C].mult(de))}}class Ly{constructor(y,C,R){const $=this.boxCells=[],G=this.circleCells=[];this.xCellCount=Math.ceil(y/R),this.yCellCount=Math.ceil(C/R);for(let Z=0;Zthis.width||$<0||C>this.height)return!G&&[];const te=[];if(y<=0&&C<=0&&this.width<=R&&this.height<=$){if(G)return!0;for(let de=0;de0:te}_queryCircle(y,C,R,$,G){const Z=y-R,te=y+R,de=C-R,xe=C+R;if(te<0||Z>this.width||xe<0||de>this.height)return!$&&[];const we=[];return this._forEachCell(Z,de,te,xe,this._queryCellCircle,we,{hitTest:$,circle:{x:y,y:C,radius:R},seenUids:{box:{},circle:{}}},G),$?we.length>0:we}query(y,C,R,$,G){return this._query(y,C,R,$,!1,G)}hitTest(y,C,R,$,G){return this._query(y,C,R,$,!0,G)}hitTestCircle(y,C,R,$){return this._queryCircle(y,C,R,!0,$)}_queryCell(y,C,R,$,G,Z,te,de){const xe=te.seenUids,we=this.boxCells[G];if(we!==null){const Le=this.bboxes;for(const Ue of we)if(!xe.box[Ue]){xe.box[Ue]=!0;const st=4*Ue;if(y<=Le[st+2]&&C<=Le[st+3]&&R>=Le[st+0]&&$>=Le[st+1]&&(!de||de(this.boxKeys[Ue]))){if(te.hitTest)return Z.push(!0),!0;Z.push({key:this.boxKeys[Ue],x1:Le[st],y1:Le[st+1],x2:Le[st+2],y2:Le[st+3]})}}}const Re=this.circleCells[G];if(Re!==null){const Le=this.circles;for(const Ue of Re)if(!xe.circle[Ue]){xe.circle[Ue]=!0;const st=3*Ue;if(this._circleAndRectCollide(Le[st],Le[st+1],Le[st+2],y,C,R,$)&&(!de||de(this.circleKeys[Ue]))){if(te.hitTest)return Z.push(!0),!0;{const Je=Le[st],mt=Le[st+1],ht=Le[st+2];Z.push({key:this.circleKeys[Ue],x1:Je-ht,y1:mt-ht,x2:Je+ht,y2:mt+ht})}}}}}_queryCellCircle(y,C,R,$,G,Z,te,de){const xe=te.circle,we=te.seenUids,Re=this.boxCells[G];if(Re!==null){const Ue=this.bboxes;for(const st of Re)if(!we.box[st]){we.box[st]=!0;const Je=4*st;if(this._circleAndRectCollide(xe.x,xe.y,xe.radius,Ue[Je+0],Ue[Je+1],Ue[Je+2],Ue[Je+3])&&(!de||de(this.boxKeys[st])))return Z.push(!0),!0}}const Le=this.circleCells[G];if(Le!==null){const Ue=this.circles;for(const st of Le)if(!we.circle[st]){we.circle[st]=!0;const Je=3*st;if(this._circlesCollide(Ue[Je],Ue[Je+1],Ue[Je+2],xe.x,xe.y,xe.radius)&&(!de||de(this.circleKeys[st])))return Z.push(!0),!0}}}_forEachCell(y,C,R,$,G,Z,te,de){const xe=this._convertToXCellCoord(y),we=this._convertToYCellCoord(C),Re=this._convertToXCellCoord(R),Le=this._convertToYCellCoord($);for(let Ue=xe;Ue<=Re;Ue++)for(let st=we;st<=Le;st++)if(G.call(this,y,C,R,$,this.xCellCount*st+Ue,Z,te,de))return}_convertToXCellCoord(y){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(y*this.xScale)))}_convertToYCellCoord(y){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(y*this.yScale)))}_circlesCollide(y,C,R,$,G,Z){const te=$-y,de=G-C,xe=R+Z;return xe*xe>te*te+de*de}_circleAndRectCollide(y,C,R,$,G,Z,te){const de=(Z-$)/2,xe=Math.abs(y-($+de));if(xe>de+R)return!1;const we=(te-G)/2,Re=Math.abs(C-(G+we));if(Re>we+R)return!1;if(xe<=de||Re<=we)return!0;const Le=xe-de,Ue=Re-we;return Le*Le+Ue*Ue<=R*R}}const Hb=Math.tan(85*Math.PI/180);function Sd(I,y,C,R,$,G,Z){const te=o.bb();if(C)if(G.name==="globe"){const de=o.bc($,y);o.aD(te,te,de)}else{const de=o.bd([],Z);te[0]=de[0],te[1]=de[1],te[4]=de[2],te[5]=de[3],R||o.ba(te,te,$.angle)}else o.aD(te,$.labelPlaneMatrix,I);return te}function zc(I,y,C,R,$,G,Z){const te=Sd(I,y,C,R,$,G,Z);return G.name==="globe"&&C||(te[2]=te[6]=te[10]=te[14]=0),te}function tp(I,y,C,R,$,G,Z){if(C){if(G.name==="globe"){const te=Sd(I,y,C,R,$,G,Z);return o.b7(te,te),o.aD(te,I,te),te}{const te=o.b8(I),de=o.b9([]);return de[0]=Z[0],de[1]=Z[1],de[4]=Z[2],de[5]=Z[3],o.aD(te,te,de),R||o.ba(te,te,-$.angle),te}}return $.glCoordMatrix}function Zc(I,y,C,R){const $=[I,y,C,1];C?o.aE($,$,R):zr($,$,R);const G=$[3];return $[0]/=G,$[1]/=G,$[2]/=G,$}function sp(I,y){return Math.min(.5+I/y*.5,1.5)}function Rp(I,y){const C=I[0]/I[3],R=I[1]/I[3];return C>=-y[0]&&C<=y[0]&&R>=-y[1]&&R<=y[1]}function Lt(I,y,C,R,$,G,Z,te,de,xe,we=1){const Re=C.transform,Le=R?I.textSizeData:I.iconSizeData,Ue=o.bj(Le,C.transform.zoom,we),st=Re.projection.name==="globe",Je=[256/C.width*2+1,256/C.height*2+1],mt=R?I.text.dynamicLayoutVertexArray:I.icon.dynamicLayoutVertexArray;mt.clear();let ht=null;st&&(ht=R?I.text.globeExtVertexArray:I.icon.globeExtVertexArray);const kt=I.lineVertexArray,Tt=R?I.text.placedSymbolArray:I.icon.placedSymbolArray,xt=C.transform.width/C.transform.height;let es,Ft=!1;for(let Qt=0;QtMath.abs(C)?{useVertical:!0}:I===o.bk.vertical?R>0?{needsFlipping:!0}:null:y!==0&&function($,G){return $===0||Math.abs(G/$)>Hb}(C,R)?y===1?{needsFlipping:!0}:null:C<0?{needsFlipping:!0}:null}function Dr(I,y,C,R,$,G,Z,te,de,xe,we,Re,Le,Ue,st,Je,mt,ht,kt,Tt){const xt=y/24,es=I.lineOffsetX*xt,Ft=I.lineOffsetY*xt,{lineStartIndex:Qt,glyphStartIndex:At,numGlyphs:Dt,segment:Gt,writingMode:gs,flipState:ns}=I,$s=Qt+I.lineLength,Ps=an=>{if(we){const[zs,Us,Ys]=an.up,Rn=xe.length;o.bm(we,Rn+0,zs,Us,Ys),o.bm(we,Rn+1,zs,Us,Ys),o.bm(we,Rn+2,zs,Us,Ys),o.bm(we,Rn+3,zs,Us,Ys)}const[mn,Ns,hs]=an.point;o.bn(xe,mn,Ns,hs,an.angle)};if(Dt>1){const an=hn(xt,te,es,Ft,C,Re,Le,I,de,G,Ue,Je,!1,mt,ht,kt,Tt);if(!an)return{notEnoughRoom:!0};if(R&&!C){let[mn,Ns,hs]=an.first.point,[zs,Us,Ys]=an.last.point;[mn,Ns]=Zc(mn,Ns,hs,Z),[zs,Us]=Zc(zs,Us,Ys,Z);const Rn=zn(gs,ns,(zs-mn)*st,Us-Ns);if(I.flipState=Rn&&Rn.needsFlipping?1:2,Rn)return Rn}Ps(an.first);for(let mn=At+1;mn0?zs:fa(Le,hs,mn,1,$,void 0,mt,ht.canonical),Ys=zn(gs,ns,(Us[0]-mn[0])*st,Us[1]-mn[1]);if(I.flipState=Ys&&Ys.needsFlipping?1:2,Ys)return Ys}const an=Xa(xt*te.getoffsetX(At),es,Ft,C,Re,Le,Gt,Qt,$s,de,G,Ue,Je,!1,!1,mt,ht,kt,Tt);if(!an)return{notEnoughRoom:!0};Ps(an)}return{}}function Gn(I,y,C,R,$){const{x:G,y:Z,z:te}=R.projectTilePoint(I.x,I.y,y);if(!$)return Zc(G,Z,te,C);const[de,xe,we]=$.getElevation(I,$.elevation,$.elevationFeature);return Zc(G+de,Z+xe,te+we,C)}function fa(I,y,C,R,$,G,Z,te){const de=Gn(I.sub(y)._unit()._add(I),te,$,Z,G);return o.ax(de,C,de),o.ay(de,de),o.bg(de,C,de,R)}function Xa(I,y,C,R,$,G,Z,te,de,xe,we,Re,Le,Ue,st,Je,mt,ht,kt){const Tt=R?I-y:I+y;let xt=Tt>0?1:-1,es=0;R&&(xt*=-1,es=Math.PI),xt<0&&(es+=Math.PI);let Ft=te+Z+(xt>0?0:1)|0,Qt=$,At=$,Dt=0,Gt=0;const gs=Math.abs(Tt),ns=[],$s=[];let Ps=G,an=Ps,mn=o.be([]);const Ns=()=>fa(an,Ps,At,gs-Dt+1,we,Le,Je,mt.canonical);for(;Dt+Gt<=gs;){if(Ft+=xt,Ft=de)return null;if(At=Qt,an=Ps,ns.push(At),Ue&&$s.push(an),Ps=new o.P(xe.getx(Ft),xe.gety(Ft)),Qt=Re[Ft],!Qt){const Cr=Gn(Ps,mt.canonical,we,Je,Le);Qt=Cr[3]>0?Re[Ft]=Cr:Ns()}Dt+=Gt;const dn=o.ax([],Qt,At),mr=o.bf(At,Qt);if(C&&mr>0&&Gt>0&&o.bi(mn,dn)/(Gt*mr)0,Tt),Qt=xe*Ft.perspectiveRatio,At=(R.x1*C+te.x-R.padding)*Qt+Ft.point.x,Dt=(R.y1*C+te.y-R.padding)*Qt+Ft.point.y,Gt=(R.x2*C+te.x+R.padding)*Qt+Ft.point.x,gs=(R.y2*C+te.y+R.padding)*Qt+Ft.point.y,ns=Ft.perspectiveRatio<=.55||Ft.occluded;return!this.isInsideGrid(At,Dt,Gt,gs)||!de&&this.grid.hitTest(At,Dt,Gt,gs,Re)||ns?{box:[],offscreen:!1,occluded:Ft.occluded}:{box:[At,Dt,Gt,gs],offscreen:this.isOffscreen(At,Dt,Gt,gs),occluded:!1}}placeCollisionCircles(y,C,R,$,G,Z,te,de,xe,we,Re,Le,Ue,st,Je,mt){const ht=[],kt=this.transform.elevation,Tt=y.getProjection(),xt=y.elevationType==="road",es=!!kt||xt,Ft=o.bu.getAtTileOffsetFunc(mt,this.transform.center.lat,this.transform.worldSize,Tt),Qt=new o.P(R.tileAnchorX,R.tileAnchorY),At=new o.P(R.tileAnchorX,R.tileAnchorY);let{x:Dt,y:Gt,z:gs}=Tt.projectTilePoint(At.x,At.y,mt.canonical),ns=null;if(es){const mr=xt?y.getElevationFeatureForText($):null;ns={getElevation:Ft,elevation:kt,elevationFeature:mr};const[Cr,ir,hr]=Ft(Qt,kt,mr);Dt+=Cr,Gt+=ir,gs+=hr}const $s=Tt.name==="globe",Ps=this.projectAndGetPerspectiveRatio(de,Dt,Gt,gs,mt,$s||!!kt||this.transform.pitch>0,Tt),{perspectiveRatio:an}=Ps,mn=(Le?te/an:te*an)/o.by,Ns=Zc(Dt,Gt,gs,xe),hs=R.lineOffsetX*mn,zs=R.lineOffsetY*mn,Us=o.ap(y.layers[0].layout.get("text-max-angle")),Ys=Math.cos(Us),Rn=Ps.signedDistanceFromCamera>0?hn(mn,Z,hs,zs,xt&&R.flipState===1,Ns,At,R,G,xe,{},es&&!Le?ns:null,Le&&es,Tt,mt,Le,Ys):null;let Sn=!1,Cn=!1,dn=!0;if(Rn&&!Ps.occluded){const mr=.5*st*an+Je,Cr=new o.P(-100,-100),ir=new o.P(this.screenRightBoundary,this.screenBottomBoundary),hr=new Mf,{first:na,last:wa}=Rn,ya=na.path.length;let Ga=[];for(let va=ya-1;va>=1;va--)Ga.push(na.path[va]);for(let va=1;va(es&&!$s&&(bo=Ft(vlva[3]<=0)&&(Ga=[]));let Wa=[];if(Ga.length>0){let va=1/0,Ii=-1/0,bo=1/0,vl=-1/0;for(const Lo of Ga)va=Math.min(va,Lo[0]),bo=Math.min(bo,Lo[1]),Ii=Math.max(Ii,Lo[0]),vl=Math.max(vl,Lo[1]);Ii>=Cr.x&&va<=ir.x&&vl>=Cr.y&&bo<=ir.y&&(Wa=[Ga.map(Lo=>new o.P(Lo[0],Lo[1]))],(vair.x||boir.y)&&(Wa=o.bv(Wa,Cr.x,Cr.y,ir.x,ir.y)))}for(const va of Wa){hr.reset(va,.25*mr);let Ii=0;Ii=hr.length<=.5*mr?1:Math.ceil(hr.paddedLength/Gr)+1;for(let bo=0;bo0?(o.aE(de,de,y),this.fogState&&G&&te.name!=="globe"&&(xe=function(Le,Ue,st,Je,mt,ht){const kt=ht.calculateFogTileMatrix(mt),Tt=[Ue,st,Je];return o.ah(Tt,Tt,kt),Hn(Le,o.ai(Tt),ht.pitch,ht._fov)}(this.fogState,C,R,$,G.toUnwrapped(),this.transform)>.9)):zr(de,de,y);const we=de[3];return{point:new o.P((de[0]/we+1)/2*this.transform.width+Cd,(-de[1]/we+1)/2*this.transform.height+Cd),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(te)/we*.5,1.5),signedDistanceFromCamera:we,occluded:Z&&de[2]>we||xe}}isOffscreen(y,C,R,$){return R=this.screenRightBoundary||$this.screenBottomBoundary}isInsideGrid(y,C,R,$){return R>=0&&y=0&&CR.collisionGroupID===C}}return this.collisionGroups[y]}}function zh(I,y,C,R,$){const{horizontalAlign:G,verticalAlign:Z}=o.bF(I),te=-(G-.5)*y,de=-(Z-.5)*C,xe=o.bG(I,R);return new o.P(te+xe[0]*$,de+xe[1]*$)}function xx(I,y,C,R,$){const G=new o.P(I,y);return C&&G._rotate(R?$:-$),G}class to{constructor(y,C,R,$,G,Z){this.transform=y.clone(),this.projection=y.projection.name,this.collisionIndex=new gm(this.transform,G),this.buildingIndex=Z,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=C,this.retainedQueryData={},this.collisionGroups=new Zi(R),this.collisionCircleArrays={},this.prevPlacement=$,$&&($.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(y,C,R,$,G=1){const Z=R.getBucket(C),te=R.latestFeatureIndex;if(!Z||!te||C.fqid!==Z.layerIds[0])return;const de=Z.layers[0].layout,xe=Z.layers[0].paint,we=R.collisionBoxArray,Re=Math.pow(2,this.transform.zoom-R.tileID.overscaledZ),Le=R.tileSize/o.an,Ue=R.tileID.toUnwrapped();this.transform.setProjection(Z.projection);const st=(Je=R.tileID,mt=Z.getProjection(),ht=this.transform,mt.name===this.projection?ht.calculateProjMatrix(Je.toUnwrapped()):Vb(ht,mt,Je));var Je,mt,ht;const kt=de.get("text-pitch-alignment")==="map",Tt=de.get("text-rotation-alignment")==="map";C.compileFilter(C.options);const xt=C.dynamicFilter(),es=C.dynamicFilterNeedsFeature(),Ft=C.dynamicFilterNeedsGeometry(),Qt=this.transform.calculatePixelsToTileUnitsMatrix(R),At=zc(st,R.tileID.canonical,kt,Tt,this.transform,Z.getProjection(),Qt);let Dt=null;const Gt=Z.getProjection().createInversionMatrix(this.transform,R.tileID.canonical);if(kt){const zs=tp(st,R.tileID.canonical,kt,Tt,this.transform,Z.getProjection(),Qt);Dt=o.aD([],this.transform.labelPlaneMatrix,zs)}let gs=null;xt&&R.latestFeatureIndex&&(gs={unwrappedTileID:Ue,dynamicFilter:xt,dynamicFilterNeedsFeature:es,needGeometry:Ft}),this.retainedQueryData[Z.bucketInstanceId]=new Mi(Z.bucketInstanceId,te,Z.sourceLayerIndex,Z.index,R.tileID);const[ns,$s]=Z.layers[0].layout.get("text-size-scale-range"),Ps=o.aC(G,ns,$s),[an,mn]=de.get("icon-size-scale-range"),Ns=o.aC(G,an,mn),hs={bucket:Z,layout:de,paint:xe,posMatrix:st,invMatrix:Gt,mercatorCenter:[o.aH(this.transform.center.lng),o.aL(this.transform.center.lat)],textLabelPlaneMatrix:At,labelToScreenMatrix:Dt,clippingData:gs,scale:Re,textPixelRatio:Le,holdingForFade:R.holdingForFade(),collisionBoxArray:we,partiallyEvaluatedTextSize:o.bj(Z.textSizeData,this.transform.zoom,Ps),partiallyEvaluatedIconSize:o.bj(Z.iconSizeData,this.transform.zoom,Ns),collisionGroup:this.collisionGroups.get(Z.sourceID),latestFeatureIndex:R.latestFeatureIndex};if($)for(const zs of Z.sortKeyRanges){const{sortKey:Us,symbolInstanceStart:Ys,symbolInstanceEnd:Rn}=zs;y.push({sortKey:Us,symbolInstanceStart:Ys,symbolInstanceEnd:Rn,parameters:hs})}else y.push({symbolInstanceStart:0,symbolInstanceEnd:Z.symbolInstances.length,parameters:hs})}attemptAnchorPlacement(y,C,R,$,G,Z,te,de,xe,we,Re,Le,Ue,st,Je,mt,ht,kt,Tt,xt,es){const{textOffset0:Ft,textOffset1:Qt,crossTileID:At}=Je,Dt=[Ft,Qt],Gt=zh(y,Z,te,Dt,de),gs=this.collisionIndex.placeCollisionBox(ht,de,C,R,$,G,xx(Gt.x,Gt.y,xe,we,this.transform.angle),st,Re,Le,Ue.predicate);if(Tt){const ns=ht.getSymbolInstanceIconSize(es,this.transform.zoom,Je.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(ht,ns,Tt,R,$,G,xx(Gt.x,Gt.y,xe,we,this.transform.angle),st,Re,Le,Ue.predicate).box.length===0)return}if(gs.box.length>0){let ns;return this.prevPlacement&&this.prevPlacement.variableOffsets[At]&&this.prevPlacement.placements[At]&&this.prevPlacement.placements[At].text&&(ns=this.prevPlacement.variableOffsets[At].anchor),this.variableOffsets[At]={textOffset:Dt,width:Z,height:te,anchor:y,textScale:de,prevAnchor:ns},this.markUsedJustification(ht,y,Je,kt),ht.allowVerticalPlacement&&(this.markUsedOrientation(ht,kt,Je),this.placedOrientations[At]=kt),{shift:Gt,placedGlyphBoxes:gs}}}placeLayerBucketPart(y,C,R,$,G=1){const{bucket:Z,layout:te,paint:de,posMatrix:xe,textLabelPlaneMatrix:we,labelToScreenMatrix:Re,clippingData:Le,textPixelRatio:Ue,mercatorCenter:st,invMatrix:Je,holdingForFade:mt,collisionBoxArray:ht,partiallyEvaluatedTextSize:kt,partiallyEvaluatedIconSize:Tt,collisionGroup:xt,latestFeatureIndex:es}=y.parameters,Ft=te.get("text-optional"),Qt=te.get("icon-optional"),At=te.get("text-allow-overlap"),Dt=te.get("icon-allow-overlap"),Gt=te.get("text-rotation-alignment")==="map",gs=te.get("icon-rotation-alignment")==="map",ns=te.get("text-pitch-alignment")==="map",$s=de.get("symbol-z-offset"),Ps=te.get("symbol-elevation-reference")==="sea",an=te.get("symbol-placement"),[mn,Ns]=te.get("text-size-scale-range"),[hs,zs]=te.get("icon-size-scale-range"),Us=o.aC(G,mn,Ns),Ys=o.aC(G,hs,zs),Rn=te.get("text-variable-anchor"),Sn=Gt&&an!=="point",Cn=gs&&an!=="point",dn=Rn&&Z.hasTextData(),mr=Z.hasIconTextFit()&&dn&&Z.hasIconData();this.transform.setProjection(Z.projection);const Cr=dn||Sn,ir=Cn||mr;let hr=At&&(Dt||!Z.hasIconData()||Qt),na=Dt&&(At||!Z.hasTextData()||Ft);const wa=!$s.isConstant();!Z.collisionArrays&&ht&&Z.deserializeCollisionBoxes(ht),R&&$&&Z.updateCollisionDebugBuffers(this.transform.zoom,ht,Us,Ys);const ya=(Gr,Wa,va)=>{const{crossTileID:Ii,numVerticalGlyphVertices:bo}=Gr;let vl=null;if(Le&&Le.dynamicFilterNeedsFeature||wa){const Bo=this.retainedQueryData[Z.bucketInstanceId],Ko=es.loadFeature({featureIndex:Gr.featureIndex,bucketIndex:Bo.bucketIndex,sourceLayerIndex:Bo.sourceLayerIndex,layoutVertexArrayOffset:0}),co=Ko.properties?Ko.properties.worldview:null;if(Z.localizable&&Z.worldview&&typeof co=="string")if(co==="all")Ko.properties.$localized=!0;else{if(!co.split(",").includes(Z.worldview))return;Ko.properties.$localized=!0,Ko.properties.worldview=Z.worldview}vl=Le&&Le.needGeometry?o.bD(Ko,!0):Ko}if(Le&&!(0,Le.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:Z.worldview},vl,this.retainedQueryData[Z.bucketInstanceId].tileID.canonical,new o.P(Gr.tileAnchorX,Gr.tileAnchorY),this.transform.calculateDistanceTileData(Le.unwrappedTileID)))return this.placements[Ii]=new If(!1,!1,!1,!0),void C.add(Ii);const Lo=$s.evaluate(vl,{});if((Gr.zOffset||0)+(Lo||0)>0&&this.frontCutoffStart>0){const Bo=2*this.frontCutoffStart-1,Ko=[Gr.tileAnchorX,Gr.tileAnchorY,0,1],co=o.aE(o.bE(),Ko,xe);if(co[1]/co[3]{Bo.tileID=this.retainedQueryData[Z.bucketInstanceId].tileID;const Ko=this.transform.elevation;Bo.elevation=Ps?Lo:Lo+o.bu.getAtTileOffset(Bo.tileID,new o.P(Bo.tileAnchorX,Bo.tileAnchorY),Ko,hd),Bo.elevation+=Gr.zOffset},$f=va.textBox;if($f){yu($f);const Bo=co=>{let pc=o.bk.horizontal;if(Z.allowVerticalPlacement&&!co&&this.prevPlacement){const Hh=this.prevPlacement.placedOrientations[Ii];Hh&&(this.placedOrientations[Ii]=Hh,pc=Hh,this.markUsedOrientation(Z,pc,Gr))}return pc},Ko=(co,pc)=>{if(Z.allowVerticalPlacement&&bo>0&&va.verticalTextBox){for(const Hh of Z.writingModes)if(Hh===o.bk.vertical?(Ca=pc(),dl=Ca):Ca=co(),Ca&&Ca.box&&Ca.box.length)break}else Ca=co()};if(Rn){let co=Rn;if(this.prevPlacement&&this.prevPlacement.variableOffsets[Ii]){const Rl=this.prevPlacement.variableOffsets[Ii];co.indexOf(Rl.anchor)>0&&(co=co.filter(Uf=>Uf!==Rl.anchor),co.unshift(Rl.anchor))}const pc=(Rl,Uf,x_)=>{const Gj=Z.getSymbolInstanceTextSize(kt,Gr,this.transform.zoom,Wa),Wj=(Rl.x2-Rl.x1)*Gj+2*Rl.padding,lk=(Rl.y2-Rl.y1)*Gj+2*Rl.padding,T1=Gr.hasIconTextFit&&!Dt?Uf:null;T1&&yu(T1);let Qy={box:[],offscreen:!1,occluded:!1};const ck=At?2*co.length:co.length;for(let Kp=0;Kp=co.length,Gr,Wa,Z,x_,T1,kt,Tt);if(g_&&(Qy=g_.placedGlyphBoxes,Qy&&Qy.box&&Qy.box.length)){Vi=!0,Hi=g_.shift;break}}return Qy};Ko(()=>pc($f,va.iconBox,o.bk.horizontal),()=>{const Rl=va.verticalTextBox;return Rl&&yu(Rl),Z.allowVerticalPlacement&&!(Ca&&Ca.box&&Ca.box.length)&&bo>0&&Rl?pc(Rl,va.verticalIconBox,o.bk.vertical):{box:null,offscreen:null,occluded:null}}),Ca&&(Vi=Ca.box,za=Ca.offscreen,Do=Ca.occluded);const Hh=Bo(!(!Ca||!Ca.box));if(!Vi&&this.prevPlacement){const Rl=this.prevPlacement.variableOffsets[Ii];Rl&&(this.variableOffsets[Ii]=Rl,this.markUsedJustification(Z,Rl.anchor,Gr,Hh))}}else{const co=(pc,Hh)=>{const Rl=Z.getSymbolInstanceTextSize(kt,Gr,this.transform.zoom,Wa),Uf=this.collisionIndex.placeCollisionBox(Z,Rl,pc,st,Je,Cr,new o.P(0,0),At,Ue,xe,xt.predicate);return Uf&&Uf.box&&Uf.box.length&&(this.markUsedOrientation(Z,Hh,Gr),this.placedOrientations[Ii]=Hh),Uf};Ko(()=>co($f,o.bk.horizontal),()=>{const pc=va.verticalTextBox;return Z.allowVerticalPlacement&&bo>0&&pc?(yu(pc),co(pc,o.bk.vertical)):{box:null,offscreen:null,occluded:null}}),Bo(!!(Ca&&Ca.box&&Ca.box.length))}}if(_o=Ca,Vi=_o&&_o.box&&_o.box.length>0,za=_o&&_o.offscreen,Do=_o&&_o.occluded,Gr.useRuntimeCollisionCircles){const Bo=Gr.centerJustifiedTextSymbolIndex>=0?Gr.centerJustifiedTextSymbolIndex:Gr.verticalPlacedTextSymbolIndex,Ko=Z.text.placedSymbolArray.get(Bo),co=o.bl(Z.textSizeData,kt,Ko),pc=te.get("text-padding");kc=this.collisionIndex.placeCollisionCircles(Z,At,Ko,Bo,Z.lineVertexArray,Z.glyphOffsetArray,co,xe,we,Re,R,ns,xt.predicate,Gr.collisionCircleDiameter*co/o.by,pc,this.retainedQueryData[Z.bucketInstanceId].tileID),Vi=At||kc.circles.length>0&&!kc.collisionDetected,za=za&&kc.offscreen,Do=kc.occluded}if(va.iconFeatureIndex&&(wh=va.iconFeatureIndex),va.iconBox){const Bo=Ko=>{yu(Ko);const co=Gr.hasIconTextFit&&Hi?xx(Hi.x,Hi.y,Gt,ns,this.transform.angle):new o.P(0,0),pc=Z.getSymbolInstanceIconSize(Tt,this.transform.zoom,Gr.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(Z,pc,Ko,st,Je,ir,co,Dt,Ue,xe,xt.predicate)};dl&&dl.box&&dl.box.length&&va.verticalIconBox?(oi=Bo(va.verticalIconBox),Fa=oi.box.length>0):(oi=Bo(va.iconBox),Fa=oi.box.length>0),za=za&&oi.offscreen,Nl=oi.occluded}const so=Ft||Gr.numHorizontalGlyphVertices===0&&bo===0,Cx=Qt||Gr.numIconVertices===0;if(so||Cx?Cx?so||(Fa=Fa&&Vi):Vi=Fa&&Vi:Fa=Vi=Fa&&Vi,Vi&&_o&&_o.box&&this.collisionIndex.insertCollisionBox(_o.box,te.get("text-ignore-placement"),Z.bucketInstanceId,dl&&dl.box&&Xc?Xc:ko,xt.ID),Fa&&oi&&this.collisionIndex.insertCollisionBox(oi.box,te.get("icon-ignore-placement"),Z.bucketInstanceId,wh,xt.ID),kc&&(Vi&&this.collisionIndex.insertCollisionCircles(kc.circles,te.get("text-ignore-placement"),Z.bucketInstanceId,ko,xt.ID),R)){const Bo=Z.bucketInstanceId;let Ko=this.collisionCircleArrays[Bo];Ko===void 0&&(Ko=this.collisionCircleArrays[Bo]=new Tr);for(let co=0;co=0;--Wa){const va=Gr[Wa];ya(Z.symbolInstances.get(va),va,Z.collisionArrays[va])}Z.hasAnyZOffset&&o.w(`${Z.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(Z.hasAnyZOffset){const Gr=Z.getSortedIndexesByZOffset();for(let Wa=0;Wa=0&&(y.text.placedSymbolArray.get(G).crossTileID=Re>=0&&G!==Re?0:xe),Z>=0&&(y.text.placedSymbolArray.get(Z).crossTileID=Re>=0&&Z!==Re?0:xe),te>=0&&(y.text.placedSymbolArray.get(te).crossTileID=Re>=0&&te!==Re?0:xe),de>=0&&(y.text.placedSymbolArray.get(de).crossTileID=Re>=0&&de!==Re?0:xe)}markUsedOrientation(y,C,R){const $=C===o.bk.horizontal||C===o.bk.horizontalOnly?C:0,G=C===o.bk.vertical?C:0,{leftJustifiedTextSymbolIndex:Z,centerJustifiedTextSymbolIndex:te,rightJustifiedTextSymbolIndex:de,verticalPlacedTextSymbolIndex:xe}=R,we=y.text.placedSymbolArray;Z>=0&&(we.get(Z).placedOrientation=$),te>=0&&(we.get(te).placedOrientation=$),de>=0&&(we.get(de).placedOrientation=$),xe>=0&&(we.get(xe).placedOrientation=G)}commit(y){this.commitTime=y,this.zoomAtLastRecencyCheck=this.transform.zoom;const C=this.prevPlacement;let R=!1;this.prevZoomAdjustment=C?C.zoomAdjustment(this.transform.zoom):0;const $=C?C.symbolFadeChange(y):1,G=C?C.opacities:{},Z=C?C.variableOffsets:{},te=C?C.placedOrientations:{};for(const de in this.placements){const xe=this.placements[de],we=G[de];we?(this.opacities[de]=new ug(we,$,xe.text,xe.icon,null,xe.clipped),R=R||xe.text!==we.text.placed||xe.icon!==we.icon.placed):(this.opacities[de]=new ug(null,$,xe.text,xe.icon,xe.skipFade,xe.clipped),R=R||xe.text||xe.icon)}for(const de in G){const xe=G[de];if(!this.opacities[de]){const we=new ug(xe,$,!1,!1);we.isHidden()||(this.opacities[de]=we,R=R||xe.text.placed||xe.icon.placed)}}for(const de in Z)this.variableOffsets[de]||!this.opacities[de]||this.opacities[de].isHidden()||(this.variableOffsets[de]=Z[de]);for(const de in te)this.placedOrientations[de]||!this.opacities[de]||this.opacities[de].isHidden()||(this.placedOrientations[de]=te[de]);R?this.lastPlacementChangeTime=y:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=C?C.lastPlacementChangeTime:y)}updateLayerOpacities(y,C,R,$){$&&(this.lastReplacementSourceUpdateTime=$.updateTime);const G=new Set;for(const Z of C){const te=Z.getBucket(y);te&&Z.latestFeatureIndex&&y.fqid===te.layerIds[0]&&(this.updateBucketOpacities(te,G,Z,Z.collisionBoxArray,R,$,Z.tileID,y.scope),te.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(te,Z.tileID),te.elevationType==="road"&&te.updateRoadElevation(Z.tileID.canonical),te.updateZOffset())}}updateBucketOpacities(y,C,R,$,G,Z,te,de){y.hasTextData()&&y.text.opacityVertexArray.clear(),y.hasIconData()&&y.icon.opacityVertexArray.clear(),y.hasIconCollisionBoxData()&&y.iconCollisionBox.collisionVertexArray.clear(),y.hasTextCollisionBoxData()&&y.textCollisionBox.collisionVertexArray.clear();const xe=y.layers[0].layout,we=y.layers[0].paint,Re=!!y.layers[0].dynamicFilter(),Le=new ug(null,0,!1,!1,!0),Ue=xe.get("text-allow-overlap"),st=xe.get("icon-allow-overlap"),Je=xe.get("text-variable-anchor"),mt=xe.get("text-rotation-alignment")==="map",ht=xe.get("text-pitch-alignment")==="map",kt=we.get("symbol-z-offset"),Tt=xe.get("symbol-elevation-reference")==="sea",xt=!kt.isConstant(),es=new ug(null,0,Ue&&(st||!y.hasIconData()||xe.get("icon-optional")),st&&(Ue||!y.hasTextData()||xe.get("text-optional")),!0);!y.collisionArrays&&$&&(y.hasIconCollisionBoxData()||y.hasTextCollisionBoxData())&&y.deserializeCollisionBoxes($);const Ft=(At,Dt,Gt)=>{for(let gs=0;gs
0||gs>0,Rn=$s>0,Sn=this.placedOrientations[ns],Cn=Sn===o.bk.vertical,dn=Sn===o.bk.horizontal||Sn===o.bk.horizontalOnly;!Ys&&!Rn||Us.isHidden()||Qt++;let mr=!1;if((Ys||Rn)&&Z)for(const Cr of y.activeReplacements){if(o.bz(Cr,G,o.bA.Symbol,de)||Cr.min.x>Ps||Ps>Cr.max.x||Cr.min.y>an||an>Cr.max.y)continue;const ir=o.bB(Ps,an,te.canonical,Cr.footprintTileId.canonical);if(mr=o.bC(ir,Cr.footprint),mr)break}if(mr&&this.collisionIndex.markSymbolAsClipped(y.bucketInstanceId,Dt.featureIndex),Ys){const Cr=mr?vx:yx(Us.text);Ft(y.text,Gt,Cn?vx:Cr),Ft(y.text,gs,dn?vx:Cr);const ir=Us.text.isHidden(),{leftJustifiedTextSymbolIndex:hr,centerJustifiedTextSymbolIndex:na,rightJustifiedTextSymbolIndex:wa,verticalPlacedTextSymbolIndex:ya}=Dt,Ga=y.text.placedSymbolArray,Gr=ir||Cn?1:0;hr>=0&&(Ga.get(hr).hidden=Gr),na>=0&&(Ga.get(na).hidden=Gr),wa>=0&&(Ga.get(wa).hidden=Gr),ya>=0&&(Ga.get(ya).hidden=ir||dn?1:0);const Wa=this.variableOffsets[ns];Wa&&this.markUsedJustification(y,Wa.anchor,Dt,Sn);const va=this.placedOrientations[ns];va&&(this.markUsedJustification(y,"left",Dt,va),this.markUsedOrientation(y,va,Dt))}if(Rn){const Cr=mr?vx:yx(Us.icon),{placedIconSymbolIndex:ir,verticalPlacedIconSymbolIndex:hr}=Dt,na=y.icon.placedSymbolArray,wa=Us.icon.isHidden()?1:0;ir>=0&&(Ft(y.icon,$s,Cn?vx:Cr),na.get(ir).hidden=wa),hr>=0&&(Ft(y.icon,Dt.numVerticalIconVertices,dn?vx:Cr),na.get(hr).hidden=wa)}if(y.hasIconCollisionBoxData()||y.hasTextCollisionBoxData()){const Cr=y.collisionArrays[At];if(Cr){let ir=new o.P(0,0),hr=!0;if(Cr.textBox||Cr.verticalTextBox){if(Je){const wa=this.variableOffsets[ns];wa?(ir=zh(wa.anchor,wa.width,wa.height,wa.textOffset,wa.textScale),mt&&ir._rotate(ht?this.transform.angle:-this.transform.angle)):hr=!1}Re&&(hr=!Us.clipped),Cr.textBox&&gx(y.textCollisionBox.collisionVertexArray,Us.text.placed,!hr||Cn,hs,Tt,ir.x,ir.y),Cr.verticalTextBox&&gx(y.textCollisionBox.collisionVertexArray,Us.text.placed,!hr||dn,hs,Tt,ir.x,ir.y)}const na=hr&&!!(!dn&&Cr.verticalIconBox);Cr.iconBox&&gx(y.iconCollisionBox.collisionVertexArray,Us.icon.placed,na,hs,Tt,Dt.hasIconTextFit?ir.x:0,Dt.hasIconTextFit?ir.y:0),Cr.verticalIconBox&&gx(y.iconCollisionBox.collisionVertexArray,Us.icon.placed,!na,hs,Tt,Dt.hasIconTextFit?ir.x:0,Dt.hasIconTextFit?ir.y:0)}}}if(y.fullyClipped=Qt===0,y.sortFeatures(this.transform.angle),this.retainedQueryData[y.bucketInstanceId]&&(this.retainedQueryData[y.bucketInstanceId].featureSortOrder=y.featureSortOrder),y.hasTextData()&&y.text.opacityVertexBuffer&&y.text.opacityVertexBuffer.updateData(y.text.opacityVertexArray),y.hasIconData()&&y.icon.opacityVertexBuffer&&y.icon.opacityVertexBuffer.updateData(y.icon.opacityVertexArray),y.hasIconCollisionBoxData()&&y.iconCollisionBox.collisionVertexBuffer&&y.iconCollisionBox.collisionVertexBuffer.updateData(y.iconCollisionBox.collisionVertexArray),y.hasTextCollisionBoxData()&&y.textCollisionBox.collisionVertexBuffer&&y.textCollisionBox.collisionVertexBuffer.updateData(y.textCollisionBox.collisionVertexArray),y.bucketInstanceId in this.collisionCircleArrays){const At=this.collisionCircleArrays[y.bucketInstanceId];y.placementInvProjMatrix=At.invProjMatrix,y.placementViewportMatrix=At.viewportMatrix,y.collisionCircleArray=At.circles,delete this.collisionCircleArrays[y.bucketInstanceId]}}symbolFadeChange(y){return this.fadeDuration===0?1:(y-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(y){return Math.max(0,(this.transform.zoom-y)/1.5)}hasTransitions(y){return y-this.lastPlacementChangeTimey}isStale(){return this.stale}setStale(){this.stale=!0}}function gx(I,y,C,R,$,G,Z){I.emplaceBack(y?1:0,C?1:0,G||0,Z||0,R,$?1:0),I.emplaceBack(y?1:0,C?1:0,G||0,Z||0,R,$?1:0),I.emplaceBack(y?1:0,C?1:0,G||0,Z||0,R,$?1:0),I.emplaceBack(y?1:0,C?1:0,G||0,Z||0,R,$?1:0)}const Dy=Math.pow(2,25),Gb=Math.pow(2,24),Yu=Math.pow(2,17),Dl=Math.pow(2,16),p6=Math.pow(2,9),Ry=Math.pow(2,8),Wb=Math.pow(2,1);function yx(I){if(I.opacity===0&&!I.placed)return 0;if(I.opacity===1&&I.placed)return 4294967295;const y=I.placed?1:0,C=Math.floor(127*I.opacity);return C*Dy+y*Gb+C*Yu+y*Dl+C*p6+y*Ry+C*Wb+y}const vx=0;class cj{constructor(y){this._sortAcrossTiles=y.layout.get("symbol-z-order")!=="viewport-y"&&y.layout.get("symbol-sort-key").constantOr(1)!==void 0,this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(y,C,R,$,G,Z){const te=this._bucketParts;for(;this._currentTileIndexde.sortKey-xe.sortKey));this._currentPartIndex{const de=o.o.now()-Z;return!this.isFullPlacementRequested()&&this._fadeDuration!==0&&de>2};for(;this._currentPlacementIndex>=0;){const de=C[y[this._currentPlacementIndex]],xe=this.placement.collisionIndex.transform.zoom;if(de.type==="symbol"&&de.visibility!=="none"&&(!de.minzoom||de.minzoom<=xe)&&(!de.maxzoom||de.maxzoom>xe)){const we=de,Re=we.layout.get("symbol-z-elevate"),Le=we.layout.get("symbol-sort-key").constantOr(1)!==void 0,Ue=we.layout.get("symbol-z-order"),st=Ue==="viewport-y"||Ue==="auto"&&!(Ue!=="viewport-y"&&Le),Je=we.layout.get("text-allow-overlap")||we.layout.get("icon-allow-overlap")||we.layout.get("text-ignore-placement")||we.layout.get("icon-ignore-placement"),mt=st&&Je,ht=this._inProgressLayer=this._inProgressLayer||new cj(we),kt=o.F(de.source,de.scope);if(ht.continuePlacement(Re||mt?$[kt]:R[kt],this.placement,this._showCollisionBoxes,de,te,G))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(y){return this.placement.commit(y),this.placement}}const Vd=512/o.an/2;class np{constructor(y,C,R){this.tileID=y,this.bucketInstanceId=R,this.index=new o.bI(C.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const $=y.canonical.x*o.an,G=y.canonical.y*o.an;for(let Z=0;Zmt-ht);for(const mt of Je){const ht=this.crossTileIDs[mt];if(this.keys[mt]===we&&!R.has(ht)){R.add(ht),xe.crossTileID=ht;break}}}}}class Hd{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class Op{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(y){const C=Math.round((y-this.lng)/360);if(C!==0)for(const R in this.indexes){const $=this.indexes[R],G={};for(const Z in $){const te=$[Z];te.tileID=te.tileID.unwrapTo(te.tileID.wrap+C),G[te.tileID.key]=te}this.indexes[R]=G}this.lng=y}addBucket(y,C,R){if(this.indexes[y.overscaledZ]&&this.indexes[y.overscaledZ][y.key]){if(this.indexes[y.overscaledZ][y.key].bucketInstanceId===C.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(y.overscaledZ,this.indexes[y.overscaledZ][y.key])}for(let G=0;Gy.overscaledZ)for(const te in Z){const de=Z[te];de.tileID.isChildOf(y)&&de.findMatches(C.symbolInstances,y,$)}else{const te=Z[y.scaledTo(Number(G)).key];te&&te.findMatches(C.symbolInstances,y,$)}}for(let G=0;G{C[R]=!0});for(const R in this.layerIndexes)C[R]||delete this.layerIndexes[R]}}const Ml=771;class sa{constructor(y,C,R,$){this.blendFunction=y,this.blendColor=C.toNonPremultipliedRenderColor(null),this.mask=R,this.blendEquation=$}}sa.Replace=[1,0,1,0],sa.disabled=new sa(sa.Replace,o.aq.transparent,[!1,!1,!1,!1]),sa.unblended=new sa(sa.Replace,o.aq.transparent,[!0,!0,!0,!0]),sa.alphaBlended=new sa([1,Ml,1,Ml],o.aq.transparent,[!0,!0,!0,!0]),sa.alphaBlendedNonPremultiplied=new sa([770,Ml,770,Ml],o.aq.transparent,[!0,!0,!0,!0]),sa.multiply=new sa([774,0,774,0],o.aq.transparent,[!0,!0,!0,!0]),sa.multiplyAccumulateAlpha=new sa([774,0,1,Ml],o.aq.transparent,[!0,!0,!0,!0]),sa.additive=new sa([1,1,1,1],o.aq.transparent,[!0,!0,!0,!0]);class ar{constructor(y,C,R){this.func=y,this.mask=C,this.range=R}}ar.ReadOnly=!1,ar.ReadWrite=!0,ar.disabled=new ar(519,ar.ReadOnly,[0,1]);const yl=7680;class oa{constructor(y,C,R,$,G,Z){this.test=y,this.ref=C,this.mask=R,this.fail=$,this.depthFail=G,this.pass=Z}}oa.disabled=new oa({func:519,mask:0},0,0,yl,yl,yl);const rp=1029,ym=2305;class Rr{constructor(y,C,R){this.enable=y,this.mode=C,this.frontFace=R}}function Oy(I,y){const C=o.bO(I,3);o.bR(I,y),o.bW(I,3,C)}function dj(I,y){const C=o.bL([]);return o.bM(C,C,-y),o.bN(C,C,-I),C}function i1(I,y){const C=[I[0],I[1],0],R=[y[0],y[1],0];if(o.ai(C)>=1e-15){const Z=o.ay([],C);o.bJ(R,Z,o.bi(R,Z)),y[0]=R[0],y[1]=R[1]}const $=o.bh([],y,I);if(o.bK($)<1e-15)return null;const G=Math.atan2(-$[1],$[0]);return dj(Math.atan2(Math.sqrt(I[0]*I[0]+I[1]*I[1]),-I[2]),G)}Rr.disabled=new Rr(!1,rp,ym),Rr.backCCW=new Rr(!0,rp,ym),Rr.backCW=new Rr(!0,rp,2304),Rr.frontCW=new Rr(!0,1028,2304),Rr.frontCCW=new Rr(!0,1028,ym);class Yb{constructor(y,C){this.position=y,this.orientation=C}get position(){return this._position}set position(y){if(y){const C=y instanceof o.ag?y:new o.ag(y[0],y[1],y[2]);this._renderWorldCopies&&(C.x=o.bs(C.x,0,1)),this._position=C}else this._position=null}lookAtPoint(y,C,R){if(this.orientation=null,!this.position)return;const $=this.position,G=R||(this._elevation?this._elevation.getAtPointOrZero(o.ag.fromLngLat(y)):0),Z=o.ag.fromLngLat(y,G),te=[Z.x-$.x,Z.y-$.y,Z.z-$.z];C||(C=[0,0,1]),C[2]=Math.abs(C[2]),this.orientation=i1(te,C)}setPitchBearing(y,C){this.orientation=dj(o.ap(y),o.ap(-C))}}class h0{constructor(y,C){this._transform=o.b9([]),this.orientation=C,this.position=y}get mercatorPosition(){const y=this.position;return new o.ag(y[0],y[1],y[2])}get position(){const y=o.bO(this._transform,3);return[y[0],y[1],y[2]]}set position(y){var C;y&&o.bW(this._transform,3,[(C=y)[0],C[1],C[2],1])}get orientation(){return this._orientation}set orientation(y){this._orientation=y||o.bL([]),y&&Oy(this._transform,this._orientation)}getPitchBearing(){const y=this.forward(),C=this.right();return{bearing:Math.atan2(-C[1],C[0]),pitch:Math.atan2(Math.sqrt(y[0]*y[0]+y[1]*y[1]),-y[2])}}setPitchBearing(y,C){this._orientation=dj(y,C),Oy(this._transform,this._orientation)}forward(){const y=o.bO(this._transform,2);return[-y[0],-y[1],-y[2]]}up(){const y=o.bO(this._transform,1);return[-y[0],-y[1],-y[2]]}right(){const y=o.bO(this._transform,0);return[y[0],y[1],y[2]]}getCameraToWorld(y,C){const R=new Float64Array(16);return o.b7(R,this.getWorldToCamera(y,C)),R}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(y,C,R){const $=this.position;o.bJ($,$,-y);const G=new Float64Array(16);return o.bP(G,[R,R,R]),o.bx(G,G,$),G[10]*=C,G}getWorldToCamera(y,C){const R=new Float64Array(16),$=new Float64Array(4),G=this.position;return o.bQ($,this._orientation),o.bJ(G,G,-y),o.bR(R,$),o.bx(R,R,G),R[1]*=-1,R[5]*=-1,R[9]*=-1,R[13]*=-1,R[8]*=C,R[9]*=C,R[10]*=C,R[11]*=C,R}getCameraToClipPerspective(y,C,R,$){const G=new Float64Array(16);return o.bS(G,y,C,R,$),G}getCameraToClipOrthographic(y,C,R,$,G,Z){const te=new Float64Array(16);return o.bT(te,y,C,R,$,G,Z),te}getDistanceToElevation(y,C=!1){const R=y===0?0:o.bU(y,C?o.bV(this.position[1]):this.position[1]),$=this.forward();return(R-this.position[2])/$[2]}clone(){return new h0([...this.position],[...this.orientation])}}const Lf=(I,y)=>({u_matrix:I,u_ground_shadow_factor:y});class vm{constructor(y=0,C=0,R=0,$=0){if(isNaN(y)||y<0||isNaN(C)||C<0||isNaN(R)||R<0||isNaN($)||$<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=y,this.bottom=C,this.left=R,this.right=$}interpolate(y,C,R){return C.top!=null&&y.top!=null&&(this.top=o.am(y.top,C.top,R)),C.bottom!=null&&y.bottom!=null&&(this.bottom=o.am(y.bottom,C.bottom,R)),C.left!=null&&y.left!=null&&(this.left=o.am(y.left,C.left,R)),C.right!=null&&y.right!=null&&(this.right=o.am(y.right,C.right,R)),this}getCenter(y,C){const R=o.aC((this.left+y-this.right)/2,0,y),$=o.aC((this.top+C-this.bottom)/2,0,C);return new o.P(R,$)}equals(y){return this.top===y.top&&this.bottom===y.bottom&&this.left===y.left&&this.right===y.right}clone(){return new vm(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const Df=15;class ap{constructor(y,C,R,$,G,Z,te){this.tileSize=512,this._renderWorldCopies=G===void 0||G,this._minZoom=y||0,this._maxZoom=C||22,this._minPitch=R??0,this._maxPitch=$??60,this.setProjection(Z),this.setMaxBounds(te),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 vm,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new h0,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 y=new ap(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies,this.getProjection(),this.maxBounds);return y._elevation=this._elevation,y._centerAltitude=this._centerAltitude,y._centerAltitudeValidForExaggeration=this._centerAltitudeValidForExaggeration,y.tileSize=this.tileSize,y.mercatorFromTransition=this.mercatorFromTransition,y.width=this.width,y.height=this.height,y.cameraElevationReference=this.cameraElevationReference,y._center=this._center,y._setZoom(this.zoom),y._seaLevelZoom=this._seaLevelZoom,y.angle=this.angle,y._fov=this._fov,y._pitch=this._pitch,y._nearZ=this._nearZ,y._farZ=this._farZ,y._nearClipOffset=this._nearClipOffset,y._averageElevation=this._averageElevation,y._orthographicProjectionAtLowPitch=this._orthographicProjectionAtLowPitch,y._unmodified=this._unmodified,y._edgeInsets=this._edgeInsets.clone(),y._camera=this._camera.clone(),y._calcMatrices(),y.freezeTileCoverage=this.freezeTileCoverage,y.frustumCorners=this.frustumCorners,y._allowWorldUnderZoom=this._allowWorldUnderZoom,y}get isOrthographic(){return this.projection.name!=="globe"&&this._orthographicProjectionAtLowPitch&&this.pitch0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||y===Number.NEGATIVE_INFINITY&&(!C||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const R=this._elevation;C||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&R.exaggeration()&&this._centerAltitudeValidForExaggeration!==R.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*R.exaggeration(),this._centerAltitudeValidForExaggeration=R.exaggeration()):(this._centerAltitude=y||0,this._centerAltitudeValidForExaggeration=R.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(this._centerAltitudeValidForExaggeration===void 0)return;const y=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(y)}sampleAverageElevation(){if(!this._elevation)return 0;const y=this._elevation,C=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],R=this.horizonLineFromTop();let $=0,G=0;for(let Z=0;Z{const mt=o.ck(Le,Re,Ue,st,Je);de.has(mt)||(G.push(new o.aR(Re,Le,Ue,st,Je)),de.add(mt))};for(let Re=0;ReLe.canonical.z)continue;const Ue=Le.canonical,st=Le.overscaledZ,Je=Le.wrap,mt=1<0,Tt=Ue.y+10,es=Le.wrap-(kt?0:1),Ft=Le.wrap+(ht?0:1),Qt=kt?Ue.x-1:mt-1,At=ht?Ue.x+1:0;if(Z)R[0]<0?(xe(st,Ft,Ue.z,At,Ue.y),R[1]<0&&Tt&&(xe(st,Je,Ue.z,Ue.x,Ue.y+1),xe(st,Ft,Ue.z,At,Ue.y+1)),R[1]>0&&xt&&(xe(st,Je,Ue.z,Ue.x,Ue.y-1),xe(st,Ft,Ue.z,At,Ue.y-1))):R[0]>0?(xe(st,es,Ue.z,Qt,Ue.y),R[1]<0&&Tt&&(xe(st,Je,Ue.z,Ue.x,Ue.y+1),xe(st,es,Ue.z,Qt,Ue.y+1)),R[1]>0&&xt&&(xe(st,Je,Ue.z,Ue.x,Ue.y-1),xe(st,es,Ue.z,Qt,Ue.y-1))):R[1]<0&&Tt?xe(st,Je,Ue.z,Ue.x,Ue.y+1):xt&&xe(st,Je,Ue.z,Ue.x,Ue.y-1);else{const Dt=Le.visibleQuadrants;1&Dt&&(xe(st,es,Ue.z,Qt,Ue.y),xt&&(xe(st,Je,Ue.z,Ue.x,Ue.y-1),xe(st,es,Ue.z,Qt,Ue.y-1))),2&Dt&&(xe(st,Ft,Ue.z,At,Ue.y),xt&&(xe(st,Je,Ue.z,Ue.x,Ue.y-1),xe(st,Ft,Ue.z,At,Ue.y-1))),4&Dt&&(xe(st,es,Ue.z,Qt,Ue.y),Tt&&(xe(st,Je,Ue.z,Ue.x,Ue.y+1),xe(st,es,Ue.z,Qt,Ue.y+1))),8&Dt&&(xe(st,Ft,Ue.z,At,Ue.y),Tt&&(xe(st,Je,Ue.z,Ue.x,Ue.y+1),xe(st,Ft,Ue.z,At,Ue.y+1)))}}const we=[];for(const Re of G)G.some(Le=>Re.isChildOf(Le))||we.push(Re);if(G=we.filter(Re=>!y.some(Le=>!!(Re.overscaledZ{const ht=mt.canonical.x+.5-Ue[0],kt=mt.canonical.y+.5-Ue[1];return ht*ht+kt*kt{const Qt=o.ck(Tt,kt,xt,es,Ft);G.has(Qt)||($.push(new o.aR(kt,Tt,xt,es,Ft)),G.add(Qt))},te=y.reduce((kt,Tt)=>Math.max(kt,Tt.overscaledZ),R),de=1<{const xt=Math.floor(kt[0]),es=Math.floor(kt[1]),Ft=(kt[0]-xt)*o.an,Qt=(kt[1]-es)*o.an,At=Math.floor(Tt[0]),Dt=Math.floor(Tt[1]),Gt=(Tt[0]-At)*o.an,gs=(Tt[1]-Dt)*o.an;for(let ns=-1;ns<=1;ns++){const $s=xt+ns;if(!($s<0||$s>=de)){we.x=Ft-ns*o.an,Re.x=Gt-($s-At)*o.an;for(let Ps=-1;Ps<=1;Ps++){const an=es+Ps;we.y=Qt-Ps*o.an,Re.y=gs-(an-Dt)*o.an,o.cI(we,Re,xe)&&Z(te,0,R,$s,an)}}}},Ue=C.points,st=Ue[o.c9],Je=Ue[o.ca],mt=this._projectToGround(st,Ue[o.cb]),ht=this._projectToGround(Je,Ue[o.cc]);return Le(st,mt),Le(Je,ht),$}_projectToGround(y,C){return o.cd(o.ce(),y,C,y[2]/(y[2]-C[2]))}_projectToZ(y,C,R){const $=y[2]-C[2];return Math.abs($)<1e-6?o.cf(y):o.cd(o.ce(),y,C,(y[2]-R)/$)}extendTileCoverForTunnels(y,C,R,$){if(R<18)return[];const G=C.points,Z=G[o.cg],te=G[o.ch],de=G[o.ci],xe=G[o.cj];if(de[2]>=0&&xe[2]>=0||Z[2]<=0||te[2]<=0)return[];const we=de[2]<0?this._projectToZ(Z,de,0):de,Re=xe[2]<0?this._projectToZ(te,xe,0):xe,Le=-$,Ue=de[2]3&&(Je.length=3),Je}_findExtensionTilesInQuad(y,C,R,$){const G=[],Z=new Set;for(const At of y)Z.add(At.key);const te=y.reduce((At,Dt)=>Math.max(At,Dt.overscaledZ),C),de=1<{const Gt=At.canonical.x+.5-Ft,gs=At.canonical.y+.5-Qt,ns=Dt.canonical.x+.5-Ft,$s=Dt.canonical.y+.5-Qt;return Gt*Gt+gs*gs-(ns*ns+$s*$s)||At.canonical.x-Dt.canonical.x||At.canonical.y-Dt.canonical.y}),G}coveringTiles(y){let C=this.coveringZoomLevel(y);const R=C,$=this.elevation&&this.elevation.exaggeration(),G=$&&!y.isTerrainDEM,Z=this.projection.name==="mercator";if(y.minzoom!==void 0&&Cy.maxzoom&&(C=y.maxzoom);const te=this.locationCoordinate(this.center),de=this.center.lat,xe=1<{const Us=new o.ag(hs.x+25e-6,hs.y,hs.z),Ys=new o.ag(hs.x,hs.y+25e-6,hs.z),Rn=hs.toLngLat(),Sn=Us.toLngLat(),Cn=Ys.toLngLat(),dn=this.locationCoordinate(Rn),mr=this.locationCoordinate(Sn),Cr=this.locationCoordinate(Cn),ir=Math.hypot(mr.x-dn.x,mr.y-dn.y),hr=Math.hypot(Cr.x-dn.x,Cr.y-dn.y);return Math.sqrt(ir*hr)*Qt/25e-6},Dt=hs=>{const zs=es,Us=Ft;return{aabb:o.cp(this,xe,0,0,0,hs,Us,zs,this.projection),zoom:0,x:0,y:0,minZ:Us,maxZ:zs,wrap:hs,fullyVisible:!1}},Gt=[];let gs=[];const ns=C,$s=y.reparseOverscaled?R:C,Ps=(mt-this._centerAltitude)*Je,an=hs=>{if(!this._elevation||!hs.tileID||!Z)return;const zs=this._elevation.getMinMaxForTile(hs.tileID),Us=hs.aabb;zs?(Us.min[2]=zs.min,Us.max[2]=zs.max,Us.center[2]=(Us.min[2]+Us.max[2])/2):(hs.shouldSplit=Ns(hs),hs.shouldSplit||(Us.min[2]=Us.max[2]=Us.center[2]=this._centerAltitude))},mn=(hs,zs)=>{if(.707*zs{if(hs.zoom=.9)return!0}else if(G&&(Ys=hs.aabb.distanceZ(ht)*Je),this.projection.isReprojectedInTileSpace&&R<=5){const hr=Math.pow(2,hs.zoom),na=At(new o.ag((hs.x+.5)/hr,(hs.y+.5)/hr));Rn=na>.85?1:na}if(!Z&&!Re){const hr=Math.sqrt(zs*zs+Us*Us+Ys*Ys);let na=(1<0;){const hs=Gt.pop(),zs=hs.x,Us=hs.y;let Ys=hs.fullyVisible;const Rn=()=>this.projection.name==="globe"&&(hs.y===0||hs.y===(1<Sn)continue;let Cn=0;if(!Ys){let ir=kt?hs.aabb.intersectsPrecise(Ue):hs.aabb.intersectsPreciseFlat(Ue);if(ir===0&&Rn()){const hr=new o.cn(hs.zoom,zs,Us);ir=o.co(this,xe,hr,!0).intersectsPrecise(Ue)}if(ir===0)continue;if(y.calculateQuadrantVisibility)if(Ue.containsPoint(hs.aabb.center))Cn=15;else for(let hr=0;hr<4;hr++)hs.aabb.quadrant(hr).intersects(Ue)!==0&&(Cn|=1<>1),mr={aabb:Z?hs.aabb.quadrant(Sn):o.cp(this,xe,hs.zoom+1,Cn,dn,hs.wrap,hs.minZ,hs.maxZ,this.projection),zoom:hs.zoom+1,x:Cn,y:dn,wrap:hs.wrap,fullyVisible:Ys,tileID:void 0,shouldSplit:void 0,minZ:hs.minZ,maxZ:hs.maxZ};G&&!Re&&(mr.tileID=new o.aR(hs.zoom+1===ns?$s:hs.zoom+1,hs.wrap,hs.zoom+1,Cn,dn),an(mr)),Gt.push(mr)}}if(this.fogCullDistSq){const hs=this.fogCullDistSq,zs=this.horizonLineFromTop();gs=gs.filter(Us=>{const Ys=[0,0,0,1],Rn=[o.an,o.an,0,1],Sn=this.calculateFogTileMatrix(Us.tileID.toUnwrapped());o.aE(Ys,Ys,Sn),o.aE(Rn,Rn,Sn);const Cn=o.cq([],Ys,Rn),dn=o.cr([],Ys,Rn),mr=o.cK(Cn,dn);if(mr===0)return!0;let Cr=!1;const ir=this._elevation;if(ir&&mr>hs&&zs!==0){const hr=this.calculateProjMatrix(Us.tileID.toUnwrapped());let na;y.isTerrainDEM||(na=ir.getMinMaxForTile(Us.tileID)),na||(na={min:Ft,max:es});const wa=o.cs(this.rotation),ya=[wa[0]*o.an,wa[1]*o.an,na.max];o.ah(ya,ya,hr),Cr=(1-ya[1])*this.height*.5hs.distanceSq-zs.distanceSq).map(hs=>hs.tileID)}resize(y,C){this.width=y,this.height=C,this.pixelsToGLUnits=[2/y,-2/C],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(y){return Math.pow(2,y)}scaleZoom(y){return Math.log2(y)}project(y){const C=o.aC(y.lat,-o.ct,o.ct),R=this.projection.project(y.lng,C);return new o.P(R.x*this.worldSize,R.y*this.worldSize)}unproject(y){return this.projection.unproject(y.x/this.worldSize,y.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(y,C){let R,$;const G=this.centerPoint;if(this.projection.name==="globe"){const te=this.worldSize;R=(C.x-G.x)/te,$=(C.y-G.y)/te}else{const te=this.pointCoordinate(C),de=this.pointCoordinate(G);R=te.x-de.x,$=te.y-de.y}const Z=this.locationCoordinate(y);this.setLocation(new o.ag(Z.x-R,Z.y-$))}setLocation(y){this.center=this.coordinateLocation(y),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(y,C){return this.projection.locationPoint(this,y,C)}locationPoint3D(y,C){return this.projection.locationPoint(this,y,C,!0)}pointLocation(y){return this.coordinateLocation(this.pointCoordinate(y))}pointLocation3D(y,C){return this.coordinateLocation(this.pointCoordinate3D(y,C))}locationCoordinate(y,C){const R=C?o.bU(C,y.lat):void 0,$=this.projection.project(y.lng,y.lat);return new o.ag($.x,$.y,R)}coordinateLocation(y){return this.projection.unproject(y.x,y.y)}pointRayIntersection(y,C){const R=C??this._centerAltitude,$=[y.x,y.y,0,1],G=[y.x,y.y,1,1];o.aE($,$,this.pixelMatrixInverse),o.aE(G,G,this.pixelMatrixInverse);const Z=G[3];o.cu($,$,1/$[3]),o.cu(G,G,1/Z);const te=$[2],de=G[2];return{p0:$,p1:G,t:te===de?0:(R-te)/(de-te)}}screenPointToMercatorRay(y){const C=[y.x,y.y,0,1],R=[y.x,y.y,1,1];return o.aE(C,C,this.pixelMatrixInverse),o.aE(R,R,this.pixelMatrixInverse),o.cu(C,C,1/C[3]),o.cu(R,R,1/R[3]),C[2]=o.bU(C[2],this._center.lat)*this.worldSize,R[2]=o.bU(R[2],this._center.lat)*this.worldSize,o.cu(C,C,1/this.worldSize),o.cu(R,R,1/this.worldSize),new o.az([C[0],C[1],C[2]],o.ay([],o.ax([],R,C)))}rayIntersectionCoordinate(y){const{p0:C,p1:R,t:$}=y,G=o.bU(C[2],this._center.lat),Z=o.bU(R[2],this._center.lat);return new o.ag(o.am(C[0],R[0],$)/this.worldSize,o.am(C[1],R[1],$)/this.worldSize,o.am(G,Z,$))}pointCoordinate(y,C=this._centerAltitude){return this.projection.pointCoordinate(this,y.x,y.y,C)}pointCoordinate3D(y,C){if(!this.elevation)return this.pointCoordinate(y,C);let R=this.projection.pointCoordinate3D(this,y.x,y.y);if(R)return new o.ag(R[0],R[1],R[2]);let $=0,G=this.horizonLineFromTop();if(y.y>G)return this.pointCoordinate(y,C);const Z=.02*G,te=y.clone();for(let de=0;de<10&&G-$>Z;de++){te.y=o.am($,G,.66);const xe=this.projection.pointCoordinate3D(this,te.x,te.y);xe?(G=te.y,R=xe):$=te.y}return R?new o.ag(R[0],R[1],R[2]):this.pointCoordinate(y)}isPointAboveHorizon(y){return this.projection.isPointAboveHorizon(this,y)}isPointOnSurface(y){if(y.y<0||y.y>this.height||y.x<0||y.x>this.width)return!1;if(this.elevation||this.zoom>=o.cv)return!this.isPointAboveHorizon(y);const C=this.pointCoordinate(y);return C.y>=0&&C.y<=1}_coordinatePoint(y,C){const R=C&&this.elevation?this.elevation.getAtPointOrZero(y,this._centerAltitude):this._centerAltitude,$=[y.x*this.worldSize,y.y*this.worldSize,R+y.toAltitude(),1];return o.aE($,$,this.pixelMatrix),$[3]>0?new o.P($[0]/$[3],$[1]/$[3]):new o.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:y,left:C}=this._edgeInsets,R=this.height-this._edgeInsets.bottom,$=this.width-this._edgeInsets.right,G=this.pointLocation3D(new o.P(C,y)),Z=this.pointLocation3D(new o.P($,y)),te=this.pointLocation3D(new o.P($,R)),de=this.pointLocation3D(new o.P(C,R));let xe=Math.min(G.lng,Z.lng,te.lng,de.lng),we=Math.max(G.lng,Z.lng,te.lng,de.lng),Re=Math.min(G.lat,Z.lat,te.lat,de.lat),Le=Math.max(G.lat,Z.lat,te.lat,de.lat);const Ue=Math.pow(2,-this.zoom)/16*270,st=this.projection.name==="globe"?1:4,Je=(mt,ht,kt,Tt,xt)=>{const es=(mt+kt)/2,Ft=(ht+Tt)/2,Qt=new o.P(es,Ft),{lng:At,lat:Dt}=this.pointLocation3D(Qt),Gt=Math.max(0,xe-At,Re-Dt,At-we,Dt-Le);xe=Math.min(xe,At),we=Math.max(we,At),Re=Math.min(Re,Dt),Le=Math.max(Le,Dt),(xtUe)&&(Je(mt,ht,es,Ft,xt+1),Je(es,Ft,kt,Tt,xt+1))};if(Je(C,y,$,y,1),Je($,y,$,R,1),Je($,R,C,R,1),Je(C,R,C,y,1),this.projection.name==="globe"){const[mt,ht]=o.cw(this);mt?(Le=90,we=180,xe=-180):ht&&(Re=-90,we=180,xe=-180)}return new o.aK(new o.aU(xe,Re),new o.aU(we,Le))}_getBoundsRectangular(y,C){const{top:R,left:$}=this._edgeInsets,G=this.height-this._edgeInsets.bottom,Z=this.width-this._edgeInsets.right,te=new o.P($,R),de=new o.P(Z,R),xe=new o.P(Z,G),we=new o.P($,G);let Re=this.pointCoordinate(te,y),Le=this.pointCoordinate(de,y);const Ue=this.pointCoordinate(xe,C),st=this.pointCoordinate(we,C),Je=(mt,ht)=>(ht.y-mt.y)/(ht.x-mt.x);return Re.y>1&&Le.y>=0?Re=new o.ag((1-st.y)/Je(st,Re)+st.x,1):Re.y<0&&Le.y<=1&&(Re=new o.ag(-st.y/Je(st,Re)+st.x,0)),Le.y>1&&Re.y>=0?Le=new o.ag((1-Ue.y)/Je(Ue,Le)+Ue.x,1):Le.y<0&&Re.y<=1&&(Le=new o.ag(-Ue.y/Je(Ue,Le)+Ue.x,0)),new o.aK().extend(this.coordinateLocation(Re)).extend(this.coordinateLocation(Le)).extend(this.coordinateLocation(st)).extend(this.coordinateLocation(Ue))}_getBoundsRectangularTerrain(){const y=this.elevation;if(!y.visibleDemTiles.length||y.isUsingMockSource())return this._getBoundsRectangular(0,0);const C=y.visibleDemTiles.reduce((R,$)=>{if($.dem){const G=$.dem.tree;R.min=Math.min(R.min,G.minimums[0]),R.max=Math.max(R.max,G.maximums[0])}return R},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(C.min*y.exaggeration(),C.max*y.exaggeration())}getBounds(){return this.projection.name==="mercator"||this.projection.name==="equirectangular"?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(y=!0){const C=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,R=this.height/2-C*(1-this._horizonShift);return y?Math.max(0,R):R}getMaxBounds(){return this.maxBounds}setMaxBounds(y){this.maxBounds=y,this.minLat=-o.ct,this.maxLat=o.ct,this.minLng=-180,this.maxLng=180,y&&(this.minLat=y.getSouth(),this.maxLat=y.getNorth(),this.minLng=y.getWest(),this.maxLng=y.getEast(),this.maxLngRe&&(te=Re-xe),Re-weUe&&(Z=Ue-de),Ue-Le{for(let Ns=0;Ns<16;Ns++)$s[Ns]=o.am(Ps[Ns],an[Ns],mn)})(te,te,de,o.cL(this.pitch>=Df?1:this.pitch/Df))}else te=de;const xe=o.cz([],de,Z);let we=o.cz([],te,Z);if(this.projection.isReprojectedInTileSpace){const Dt=this.locationCoordinate(this.center),Gt=o.b9([]);o.bx(Gt,Gt,[Dt.x*this.worldSize,Dt.y*this.worldSize,0]),o.aD(Gt,Gt,o.cA(this)),o.bx(Gt,Gt,[-Dt.x*this.worldSize,-Dt.y*this.worldSize,0]),o.aD(we,we,Gt),o.aD(xe,xe,Gt),this.inverseAdjustmentMatrix=o.cB(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=o.cC([],we,[this.worldSize,this.worldSize,this.worldSize/G,1]),this.projMatrix=we,this.invProjMatrix=o.b7(new Float64Array(16),this.projMatrix),C){const Dt=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);Dt[8]=2*-y.x/this.width,Dt[9]=2*y.y/this.height,this.expandedFarZProjMatrix=o.cz([],Dt,Z)}else this.expandedFarZProjMatrix=this.projMatrix;const Re=o.b7([],te);this.frustumCorners=o.cD.fromInvProjectionMatrix(Re,this.horizonLineFromTop(),this.height),this.cameraFrustum=o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!C);const Le=new Float32Array(16);o.b9(Le),o.cC(Le,Le,[1,-1,1]),o.cE(Le,Le,this._pitch),o.ba(Le,Le,this.angle);const Ue=o.bS(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=o.b8(Ue);const st=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;Ue[8]=2*-y.x/this.width,Ue[9]=2*(y.y+st)/this.height,this.skyboxMatrix=o.aD(Le,Ue,Le);const Je=this.point,mt=Je.x,ht=Je.y,kt=this.width%2/2,Tt=this.height%2/2,xt=Math.cos(this.angle),es=Math.sin(this.angle),Ft=mt-Math.round(mt)+xt*kt+es*Tt,Qt=ht-Math.round(ht)+xt*Tt+es*kt,At=new Float64Array(we);if(o.bx(At,At,[Ft>.5?Ft-1:Ft,Qt>.5?Qt-1:Qt,0]),this.alignedProjMatrix=At,we=o.bb(),o.cC(we,we,[this.width/2,-this.height/2,1]),o.bx(we,we,[1,-1,0]),this.labelPlaneMatrix=we,we=o.bb(),o.cC(we,we,[1,-1,1]),o.bx(we,we,[-1,-1,0]),o.cC(we,we,[2/this.width,2/this.height,1]),this.glCoordMatrix=we,this.pixelMatrix=o.aD(new Float64Array(16),this.labelPlaneMatrix,xe),this._calcFogMatrices(),this._distanceTileDataCache={},we=o.b7(new Float64Array(16),this.pixelMatrix),!we)throw new Error("failed to invert matrix");if(this.pixelMatrixInverse=we,this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=o.cF(this);const Dt=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=o.ah(Dt,Dt,Z),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=we;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const y=this.cameraWorldSizeForFog,C=this.cameraPixelsPerMeter,R=this._camera.position,$=1/this.height/this._pixelsPerMercatorPixel,G=[y,y,C];o.bJ(G,G,$),o.bJ(R,R,-1),o.cG(R,R,G);const Z=o.bb();o.bx(Z,Z,R),o.cC(Z,Z,G),this.mercatorFogMatrix=Z,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(y,C,$)}_computeCameraPosition(y){const C=(y=y||this.pixelsPerMeter)/this.pixelsPerMeter,R=this._camera.forward(),$=this.point,G=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*C-y/this.worldSize*this._centerAltitude;return[$.x/this.worldSize-R[0]*G,$.y/this.worldSize-R[1]*G,y/this.worldSize*this._centerAltitude-R[2]*G]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(y){const C=this._maxCameraBoundsDistance()*Math.cos(this._pitch),R=this._camera.position[2],$=y[2];let G=1;this.projection.wrap&&(this.center=this.center.wrap()),$>0&&(G=Math.min((C-R)/$,1)),this._camera.position=o.bg([],this._camera.position,y,G),this._updateStateFromCamera()}_updateStateFromCamera(){const y=this._camera.position,C=this._camera.forward(),{pitch:R,bearing:$}=this._camera.getPitchBearing(),G=o.bU(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,Z=this._mercatorZfromZoom(this._maxZoom)*Math.cos(o.ap(this._maxPitch)),te=Math.max((y[2]-G)/Math.cos(R),Z),de=this._zoomFromMercatorZ(te);o.bg(y,y,C,te),this._pitch=o.aC(R,o.ap(this.minPitch),o.ap(this.maxPitch)),this.angle=o.bs($,-Math.PI,Math.PI),this._setZoom(o.aC(de,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new o.ag(y[0],y[1],y[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(y){return Math.pow(2,y)*this.tileSize}_mercatorZfromZoom(y){return this.cameraToCenterDistance/this._worldSizeFromZoom(y)}_minimumHeightOverTerrain(){const y=Math.min(this._seaLevelZoom!=null?this._seaLevelZoom:this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(y)}_zoomFromMercatorZ(y){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,y)*this.tileSize))}zoomFromMercatorZAdjusted(y){let C=0,R=o.cv,$=0,G=1/0;for(;R-C>1e-6&&R>C;){const Z=C+.5*(R-C),te=this.tileSize*Math.pow(2,Z),de=this.getCameraToCenterDistance(this.projection,Z,te),xe=this.scaleZoom(de/(Math.max(0,y)*this.tileSize)),we=Math.abs(Z-xe);wexe||Le.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(y,C){const R=o.ai(o.ax([],this._camera.position,y)),$=this._zoomFromMercatorZ(R)+C;return R-this._mercatorZfromZoom($)}getCameraPoint(){if(this.projection.name==="globe"){const y=function([C,R,$],G){const Z=[C,R,$,1];o.aE(Z,Z,G);const te=Z[3]=Math.max(Z[3],1e-6);return Z[0]/=te,Z[1]/=te,Z[2]/=te,Z}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new o.P(y[0],y[1])}{const y=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new o.P(0,y))}}getCameraToCenterDistance(y,C=this.zoom,R=this.worldSize){const $=o.cy(y,C,this.width,this.height,1024),G=y.pixelSpaceConversion(this.center.lat,R,$);let Z=.5/Math.tan(.5*this._fov)*this.height*G;return this.isOrthographic&&(Z=o.am(1,Z,o.cL(this.pitch>=Df?1:this.pitch/Df))),Z}getWorldToCameraMatrix(){const y=this._camera.getWorldToCamera(this.worldSize,this.projection.zAxisUnit==="meters"?this.pixelsPerMeter:1);return this.projection.name==="globe"&&o.aD(y,y,this.globeMatrix),y}getFrustum(y){return o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,y,this.projection.zAxisUnit==="meters")}}const Bc=(I,y)=>{if(y>0&&I.terrain&&o.w("Cutoff is currently disabled on terrain"),y<=0||I.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const C=I.transform,R=C.pitch,$=C.isLODDisabled(!1)?60:30;if(R<$-15)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const G=C._farZ-C._nearZ,Z=y*C.height*1.3,te=Math.pow(2,.85*Math.max(C._zoom-I.minCutoffZoom,0)),de=1.4*C.cameraToCenterDistance*te,xe=o.aj($-15,$,R),we=(1-(Re=xe))*(C._farZ+Z)+Re*de;var Re;const Le=Math.min(Z,we-C._nearZ);return{shouldRenderCutoff:xe>0,uniformValues:{u_cutoff_params:[C._nearZ,C._farZ,(we-C._nearZ)/G,(we-Le-C._nearZ)/G]}}},Fp=2048;class uj{constructor(y,C){this.aabb=y,this.lastCascade=C}}class PN{add(y,C){const R=this.receivers[y.key];R!==void 0?(R.aabb.min[0]=Math.min(R.aabb.min[0],C.min[0]),R.aabb.min[1]=Math.min(R.aabb.min[1],C.min[1]),R.aabb.min[2]=Math.min(R.aabb.min[2],C.min[2]),R.aabb.max[0]=Math.max(R.aabb.max[0],C.max[0]),R.aabb.max[1]=Math.max(R.aabb.max[1],C.max[1]),R.aabb.max[2]=Math.max(R.aabb.max[2],C.max[2])):this.receivers[y.key]=new uj(C,null)}clear(){this.receivers={}}get(y){return this.receivers[y.key]}computeRequiredCascades(y,C,R){const $=o.cU.fromPoints(y.points);let G=0;for(const Z in this.receivers){const te=this.receivers[Z];if(!te||!$.intersectsAabb(te.aabb))continue;te.aabb.min=$.closestPoint(te.aabb.min),te.aabb.max=$.closestPoint(te.aabb.max);const de=te.aabb.getCorners();for(let xe=0;xe1||Le[1]<-1||Le[1]>1){we=!1;break}}if(te.lastCascade=xe,G=Math.max(G,xe),we)break}}return G+1}}class ec{constructor(y){this.painter=y,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new PN,this._depthMode=new ar(y.context.gl.LEQUAL,ar.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 y of this._cascades)y.texture.destroy(),y.framebuffer.destroy();this._cascades=[]}updateShadowParameters(y,C){const R=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!C||!C.properties)return;const $=C.properties.get("shadow-intensity"),G=C.properties.get("shadow-draw-before-layer");if(!C.shadowsEnabled()||$<=0)return;let Z=-1,te=0;for(const ht of R.style.order){const kt=R.style._mergedLayers[ht];kt.hasShadowPass()&&!kt.isHidden(y.zoom)&&(Z=te),!G||G!==ht&&G!==kt.slot||(this._drawShadowAfterLayer=te>0?te-1:0),te+=1}if(this._enabled=Z>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=Z);const de=R.context,xe=Fp,we=Fp;if(this._cascades.length===0||Fp!==this._cascades[0].texture.size[0]){this._cascades=[];for(let ht=0;ht<2;++ht){const kt=de.gl,Tt=de.createFramebuffer(xe,we,0,"texture"),xt=new o.T(de,{width:xe,height:we,data:null},kt.DEPTH_COMPONENT16);Tt.depthAttachment.set(xt.texture),this._cascades.push({framebuffer:Tt,texture:xt,matrix:[],far:0,boundingSphereRadius:0,frustum:new o.cl,scale:0})}}this.shadowDirection=LN(C);let Re=0;if(y.elevation){const ht=y.elevation,kt=[1e4,-1e4];ht.visibleDemTiles.filter(Tt=>Tt.dem).forEach(Tt=>{const xt=Tt.dem.tree;kt[0]=Math.min(kt[0],xt.minimums[0]),kt[1]=Math.max(kt[1],xt.maximums[0])}),kt[0]!==1e4&&(Re=(kt[1]-kt[0])*ht.exaggeration())}const Le=1.5*y.cameraToCenterDistance,Ue=3*Le,st=new Float64Array(16);for(let ht=0;ht=0)return{};const G=function(de,xe,we){const Re=we/(1<0&&(o.cT(G[1],G[1],[$[0]*Z,0,0]),o.cT(G[2],G[2],[$[0]*Z,0,0])),$[1]<0?(o.cT(G[0],G[0],[0,$[1]*Z,0]),o.cT(G[1],G[1],[0,$[1]*Z,0])):$[1]>0&&(o.cT(G[2],G[2],[0,$[1]*Z,0]),o.cT(G[3],G[3],[0,$[1]*Z,0]));const te={};return te.vertices=G,te.planes=[o1(G[1],G[0],G[4]),o1(G[2],G[1],G[5]),o1(G[3],G[2],G[6]),o1(G[0],G[3],G[7])],te}addShadowReceiver(y,C,R){this._receivers.add(y,o.cU.fromTileIdAndHeight(y,C,R))}getMaxCascadeForTile(y){const C=this._receivers.get(y);return C&&C.lastCascade?C.lastCascade:0}}function o1(I,y,C){const R=o.ax([],C,y),$=o.ax([],I,y),G=o.bh([],R,$),Z=o.ai(G);return Z===0?[0,0,1,0]:(o.bJ(G,G,1/Z),[G[0],G[1],G[2],-o.bi(G,y)])}function LN(I){const y=I.properties.get("direction"),C=o.cP(y.x,y.y,y.z);C[2]=o.aC(C[2],0,75);const R=o.cR([C[0],C[1],C[2]]);return o.cQ(R.x,R.y,R.z)}function zp(I,y,C){const R=y.properties.get("color-use-theme")==="none",$=y.properties.get("color"),G=y.properties.get("intensity"),Z=y.properties.get("direction"),te=[Z.x,Z.y,Z.z],de=C.properties.get("color-use-theme")==="none",xe=C.properties.get("color"),we=C.properties.get("intensity"),Re=Math.max(o.bi([0,0,1],te),0),Le=[0,0,0];o.bJ(Le,xe.toPremultipliedRenderColor(de?null:I.getLut(y.scope)).toArray01Linear().slice(0,3),we);const Ue=[0,0,0];return o.bJ(Ue,$.toPremultipliedRenderColor(R?null:I.getLut(C.scope)).toArray01Linear().slice(0,3),Re*G),o.cW([Le[0]>0?Le[0]/(Le[0]+Ue[0]):0,Le[1]>0?Le[1]/(Le[1]+Ue[1]):0,Le[2]>0?Le[2]/(Le[2]+Ue[2]):0])}function Fy(I,y,C,R,$,G){const Z=I.zoom,te=I.scale,de=I.worldSize,xe=1/de,we=I.aspect,Re=Math.sqrt(1+we*we)*Math.tan(.5*I.fovX),Le=Re*Re,Ue=R-C,st=R+C;let Je,mt;Le>Ue/st?(Je=R,mt=R*Re):(Je=.5*st*(1+Le),mt=.5*Math.sqrt(Ue*Ue+2*(R*R+C*C)*Le+st*st*Le*Le));const ht=I.projection.pixelsPerMeter(I.center.lat,de),kt=I._camera.getCameraToWorldMercator(),Tt=[0,0,-Je*xe];o.ah(Tt,Tt,kt);let xt=mt*xe;const es=function(Ys){return Ys[0]/=te,Ys[1]/=te,Ys[2]=o.bU(Ys[2],I._center.lat),Ys},Ft=I._edgeInsets;if(!(Ft.left===0&&Ft.top===0&&Ft.right===0&&Ft.bottom===0||Ft.left===Ft.right&&Ft.top===Ft.bottom)){const Ys=I._camera.getWorldToCamera(I.worldSize,I.projection.zAxisUnit==="meters"?ht:1),Rn=I._camera.getCameraToClipPerspective(I._fov,I.width/I.height,C,R);Rn[8]=2*-I.centerOffset.x/I.width,Rn[9]=2*I.centerOffset.y/I.height;const Sn=new Float64Array(16);o.cz(Sn,Rn,Ys);const Cn=new Float64Array(16);o.b7(Cn,Sn);const dn=o.cl.fromInvProjectionMatrix(Cn,de,Z,!0);for(const mr of dn.points){const Cr=es(mr);xt=Math.max(xt,o.bK(o.cV([],Tt,Cr)))}}xt*=$/($-1);const Qt=Math.acos(y[2]),At=Math.atan2(-y[0],-y[1]),Dt=new h0;Dt.position=Tt,Dt.setPitchBearing(Qt,At);const Gt=Dt.getWorldToCamera(de,ht),gs=xt*de,ns=Math.min(I._mercatorZfromZoom(17)*de*-2,-2*gs),$s=Dt.getCameraToClipOrthographic(-gs,gs,-gs,gs,ns,(gs+G*ht)/y[2]),Ps=new Float64Array(16);o.aD(Ps,$s,Gt);const an=o.cQ(Math.floor(1e6*Tt[0])/1e6*de,Math.floor(1e6*Tt[1])/1e6*de,0),mn=.5*$,Ns=[0,0,0];o.ah(Ns,an,Ps),o.bJ(Ns,Ns,mn);const hs=[Math.floor(Ns[0]),Math.floor(Ns[1]),Math.floor(Ns[2])],zs=[0,0,0];o.ax(zs,Ns,hs),o.bJ(zs,zs,-1/mn);const Us=new Float64Array(16);return o.b9(Us),o.bx(Us,Us,zs),o.aD(Ps,Us,Ps),[Ps,gs]}class xC extends o.E{constructor(y){super(),this.requestManager=y,this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}loadModel(y,C){return o.cX(this.requestManager.transformRequest(C,o.R.Model).url).then(R=>{const $=o.cY(R),G=new o.cZ(y,C,void 0,void 0,$);return G.computeBoundsAndApplyParent(),G}).catch(R=>{if(R&&R.status===404)return null;this.fire(new o.B(new Error(`Could not load model ${y} from ${C}: ${R.message}`)))})}load(y,C,R={forceReload:!1}){this.models[C]||(this.models[C]={});const $=Object.keys(y),G=[],Z=[];for(const te of $){const de=y[te];this.hasURLBeenRequested(de)&&!R.forceReload||(this.modelByURL[de]={modelId:te,scope:C},G.push(this.loadModel(te,de)),Z.push(te)),this.models[C][te]||(this.models[C][te]={model:null,numReferences:1})}this.numModelsLoading[C]=(this.numModelsLoading[C]||0)+Z.length,Promise.allSettled(G).then(te=>{for(let de=0;de{this.fire(new o.B(new Error(`Could not load models: ${te.message}`)))})}isLoaded(){for(const y in this.numModelsLoading)if(this.numModelsLoading[y]>0)return!1;return!0}hasModel(y,C,R={exactIdMatch:!1}){return!!(R.exactIdMatch?this.getModel(y,C):this.getModelByURL(this.modelUris[C][y]))}getModel(y,C){return this.models[C]||(this.models[C]={}),this.models[C][y]?this.models[C][y].model:void 0}getModelByURL(y){if(!y)return null;const C=this.modelByURL[y];return C?this.models[C.scope][C.modelId].model:null}hasModelBeenAdded(y,C){return this.models[C]&&this.models[C][y]!==void 0}getModelURIs(y){return this.modelUris[y]||{}}addModel(y,C,R){this.models[R]||(this.models[R]={}),this.modelUris[R]||(this.modelUris[R]={});const $=this.requestManager.normalizeModelURL(C);if((this.hasModel(y,R,{exactIdMatch:!0})||this.hasModelBeenAdded(y,R))&&this.modelUris[R][y]===$)this.models[R][y].numReferences++;else if(this.hasURLBeenRequested($)){const{scope:G,modelId:Z}=this.modelByURL[$];this.models[G][Z].numReferences++}else this.modelUris[R][y]=$,this.load({[y]:this.modelUris[R][y]},R)}addModelURLs(y,C){this.models[C]||(this.models[C]={}),this.modelUris[C]||(this.modelUris[C]={});const R=this.modelUris[C];for(const $ in y)R[$]=this.requestManager.normalizeModelURL(y[$])}reloadModels(y){this.load(this.modelUris[y],y,{forceReload:!0})}addModelsFromBucket(y,C){this.models[C]||(this.models[C]={}),this.modelUris[C]||(this.modelUris[C]={});const R={};for(const $ of y)this.hasModel($,C,{exactIdMatch:!0})||this.hasURLBeenRequested($)?this.models[C][$].numReferences++:this.modelUris[C][$]&&!this.hasURLBeenRequested($)?R[$]=this.modelUris[C][$]:!this.hasURLBeenRequested($)&&o.c_($,!1)&&(this.modelUris[C][$]=this.requestManager.normalizeModelURL($),R[$]=this.modelUris[C][$]);this.load(R,C)}hasURLBeenRequested(y){return this.modelByURL[y]!==void 0}removeModel(y,C,R=!1,$=!1){if(this.models[C]&&this.models[C][y]&&(this.models[C][y].numReferences--,this.models[C][y].numReferences===0||$)){const G=this.modelUris[C][y];R||delete this.modelUris[C][y],delete this.modelByURL[G];const Z=this.models[C][y].model;if(!Z)return;delete this.models[C][y],Z.destroy()}}destroy(){for(const y of Object.keys(this.models))for(const C of Object.keys(this.models[y])){const R=this.models[y][C].model;delete this.models[y][C],R&&R.destroy()}this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}listModels(y){return this.models[y]||(this.models[y]={}),Object.keys(this.models[y])}upload(y,C){this.models[C]||(this.models[C]={});for(const R in this.models[C])this.models[C][R].model&&this.models[C][R].model.upload(y.context)}}const m0=o.a8.colorTheme,Wl=new o.ab({data:new o.ac(m0.data)});function Gd(I){if(!I.metadata||!I.metadata.content_area)return;const y=o.o.devicePixelRatio,{left:C,top:R,width:$,height:G}=I.metadata.content_area,Z=C*y,te=R*y;return[Z,te,Z+$*y,te+G*y]}function ld(I){if(I)return I.map(([y,C])=>[y*o.o.devicePixelRatio,C*o.o.devicePixelRatio])}class Zb{constructor(y,C,R){this.id=y,this.scope=C,this.sourceCache=R,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(y){this.missingRequests.has(y.name)||this.pendingRequests.has(y.name)||this.pendingRequests.add(y.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const y=new Map;if(!this.sourceCache.loaded())return y;const C=this.sourceCache.getVisibleCoordinates();if(C.length===0)return y;const R=this.sourceCache.getSource();if(!(R instanceof fm))return y;const $=C.map(Z=>this.sourceCache.getTile(Z)),G=R.getImages($,Array.from(this.pendingRequests));for(const[Z,te]of G)y.set(o.I.from({name:Z,iconsetId:this.id}),te),this.pendingRequests.delete(Z);for(const Z of this.pendingRequests)this.missingRequests.add(Z);return this.pendingRequests.clear(),y}}class Rf{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(y,C,R,$,G){if(Rde*this._hysteresisRatio&&(Z=this._previousClosestBuildingId):xe&&!Z&&(Z=this._previousClosestBuildingId),this._previousClosestBuildingId=Z,Z}_calculateDistance(y,C){if(!C.center)return Number.MAX_VALUE;const R=y.lat-C.center[1],$=y.lng-C.center[0];return R*R+$*$}_isBuildingVisible(y,C,R){if(!R)return!1;for(const $ of y.floorIds){const G=y.floors[$];if(!G.geometry)continue;const Z=G.geometry;if(Z.type==="Polygon"){const te=this._convertRingToPoints(Z.coordinates[0]);if(o.bw(te,R))return!0}else if(Z.type==="MultiPolygon"){const te=this._convertMultiPolygonToPoints(Z.coordinates);if(o.d0(R,te))return!0}}return!1}_convertRingToPoints(y){return y.map(C=>new o.P(C[0],C[1]))}_convertMultiPolygonToPoints(y){return y.map(C=>C.length===0?[]:C[0].map(R=>new o.P(R[0],R[1])))}}class hj extends o.E{constructor(y){super(),this._style=y,this._buildings={},this._activeFloors=new Set,this._closestBuildingId=null,this._indoorState={selectedFloorId:null,activeFloorsVisible:!0,activeFloors:this._activeFloors},this._buildingDetectionStrategy=new Rf,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(y){y===this._selectedFloorId&&this._indoorState&&this._indoorState.activeFloorsVisible||(this._selectedFloorId=y,this._recalculateActiveFloors())}setActiveFloorsVisibility(y){this._updateActiveFloors(y),this._updateIndoorSelector()}setIndoorData(y){let C=!1;for(const[R,$]of Object.entries(y.buildings))if(this._buildings[R])for(const G of $.floorIds)this._buildings[R].floorIds.add(G),this._buildings[R].floors[G]?this._mergeFloors(this._buildings[R].floors[G],$.floors[G]):(this._buildings[R].floors[G]=$.floors[G],C=!0);else this._buildings[R]=$,C=!0;C&&this._recalculateActiveFloors()}getIndoorTileOptions(y,C){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(y,C),indoorState:this._indoorState}:null}getControlState(){const y=this._buildings,C=this._closestBuildingId,R=C&&y?y[C]:void 0;if(!R)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let $=null;for(const Z of R.floorIds)if(this._activeFloors&&this._activeFloors.has(Z)){$=Z;break}const G=Array.from(R.floorIds).map(Z=>({id:Z,name:R.floors[Z].name,zIndex:R.floors[Z].zIndex})).sort((Z,te)=>te.zIndex-Z.zIndex).filter((Z,te,de)=>te===0||Z.zIndex!==de[te-1].zIndex);return{selectedFloorId:$,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:G}}_updateUI(){this._initialLoadDone=!0;const y=this._style.map.transform,C=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,y.center,y.zoom,y.getBounds(),this._makeViewportPolygon());if(C!==this._closestBuildingId){const R=this._closestBuildingId;this._closestBuildingId=C,this._onBuildingTransition(R,C),this._updateIndoorSelector()}}_onBuildingTransition(y,C){if(!this._indoorState)return;!C&&y?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!C&&!y&&(this._recalculateActiveFloors(),this._updateActiveFloors(!0))}_updateIndoorSelector(){this.fire(new o.C("selector-update",this.getControlState()))}_updateActiveFloors(y){this._indoorState={selectedFloorId:this._selectedFloorId,activeFloorsVisible:y,activeFloors:this._activeFloors},this._initialLoadDone?this._style.updateIndoorDependentLayers():this._indoorState.needsUpdate=!0}_recalculateActiveFloors(){if(!this._buildings)return;const y=o.d1.calculate(this._buildings,this._selectedFloorId,this._activeFloors);(function(C,R){if(C===R)return!0;if(!C||!R||C.size!==R.size)return!1;for(const $ of C)if(!R.has($))return!1;return!0})(y,this._activeFloors)||(this._activeFloors=y,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(y,C){C.geometry&&(y.geometry?(y.geometry.type==="Polygon"&&(y.geometry={type:"MultiPolygon",coordinates:[y.geometry.coordinates]}),C.geometry.type==="Polygon"?y.geometry.coordinates.push(C.geometry.coordinates):C.geometry.type==="MultiPolygon"&&y.geometry.coordinates.push(...C.geometry.coordinates)):y.geometry=C.geometry)}_makeViewportPolygon(){const y=this._style.map.transform,C=y.width,R=y.height;return[y.pointLocation(new o.P(0,0)),y.pointLocation(new o.P(C,0)),y.pointLocation(new o.P(C,R)),y.pointLocation(new o.P(0,R))].map($=>new o.P($.lng,$.lat))}}const l1=(I,y)=>Un(I,y&&y.filter(C=>C.identifier!=="source.canvas")),Bh=o.aJ(Qa,["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"]),DN=o.aJ(Qa,["setCenter","setZoom","setBearing","setPitch"]),mj=new Set(["background","sky","slot","custom"]),Qb={version:8,layers:[],sources:{}},Of={duration:300,delay:0};class Qc extends o.E{constructor(y,C={}){if(super(),this.map=y,this.scope=C.scope||"",this.globalId=null,this.fragments=[],this.importDepth=C.importDepth||0,this.importsCache=C.importsCache||new Map,this.resolvedImports=C.resolvedImports||new Set,this.transition=Object.assign({},Of),this._buildingIndex=new u0(this),this.crossTileSymbolIndex=new Pf,this._mergedOrder=[],this._drapedFirstOrder=[],this._mergedLayers={},this._mergedIndoor={},this._mergedSourceCaches={},this._mergedOtherSourceCaches={},this._mergedSymbolSourceCaches={},this._mergedFillExtrusionSourceCaches={},this._clipLayerPresent=!1,this._hasAppearances=!1,this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this._importedAsBasemap=!1,this._changes=C.styleChanges||new Ye,this._hasDataDrivenEmissive=!1,this.indoorManager=new hj(this),this.dispatcher=C.dispatcher?C.dispatcher:new dt(Bt(),this),this.map.painter&&this.map.painter.context){const $=this.map.painter.context.maxUniformBufferBindings,G=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:$,maxUniformBlockSizeDwords:G,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}C.imageManager?this.imageManager=C.imageManager:(this.imageManager=new Zt(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=C.glyphManager?C.glyphManager:new o.d2(y._requestManager,C.localFontFamily?o.d3.all:C.localIdeographFontFamily?o.d3.ideographs:o.d3.none,C.localFontFamily||C.localIdeographFontFamily,C.useServerFontComposition),C.modelManager?this.modelManager=C.modelManager:(this.modelManager=new xC(y._requestManager),this.modelManager.setEventedParent(this)),this._layers={},this._sourceCaches={},this._otherSourceCaches={},this._symbolSourceCaches={},this._fillExtrusionSourceCaches={},this._loaded=!1,this._precompileDone=!1,this._shouldPrecompile=!1,this._availableImages=[],this._availableModels={},this._order=[],this._markersNeedUpdate=!1,this.options=C.configOptions?C.configOptions:new Map,this._configDependentLayers=C.configDependentLayers?C.configDependentLayers:new Set,this._indoorDependentLayers=C.indoorDependentLayers?C.indoorDependentLayers:new Set,this._config=C.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:C.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=C.initialConfig,this.dispatcher.broadcast("setReferrer",o.d4()),this.dispatcher.broadcast("setConfig",o.d5());const R=this;this._rtlTextPluginCallback=Qc.registerForPluginStateChange($=>{R.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:$.pluginStatus,pluginURL:$.pluginURL},(G,Z)=>{if(o.d6(G),Z&&Z.every(te=>te))for(const te in R._sourceCaches){const de=R._sourceCaches[te],xe=de.getSource().type;xe!=="vector"&&xe!=="geojson"||de.reload()}})}),this.on("data",$=>{if($.dataType!=="source"||$.sourceDataType!=="metadata")return;const G=this.getOwnSource($.sourceId);if(G&&G.vectorLayerIds)for(const Z in this._layers){const te=this._layers[Z];te.source===G.id&&this._validateLayer(te)}})}load(y){return y?(typeof y=="string"?this.loadURL(y):this.loadJSON(y),this):this}_getGlobalId(y){if(!y)return null;if(typeof y=="string"){if(o.e(y))return y;const C=o.d7(y);if(!C.startsWith("http"))try{return new URL(C,location.href).toString()}catch{return C}return C}return`json://${o.d8(JSON.stringify(y))}`}_diffStyle(y,C,R){this.globalId=this._getGlobalId(y);const $=(G,Z)=>{try{Z(null,this.setState(G,R))}catch(te){Z(te,!1)}};if(typeof y=="string"){const G=this.map._requestManager.normalizeStyleURL(y),Z=this.map._requestManager.transformRequest(G,o.R.Style);o.m(Z,(te,de)=>{te?this.fire(new o.B(te)):de&&$(de,C)})}else typeof y=="object"&&$(y,C)}loadURL(y,C={}){this.fire(new o.C("dataloading",{dataType:"style"}));const R=typeof C.validate=="boolean"?C.validate:!o.e(y);this.globalId=this._getGlobalId(y),y=this.map._requestManager.normalizeStyleURL(y,C.accessToken),this.resolvedImports.add(y);const $=this.importsCache.get(y);if($)return this._load($,R);const G=this.map._requestManager.transformRequest(y,o.R.Style);this._request=o.m(G,(Z,te)=>{if(this._request=null,Z)this.fire(new o.B(Z));else if(te)return this.importsCache.set(y,te),this._load(te,R)})}loadJSON(y,C={}){this.fire(new o.C("dataloading",{dataType:"style"})),this.globalId=this._getGlobalId(y),this._request=o.o.frame(()=>{this._request=null,this._load(y,C.validate!==!1)})}loadEmpty(){this.fire(new o.C("dataloading",{dataType:"style"})),this._load(Qb,!1)}_loadImports(y,C,R){if(this.importDepth>=4)return o.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const $=[];for(const G of y){const Z=this._createFragmentStyle(G),te=new Promise(we=>{Z.once("style.import.load",we),Z.once("error",we)}).then(()=>{this.mergeAll(),this.fire(new o.C("data",{dataType:"style"}))});if($.push(te),this.resolvedImports.has(G.url)){Z.loadEmpty();continue}const de=G.data||this.importsCache.get(G.url);de?(G.data?(Z.fire(new o.C("dataloading",{dataType:"style"})),Z.globalId=Z._getGlobalId(de),queueMicrotask(()=>Z._load(de,C))):Z.loadJSON(de,{validate:C}),this._isInternalStyle(de)&&(Z.globalId=null)):G.url?Z.loadURL(G.url,{validate:C}):Z.loadEmpty();const xe={style:Z,id:G.id,config:G.config};if(R){const we=this.fragments.findIndex(({id:Re})=>Re===R);this.fragments=this.fragments.slice(0,we).concat(xe).concat(this.fragments.slice(we))}else this.fragments.push(xe)}return Promise.allSettled($)}getImportGlobalIds(y=this,C=new Set){for(const R of y.fragments)R.style.globalId&&C.add(R.style.globalId),this.getImportGlobalIds(R.style,C);return[...C.values()]}_createFragmentStyle(y){const C=this.scope?o.F(y.id,this.scope):y.id;let R;const $=this._initialConfig&&this._initialConfig[C];(y.config||$)&&(R=Object.assign({},y.config,$));const G=new Qc(this.map,{scope:C,styleChanges:this._changes,importDepth:this.importDepth+1,importsCache:this.importsCache,resolvedImports:new Set(this.resolvedImports),dispatcher:this.dispatcher,imageManager:this.imageManager,glyphManager:this.glyphManager,modelManager:this.modelManager,config:R,configOptions:this.options,colorThemeOverride:y["color-theme"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return G.setEventedParent(this.map,{style:G}),G}_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(y){return this.isRootStyle()&&(y.fragment||!!y.schema&&y.fragment!==!1)}_load(y,C){if(this._isInternalStyle(y)){const G=Object.assign({},Qb,{imports:[{id:"basemap",data:y,url:""}]},y.center?{center:y.center}:{},y.bearing?{bearing:y.bearing}:{},y.pitch?{pitch:y.pitch}:{},y.zoom?{zoom:y.zoom}:{},y.light?{light:y.light}:{});return this._importedAsBasemap=!0,void this._load(G,C)}if(this.updateConfig(this._config,y.schema),C&&l1(this,wr(y)))return;this._loaded=!0;for(const G in y.sources)this.addSource(G,y.sources[G],{validate:!1,isInitialLoad:!0});this.stylesheet=o.d9(y);const R=()=>{if(y.iconsets)for(const de in y.iconsets)this.addIconset(de,y.iconsets[de]);y.sprite?this._loadIconset(y.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0})),!this.glyphManager.url&&y.glyphs&&this.glyphManager.setURL(y.glyphs);const G=Af(this.stylesheet.layers);if(this._order=G.map(de=>de.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 de=this.stylesheet.lights[0];this.light=new nr(de.properties,de.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new nr(this.stylesheet.light)),this._layers={};for(const de of G){const xe=o.de(de,this.scope,this._styleColorTheme.lut,this.options);xe.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(xe.fqid),xe.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(xe.fqid),this._hasAppearances=this._hasAppearances||xe.getAppearances().length!==0,xe.setEventedParent(this,{layer:{id:xe.id}}),this._layers[xe.id]=xe;const we=this.getOwnLayerSourceCache(xe),Re=!!this.directionalLight&&this.directionalLight.shadowsEnabled();we&&xe.canCastShadows()&&Re&&(we.castsShadows=!0)}if(this.glyphManager.url){const de=new Set;for(const xe in this._layers){const we=this._layers[xe];if(we.type==="symbol"&&we.layout){const Re=we.layout.get("text-font");Re&&Re.value&&Re.value.kind==="constant"&&de.add(Re.value.value.join(","))}}for(const xe of de)this.glyphManager.prefetchRange(xe,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const Z=this.stylesheet.terrain;Z&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(Z,1)),this.stylesheet.fog&&this._createFog(this.stylesheet.fog),this.stylesheet.snow&&this._createSnow(this.stylesheet.snow),this.stylesheet.rain&&this._createRain(this.stylesheet.rain),this.stylesheet.transition&&this.setTransition(this.stylesheet.transition),this.fire(new o.C("data",{dataType:"style"}));const te=this.isRootStyle();y.imports?this._loadImports(y.imports,C).then(()=>{this._reloadImports(),this.fire(new o.C(te?"style.load":"style.import.load"))}).catch(de=>{this.fire(new o.B(new Error("Failed to load imports",de))),this.fire(new o.C(te?"style.load":"style.import.load"))}):(this._reloadImports(),this.fire(new o.C(te?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const $=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if($){const G=this._evaluateColorThemeData($);this._loadColorTheme(G).then(()=>{R()}).catch(Z=>{o.w(`Couldn't load color theme from the stylesheet: ${Z}`),R()})}else this._styleColorTheme.lut=null,R()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(y=>y.style.hasAppearances())}mergeAll(){let y,C,R,$,G,Z,te,de,xe,we;const Re={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(Le=>{if(Le.stylesheet){if(Le.light!=null&&(y=Le.light),Le.stylesheet.lights)for(const Ue of Le.stylesheet.lights)Ue.type==="ambient"&&Le.ambientLight!=null&&(C=Le.ambientLight),Ue.type==="directional"&&Le.directionalLight!=null&&(R=Le.directionalLight);$=this._prioritizeTerrain($,Le.terrain,Le.stylesheet.terrain),Le.stylesheet.fog&&Le.fog!=null&&(G=Le.fog),Le.stylesheet.snow&&Le.snow!=null&&(Z=Le.snow),Le.stylesheet.rain&&Le.rain!=null&&(te=Le.rain),Le.stylesheet.camera!=null&&(we=Le.stylesheet.camera),Le.stylesheet.projection!=null&&(de=Le.stylesheet.projection),Le.stylesheet.transition!=null&&(xe=Le.stylesheet.transition),Re[Le.scope]=Le._styleColorTheme}}),this.light=y,this.ambientLight=C,this.directionalLight=R,this.fog=G,this.snow=Z,this.rain=te,this._styleColorThemeForScope=Re,$===null?delete this.terrain:this.terrain=$,this.camera=we||{"camera-projection":"perspective"},this.projection=de||{name:"mercator"},this.transition=Object.assign({},Of,xe),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(y){const C=R=>{for(const $ of R.fragments)C($.style);y(R)};C(this)}_prioritizeTerrain(y,C,R){const $=y&&y.drapeRenderMode===0;return R===null?C&&C.drapeRenderMode===0?C:$?y:null:C!=null&&(!y||$||C&&C.drapeRenderMode===1)?C:y}mergeTerrain(){let y;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(C=>{y=this._prioritizeTerrain(y,C.terrain,C.stylesheet.terrain)}),y===null?delete this.terrain:this.terrain=y}mergeProjection(){let y;this.forEachFragmentStyle(C=>{C.stylesheet.projection!=null&&(y=C.stylesheet.projection)}),this.projection=y||{name:"mercator"}}mergeSources(){const y={},C={},R={},$={};this.forEachFragmentStyle(G=>{for(const Z in G._sourceCaches){const te=o.F(Z,G.scope);y[te]=G._sourceCaches[Z]}for(const Z in G._otherSourceCaches){const te=o.F(Z,G.scope);C[te]=G._otherSourceCaches[Z]}for(const Z in G._symbolSourceCaches){const te=o.F(Z,G.scope);R[te]=G._symbolSourceCaches[Z]}for(const Z in G._fillExtrusionSourceCaches){const te=o.F(Z,G.scope);$[te]=G._fillExtrusionSourceCaches[Z]}}),this._mergedSourceCaches=y,this._mergedOtherSourceCaches=C,this._mergedSymbolSourceCaches=R,this._mergedFillExtrusionSourceCaches=$}mergeIndoor(){this.forEachFragmentStyle(y=>{if(y.stylesheet&&y.stylesheet.indoor)for(const C of Object.values(y.stylesheet.indoor)){const R=C,$=o.F(R.sourceId,y.scope);this._mergedIndoor[$]=new Set(R.sourceLayers||[])}})}mergeLayers(){const y={},C=[],R={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(Z=>{for(const te of Z._order){const de=Z._layers[te];if(de.type==="slot"){const xe=o.da(te);if(y[xe])continue;y[xe]=[]}de.slot&&y[de.slot]?y[de.slot].push(de):C.push(de)}}),this._mergedOrder=[];let $=-1;const G=(Z=[])=>{for(const te of Z)if(te.type==="slot"){const de=o.da(te.id);y[de]&&G(y[de]),this._mergedSlots.push(de)}else{const de=o.F(te.id,te.scope);this._mergedOrder.push(de),R[de]=te,te.is3D(!!this.terrain)&&(this._has3DLayers=!0,$=this._mergedOrder.length-1),te.type==="circle"&&(this._hasCircleLayers=!0),te.type==="symbol"&&(this._hasSymbolLayers=!0),te.type==="clip"&&(this._clipLayerPresent=!0)}};if(G(C),this._has3DLayers){const Z={};for(let te=0;teZ[te]-Z[de])}this._mergedLayers=R,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(y){return this.stylesheet.camera=Object.assign({},this.stylesheet.camera,y),this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(y){return y.data?function(C,R,$){const G=Object.assign({},R);for(const te of Object.keys(m0))G[te]===void 0&&(G[te]=m0[te].default);const Z=new o.aa(Wl,C,new Map($));return Z.setTransitionOrValue(G,$),Z.untransitioned().possiblyEvaluate(new o.ae(0,{worldview:void 0}))}(this.scope,y,this.options).get("data"):null}_loadColorTheme(y){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const C=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((R,$)=>{const G="data:image/png;base64,";if(!y||y.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void R();let Z=y;Z.startsWith(G)||(Z=G+Z);const te=o.I.from("mapbox-reserved-lut"),de=new Image;de.src=Z,de.onerror=()=>{this._styleColorTheme.lutLoading=!1,$(new Error("Failed to load image data"))},de.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==C)return void R();this._styleColorTheme.lutLoading=!1;const{width:xe,height:we,data:Re}=o.o.getImageData(de);if(we>32)return void $(new Error("The height of the image must be less than or equal to 32 pixels."));if(xe!==we*we)return void $(new Error("The width of the image must be equal to the height squared."));this.getImage(te)&&this.removeImage(te),this.addImage(te,{data:new o.q({width:xe,height:we},Re),pixelRatio:1,sdf:!1,usvg:!1,version:0});const Le=this.imageManager.getImage(te,this.scope);Le?(this._styleColorTheme.lut={image:Le.data,data:y},R()):$(new Error("Missing LUT image."))}})}getLut(y){const C=this._styleColorThemeForScope[y];return C?C.lut:null}setProjection(y){y?this.stylesheet.projection=y: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(y){this._spriteRequest=function(C,R,$){let G,Z,te;const de=o.o.devicePixelRatio>1?"@2x":"";let xe=o.m(R.transformRequest(R.normalizeSpriteURL(C,de,".json"),o.R.SpriteJSON),(Le,Ue)=>{xe=null,te||(te=Le,G=Ue,Re())}),we=o.n(R.transformRequest(R.normalizeSpriteURL(C,de,".png"),o.R.SpriteImage),(Le,Ue)=>{we=null,te||(te=Le,Z=Ue,Re())});function Re(){if(te)$(te);else if(G&&Z){const Le=o.o.getImageData(Z),Ue={};for(const st in G){const{width:Je,height:mt,x:ht,y:kt,sdf:Tt,pixelRatio:xt,stretchX:es,stretchY:Ft,content:Qt}=G[st],At=new o.q({width:Je,height:mt});o.q.copy(Le,At,{x:ht,y:kt},{x:0,y:0},{width:Je,height:mt},null),Ue[st]={data:At,pixelRatio:xt!==void 0?xt:1,sdf:Tt!==void 0&&Tt,stretchX:es,stretchY:Ft,content:Qt,usvg:!1,version:0}}$(null,Ue)}}return{cancel(){xe&&(xe.cancel(),xe=null),we&&(we.cancel(),we=null)}}}(y,this.map._requestManager,(C,R)=>{if(this._spriteRequest=null,C)this.fire(new o.B(C));else if(R){const $=new Map;for(const G in R)$.set(o.I.from(G),R[G]);this.addImages($)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new o.C("data",{dataType:"style"}))})}addIconset(y,C){if(C.type==="sprite")return void this._loadSprite(C.url);const R=this.getOwnSourceCache(C.source);if(!R)return void this.fire(new o.B(new Error(`Source "${C.source}" as specified by iconset "${y}" does not exist and cannot be used as an iconset source`)));const $=R.getSource();if($.type!=="raster-array")return void this.fire(new o.B(new Error(`Source "${C.source}" as specified by iconset "${y}" is not a "raster-array" source and cannot be used as an iconset source`)));$.partial=!1;const G=new Zb(y,this.scope,R);this.imageManager.addImageProvider(G,this.scope)}removeIconset(y){this.imageManager.removeImageProvider(y,this.scope)}_loadIconset(y){if(!o.e(y)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(y);const C=this.map._spriteFormat==="auto";var R,$;this._spriteRequest=($=(G,Z)=>{if(this._spriteRequest=null,G)C?this._loadSprite(y):this.fire(new o.B(G));else if(Z){const te=new Map;for(const de in Z)te.set(o.I.from(de),Z[de]);this.addImages(te)}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((R=this.map._requestManager).transformRequest(R.normalizeIconsetURL(y),o.R.Iconset),(G,Z)=>{if(G)return void $(G);const te={},de=o.c$(new o.a$(Z));for(const xe of de.icons){const we={version:1,pixelRatio:o.o.devicePixelRatio,content:Gd(xe),stretchX:xe.metadata?ld(xe.metadata.stretch_x_areas):void 0,stretchY:xe.metadata?ld(xe.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:xe};te[xe.name]=we}$(null,te)}))}_validateLayer(y){const C=this.getOwnSource(y.source);if(!C)return;const R=y.sourceLayer;R&&(C.type==="geojson"||C.vectorLayerIds&&C.vectorLayerIds.indexOf(R)===-1)&&this.fire(new o.B(new Error(`Source layer "${R}" does not exist on source "${C.id}" as specified by style layer "${y.id}"`)))}loaded(){if(!this._loaded||Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const y in this._sourceCaches)if(!this._sourceCaches[y].loaded())return!1;if(!this.imageManager.isLoaded()||this.imageManager.hasPatternsInFlight()||!this.modelManager.isLoaded()||this._styleColorTheme.lutLoading)return!1;for(const{style:y}of this.fragments)if(!y.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((y,C)=>{const R=this.fragments[C];return R&&R.style&&(y.data=R.style.serialize()),y})}_serializeSources(){const y={};for(const C in this._sourceCaches){const R=this._sourceCaches[C].getSource();y[R.id]||(y[R.id]=R.serialize())}return y}_serializeLayers(y){const C=[];for(const R of y){const $=this._layers[R];$&&$.type!=="custom"&&C.push($.serialize())}return C}hasLightTransitions(){return!(!this.light||!this.light.hasTransition())||!(!this.ambientLight||!this.ambientLight.hasTransition())||!(!this.directionalLight||!this.directionalLight.hasTransition())}hasFogTransition(){return!!this.fog&&this.fog.hasTransition()}hasSnowTransition(){return!!this.snow&&this.snow.hasTransition()}hasRainTransition(){return!!this.rain&&this.rain.hasTransition()}hasTransitions(){if(this.hasLightTransitions()||this.hasFogTransition()||this.hasSnowTransition()||this.hasRainTransition())return!0;for(const y in this._sourceCaches)if(this._sourceCaches[y].hasTransition())return!0;for(const y in this._layers)if(this._layers[y].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const y in this._mergedLayers){const C=this._mergedLayers[y];if(C._transitionablePaint&&C._transitionablePaint._values){const R=C._transitionablePaint._values["line-emissive-strength"];if(R&&R.value&&R.value.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(y){return y?this.order:this._mergedOrder}isLayerDraped(y){return!!this.terrain&&y.isDraped(this.getLayerSourceCache(y))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(y){const C=this.getOwnLayer(y);if(C)return C;this.fire(new o.B(new Error(`The layer '${y}' does not exist in the map's style.`)))}_checkSource(y){const C=this.getOwnSource(y);if(C)return C;this.fire(new o.B(new Error(`The source '${y}' does not exist in the map's style.`)))}precompilePrograms(y,C){const R=this.map.painter;if(R)for(let $=y.minzoom||0;$<(y.maxzoom||25.5);$++){const G=y.getProgramIds();if(G)for(const Z of G){const te=y.getDefaultProgramParams(Z,C.zoom,this._styleColorTheme.lut);te&&(R.style=this,this.fog&&(R._fogVisible=!0,te.overrideFog=!0,R.getOrCreateProgram(Z,te)),R._fogVisible=!1,te.overrideFog=!1,R.getOrCreateProgram(Z,te),(this.stylesheet.terrain||this.stylesheet.projection&&this.stylesheet.projection.name==="globe")&&(te.overrideRtt=!0,R.getOrCreateProgram(Z,te)))}}}update(y){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(y),this.directionalLight&&this.directionalLight.recalculate(y);const C=this.calculateLightsBrightness();y.brightness=C||0,C!==this._brightness&&(this._brightness=C,this.dispatcher.broadcast("setBrightness",C)),y.worldview!==this._worldview&&(this._worldview=y.worldview,this.dispatcher.broadcast("setWorldview",this._worldview));const R=this._changes.isDirty();let $=!1;if(this._changes.isDirty()){const de=this._changes.getLayerUpdatesByScope();for(const xe in de){const{updatedIds:we,removedIds:Re}=de[xe];(we||Re)&&(this._updateWorkerLayers(xe,we,Re),$=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(y),this.light&&this.light.updateTransitions(y),this.ambientLight&&this.ambientLight.updateTransitions(y),this.directionalLight&&this.directionalLight.updateTransitions(y),this.fog&&this.fog.updateTransitions(y),this.snow&&this.snow.updateTransitions(y),this.rain&&this.rain.updateTransitions(y),this._changes.reset()}const G={};for(const de in this._mergedSourceCaches){const xe=this._mergedSourceCaches[de];G[de]=xe.used,xe.used=!1,xe.tileCoverLift=0}const Z={};for(const de of this._mergedOrder){const xe=this._mergedLayers[de];if((xe.visibility!=="none"||xe.hasTransition())&&xe.recalculate(y,this._availableImages),!xe.isHidden(y.zoom)){const we=this.getLayerSourceCache(xe);we&&(we.used=!0,we.tileCoverLift=Math.max(we.tileCoverLift,xe.tileCoverLift()))}if(xe.type==="fill-extrusion"){const we=o.F(xe.source,xe.scope);if(we in this._mergedFillExtrusionSourceCaches){const Re=xe.layout&&xe.layout.get("source-max-zoom");if(Re!=null){const Le=Z[we];Z[we]=Le==null?Re:Math.min(Le,Re)}}}!this._precompileDone&&this._shouldPrecompile&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.precompilePrograms(xe,y)}):this.precompilePrograms(xe,y))}this._shouldPrecompile&&(this._precompileDone=!0);for(const de in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[de].setMaxzoomOverride(Z[de]!=null?Z[de]:null);this.terrain&&$&&this.mergeLayers();const te=this.imageManager.getPendingImageProviders();for(const de of te)de.sourceCache.used=!0;for(const de in G){const xe=this._mergedSourceCaches[de];G[de]!==xe.used&&xe.getSource().fire(new o.C("data",{sourceDataType:"visibility",dataType:"source",sourceId:xe.getSource().id}))}this.light&&this.light.recalculate(y),this.terrain&&this.terrain.recalculate(y),this.fog&&this.fog.recalculate(y),this.snow&&this.snow.recalculate(y),this.rain&&this.rain.recalculate(y),this.z=y.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),R&&this.fire(new o.C("data",{dataType:"style"}))}updateImageProviders(){const y=this.imageManager.getPendingImageProviders();for(const C of y){const R=C.resolvePendingRequests(),$=this.getFragmentStyle(C.scope);$&&$.addImages(R)}}_updateTilesForChangedImages(){const y={};for(const C in this._mergedSourceCaches){const R=this._mergedSourceCaches[C].getSource().scope;y[R]=y[R]||this._changes.getUpdatedImages(R),y[R].length!==0&&this._mergedSourceCaches[C].reloadTilesForDependencies(["icons","patterns"],y[R])}for(const C in y)this._changes.resetUpdatedImages(C)}_updateWorkerLayers(y,C,R){const $=this.getFragmentStyle(y);$&&this.dispatcher.broadcast("updateLayers",{layers:C?$._serializeLayers(C):[],scope:y,removedIds:R||[],options:$.options})}setState(y,C){if(this._checkLoaded(),l1(this,wr(y)))return!1;(y=o.d9(y)).layers=Af(y.layers);const R=function(Z,te){if(!Z)return[{command:Qa.setStyle,args:[te]}];let de=[];try{if(!o.b6(Z.version,te.version))return[{command:Qa.setStyle,args:[te]}];if(o.b6(Z.center,te.center)||de.push({command:Qa.setCenter,args:[te.center]}),o.b6(Z.zoom,te.zoom)||de.push({command:Qa.setZoom,args:[te.zoom]}),o.b6(Z.bearing,te.bearing)||de.push({command:Qa.setBearing,args:[te.bearing]}),o.b6(Z.pitch,te.pitch)||de.push({command:Qa.setPitch,args:[te.pitch]}),o.b6(Z.sprite,te.sprite)||de.push({command:Qa.setSprite,args:[te.sprite]}),o.b6(Z.glyphs,te.glyphs)||de.push({command:Qa.setGlyphs,args:[te.glyphs]}),o.b6(Z.imports,te.imports)||function(Ue=[],st=[],Je){st=st||[];const mt=(Ue=Ue||[]).map(fx),ht=st.map(fx),kt=Ue.reduce(dg,{}),Tt=st.reduce(dg,{}),xt=mt.slice();let es,Ft,Qt,At;for(es=0,Ft=0;es{Ue.source&&xe[Ue.source]?de.push({command:Qa.removeLayer,args:[Ue.id]}):Re.push(Ue)});let Le=Z.terrain;Le&&xe[Le.source]&&(de.push({command:Qa.setTerrain,args:[void 0]}),Le=void 0),de=de.concat(we),o.b6(Le,te.terrain)||de.push({command:Qa.setTerrain,args:[te.terrain]}),function(Ue,st,Je){st=st||[];const mt=(Ue=Ue||[]).map(fx),ht=st.map(fx),kt=Ue.reduce(dg,{}),Tt=st.reduce(dg,{}),xt=mt.slice(),es=Object.create(null);let Ft,Qt,At,Dt,Gt,gs,ns;for(Ft=0,Qt=0;Ft!(Z.command in DN));if(R.length===0)return!1;const $=R.filter(Z=>!(Z.command in Bh));if($.length>0)throw new Error(`Unimplemented: ${$.map(Z=>Z.command).join(", ")}.`);const G=[];return R.forEach(Z=>{G.push(this[Z.command](...Z.args))}),C&&Promise.all(G).then(C).catch(C),this.stylesheet=y,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(y){if(y.size===0)return this;for(const[C,R]of y.entries()){if(this.getImage(C))return this.fire(new o.B(new Error(`An image with the name "${C.name}" already exists.`)));this.imageManager.addImage(C,this.scope,R),this._changes.updateImage(C,this.scope)}return this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this}addImage(y,C){return this.getImage(y)?this.fire(new o.B(new Error(`An image with the name "${y.name}" already exists.`))):(this.imageManager.addImage(y,this.scope,C),this._changes.updateImage(y,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this)}updateImage(y,C,R=!1){this.imageManager.updateImage(y,this.scope,C),R&&(this._changes.updateImage(y,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})))}getImage(y){return this.imageManager.getImage(y,this.scope)}removeImage(y){return this.getImage(y)?(this.imageManager.removeImage(y,this.scope),this._changes.updateImage(y,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(y){return this.modelManager.addModelURLs(y,this.getActualScope()),this._updateWorkerModels(),this.fire(new o.C("data",{dataType:"style"})),this}addModel(y,C,R={}){return this._checkLoaded(),this._validate(ln,`models.${y}`,C,null,R)||(this.modelManager.addModel(y,C,this.getActualScope()),this.fire(new o.C("data",{dataType:"style"}))),this}hasModel(y){return this.modelManager.hasModel(y,this.getActualScope())}removeModel(y){return this.hasModel(y)?(this.modelManager.removeModel(y,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(y,C,R={}){if(this._checkLoaded(),this.getOwnSource(y)!==void 0)throw new Error(`There is already a source with ID "${y}".`);if(!C.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(C).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(C.type)>=0&&this._validate($r,`sources.${y}`,C,null,R))return;this.map&&this.map._collectResourceTiming&&(C.collectResourceTiming=!0);const $=My(y,C,this.dispatcher,this);$.scope=this.scope,$.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded($.id),source:$.serialize(),sourceId:$.id}));const G=Z=>{const te=(Z===o.b4.Symbol?"symbol:":Z===o.b4.FillExtrusion?"fill-extrusion:":"other:")+$.id,de=o.F(te,this.scope),xe=this._sourceCaches[te]=new al(de,$,Z);Z===o.b4.Symbol?this._symbolSourceCaches[$.id]=xe:Z===o.b4.FillExtrusion?this._fillExtrusionSourceCaches[$.id]=xe:this._otherSourceCaches[$.id]=xe,xe.onAdd(this.map)};G(o.b4.Other),C.type!=="vector"&&C.type!=="geojson"||(G(o.b4.Symbol),C.type==="vector"&&G(o.b4.FillExtrusion)),$.onAdd&&$.onAdd(this.map),R.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(y){this._checkLoaded();const C=this.getOwnSource(y);if(!C)throw new Error("There is no source with this ID");for(const $ in this._layers)if(this._layers[$].source===y)return this.fire(new o.B(new Error(`Source "${y}" cannot be removed while layer "${$}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===y)return this.fire(new o.B(new Error(`Source "${y}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const $=Object.entries(this.stylesheet.iconsets).find(([G,Z])=>Z.type==="source"&&Z.source===y);if($)return this.fire(new o.B(new Error(`Source "${y}" cannot be removed while iconset "${$[0]}" is using it.`)))}const R=this.getOwnSourceCaches(y);for(const $ of R){const G=o.da($.id);delete this._sourceCaches[G],this._changes.discardSourceCacheUpdate($.id),$.fire(new o.C("data",{sourceDataType:"metadata",dataType:"source",sourceId:$.getSource().id})),$.setEventedParent(null),$.clearTiles()}return delete this._otherSourceCaches[y],delete this._symbolSourceCaches[y],delete this._fillExtrusionSourceCaches[y],this.mergeSources(),C.setEventedParent(null),C.onRemove&&C.onRemove(this.map),this._changes.setDirty(),this}setGeoJSONSourceData(y,C){this._checkLoaded(),this.getOwnSource(y).setData(C),this._changes.setDirty()}getOwnSource(y){const C=this.getOwnSourceCache(y);return C&&C.getSource()}getOwnSources(){const y=[];for(const C in this._otherSourceCaches){const R=this.getOwnSourceCache(C);R&&y.push(R.getSource())}return y}areTilesLoaded(){const y=this._mergedSourceCaches;for(const C in y){const R=y[C]._tiles;for(const $ in R){const G=R[$];if(G.state!=="loaded"&&G.state!=="errored")return!1}}return!0}setLights(y){if(this._checkLoaded(),!y)return delete this.ambientLight,void delete this.directionalLight;const C=this._getTransitionParameters();for(const G of y){if(this._validate(Oe,"lights",G))return;switch(G.type){case"ambient":if(this.ambientLight){const Z=this.ambientLight;Z.set(G),Z.updateTransitions(C)}else this.ambientLight=new wn(G,Ta(),this.scope,this.options);break;case"directional":if(this.directionalLight){const Z=this.directionalLight;Z.set(G),Z.updateTransitions(C)}else this.directionalLight=new wn(G,zo(),this.scope,this.options)}}const R=Object.assign(C,{worldview:this.map.getWorldview()}),$=new o.ae(this.z||0,R);this.ambientLight&&this.ambientLight.recalculate($),this.directionalLight&&this.directionalLight.recalculate($),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const y=this.directionalLight,C=this.ambientLight;if(!y||!C)return;const R=Le=>.2126*(Le[0]<=.03928?Le[0]/12.92:Math.pow((Le[0]+.055)/1.055,2.4))+.7152*(Le[1]<=.03928?Le[1]/12.92:Math.pow((Le[1]+.055)/1.055,2.4))+.0722*(Le[2]<=.03928?Le[2]/12.92:Math.pow((Le[2]+.055)/1.055,2.4)),$=y.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),G=y.properties.get("intensity"),Z=y.properties.get("direction"),te=1-o.cP(Z.x,Z.y,Z.z)[2]/90,de=R($)*G*te,xe=C.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),we=C.properties.get("intensity"),Re=R(xe)*we;return Number(((de+Re)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const y=[];return this.directionalLight&&y.push(this.directionalLight.get()),this.ambientLight&&y.push(this.ambientLight.get()),y}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(y){if(y==null||y===""&&this.isRootStyle())return this;if(o.db(y)){const C=o.dc(y),R=this.fragments.find(({id:G})=>G===C);if(!R)return;const $=o.da(y);return R.style.getFragmentStyle($)}{const C=this.fragments.find(({id:R})=>R===y);return C?C.style:void 0}}setFeaturesetSelectors(y){if(!y)return;const C=(R,$="")=>`${R}::${$}`;this._featuresetSelectors={};for(const R in y){const $={},G=this._featuresetSelectors[R]=[];for(const Z of y[R].selectors){if(Z.featureNamespace){const de=this.getOwnLayer(Z.layer);if(!de){o.w(`Layer is undefined for selector: ${Z.layer}`);continue}const xe=C(de.source,de.sourceLayer);if(xe in $&&$[xe]!==Z.featureNamespace){o.w(`"featureNamespace ${Z.featureNamespace} of featureset ${R}'s selector is not associated to the same source, skip this selector`);continue}$[xe]=Z.featureNamespace}let te;if(Z.properties)for(const de in Z.properties){const xe=o.X(Z.properties[de]);xe.result==="success"&&(te=te||{},te[de]=xe.value)}G.push({layerId:Z.layer,namespace:Z.featureNamespace,properties:te,uniqueFeatureID:Z._uniqueFeatureID})}}}getFeaturesetDescriptors(y){const C=this.getFragmentStyle(y);if(!C||!C.stylesheet.featuresets)return[];const R=[];for(const $ in C.stylesheet.featuresets)R.push({featuresetId:$,importId:C.scope?C.scope:void 0});return R}getFeaturesetLayers(y,C){const R=this.getFragmentStyle(C),$=R.stylesheet.featuresets;if(!$||!$[y])return this.fire(new o.B(new Error(`The featureset '${y}' does not exist in the map's style and cannot be queried.`))),[];const G=[];for(const Z of $[y].selectors){const te=R.getOwnLayer(Z.layer);te&&G.push(te)}return G}getConfigProperty(y,C){const R=this.getFragmentStyle(y);if(!R)return null;const $=o.F(C,R.scope),G=R.options.get($),Z=G?G.value||G.default:null;return Z?Z.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(y,C){const R=o.F(y,C);return this._mergedIndoor[R]}setIndoorData(y,C){this.indoorManager.setIndoorData(C)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(y,C,R){const $=this.getFragmentStyle(y);if(!$)return;const G=$.stylesheet.schema;if(!G||!G[C])return;const Z=o.X(R);if(Z.result!=="success")return void l1(this,Z.value);const te=Z.value.expression,de=o.F(C,$.scope),xe=$.options.get(de);if(!xe)return;let we;const{minValue:Re,maxValue:Le,stepValue:Ue,type:st,values:Je}=G[C],mt=o.X(G[C].default);mt.result==="success"&&(we=mt.value.expression),we?(this.options.set(de,Object.assign({},xe,{value:te,default:we,minValue:Re,maxValue:Le,stepValue:Ue,type:st,values:Je})),this.updateConfigDependencies(C)):this.fire(new o.B(new Error(`No schema defined for the config option "${C}" in the "${y}" fragment.`)))}getConfig(y){const C=this.getFragmentStyle(y);if(!C)return null;const R=C.stylesheet.schema;if(!R)return null;const $={};for(const G in R){const Z=o.F(G,C.scope),te=C.options.get(Z),de=te?te.value||te.default:null;$[G]=de?de.serialize():null}return $}setConfig(y,C){const R=this.getFragmentStyle(y);R&&(R.updateConfig(C,R.stylesheet.schema),this.updateConfigDependencies())}getSchema(y){const C=this.getFragmentStyle(y);return C?C.stylesheet.schema:null}setSchema(y,C){const R=this.getFragmentStyle(y);R&&(R.stylesheet.schema=C,R.updateConfig(R._config,C),this.updateConfigDependencies())}updateConfig(y,C){if(this._config=y,y||C)if(C)for(const R in C){let $,G;const Z=o.X(C[R].default);if(Z.result==="success"&&($=Z.value.expression),y&&y[R]!==void 0){const Le=o.X(y[R]);Le.result==="success"&&(G=Le.value.expression)}const{minValue:te,maxValue:de,stepValue:xe,type:we,values:Re}=C[R];if($){const Le=o.F(R,this.scope);this.options.set(Le,{default:$,value:G,minValue:te,maxValue:de,stepValue:xe,type:we,values:Re})}else this.fire(new o.B(new Error(`No schema defined for config option "${R}".`)))}else this.fire(new o.B(new Error("Attempting to set config for a style without schema.")))}_updateLayers(y,C=()=>!0){for(const R of y){const $=this.getLayer(R);$&&C($)&&($.possiblyEvaluateVisibility(),this._updateLayer($),this._changes.setDirty())}}updateConfigDependencies(y){this._updateLayers(this._configDependentLayers,C=>!y||C.expressionDependencies.configDependencies.has(y)),this.ambientLight&&this.ambientLight.updateConfig(this.options),this.directionalLight&&this.directionalLight.updateConfig(this.options),this.fog&&this.fog.updateConfig(this.options),this.snow&&this.snow.updateConfig(this.options),this.rain&&this.rain.updateConfig(this.options),this.forEachFragmentStyle(C=>{const R=C._styleColorTheme.colorThemeOverride?C._styleColorTheme.colorThemeOverride:C._styleColorTheme.colorTheme;if(R){const $=C._evaluateColorThemeData(R);(!C._styleColorTheme.lut&&$!==""||C._styleColorTheme.lut&&$!==C._styleColorTheme.lut.data)&&C.setColorTheme(R)}}),this._changes.setDirty()}addLayer(y,C,R={}){this._checkLoaded();const $=y.id;if(this._layers[$])return void this.fire(new o.B(new Error(`Layer with id "${$}" already exists on this map`)));let G;if(y.type==="custom"){if(l1(this,o.dd(y)))return;G=o.de(y,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof y.source=="object"&&(this.addSource($,y.source),y=o.d9(y),y=Object.assign(y,{source:$})),this._validate(qt,`layers.${$}`,y,{arrayIndex:-1},R))return;G=o.de(y,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(G),G.setEventedParent(this,{layer:{id:$}})}const Z=o.F(G.source,G.scope);G.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Z),G.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Z);let te=this._order.length;if(C){const Re=this._order.indexOf(C);if(Re===-1)return void this.fire(new o.B(new Error(`Layer with id "${C}" does not exist on this map.`)));G.slot&&G.slot!==this._layers[C].slot?o.w(`Layer with id "${C}" has a different slot. Layers can only be rearranged within the same slot.`):te=Re}this._order.splice(te,0,$),this._handleLayerOrderChange(),this._layers[$]=G;const de=this.getOwnLayerSourceCache(G),xe=!!this.directionalLight&&this.directionalLight.shadowsEnabled();de&&G.canCastShadows()&&xe&&(de.castsShadows=!0);const we=this._changes.getRemovedLayer(G);if(we&&G.source&&de&&G.type!=="custom"){this._changes.discardLayerRemoval(G);const Re=o.F(G.source,G.scope);we.type!==G.type?this._changes.updateSourceCache(Re,"clear"):(this._changes.updateSourceCache(Re,"reload"),de.pause())}this._updateLayer(G),G.onAdd&&G.onAdd(this.map),G.scope=this.scope,this.mergeLayers()}moveLayer(y,C){this._checkLoaded();const R=this._checkLayer(y);if(!R||y===C)return;const $=this._order.indexOf(y);this._order.splice($,1);let G=this._order.length;if(C){const Z=this._order.indexOf(C);if(Z===-1)return void this.fire(new o.B(new Error(`Layer with id "${C}" does not exist on this map.`)));R.slot&&R.slot!==this._layers[C].slot?o.w(`Layer with id "${C}" has a different slot. Layers can only be rearranged within the same slot.`):G=Z}this._order.splice(G,0,y),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(y){this._checkLoaded();const C=this._checkLayer(y);if(!C)return;C.setEventedParent(null);const R=this._order.indexOf(y);this._order.splice(R,1),delete this._layers[y],this._changes.setDirty(),this._handleLayerOrderChange(),this._configDependentLayers.delete(C.fqid),this._indoorDependentLayers.delete(C.fqid),this._changes.removeLayer(C);const $=this.getOwnLayerSourceCache(C);if($&&$.castsShadows){let G=!1;for(const Z in this._layers)if(this._layers[Z].source===C.source&&this._layers[Z].canCastShadows()){G=!0;break}$.castsShadows=G}C.onRemove&&C.onRemove(this.map),this.mergeLayers()}getOwnLayer(y){return this._layers[y]}hasLayer(y){return y in this._mergedLayers}hasLayerType(y){for(const C in this._layers)if(this._layers[C].type===y)return!0;return!1}setLayerZoomRange(y,C,R){this._checkLoaded();const $=this._checkLayer(y);$&&($.minzoom===C&&$.maxzoom===R||(C!=null&&($.minzoom=C),R!=null&&($.maxzoom=R),this._updateLayer($)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(y,C){this._checkLoaded();const R=this._checkLayer(y);R&&R.slot!==C&&(R.slot=C,this._updateLayer(R))}setFilter(y,C,R={}){this._checkLoaded();const $=this._checkLayer(y);if($&&!o.b6($.filter,C))return C==null?($.filter=void 0,void this._updateLayer($)):void(this._validate(xs,`layers.${$.id}.filter`,C,{layerType:$.type},R)||($.filter=o.d9(C),this._updateLayer($)))}getFilter(y){const C=this._checkLayer(y);if(C)return o.d9(C.filter)}setLayoutProperty(y,C,R,$={}){this._checkLoaded();const G=this._checkLayer(y);if(G&&!o.b6(G.getLayoutProperty(C),R)){if(R!=null&&(!$||$.validate!==!1)&&l1(G,ks.call(wr,{key:`layers.${y}.layout.${C}`,layerType:G.type,objectKey:C,value:R,styleSpec:o.a8,style:{glyphs:!0,sprite:!0}})))return;G.setLayoutProperty(C,R),G.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(G.fqid),G.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(G.fqid),this._updateLayer(G)}}setLayerProperty(y,C,R,$={}){this._checkLoaded();const G=this._checkLayer(y);G&&(C==="appearances"?(G.setAppearances(R),this._updateLayer(G)):G.isPaintProperty(C)?this.setPaintProperty(y,C,R,$):this.setLayoutProperty(y,C,R,$))}getLayoutProperty(y,C){const R=this._checkLayer(y);if(R)return R.getLayoutProperty(C)}setPaintProperty(y,C,R,$={}){this._checkLoaded();const G=this._checkLayer(y);if(!G||o.b6(G.getPaintProperty(C),R)||R!=null&&(!$||$.validate!==!1)&&l1(G,rs.call(wr,{key:`layers.${y}.paint.${C}`,layerType:G.type,objectKey:C,value:R,styleSpec:o.a8})))return;const Z=G.setPaintProperty(C,R);G.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(G.fqid),G.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(G.fqid),Z&&this._updateLayer(G),this._changes.updatePaintProperties(G)}getPaintProperty(y,C){const R=this._checkLayer(y);if(R)return R.getPaintProperty(C)}setFeatureState(y,C){if(this._checkLoaded(),"target"in y){if("featuresetId"in y.target){const{featuresetId:de,importId:xe}=y.target,we=this.getFragmentStyle(xe),Re=we.getFeaturesetLayers(de);for(const{source:Le,sourceLayer:Ue}of Re)we.setFeatureState({id:y.id,source:Le,sourceLayer:Ue},C)}else if("layerId"in y.target){const{layerId:de}=y.target,xe=this.getLayer(de);this.setFeatureState({id:y.id,source:xe.source,sourceLayer:xe.sourceLayer},C)}return}const R=y.source,$=y.sourceLayer,G=this._checkSource(R);if(!G)return;const Z=G.type;if(Z==="geojson"&&$)return void this.fire(new o.B(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(Z==="vector"&&!$)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));y.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided.")));const te=this.getOwnSourceCaches(R);for(const de of te)de.setFeatureState($,y.id,C)}removeFeatureState(y,C){if(this._checkLoaded(),"target"in y){if("featuresetId"in y.target){const{featuresetId:de,importId:xe}=y.target,we=this.getFragmentStyle(xe),Re=we.getFeaturesetLayers(de);for(const{source:Le,sourceLayer:Ue}of Re)we.removeFeatureState({id:y.id,source:Le,sourceLayer:Ue},C)}else if("layerId"in y.target){const{layerId:de}=y.target,xe=this.getLayer(de);this.removeFeatureState({id:y.id,source:xe.source,sourceLayer:xe.sourceLayer},C)}return}const R=y.source,$=this._checkSource(R);if(!$)return;const G=$.type,Z=G==="vector"?y.sourceLayer:void 0;if(G==="vector"&&!Z)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));if(C&&typeof y.id!="string"&&typeof y.id!="number")return void this.fire(new o.B(new Error("A feature id is required to remove its specific state property.")));const te=this.getOwnSourceCaches(R);for(const de of te)de.removeFeatureState(Z,y.id,C)}getFeatureState(y){if(this._checkLoaded(),"target"in y){let G;if("featuresetId"in y.target){const{featuresetId:Z,importId:te}=y.target,de=this.getFragmentStyle(te),xe=de.getFeaturesetLayers(Z);for(const{source:we,sourceLayer:Re}of xe){const Le=de.getFeatureState({id:y.id,source:we,sourceLayer:Re});if(Le&&!G)G=Le;else if(!o.b6(G,Le))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 y.target){const{layerId:Z}=y.target,te=this.getLayer(Z);G=this.getFeatureState({id:y.id,source:te.source,sourceLayer:te.sourceLayer})}return G}const C=y.source,R=y.sourceLayer,$=this._checkSource(C);if($){if($.type!=="vector"||R)return y.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(C)[0].getFeatureState(R,y.id);this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")))}}setTransition(y){return this.stylesheet.transition=Object.assign({},this.stylesheet.transition,y),this.transition=this.stylesheet.transition,this}getTransition(){return Object.assign({},this.stylesheet.transition)}setWorldview(y){y!==this._worldview&&(this._worldview=y,this.dispatcher.broadcast("setWorldview",this._worldview),this.reloadSources())}serialize(){this._checkLoaded();const y=this.getTerrain(),C=y&&this.terrain&&this.terrain.scope===this.scope?y:this.stylesheet.terrain;return o.df({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,fragment:this.stylesheet.fragment,iconsets:this.stylesheet.iconsets,featuresets:this.stylesheet.featuresets,imports:this._serializeImports(),schema:this.stylesheet.schema,camera:this.stylesheet.camera,light:this.stylesheet.light,lights:this.stylesheet.lights,terrain:C,fog:this.stylesheet.fog,snow:this.stylesheet.snow,rain:this.stylesheet.rain,indoor:this.stylesheet.indoor,center:this.stylesheet.center,"color-theme":this.stylesheet["color-theme"],zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,projection:this.stylesheet.projection,sources:this._serializeSources(),layers:this._serializeLayers(this._order)},R=>R!==void 0)}_updateFilteredLayers(y){for(const C of Object.values(this._mergedLayers))y(C)&&this._updateLayer(C)}_updateLayer(y){this._changes.updateLayer(y);const C=this.getLayerSourceCache(y),R=o.F(y.source,y.scope),$=this._changes.getUpdatedSourceCaches();y.source&&!$[R]&&C&&C.getSource().type!=="raster"&&(this._changes.updateSourceCache(R,"reload"),C.pause()),y.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(y){const C=te=>this._mergedLayers[te].is3D(!!this.terrain),R=this.order,$={},G=[];for(let te=R.length-1;te>=0;te--){const de=R[te];if(C(de)){$[de]=te;for(const xe of y){const we=xe[de];if(we)for(const Re of we)G.push(Re)}}}G.sort((te,de)=>de.intersectionZ-te.intersectionZ);const Z=[];for(let te=R.length-1;te>=0;te--){const de=R[te];if(C(de))for(let xe=G.length-1;xe>=0;xe--){const we=G[xe].feature;if(we.layer&&$[we.layer.id]{if(mj.has(we.type))return;const Re=this.getOwnLayerSourceCache(we),Le=G[Re.id]=G[Re.id]||{sourceCache:Re,layers:{},has3DLayers:!1};we.is3D(!!this.terrain)&&(Le.has3DLayers=!0),Le.layers[we.fqid]=Le.layers[we.fqid]||{styleLayer:we,targets:[]},Le.layers[we.fqid].targets.push({filter:$})};if(C&&C.layers){if(!Array.isArray(C.layers))return this.fire(new o.B(new Error("parameters.layers must be an Array."))),[];for(const we of C.layers){const Re=this._layers[we];if(!Re)return this.fire(new o.B(new Error(`The layer '${we}' does not exist in the map's style and cannot be queried for features.`))),[];Z(Re)}}else for(const we in this._layers)Z(this._layers[we]);const te=this._queryRenderedFeatures(y,G,R),de=this._flattenAndSortRenderedFeatures(te),xe=[];for(const we of de)o.dh(we.layer.id)===this.scope&&xe.push(we);return xe}queryRenderedFeatureset(y,C,R){let $;C&&!Array.isArray(C)&&C.filter&&(this._validate(xs,"queryRenderedFeatures.filter",C.filter,null,C),$=o.dg(C.filter));const G="mock",Z=[];if(C&&C.target)Z.push(Object.assign({},C,{targetId:G,filter:$}));else{const we=this.getFeaturesetDescriptors();for(const Re of we)Z.push({targetId:G,filter:$,target:Re});for(const{style:Re}of this.fragments){const Le=Re.getFeaturesetDescriptors();for(const Ue of Le)Z.push({targetId:G,filter:$,target:Ue})}}const te=this.queryRenderedTargets(y,Z,R),de=[],xe=new Set;for(const we of te)for(const Re of we.variants[G])yh(Re,we,xe)||de.push(new o.di(we,Re));return de}queryRenderedTargets(y,C,R){const $={},G=(te,de,xe,we)=>{const Re=$[de.id]=$[de.id]||{sourceCache:de,layers:{},has3DLayers:!1};if(Re.layers[te.fqid]=Re.layers[te.fqid]||{styleLayer:te,targets:[]},te.is3D(!!this.terrain)&&(Re.has3DLayers=!0),!we)return xe.uniqueFeatureID=!1,void Re.layers[te.fqid].targets.push(xe);Re.layers[te.fqid].targets.push(Object.assign({},xe,{namespace:we.namespace,properties:we.properties,uniqueFeatureID:we.uniqueFeatureID}))};for(const te of C)if("featuresetId"in te.target){const{featuresetId:de,importId:xe}=te.target,we=this.getFragmentStyle(xe);if(!we||!we._featuresetSelectors)continue;const Re=we._featuresetSelectors[de];if(!Re){this.fire(new o.B(new Error(`The featureset '${de}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const Le of Re){const Ue=we.getOwnLayer(Le.layerId);Ue&&!mj.has(Ue.type)&&G(Ue,we.getOwnLayerSourceCache(Ue),te,Le)}}else if("layerId"in te.target){const{layerId:de}=te.target,xe=this.getLayer(de);if(!xe||mj.has(xe.type))continue;G(xe,this.getLayerSourceCache(xe),te)}const Z=this._queryRenderedFeatures(y,$,R);return this._flattenAndSortRenderedFeatures(Z)}_queryRenderedFeatures(y,C,R){const $=[],G=!!this.map._showQueryGeometry,Z=rl.createFromScreenPoints(y,R);for(const te in C){const de=mx(Z,C[te],this._availableImages,R,G,this.getActualScope());Object.keys(de).length&&$.push(de)}if(this.placement)for(const te in C){if(C[te].sourceCache._renderSourceType!==o.b4.Symbol)continue;const de=fo(Z.screenGeometry,C[te],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(de).length&&$.push(de)}return $}querySourceFeatures(y,C){const R=C&&C.filter;R&&this._validate(xs,"querySourceFeatures.filter",R,null,C);let $=[];const G=this.getOwnSourceCaches(y);for(const Z of G)$=$.concat(qb(Z,C));return $}addSourceType(y,C,R){return Qc.getSourceType(y)?R(new Error(`A source type called "${y}" already exists.`)):(Qc.setSourceType(y,C),C.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:y,url:C.workerSourceURL},R):R(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(y,C,R={}){this._checkLoaded();const $=this.light.getLight();let G=!1;for(const te in y)if(!o.b6(y[te],$[te])){G=!0;break}if(!G)return;const Z=this._getTransitionParameters();this.light.setLight(y,C,R),this.light.updateTransitions(Z)}getTerrain(){return this.terrain&&this.terrain.drapeRenderMode===1?this.terrain.get():null}setTerrainForDraping(){this.setTerrain({source:"",exaggeration:0},0)}checkCanvasFingerprintNoise(){this.disableElevatedTerrain===void 0&&(this.disableElevatedTerrain=o.o.hasCanvasFingerprintNoise(),this.disableElevatedTerrain&&o.w("Terrain and hillshade are disabled because of Canvas2D limitations when fingerprinting protection is enabled (e.g. in private browsing mode)."))}setTerrain(y,C=1){if(this._checkLoaded(),!y)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),C===0&&delete this.terrain,y===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let R=y;const $=!("source"in y)||y.source==null;if(C===1){if(this.disableElevatedTerrain)return;if("source"in R&&typeof R.source=="object"){const te="terrain-dem-src";this.addSource(te,R.source),R=o.d9(R),R=Object.assign(R,{source:te})}const G=Object.assign({},R),Z={};if(this.terrain&&$){G.source=this.terrain.get().source;const te=this.terrain?this.getFragmentStyle(this.terrain.scope):null;te&&(Z.style=te.serialize())}if(this._validate(Xe,"terrain",G,Z))return}if(!this.terrain||this.terrain.scope!==this.scope&&!$||this.terrain&&C!==this.terrain.drapeRenderMode){if(!R)return;this._createTerrain(R,C),this.fire(new o.C("data",{dataType:"style"}))}else{const G=this.terrain,Z=G.get();for(const te of Object.keys(o.a8.terrain))!R.hasOwnProperty(te)&&o.a8.terrain[te].default&&(R[te]=o.a8.terrain[te].default);for(const te in y)if(!o.b6(y[te],Z[te])){G.set(y,this.options),this.stylesheet.terrain=y;const de=this._getTransitionParameters({duration:0});G.updateTransitions(de),this.fire(new o.C("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(y){const C=this.fog=new zi(y,this.map.transform,this.scope,this.options);this.stylesheet.fog=C.get();const R=this._getTransitionParameters({duration:0});C.updateTransitions(R)}_createSnow(y){const C=this.snow=new qi(y,this.map.transform,this.scope,this.options);this.stylesheet.snow=C.get();const R=this._getTransitionParameters({duration:0});C.updateTransitions(R)}_createRain(y){const C=this.rain=new ga(y,this.map.transform,this.scope,this.options);this.stylesheet.rain=C.get();const R=this._getTransitionParameters({duration:0});C.updateTransitions(R)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const y of this.map._markers)y._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(y){if(this._checkLoaded(),!y)return delete this.fog,delete this.stylesheet.fog,void(this._markersNeedUpdate=!0);if(this.fog){const C=this.fog;if(!o.b6(C.get(),y)){C.set(y,this.options),this.stylesheet.fog=C.get();const R=this._getTransitionParameters({duration:0});C.updateTransitions(R)}}else this._createFog(y);this._markersNeedUpdate=!0}getSnow(){return this.snow?this.snow.get():null}setSnow(y){if(this._checkLoaded(),!y)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const C=this.snow;if(!o.b6(C.get(),y)){C.set(y,this.options),this.stylesheet.snow=C.get();const R=this._getTransitionParameters({duration:0});C.updateTransitions(R)}}else this._createSnow(y);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(y){if(this._checkLoaded(),!y)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const C=this.rain;if(!o.b6(C.get(),y)){C.set(y,this.options),this.stylesheet.rain=C.get();const R=this._getTransitionParameters({duration:0});C.updateTransitions(R)}}else this._createRain(y);this._markersNeedUpdate=!0}_reloadColorTheme(){const y=()=>{for(const $ in this._layers)this._layers[$].lut=this._styleColorTheme.lut;for(const $ in this._sourceCaches)this._sourceCaches[$].clearTiles()},C=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!C)return this._styleColorTheme.lut=null,void y();const R=this._evaluateColorThemeData(C);this._loadColorTheme(R).then(()=>{this.fire(new o.C("colorthemeset")),y()}).catch($=>{o.w(`Couldn't set color theme: ${$}`)})}setColorTheme(y){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=y,this._reloadColorTheme()}setImportColorTheme(y,C){const R=this.getFragmentStyle(y);R&&(R._styleColorTheme.colorThemeOverride=C,R._reloadColorTheme())}_getTransitionParameters(y){return{now:o.o.now(),transition:Object.assign(this.transition,y)}}updateDrapeFirstLayers(){if(!this.terrain)return;const y=[],C=[];for(const R of this._mergedOrder)this.isLayerDraped(this._mergedLayers[R])?y.push(R):C.push(R);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...y),this._drapedFirstOrder.push(...C)}_createTerrain(y,C){const R=this.terrain=new fn(y,C,this.scope,this.options,this.map.getWorldview());C===1&&(this.stylesheet.terrain=y),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const $=this._getTransitionParameters({duration:0});R.updateTransitions($)}_force3DLayerUpdate(){for(const y in this._layers){const C=this._layers[y];C.type==="fill-extrusion"&&this._updateLayer(C)}}_forceSymbolLayerUpdate(){for(const y in this._layers){const C=this._layers[y];C.type==="symbol"&&this._updateLayer(C)}}_validate(y,C,R,$,G={}){if(G&&G.validate===!1)return!1;const Z=Object.assign({},this.serialize());return l1(this,y.call(wr,Object.assign({key:C,style:Z,value:R,styleSpec:o.a8},$)))}_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 y in this._mergedLayers)this._mergedLayers[y].setEventedParent(null);for(const y in this._mergedSourceCaches)this._mergedSourceCaches[y].clearTiles(),this._mergedSourceCaches[y].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(y){const C=this.getSourceCaches(y);for(const R of C)R.clearTiles()}clearSources(){for(const y in this._mergedSourceCaches)this._mergedSourceCaches[y].clearTiles()}clearLayers(){for(const y in this._mergedLayers){const C=this._mergedLayers[y];C._clear&&C._clear()}}reloadSource(y){const C=this.getSourceCaches(y);for(const R of C)R.resume(),R.reload()}reloadSources(){for(const y of this.getSources())y.reload&&y.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(y=>{y.modelManager.reloadModels(y.scope)})}updateSources(y){let C;this.directionalLight&&(C=LN(this.directionalLight));const R=new Set,$=new Set,G=new Set;for(const Z in this._mergedLayers){const te=this._mergedLayers[Z];te.type==="building"?R.add(te.source):te.type==="raster"&&te.paint&&te.paint.get("raster-elevation-reference")==="ground"&&G.add(te.source),te.hasElevation()&&!$.has(te.source)&&$.add(te.source)}for(const Z in this._mergedSourceCaches){const te=this._mergedSourceCaches[Z],de=$.has(te._source.id);te._isRasterElevatedOverTerrain=G.has(te._source.id),R.has(te._source.id)&&(te._source.reparseOverscaled=!1),te.update(y,void 0,void 0,C,de)}}_generateCollisionBoxes(){for(const y in this._sourceCaches){const C=this._sourceCaches[y];C.resume(),C.reload()}}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new o.C("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new Kb),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(y,C,R,$,G){this.pauseablePlacement||(this.pauseablePlacement=new Kb);let Z=!1,te=!1;const de={},xe={};for(const Je of this._mergedOrder){const mt=this._mergedLayers[Je];if(mt.type!=="symbol")continue;const ht=o.F(mt.source,mt.scope);let kt=de[ht];if(!kt){const xt=this.getLayerSourceCache(mt);if(!xt)continue;const es=xt.getRenderableIds(!0).map(Ft=>xt.getTileByID(Ft));xe[ht]=es.slice(),kt=de[ht]=es.sort((Ft,Qt)=>Qt.tileID.overscaledZ-Ft.tileID.overscaledZ||(Ft.tileID.isLessThan(Qt.tileID)?-1:1))}const Tt=this.crossTileSymbolIndex.addLayer(mt,kt,y.center.lng,y.projection);Z=Z||Tt}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const we=!!(this.placement&&!y.equals(this.placement.transform)),Re=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!G||this.placement.lastReplacementSourceUpdateTime!==G.updateTime)),Le=we||Re||Z,Ue=(Le||this.pauseablePlacement.isStale())&&R===0,st=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.o.now(),y.zoom)&&R!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||Ue||st)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(y,this._mergedOrder,C,R,$,this.placement,this.fog&&y.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const Je=this.map.painter.maxFrontCutoffRawStart;if(Je>0){const mt=180*y.pitch/Math.PI;if(mt>=15){const ht=Math.min(1,Math.max(0,(mt-15)/5)),kt=ht*ht*(3-2*ht);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-kt)+Je*kt}}}if(this.pauseablePlacement.isDone()?Le&&R!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,de,xe,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.o.now()),te=!0),Z&&this.pauseablePlacement.setStale()),te||Z){this._buildingIndex.onNewFrame(y.zoom);for(let Je=0;JeG===y.id)!==-1)return void this.fire(new o.B(new Error(`Import with id '${y.id}' already exists in the map's style.`)));if(!C)return R.push(y),this._loadImports([y],!0);const $=R.findIndex(({id:G})=>G===C);return $===-1&&this.fire(new o.B(new Error(`Import with id "${C}" does not exist on this map.`))),this.stylesheet.imports=R.slice(0,$).concat(y).concat(R.slice($)),this._loadImports([y],!0,C)}updateImport(y,C){this._checkLoaded();const R=this.stylesheet.imports||[],$=this.getImportIndex(y);return $===-1?this:typeof C=="string"?(this.setImportUrl(y,C),this):(C.url&&C.url!==R[$].url&&this.setImportUrl(y,C.url),o.b6(C.config,R[$].config)||this.setImportConfig(y,C.config,C.data.schema),o.b6(C.data,R[$].data)||this.setImportData(y,C.data),this)}moveImport(y,C){this._checkLoaded();let R=this.stylesheet.imports||[];const $=this.getImportIndex(y);if($===-1)return this;const G=this.getImportIndex(C);if(G===-1)return this;const Z=R[$],te=this.fragments[$];return R=R.filter(({id:de})=>de!==y),this.fragments=this.fragments.filter(({id:de})=>de!==y),this.stylesheet.imports=R.slice(0,G).concat(Z).concat(R.slice(G)),this.fragments=this.fragments.slice(0,G).concat(te).concat(this.fragments.slice(G)),this.mergeLayers(),this}setImportUrl(y,C){this._checkLoaded();const R=this.stylesheet.imports||[],$=this.getImportIndex(y);if($===-1)return this;R[$].url=C;const G=this.fragments[$];return G.style=this._createFragmentStyle(R[$]),G.style.on("style.import.load",()=>this.mergeAll()),G.style.loadURL(C),this}setImportData(y,C){this._checkLoaded();const R=this.getImportIndex(y),$=this.stylesheet.imports||[];return R===-1?this:C?(this.fragments[R].style.setState(C),this._reloadImports(),this):(delete $[R].data,this.setImportUrl(y,$[R].url))}setImportConfig(y,C,R){this._checkLoaded();const $=this.getImportIndex(y),G=this.stylesheet.imports||[];if($===-1)return this;C?G[$].config=C:delete G[$].config;const Z=this.fragments[$];R&&Z.style.stylesheet&&(Z.style.stylesheet.schema=R);const te=Z.style.stylesheet&&Z.style.stylesheet.schema;return Z.config=C,Z.style.updateConfig(C,te),this.updateConfigDependencies(),this}removeImport(y){this._checkLoaded();const C=this.stylesheet.imports||[],R=this.getImportIndex(y);R!==-1&&(C.splice(R,1),this.fragments[R].style._remove(),this.fragments.splice(R,1),this._reloadImports())}getImportIndex(y){const C=(this.stylesheet.imports||[]).findIndex(R=>R.id===y);return C===-1&&this.fire(new o.B(new Error(`Import '${y}' does not exist in the map's style and cannot be updated.`))),C}getLayer(y){return this._mergedLayers[y]}getSources(){const y=[];for(const C in this._mergedOtherSourceCaches){const R=this._mergedOtherSourceCaches[C];R&&y.push(R.getSource())}return y}getSource(y,C){const R=this.getSourceCache(y,C);return R&&R.getSource()}getLayerSource(y){const C=this.getLayerSourceCache(y);return C&&C.getSource()}getSourceCache(y,C){const R=o.F(y,C);return this._mergedOtherSourceCaches[R]}getLayerSourceCache(y){const C=o.F(y.source,y.scope);return y.type==="symbol"?this._mergedSymbolSourceCaches[C]:y.type==="fill-extrusion"&&this._mergedFillExtrusionSourceCaches[C]||this._mergedOtherSourceCaches[C]}getSourceCaches(y){if(y==null)return Object.values(this._mergedSourceCaches);const C=[];return this._mergedOtherSourceCaches[y]&&C.push(this._mergedOtherSourceCaches[y]),this._mergedSymbolSourceCaches[y]&&C.push(this._mergedSymbolSourceCaches[y]),this._mergedFillExtrusionSourceCaches[y]&&C.push(this._mergedFillExtrusionSourceCaches[y]),C}updateSourceCaches(){const y=this._changes.getUpdatedSourceCaches();for(const C in y){const R=y[C];R==="reload"?this.reloadSource(C):R==="clear"&&this.clearSource(C)}}updateLayers(y){const C=this._changes.getUpdatedPaintProperties();for(const R of C){const $=this.getLayer(R);$&&$.updateTransitions(y)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(y){this.stylesheet.glyphs=y,this.glyphManager.setURL(y)}getImages(y,C,R){this.imageManager.getImages(C.images,C.scope,R),this._updateTilesForChangedImages();const $=Z=>{if(Z){const te=C.images.map(de=>o.I.toString(de));Z.setDependencies(C.tileID.key,C.type,te)}},G=o.F(C.source,C.scope);$(this._mergedOtherSourceCaches[G]),$(this._mergedSymbolSourceCaches[G]),C.images.some(Z=>Z.iconsetId)&&this.fire(new o.C("data",{dataType:"style"}))}rasterizeImages(y,C,R){this.imageManager.rasterizeImages(C,R)}checkAtlasCache(y,C,R){const $=this.imageManager.imageAtlasCache.findCachedAtlas(C.descriptor);R(null,$&&$.contentDescriptor?{iconPositions:$.iconPositions,patternPositions:$.patternPositions,sourceHash:$.contentDescriptor.hash}:null)}getGlyphs(y,C,R){this.glyphManager.getGlyphs(C.stacks,R)}getOwnSourceCache(y){return this._otherSourceCaches[y]}getOwnLayerSourceCache(y){return y.type==="symbol"?this._symbolSourceCaches[y.source]:y.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[y.source]||this._otherSourceCaches[y.source]}getOwnSourceCaches(y){const C=[];return this._otherSourceCaches[y]&&C.push(this._otherSourceCaches[y]),this._symbolSourceCaches[y]&&C.push(this._symbolSourceCaches[y]),this._fillExtrusionSourceCaches[y]&&C.push(this._fillExtrusionSourceCaches[y]),C}_isSourceCacheLoaded(y){const C=this.getOwnSourceCaches(y);return C.length===0?(this.fire(new o.B(new Error(`There is no source with ID '${y}'`))),!1):C.every(R=>R.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(y,C){if(!this._clipLayerPresent&&y.type!=="fill-extrusion"&&y.type!=="building")return!1;const R=y.type==="fill-extrusion"&&(y.sourceLayer==="building"||y.sourceLayer==="procedural_buildings"),$=y.type==="building";if(y.is3D(!!this.terrain)){if(R||$||C&&C.type==="batched-model"||y.type==="model")return!0}else if(y.type==="symbol")return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(y=>{y.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}}Qc.getSourceType=function(I){return Ay[I]},Qc.setSourceType=function(I,y){Ay[I]=y},Qc.registerForPluginStateChange=o.dk;var c1=` #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`,pj=` #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;}`,hg=` #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`,Xb="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;}",RN=` #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`,ON=`#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`,d1=`#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`,u1=`#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`,FN=`#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;}`,fj=`#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`,ip=`#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 p0=/#include\s+"([^"]+)"/g,$n=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,xj=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,gj=new Set(["ifdef","ifndef","elif","if","defined"]),zy=new Set;mg(c1,zy),mg(hg,zy),mg(pj,zy);const Bp={"_prelude_fog.vertex.glsl":ON,"_prelude_terrain.vertex.glsl":RN,"_prelude_shadow.vertex.glsl":fj,"_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":d1,"_prelude_shadow.fragment.glsl":ip,"_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":u1,"_prelude_raster_particle.glsl":FN},h1={};xi("",RN),xi(d1,ON),xi(ip,fj),xi(u1,""),xi(FN,"");const f0=xi(pj,hg),Jb=c1,m1=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",Jb,f0.fragmentSource].join(` `),gC=["precision highp float;",Jb,f0.vertexSource].join(` `);var yC={background:xi(`#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:xi(`#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:xi(`#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:xi(`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:xi("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),circle:xi(`#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:xi("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:xi(`#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:xi(`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:xi("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:xi("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:xi("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:xi("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:xi(`#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:xi(`#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:xi(`#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:xi(`#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:xi(`#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:xi(`#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:xi(`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:xi(`#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:xi("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:xi(`#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:xi(`#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:xi(`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:xi(`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:xi(`#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:xi(`#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:xi(`#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:xi(`#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:xi(`#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:xi("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:xi("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:xi(`#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:xi(`#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:xi(`#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:xi("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:xi(`#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 }`,Xb),skyboxGradient:xi(`#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 }`,Xb),skyboxCapture:xi(` 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:xi(`#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:xi(`#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:xi(`#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:xi("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:xi(`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:xi("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:xi("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:xi("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:xi("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 mg(I,y){const C=I.split(` `);for(let R of C){if(R=R.trimStart(),R[0]!=="#"||!R.includes("if")||R.startsWith("#endif"))continue;const $=R.match(xj);if($)for(const G of $)gj.has(G)||y.add(G)}}function vC(I){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(I)}function xi(I,y){const C=new Set,R=[],$=[];I=I.replace(p0,(Z,te)=>($.push(te),"")),y=y.replace(p0,(Z,te)=>(R.push(te),""));let G=new Set(zy);mg(I,G),mg(y,G);for(const Z of[...R,...$])h1[Z]||(h1[Z]=new Set,mg(Bp[Z],h1[Z])),G=new Set([...G,...h1[Z]]);return{fragmentSource:I=I.replace($n,(Z,te,de,xe,we)=>(C.add(we),te==="define"?` #ifndef HAS_UNIFORM_u_${we} ${vC(xe)?"flat ":""}in ${de} ${xe} ${we}; #else uniform ${de} ${xe} u_${we}; #endif `:te==="initialize"?` #ifdef HAS_UNIFORM_u_${we} ${de} ${xe} ${we} = u_${we}; #endif `:te==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${we} in ${de} ${xe} ${we}; #endif `:te==="initialize-attribute"?"":void 0)),vertexSource:y=y.replace($n,(Z,te,de,xe,we)=>{const Re=`MATERIAL_ATTRIBUTE_OFFSET_${we}`,Le=xe==="float"?"vec2":xe,Ue=`GET_ATTRIBUTE_${Le}(a_${we}, materialInfo, ${Re})`,st=we.match(/color/)?"color":Le;return te==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${we} in ${de} ${xe} a_${we}; #endif `:C.has(we)?te==="define"?` #ifndef HAS_UNIFORM_u_${we} uniform lowp float u_${we}_t; #if !defined(${Re}) in ${de} ${Le} a_${we}; #endif ${vC(xe)?"flat ":""}out ${de} ${xe} ${we}; #else uniform ${de} ${xe} u_${we}; #endif `:te==="initialize"?st==="vec4"||st==="uvec4"?` #ifndef HAS_UNIFORM_u_${we} ${we} = a_${we}; #else ${de} ${xe} ${we} = u_${we}; #endif `:` #if !defined(HAS_UNIFORM_u_${we}) #ifdef ${Re} ${we} = unpack_mix_${st}(${Ue}, u_${we}_t); #else ${we} = unpack_mix_${st}(a_${we}, u_${we}_t); #endif #else ${de} ${xe} ${we} = u_${we}; #endif `:te==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${we} in ${de} ${xe} a_${we}; out ${de} ${xe} ${we}; #endif `:te==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${we} ${we} = a_${we}; #endif `:void 0:te==="define"?` #ifndef HAS_UNIFORM_u_${we} uniform lowp float u_${we}_t; #if !defined(${Re}) in ${de} ${Le} a_${we}; #endif #else uniform ${de} ${xe} u_${we}; #endif `:te==="define-instanced"?st==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${we}0; in vec4 a_${we}1; in vec4 a_${we}2; in vec4 a_${we}3; #else uniform ${de} ${xe} u_${we}; #endif `:` #ifdef INSTANCED_ARRAYS in ${de} ${Le} a_${we}; #else uniform ${de} ${xe} u_${we}; #endif `:te==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${we} ${de} ${xe} ${we} = a_${we}; #endif `:st==="vec4"||st==="uvec4"?` #ifndef HAS_UNIFORM_u_${we} #ifdef ${Re} ${de} ${xe} ${we} = ${Ue}; #else ${de} ${xe} ${we} = a_${we}; #endif #else ${de} ${xe} ${we} = u_${we}; #endif `:` #ifndef HAS_UNIFORM_u_${we} #ifdef ${Re} ${de} ${xe} ${we} = unpack_mix_${st}(${Ue}, u_${we}_t); #else ${de} ${xe} ${we} = unpack_mix_${st}(a_${we}, u_${we}_t); #endif #else ${de} ${xe} ${we} = u_${we}; #endif `}),usedDefines:G,vertexIncludes:R,fragmentIncludes:$}}class bC{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(y,C,R,$,G,Z,te,de){this.context=y;let xe=this.boundPaintVertexBuffers.length!==$.length;for(let Re=0;!xe&&Re<$.length;Re++)this.boundPaintVertexBuffers[Re]!==$[Re]&&(xe=!0);let we=this.boundDynamicVertexBuffers.length!==te.length;for(let Re=0;!we&&Re{const es=Tt.paint.get("hillshade-shadow-color"),Ft=Tt.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",Qt=Tt.paint.get("hillshade-highlight-color"),At=Tt.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",Dt=Tt.paint.get("hillshade-accent-color"),Gt=Tt.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",gs=Tt.paint.get("hillshade-emissive-strength");let ns=o.ap(Tt.paint.get("hillshade-illumination-direction"));if(Tt.paint.get("hillshade-illumination-anchor")==="viewport")ns-=ht.transform.angle;else if(ht.style&&ht.style.enable3dLights()&&ht.style.directionalLight){const Ps=ht.style.directionalLight.properties.get("direction"),an=o.cP(Ps.x,Ps.y,Ps.z);ns=o.ap(an[1])}const $s=!ht.options.moving;return{u_matrix:xt||ht.transform.calculateProjMatrix(kt.tileID.toUnwrapped(),$s),u_image:0,u_latrange:_C(0,kt.tileID),u_light:[Tt.paint.get("hillshade-exaggeration"),ns],u_shadow:es.toPremultipliedRenderColor(Ft?null:Tt.lut),u_highlight:Qt.toPremultipliedRenderColor(At?null:Tt.lut),u_emissive_strength:gs,u_accent:Dt.toPremultipliedRenderColor(Gt?null:Tt.lut)}})(I,C,R,I.terrain?y.projMatrix:null);I.uploadCommonUniforms(te,Le,y.toUnwrapped());const{tileBoundsBuffer:st,tileBoundsIndexBuffer:Je,tileBoundsSegments:mt}=I.getTileBoundsBuffers(C);Le.draw(I,de.TRIANGLES,$,G,Z,Rr.disabled,Ue,R.id,st,Je,mt)}function wC(I,y,C){if(!y.needsDEMTextureUpload)return;const R=I.context,$=R.gl;R.pixelStoreUnpackPremultiplyAlpha.set(!1),y.demTexture=y.demTexture||I.getTileTexture(C.stride);const G=C.getPixels();y.demTexture?y.demTexture.update(G,{premultiply:!1}):y.demTexture=new o.T(R,G,$.R32F,{premultiply:!1}),y.needsDEMTextureUpload=!1}function f6(I,y,C){const R=I.context,$=R.gl;if(!y.dem)return;const G=y.dem;if(R.activeTexture.set($.TEXTURE1),wC(I,y,G),!y.demTexture)return;y.demTexture.bind($.NEAREST,$.CLAMP_TO_EDGE);const Z=G.dim;R.activeTexture.set($.TEXTURE0);let te=y.hillshadeFBO;if(!te){const Le=new o.T(R,{width:Z,height:Z,data:null},$.RGBA8);Le.bind($.LINEAR,$.CLAMP_TO_EDGE),te=y.hillshadeFBO=R.createFramebuffer(Z,Z,1,"renderbuffer"),te.colorAttachment0.set(Le.texture)}R.bindFramebuffer.set(te.framebuffer),R.viewport.set([0,0,Z,Z]);const{tileBoundsBuffer:de,tileBoundsIndexBuffer:xe,tileBoundsSegments:we}=I.getMercatorTileBoundsBuffers(),Re=[];I.linearFloatFilteringSupported()&&Re.push("TERRAIN_DEM_FLOAT_FORMAT"),I.terrain&&I.terrain.renderingToTexture&&I.emissiveMode==="mrt-fallback"&&Re.push("USE_MRT1"),I.getOrCreateProgram("hillshadePrepare",{defines:Re}).draw(I,$.TRIANGLES,ar.disabled,oa.disabled,sa.unblended,Rr.disabled,((Le,Ue)=>{const st=Ue.stride,Je=o.bb();return o.bT(Je,0,o.an,-o.an,0,0,1),o.bx(Je,Je,[0,-o.an,0]),{u_matrix:Je,u_image:1,u_dimension:[st,st],u_zoom:Le.overscaledZ}})(y.tileID,G),C.id,de,xe,we),y.needsHillshadePrepare=!1}class cl{constructor(y){this.gl=y.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(y){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class yj extends cl{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(y){const C=this.current;(y.r!==C.r||y.g!==C.g||y.b!==C.b||y.a!==C.a||this.dirty)&&(this.gl.clearColor(y.r,y.g,y.b,y.a),this.current=y,this.dirty=!1)}}class BR extends cl{getDefault(){return 1}set(y){(y!==this.current||this.dirty)&&(this.gl.clearDepth(y),this.current=y,this.dirty=!1)}}class zN extends cl{getDefault(){return 0}set(y){(y!==this.current||this.dirty)&&(this.gl.clearStencil(y),this.current=y,this.dirty=!1)}}class $R extends cl{getDefault(){return[!0,!0,!0,!0]}set(y){const C=this.current;(y[0]!==C[0]||y[1]!==C[1]||y[2]!==C[2]||y[3]!==C[3]||this.dirty)&&(this.gl.colorMask(y[0],y[1],y[2],y[3]),this.current=y,this.dirty=!1)}}class Ff extends cl{getDefault(){return!0}set(y){(y!==this.current||this.dirty)&&(this.gl.depthMask(y),this.current=y,this.dirty=!1)}}class vj extends cl{getDefault(){return 255}set(y){(y!==this.current||this.dirty)&&(this.gl.stencilMask(y),this.current=y,this.dirty=!1)}}class p1 extends cl{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(y){const C=this.current;(y.func!==C.func||y.ref!==C.ref||y.mask!==C.mask||this.dirty)&&(this.gl.stencilFunc(y.func,y.ref,y.mask),this.current=y,this.dirty=!1)}}class BN extends cl{getDefault(){const y=this.gl;return[y.KEEP,y.KEEP,y.KEEP]}set(y){const C=this.current;(y[0]!==C[0]||y[1]!==C[1]||y[2]!==C[2]||this.dirty)&&(this.gl.stencilOp(y[0],y[1],y[2]),this.current=y,this.dirty=!1)}}class By extends cl{getDefault(){return!1}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;y?C.enable(C.STENCIL_TEST):C.disable(C.STENCIL_TEST),this.current=y,this.dirty=!1}}class $y extends cl{getDefault(){return[0,1]}set(y){const C=this.current;(y[0]!==C[0]||y[1]!==C[1]||this.dirty)&&(this.gl.depthRange(y[0],y[1]),this.current=y,this.dirty=!1)}}class Uy extends cl{getDefault(){return!1}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;y?C.enable(C.DEPTH_TEST):C.disable(C.DEPTH_TEST),this.current=y,this.dirty=!1}}class bm extends cl{getDefault(){return this.gl.LESS}set(y){(y!==this.current||this.dirty)&&(this.gl.depthFunc(y),this.current=y,this.dirty=!1)}}class $N extends cl{getDefault(){return!1}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;y?C.enable(C.BLEND):C.disable(C.BLEND),this.current=y,this.dirty=!1}}class bj extends cl{getDefault(){const y=this.gl;return[y.ONE,y.ZERO,y.ONE,y.ZERO]}set(y){const C=this.current;(y[0]!==C[0]||y[1]!==C[1]||y[2]!==C[2]||y[3]!==C[3]||this.dirty)&&(this.gl.blendFuncSeparate(y[0],y[1],y[2],y[3]),this.current=y,this.dirty=!1)}}class x6 extends cl{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(y){const C=this.current;(y.r!==C.r||y.g!==C.g||y.b!==C.b||y.a!==C.a||this.dirty)&&(this.gl.blendColor(y.r,y.g,y.b,y.a),this.current=y,this.dirty=!1)}}class f1 extends cl{getDefault(){return this.gl.FUNC_ADD}set(y){(y!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(y,y),this.current=y,this.dirty=!1)}}class _j extends cl{getDefault(){return!1}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;y?C.enable(C.CULL_FACE):C.disable(C.CULL_FACE),this.current=y,this.dirty=!1}}class wj extends cl{getDefault(){return this.gl.BACK}set(y){(y!==this.current||this.dirty)&&(this.gl.cullFace(y),this.current=y,this.dirty=!1)}}class UN extends cl{getDefault(){return this.gl.CCW}set(y){(y!==this.current||this.dirty)&&(this.gl.frontFace(y),this.current=y,this.dirty=!1)}}let jj=class extends cl{getDefault(){return null}set(I){(I!==this.current||this.dirty)&&(this.gl.useProgram(I),this.current=I,this.dirty=!1)}};class Nj extends cl{getDefault(){return this.gl.TEXTURE0}set(y){(y!==this.current||this.dirty)&&(this.gl.activeTexture(y),this.current=y,this.dirty=!1)}}class _m extends cl{getDefault(){const y=this.gl;return[0,0,y.drawingBufferWidth,y.drawingBufferHeight]}set(y){const C=this.current;(y[0]!==C[0]||y[1]!==C[1]||y[2]!==C[2]||y[3]!==C[3]||this.dirty)&&(this.gl.viewport(y[0],y[1],y[2],y[3]),this.current=y,this.dirty=!1)}}class $h extends cl{getDefault(){return null}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;C.bindFramebuffer(C.FRAMEBUFFER,y),this.current=y,this.dirty=!1}}class jC extends cl{getDefault(){return null}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;C.bindRenderbuffer(C.RENDERBUFFER,y),this.current=y,this.dirty=!1}}class x1 extends cl{getDefault(){return null}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;C.bindTexture(C.TEXTURE_2D,y),this.current=y,this.dirty=!1}}class NC extends cl{getDefault(){return null}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;C.bindBuffer(C.ARRAY_BUFFER,y),this.current=y,this.dirty=!1}}class g6 extends cl{getDefault(){return null}set(y){const C=this.gl;C.bindBuffer(C.ELEMENT_ARRAY_BUFFER,y),this.current=y,this.dirty=!1}}class y6 extends cl{getDefault(){return null}set(y){this.gl&&(y!==this.current||this.dirty)&&(this.gl.bindVertexArray(y),this.current=y,this.dirty=!1)}}class kC extends cl{getDefault(){return 4}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;C.pixelStorei(C.UNPACK_ALIGNMENT,y),this.current=y,this.dirty=!1}}class qN extends cl{getDefault(){return!1}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;C.pixelStorei(C.UNPACK_PREMULTIPLY_ALPHA_WEBGL,y),this.current=y,this.dirty=!1}}class kj extends cl{getDefault(){return!1}set(y){if(y===this.current&&!this.dirty)return;const C=this.gl;C.pixelStorei(C.UNPACK_FLIP_Y_WEBGL,y),this.current=y,this.dirty=!1}}class e_ extends cl{constructor(y,C){super(y),this.context=y,this.parent=C}getDefault(){return null}}class g1 extends e_{constructor(y,C,R=0){super(y,C),this.attachmentPoint=y.gl.COLOR_ATTACHMENT0+R}setDirty(){this.dirty=!0}set(y){if(y===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const C=this.gl;C.framebufferTexture2D(C.FRAMEBUFFER,this.attachmentPoint,C.TEXTURE_2D,y,0),this.current=y,this.dirty=!1}}class Sj extends e_{attachment(){return this.gl.DEPTH_ATTACHMENT}set(y){if(y===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const C=this.gl;C.framebufferRenderbuffer(C.FRAMEBUFFER,this.attachment(),C.RENDERBUFFER,y),this.current=y,this.dirty=!1}}class VN extends e_{attachment(){return this.gl.DEPTH_ATTACHMENT}set(y){if(y===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const C=this.gl;C.framebufferTexture2D(C.FRAMEBUFFER,this.attachment(),C.TEXTURE_2D,y,0),this.current=y,this.dirty=!1}}class v6 extends Sj{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const y1=(I,y,C,R)=>({u_matrix:I,u_image0:0,u_image1:1,u_skirt_height:y,u_ground_shadow_factor:C,u_emissive_texture_available:R}),x0=(I,y,C,R,$,G,Z,te,de,xe,we,Re,Le,Ue,st,Je,mt)=>({u_proj_matrix:Float32Array.from(I),u_globe_matrix:y,u_normalize_matrix:Float32Array.from(R),u_merc_matrix:C,u_zoom_transition:$,u_merc_center:G,u_image0:0,u_image1:1,u_frustum_tl:Z,u_frustum_tr:te,u_frustum_br:de,u_frustum_bl:xe,u_globe_pos:we,u_globe_radius:Re,u_viewport:Le,u_grid_matrix:mt?Float32Array.from(mt):new Float32Array(9),u_skirt_height:Ue,u_far_z_cutoff:st,u_emissive_texture_available:Je});function SC(I,y){return I!=null&&y!=null&&!(!I.hasData()||!y.hasData())&&I.demTexture!=null&&y.demTexture!=null&&I.tileID.key!==y.tileID.key}const gu=new class{constructor(){this.operations={}}newMorphing(I,y,C,R,$){if(I in this.operations){const G=this.operations[I];G.to.tileID.key!==C.tileID.key&&(G.queued=C)}else this.operations[I]={startTime:R,phase:0,duration:$,from:y,to:C,queued:null}}getMorphValuesForProxy(I){if(!(I in this.operations))return null;const y=this.operations[I];return{from:y.from,to:y.to,phase:y.phase}}update(I){for(const y in this.operations){const C=this.operations[y];for(C.phase=(I-C.startTime)/C.duration;C.phase>=1||!this._validOp(C);)if(!this._nextOp(C,I)){delete this.operations[y];break}}}_nextOp(I,y){return!!I.queued&&(I.from=I.to,I.to=I.queued,I.queued=null,I.phase=0,I.startTime=y,!0)}_validOp(I){return I.from.hasData()&&I.to.hasData()}},t_={0:null,1:"TERRAIN_VERTEX_MORPHING"};function s_(I,y,C){if(y===0)return 0;const R=y<1&&C===514?.25/y:1;return 6*Math.pow(1.5,22-I)*Math.max(y,1)*R}function v1(I,y){const C=1<({u_matrix:I});function op(I,y,C,R,$){if($>0){const G=o.o.now(),Z=(G-I.timeAdded)/$,te=y?(G-y.timeAdded)/$:-1,de=C.getSource(),xe=R.coveringZoomLevel({tileSize:de.tileSize,roundZoom:de.roundZoom}),we=!y||Math.abs(y.tileID.overscaledZ-xe)>Math.abs(I.tileID.overscaledZ-xe),Re=we&&I.refreshedUponExpiration?1:o.aC(we?Z:1-te,0,1);return y?{opacity:1,mix:1-Re,isFading:Z<1}:{opacity:Re,mix:0,isFading:Z<1}}return{opacity:1,mix:0,isFading:!1}}class Tj extends al{constructor(y){const C={type:"raster-dem",maxzoom:Math.ceil(y.transform.maxZoom)},R=My("mock-dem",C,y.style.dispatcher,y.style);super("mock-dem",R,null),R.setEventedParent(this),this._sourceLoaded=!0}_loadTile(y,C){y.state="loaded",C(null)}}class b1 extends al{constructor(y){const C=My("proxy",{type:"geojson",maxzoom:Math.ceil(y.transform.maxZoom)},y.style.dispatcher,y.style);super("proxy",C,null),C.setEventedParent(this),this.map=this.getSource().map=y,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(y,C,R){if(y.freezeTileCoverage)return;this.transform=y;const $=y.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((G,Z)=>{if(G[Z.key]="",!this._tiles[Z.key]){const te=new o.b0(Z,this._source.tileSize*Z.overscaleFactor(),y.tileZoom,void 0,void 0,this._source.worldview);te.state="loaded",this._tiles[Z.key]=te}return G},{});for(const G in this._tiles)G in $||(this.freeFBO(G),this._tiles[G].unloadVectorData(),delete this._tiles[G])}freeFBO(y){const C=this.proxyCachedFBO[y];if(C!==void 0){const R=Object.values(C);this.renderCachePool.push(...R),delete this.proxyCachedFBO[y]}}deallocRenderCache(){this.renderCache.forEach(y=>y.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class qy extends o.aR{constructor(y,C,R){super(y.overscaledZ,y.wrap,y.canonical.z,y.canonical.x,y.canonical.y),this.proxyTileKey=C,this.projMatrix=R}}class Vy extends o.bu{constructor(y,C){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=y,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[R,$,G]=function(){const de=new o.dB,xe=new o.dC,we=131;de.reserve(17161),xe.reserve(33800);const Re=o.an/128,Le=o.an+Re/2,Ue=Le+Re;for(let Je=-Re;JeLe||Je<0||Je>Le?24575:0,kt=o.aC(Math.round(mt),0,o.an),Tt=o.aC(Math.round(Je),0,o.an);de.emplaceBack(kt+ht,Tt)}const st=(Je,mt)=>{const ht=mt*we+Je;xe.emplaceBack(ht+1,ht,ht+we),xe.emplaceBack(ht+we,ht+we+1,ht+1)};for(let Je=1;Je<129;Je++)for(let mt=1;mt<129;mt++)st(mt,Je);return[0,129].forEach(Je=>{for(let mt=0;mt<130;mt++)st(mt,Je),st(Je,mt)}),[de,xe,32768]}(),Z=y.context;this.gridBuffer=Z.createVertexBuffer(R,o.dx.members),this.gridIndexBuffer=Z.createIndexBuffer($),this.gridSegments=o.dy.simpleSegment(0,0,R.length,$.length),this.gridNoSkirtSegments=o.dy.simpleSegment(0,0,R.length,G),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new b1(C.map),this.orthoMatrix=o.bb(),o.bT(this.orthoMatrix,this.painter.transform.projection.name==="globe"?.015:0,o.an,0,o.an,0,1);const te=Z.gl;this._overlapStencilMode=new oa({func:te.GEQUAL,mask:255},0,255,te.KEEP,te.KEEP,te.REPLACE),this._previousZoom=y.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=C,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new Tj(C.map),this._pendingGroundEffectLayers=[],this._emissiveTexture=!1}set style(y){y.on("data",this._onStyleDataEvent.bind(this)),this._style=y,this._style.map.on("moveend",()=>{this._clearLineLayersFromRenderCache()})}update(y,C,R){if(y&&y.terrain){this._style!==y&&(this.style=y,this._evaluationZoom=void 0);const $=y.terrain.properties,G=y.terrain.drapeRenderMode===0,Z=y.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=o.o.now();const te=y.terrain&&y.terrain.scope,de=$.get("source"),xe=G?this._mockSourceCache:y.getSourceCache(de,te);if(!xe)return void o.w(`Couldn't find terrain source "${de}".`);if(this.sourceCache=xe,this._attenuationRange=y.terrain.getAttenuationRange(),this._exaggeration=Z?this.calculateExaggeration(C):$.get("exaggeration"),!C.projection.requiresDraping&&Z&&this._exaggeration===0)return void this._disable();this.enabled=!0;const we=()=>{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 Re=this.getScaledDemTileSize();this.sourceCache.update(C,Re,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,we(),this._initializing=!0),we(),C.updateElevation(!0,R),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(C),this._emptyDEMTextureDirty=!0,this._previousZoom=C.zoom}else this._disable()}calculateExaggeration(y){if(this._attenuationRange&&y.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(y.zoom);const C=this._previousCameraAltitude,R=y.getFreeCameraOptions().position.z/y.pixelsPerMeter*y.worldSize;this._previousCameraAltitude=R;const $=C!=null?R-C:Number.MAX_VALUE;if(Math.abs($)<2)return this._exaggeration;const G=y.zoom,Z=this._style.terrain;if(!this._previousUpdateTimestamp)return Z.getExaggeration(G);let te=G-this._previousZoom;const de=this._previousUpdateTimestamp;let xe=G;this._evaluationZoom!=null&&(xe=this._evaluationZoom,Math.abs(G-xe)>.5&&(te=.5*(G-xe+te)),te*$<0&&(xe+=te)),this._evaluationZoom=xe;const we=Z.getExaggeration(xe),Re=we===Z.getExaggeration(Math.max(0,xe-.1));if(Re&&Math.abs(we-this._exaggeration)<.01)return we;let Le=Math.min(.1,.00375*(this._updateTimestamp-de));return(Re||we<.1||Math.abs(te)<1e-4)&&(Le=Math.min(.2,4*Le)),o.am(this._exaggeration,we,Le)}resetTileLookupCache(y){this._findCoveringTileCache[y]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(y){y.dataType==="source"&&y.coord?this._clearRenderCacheForTile(y.sourceCacheId,y.coord):y.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 y in this._style._mergedSourceCaches)this._style._mergedSourceCaches[y].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(y=>y.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 y=2*this.proxySourceCache.getSource().tileSize;return[y,y]}set useVertexMorphing(y){this._useVertexMorphing=y}updateTileBinding(y){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const C=this.proxySourceCache,R=this.painter.transform;this._initializing&&(this._initializing=R._centerAltitude===0&&this.getAtPointOrZero(o.ag.fromLngLat(R.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const $=this.proxyCoords=C.getIds().map(de=>{const xe=C.getTileByID(de).tileID;return xe.projMatrix=R.calculateProjMatrix(xe.toUnwrapped()),xe});(function(de,xe){const we=xe.transform.pointCoordinate(xe.transform.getCameraPoint()),Re=new o.P(we.x,we.y);de.sort((Le,Ue)=>{if(Ue.overscaledZ-Le.overscaledZ)return Ue.overscaledZ-Le.overscaledZ;const st=new o.P(Le.canonical.x+(1<{this.proxyToSource[de.key]={}}),this.terrainTileForTile={};const Z=this._style._mergedSourceCaches;for(const de in Z){const xe=Z[de];if(!xe.used||(xe!==this.sourceCache&&this.resetTileLookupCache(xe.id),this._setupProxiedCoordsForOrtho(xe,y[de],G),xe.usedForTerrain))continue;const we=y[de];(xe.getSource().reparseOverscaled||xe._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(we)}this.proxiedCoords[C.id]=$.map(de=>new qy(de,de.key,this.orthoMatrix)),this._assignTerrainTiles($),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(G),this.renderingToTexture=!1;const te={};this._visibleDemTiles=[];for(const de of this.proxyCoords){const xe=this.terrainTileForTile[de.key];if(!xe)continue;const we=xe.tileID.key;we in te||(this._visibleDemTiles.push(xe),te[we]=we)}}_assignTerrainTiles(y){this._initializing||y.forEach(C=>{if(this.terrainTileForTile[C.key])return;const R=this._findTileCoveringTileID(C,this.sourceCache);R&&(this.terrainTileForTile[C.key]=R)})}_prepareDEMTextures(){const y=this.painter.context,C=y.gl;for(const R in this.terrainTileForTile){const $=this.terrainTileForTile[R],G=$.dem;!G||$.demTexture&&!$.needsDEMTextureUpload||(y.activeTexture.set(C.TEXTURE1),wC(this.painter,$,G))}}_prepareDemTileUniforms(y,C,R,$){if(!C||C.demTexture==null)return!1;const G=y.tileID.canonical,Z=Math.pow(2,C.tileID.canonical.z-G.z),te=$||"";return R[`u_dem_tl${te}`]=[G.x*Z%1,G.y*Z%1],R[`u_dem_scale${te}`]=Z,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let y=0;const C=this._visibleDemTiles.reduce((R,$)=>{if(!$.dem)return R;const G=$.dem.tree.minimums[0];return G>0&&y++,R+G},0);return y?C/y:0}_updateEmptyDEMTexture(){const y=this.painter.context,C=y.gl;y.activeTexture.set(C.TEXTURE2);const R=this._getLoadedAreaMinimum(),$=new o.dz({width:1,height:1},new Float32Array([R]));this._emptyDEMTextureDirty=!1;let G=this._emptyDEMTexture;return G?G.update($,{premultiply:!1}):G=this._emptyDEMTexture=new o.T(y,$,C.R32F,{premultiply:!1}),G}setupElevationDraw(y,C,R){const $=this.painter.context,G=$.gl,Z={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0};Z.u_exaggeration=this.exaggeration();let te=null,de=null,xe=1;if(R&&R.morphing&&this._useVertexMorphing){const Ue=R.morphing.srcDemTile,st=R.morphing.dstDemTile;xe=R.morphing.phase,Ue&&st&&(this._prepareDemTileUniforms(y,Ue,Z,"_prev")&&(de=Ue),this._prepareDemTileUniforms(y,st,Z)&&(te=st))}const we=Ue=>Ue&&Ue.demTexture&&this.painter.linearFloatFilteringSupported()?G.LINEAR:G.NEAREST;let Re=null;var Le;if(this.enabled?de&&te?(Re=te.demTexture,$.activeTexture.set(G.TEXTURE4),de.demTexture.bind(we(de),G.CLAMP_TO_EDGE),Z.u_dem_lerp=xe):(te=this.terrainTileForTile[y.tileID.key],Re=this._prepareDemTileUniforms(y,te,Z)?te.demTexture:this.emptyDEMTexture):Re=this.emptyDEMTexture,$.activeTexture.set(G.TEXTURE2),Re&&(Z.u_dem_size=(Le=Re).size[0]===1?1:Le.size[0]-2,Re.bind(we(te),G.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(R&&R.useDepthForOcclusion,C,Z),R&&R.useMeterToDem&&te){const Ue=(1<{if(ht===Ps)return;const an=[t_[Ps],"PROJECTION_GLOBE_VIEW"];Tt&&an.push("CUSTOM_ANTIALIASING");const mn=xe.isTileAffectedByFog($s);mt=xe.getOrCreateProgram("globeRaster",{defines:an,overrideFog:mn}),ht=Ps},es=xe.colorModeForRenderPass(),Ft=new ar(Je.LEQUAL,ar.ReadWrite,xe.depthRangeFor3D);gu.update(Ue);const Qt=o.dq(kt),At=[o.aH(kt.center.lng),o.aL(kt.center.lat)],Dt=xe.globeSharedBuffers,Gt=[kt.width*o.o.devicePixelRatio,kt.height*o.o.devicePixelRatio],gs=Float32Array.from(kt.globeMatrix),ns={useDenormalizedUpVectorScale:!0};{const $s=xe.transform,Ps=s_($s.zoom,we.exaggeration(),we.sourceCache._source.tileSize);ht=-1;const an=Je.TRIANGLES;for(const mn of Le){const Ns=Re.getTile(mn),hs=oa.disabled,zs=we.prevTerrainTileForTile[mn.key],Us=we.terrainTileForTile[mn.key];SC(zs,Us)&&gu.newMorphing(mn.key,zs,Us,Ue,250),$p(xe,Ns.emissiveTexture),st.activeTexture.set(Je.TEXTURE0),Ns.texture&&Ns.texture.bind(Je.LINEAR,Je.CLAMP_TO_EDGE);const Ys=gu.getMorphValuesForProxy(mn.key),Rn=Ys?1:0;Ys&&Object.assign(ns,{morphing:{srcDemTile:Ys.from,dstDemTile:Ys.to,phase:o.dn(Ys.phase)}});const Sn=o.dr(mn.canonical),Cn=o.ds(Sn.getCenter().lat),dn=o.dt(mn.canonical,Sn,Cn,$s.worldSize/$s._pixelsPerMercatorPixel),mr=o.du(o.dv(mn.canonical)),Cr=xe.emissiveMode==="mrt-fallback"?1:0,ir=x0($s.expandedFarZProjMatrix,gs,Qt,mr,o.al($s.zoom),At,$s.frustumCorners.TL,$s.frustumCorners.TR,$s.frustumCorners.BR,$s.frustumCorners.BL,$s.globeCenterInViewSpace,$s.globeRadius,Gt,Ps,$s._farZ,Cr,dn);if(xt(mn,Rn),mt&&(we.setupElevationDraw(Ns,mt,ns),xe.uploadCommonUniforms(st,mt,mn.toUnwrapped()),Dt)){const[hr,na,wa]=Dt.getGridBuffers(Cn,Ps!==0);mt.draw(xe,an,Ft,hs,es,Rr.backCCW,ir,"globe_raster",hr,na,wa)}}}if(Dt&&(xe.renderDefaultNorthPole||xe.renderDefaultSouthPole)){const $s=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Tt&&$s.push("CUSTOM_ANTIALIASING"),mt=xe.getOrCreateProgram("globeRaster",{defines:$s});for(const Ps of Le){const{x:an,y:mn,z:Ns}=Ps.canonical,hs=mn===0,zs=mn===(1<hr.draw(xe,Je.TRIANGLES,Ft,oa.disabled,es,Rr.disabled,x0(kt.expandedFarZProjMatrix,dn,dn,mr,0,At,kt.frustumCorners.TL,kt.frustumCorners.TR,kt.frustumCorners.BR,kt.frustumCorners.BL,kt.globeCenterInViewSpace,kt.globeRadius,Gt,0,kt._farZ,Cr),"globe_pole_raster",na,Rn,Sn);we.setupElevationDraw(Cn,mt,ns),xe.uploadCommonUniforms(st,mt,Ps.toUnwrapped()),hs&&xe.renderDefaultNorthPole&&ir(mt,Us),zs&&xe.renderDefaultSouthPole&&(dn=o.cC(o.bb(),dn,[1,-1,1]),ir(mt,Ys))}}}})($,G,Z,te,de);else{const xe=$.context,we=xe.gl;let Re,Le;const Ue=$.shadowRenderer,st=Bc($,$.longestCutoffRange),Je=es=>{if(Le===es)return;const Ft=[];Ft.push(t_[es]),st.shouldRenderCutoff&&Ft.push("RENDER_CUTOFF"),Ue&&(Ft.push("RENDER_SHADOWS"),Ue.useNormalOffset&&Ft.push("NORMAL_OFFSET")),Re=$.getOrCreateProgram("terrainRaster",{defines:Ft}),Le=es},mt=$.colorModeForRenderPass(),ht=new ar(we.LEQUAL,ar.ReadWrite,$.depthRangeFor3D);gu.update(de);const kt=$.transform,Tt=s_(kt.zoom,G.exaggeration(),G.sourceCache._source.tileSize);let xt=[0,0,0];if(Ue){const es=$.style.directionalLight,Ft=$.style.ambientLight;es&&Ft&&(xt=zp($.style,es,Ft))}{Le=-1;const es=we.TRIANGLES,[Ft,Qt]=[G.gridIndexBuffer,G.gridSegments];for(const At of te){const Dt=Z.getTile(At),Gt=oa.disabled,gs=G.prevTerrainTileForTile[At.key],ns=G.terrainTileForTile[At.key];SC(gs,ns)&&gu.newMorphing(At.key,gs,ns,de,250),$p($,Dt.emissiveTexture),xe.activeTexture.set(we.TEXTURE0),Dt.texture&&Dt.texture.bind(we.LINEAR,we.CLAMP_TO_EDGE);const $s=gu.getMorphValuesForProxy(At.key),Ps=$s?1:0;let an;$s&&(an={morphing:{srcDemTile:$s.from,dstDemTile:$s.to,phase:o.dn($s.phase)}});const mn=$.emissiveMode==="mrt-fallback"?1:0,Ns=y1(At.projMatrix,v1(At.canonical,kt.renderWorldCopies)?Tt/10:Tt,xt,mn);if(Je(Ps),!Re)continue;G.setupElevationDraw(Dt,Re,an);const hs=At.toUnwrapped();Ue&&Ue.setupShadows(hs,Re),$.uploadCommonUniforms(xe,Re,hs,null,st),Re.draw($,es,ht,Gt,mt,Rr.backCCW,Ns,"terrain_raster",G.gridBuffer,Ft,Qt)}}}}(C,this,this.proxySourceCache,y,this._updateTimestamp),this.renderingToTexture=!0,C.gpuTimingDeferredRenderEnd(),y.splice(0,y.length))}renderBatch(y){if(this._drapedRenderBatches.length===0)return y+1;this.renderingToTexture=!0;const C=this.painter,R=this.painter.context,$=this.proxySourceCache,G=this.proxiedCoords[$.id],Z=this._drapedRenderBatches.shift(),te=C.style.order,de=[];this._updateFBOs(C.emissiveMode==="mrt-fallback");let xe=0;for(const we of G){const Re=$.getTileByID(we.proxyTileKey),Le=$.proxyCachedFBO[we.key]?$.proxyCachedFBO[we.key][y]:void 0,Ue=Le!==void 0?$.renderCache[Le]:this.pool[xe++],st=Le!==void 0;if(Re.texture=Ue.tex,Re.emissiveTexture=Ue.emissiveTex,st&&!Ue.dirty){de.push(Re.tileID);continue}R.bindFramebuffer.set(Ue.fb.framebuffer);const Je=R.gl;let mt;Je.drawBuffers(C.emissiveMode==="mrt-fallback"?[Je.COLOR_ATTACHMENT0,Je.COLOR_ATTACHMENT1]:[Je.COLOR_ATTACHMENT0]),this.renderedToTile=!1,Ue.dirty&&(R.clear({color:o.aq.transparent,stencil:0}),Ue.dirty=!1);for(let ht=Z.start;ht<=Z.end;++ht){const kt=C.style._mergedLayers[te[ht]];if(kt.isHidden(C.transform.zoom))continue;const Tt=C.style.getLayerSourceCache(kt),xt=Tt?this.proxyToSource[we.key][Tt.id]:[we];if(!xt)continue;const es=xt;R.viewport.set([0,0,Ue.fb.width,Ue.fb.height]),mt!==(Tt?Tt.id:null)&&(this._setupStencil(Ue,xt,kt,Tt),mt=Tt?Tt.id:null),C.renderLayer(C,Tt,kt,es)}if(Je.drawBuffers([Je.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const ht of this._pendingGroundEffectLayers){const kt=C.style._mergedLayers[te[ht]];if(kt.isHidden(C.transform.zoom))continue;const Tt=C.style.getLayerSourceCache(kt),xt=Tt?this.proxyToSource[we.key][Tt.id]:[we];if(!xt)continue;const es=xt;R.viewport.set([0,0,Ue.fb.width,Ue.fb.height]),mt!==(Tt?Tt.id:null)&&(this._setupStencil(Ue,xt,kt,Tt),mt=Tt?Tt.id:null),C.renderLayer(C,Tt,kt,es)}this.renderedToTile?(Ue.dirty=!0,de.push(Re.tileID)):st||--xe,xe===5&&(xe=0,this.renderToBackBuffer(de))}return this.renderToBackBuffer(de),this.renderingToTexture=!1,R.bindFramebuffer.set(null),R.viewport.set([0,0,C.width,C.height]),Z.end+1}postRender(){}isLayerOrderingCorrect(y){const C=y.order.length;let R=-1,$=C;for(let G=0;GR}getMinElevationBelowMSL(){let y=0;return this._visibleDemTiles.filter(C=>C.dem).forEach(C=>{y=Math.min(y,C.dem.tree.minimums[0])}),y===0?y:(y-30)*this._exaggeration}raycast(y,C,R){if(!this._visibleDemTiles)return null;const $=this._visibleDemTiles.filter(G=>G.dem).map(G=>{const Z=G.tileID,te=1<(G.t!==null?G.t:Number.MAX_VALUE)-(Z.t!==null?Z.t:Number.MAX_VALUE));for(const G of $){if(G.t==null)return null;const Z=G.tile.dem.tree.raycast(G.minx,G.miny,G.maxx,G.maxy,y,C,R);if(Z!=null)return Z}return null}_createFBO(){const y=this.painter.context,C=y.gl,R=this.drapeBufferSize;y.activeTexture.set(C.TEXTURE0);const $=new o.T(y,{width:R[0],height:R[1],data:null},C.RGBA8);$.bind(C.LINEAR,C.CLAMP_TO_EDGE);const G=y.createFramebuffer(R[0],R[1],1,null);let Z;return G.colorAttachment0.set($.texture),this._emissiveTexture&&(Z=new o.T(y,{width:R[0],height:R[1],data:null},C.R8),Z.bind(C.LINEAR,C.CLAMP_TO_EDGE),G.createColorAttachment(y,1),G.colorAttachment1.set(Z.texture)),G.depthAttachment=new v6(y,G.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=y.createRenderbuffer(y.gl.DEPTH_STENCIL,R[0],R[1]),this._stencilRef=0,G.depthAttachment.set(this._sharedDepthStencil),y.clear({stencil:0})):G.depthAttachment.set(this._sharedDepthStencil),y.extTextureFilterAnisotropic&&C.texParameterf(C.TEXTURE_2D,y.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,y.extTextureFilterAnisotropicMax),{fb:G,tex:$,emissiveTex:Z,dirty:!1}}_updateFBOs(y){if(this._emissiveTexture!==y){for(const C of this.pool)this._updateFBO(C,y);for(const C of this.proxySourceCache.renderCache)this._updateFBO(C,y);this._emissiveTexture=y}}_updateFBO(y,C){const R=y.fb,$=this.painter.context,G=$.gl,Z=this.drapeBufferSize;if(C){const te=new o.T($,{width:Z[0],height:Z[1],data:null},G.R8);te.bind(G.LINEAR,G.CLAMP_TO_EDGE),y.emissiveTex=te,R.createColorAttachment($,1),R.colorAttachment1.set(te.texture)}else y.emissiveTex=void 0,R.removeColorAttachment($,1);y.dirty=!0}_initFBOPool(){for(;this.pool.length{const C=this._style._mergedLayers[y],R=C.isHidden(this.painter.transform.zoom);return C.type==="hillshade"||C.type==="custom"?!R&&C.shouldRedrape():!R&&C.hasTransition()})}_clearLineLayersFromRenderCache(){let y=!1;for(const R of this._style.getSources())if(R instanceof qd){y=!0;break}if(!y)return;const C={};for(let R=0;Rde>te.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=R}_setupRenderCache(y){const C=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,C.renderCache.length>C.renderCachePool.length){const Z=Object.values(C.proxyCachedFBO);C.proxyCachedFBO={};for(let te=0;te=0;Z--){const te=R[Z];if(C.getTileByID(te.key),C.proxyCachedFBO[te.key]!==void 0){const de=y[te.key],xe=this.proxyToSource[te.key];let we=0;for(const Re in xe){const Le=xe[Re],Ue=de[Re];if(!Ue||Ue.length!==Le.length||Le.some((st,Je)=>st!==Ue[Je]||$[Re]&&$[Re].hasOwnProperty(st.key))){we=-1;break}++we}for(const Re in C.proxyCachedFBO[te.key])C.renderCache[C.proxyCachedFBO[te.key][Re]].dirty=we<0||we!==Object.values(de).length}}const G=[...this._drapedRenderBatches];G.sort((Z,te)=>te.end-te.start-(Z.end-Z.start));for(const Z of G)for(const te of R){if(C.proxyCachedFBO[te.key])continue;let de=C.renderCachePool.pop();de===void 0&&C.renderCache.length<50&&(de=C.renderCache.length,C.renderCache.push(this._createFBO())),de!==void 0&&(C.proxyCachedFBO[te.key]={},C.proxyCachedFBO[te.key][Z.start]=de,C.renderCache[de].dirty=!0)}this._tilesDirty={}}_setupStencil(y,C,R,$){if(!$||!this._sourceTilesOverlap[$.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const G=this.painter.context,Z=G.gl;if(C.length<=1)return void(this._overlapStencilType=!1);let te;if(R.isTileClipped())te=C.length,this._overlapStencilMode.test={func:Z.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(C[0].overscaledZ>C[C.length-1].overscaledZ))return void(this._overlapStencilType=!1);te=1,this._overlapStencilMode.test={func:Z.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+te>255&&(G.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=te,this._overlapStencilMode.ref=this._stencilRef,R.isTileClipped()&&this._renderTileClippingMasks(C,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}stencilModeForRTTOverlap(y){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[y.key]),this._overlapStencilMode):oa.disabled}_renderTileClippingMasks(y,C){const R=this.painter,$=this.painter.context,G=$.gl;R._tileClippingMaskIDs={},$.setColorMode(sa.disabled),$.setDepthMode(ar.disabled);const Z=R.getOrCreateProgram("clippingMask");for(const te of y){const de=R._tileClippingMaskIDs[te.key]=--C;Z.draw(R,G.TRIANGLES,ar.disabled,new oa({func:G.ALWAYS,mask:0},de,255,G.KEEP,G.KEEP,G.REPLACE),sa.disabled,Rr.disabled,Cj(te.projMatrix),"$clipping",R.tileExtentBuffer,R.quadTriangleIndexBuffer,R.tileExtentSegments)}}pointCoordinate(y){const C=this.painter.transform;if(y.x<0||y.x>C.width||y.y<0||y.y>C.height)return null;const R=[y.x,y.y,1,1];o.aE(R,R,C.pixelMatrixInverse),o.cu(R,R,1/R[3]),R[0]/=C.worldSize,R[1]/=C.worldSize;const $=C._camera.position,G=o.bU(1,C.center.lat),Z=[$[0],$[1],$[2]/G,0],te=o.cV([],R.slice(0,3),Z);o.ay(te,te);const de=this.raycast(Z,te,this._exaggeration);return de!==null&&de?(o.bg(Z,Z,te,de),Z[3]=Z[2],Z[2]*=G,Z):null}_setupProxiedCoordsForOrtho(y,C,R){if(y.getSource()instanceof o.aV)return this._setupProxiedCoordsForImageSource(y,C,R);this._findCoveringTileCache[y.id]=this._findCoveringTileCache[y.id]||{};const $=this.proxiedCoords[y.id]=[],G=this.proxyCoords;for(let de=0;dewe.overscaledZ-xe.overscaledZ)}_setupProxiedCoordsForImageSource(y,C,R){if(!y.getSource().loaded())return;const $=this.proxiedCoords[y.id]=[],G=this.proxyCoords,Z=y.getSource(),te=Z.tileID;if(!te)return;const de=new o.P(te.x,te.y)._div(1<(Re.min.x=Math.min(Re.min.x,Le.x-de.x),Re.min.y=Math.min(Re.min.y,Le.y-de.y),Re.max.x=Math.max(Re.max.x,Le.x-de.x),Re.max.y=Math.max(Re.max.y,Le.y-de.y),Re),{min:new o.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),we=(Re,Le)=>{const Ue=Re.wrap+Re.canonical.x/(1<mt+xe.max.x||st+Jeht+xe.max.y};for(let Re=0;ReZ.key===C.tileID.key);if(G)return G}if(C.tileID.key!==y.key){const G=y.canonical.z-C.tileID.canonical.z;let Z,te,de;$=o.bb();const xe=C.tileID.wrap-y.wrap<0?(Z=o.an>>G,te=Z*((C.tileID.canonical.x<=Re){const Le=y.canonical.z-Re;C.getSource().reparseOverscaled?(te=Math.max(y.canonical.z+2,C.transform.tileZoom),Z=new o.aR(te,y.wrap,Re,y.canonical.x>>Le,y.canonical.y>>Le)):Le!==0&&(te=Re,Z=new o.aR(te,y.wrap,Re,y.canonical.x>>Le,y.canonical.y>>Le))}Z.key!==y.key&&(xe.push(Z.key),R=C.getTile(Z))}const we=Re=>{xe.forEach(Le=>{$[Le]=Re}),xe.length=0};for(te-=1;te>=de&&(!R||!R.hasData());te--){R&&we(R.tileID.key);const Re=Z.calculateScaledKey(te);if(R=C.getTileByID(Re),R&&R.hasData())break;const Le=$[Re];if(Le===null)break;Le===void 0?xe.push(Re):R=C.getTileByID(Le)}return we(R?R.tileID.key:null),R&&R.hasData()?R:null}findDEMTileFor(y){return this.enabled?this._findTileCoveringTileID(y,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(y,C){let R=this._tilesDirty[y];R||(R=this._tilesDirty[y]={}),R[C.key]=!0}}function n_(I,y,C){const R=function(te,de,xe){const we=o.bi(de,te),Re=o.bi(xe,[.2126,.7152,.0722]),Le=(st,Je,mt)=>(1-mt)*st+mt*Je,Ue=Le(1-.3*Math.min(Re,1),1,Math.min(we+1,1));return Le(.92,1,Math.asin(o.aC(de[2],-1,1))/Math.PI+.5)*Ue}(I,[0,0,1],y),$=[0,0,0];o.bJ($,C.slice(0,3),R);const G=[0,0,0];o.bJ(G,y.slice(0,3),I[2]);const Z=[0,0,0];return o.cT(Z,$,G),o.cW(Z)}const CC=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],r_=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class cd{static cacheKey(y,C,R,$){const G=[C];$&&G.push($.cacheKey);for(const Z of R)(typeof Z=="string"&&Z.includes(" ")||y.usedDefines.has(Z))&&G.push(Z);return G.join("/")}constructor(y,C,R,$,G,Z){const te=y.gl;this.program=te.createProgram(),this.configuration=$,this.name=C,this.fixedDefines=[...Z];const de=`#version 300 es ${($?$.defines():[]).concat(Z.map(Je=>`#define ${Je}`)).join(` `)}`,xe=[de,m1];for(const Je of R.fragmentIncludes)xe.push(Bp[Je]);xe.push(R.fragmentSource);const we=xe.join(` `),Re=[de,gC];for(const Je of R.vertexIncludes)Re.push(Bp[Je]);this.forceManualRenderingForInstanceIDShaders=y.forceManualRenderingForInstanceIDShaders&&R.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&Re.push("uniform int u_instanceID;"),Re.push(R.vertexSource);let Le=Re.join(` `);this.forceManualRenderingForInstanceIDShaders&&(Le=Le.replaceAll("gl_InstanceID","u_instanceID"));const Ue=te.createShader(te.FRAGMENT_SHADER);if(te.isContextLost())return void(this.failedToCreate=!0);te.shaderSource(Ue,we),te.compileShader(Ue),te.attachShader(this.program,Ue);const st=te.createShader(te.VERTEX_SHADER);te.isContextLost()?this.failedToCreate=!0:(te.shaderSource(st,Le),te.compileShader(st),te.attachShader(this.program,st),this.attributes={},te.linkProgram(this.program),te.deleteShader(st),te.deleteShader(Ue),this.fixedUniforms=G(y),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=$?$.getUniforms(y):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(Je=>({u_instanceID:new o.bX(Je)}))(y)),(Z.includes("TERRAIN")||Z.includes("ELEVATED")||C.includes("symbol")||C.includes("circle"))&&(this.terrainUniforms=(Je=>({u_dem:new o.bX(Je),u_dem_prev:new o.bX(Je),u_dem_tl:new o.b_(Je),u_dem_scale:new o.bZ(Je),u_dem_tl_prev:new o.b_(Je),u_dem_scale_prev:new o.bZ(Je),u_dem_size:new o.bZ(Je),u_dem_lerp:new o.bZ(Je),u_exaggeration:new o.bZ(Je),u_depth:new o.bX(Je),u_depth_size_inv:new o.b_(Je),u_depth_range_unpack:new o.b_(Je),u_occluder_half_size:new o.bZ(Je),u_occlusion_depth_offset:new o.bZ(Je),u_meter_to_dem:new o.bZ(Je),u_label_plane_matrix_inv:new o.b$(Je)}))(y)),Z.includes("GLOBE")&&(this.globeUniforms=(Je=>({u_tile_tl_up:new o.bY(Je),u_tile_tr_up:new o.bY(Je),u_tile_br_up:new o.bY(Je),u_tile_bl_up:new o.bY(Je),u_tile_up_scale:new o.bZ(Je)}))(y)),Z.includes("FOG")&&(this.fogUniforms=(Je=>({u_fog_matrix:new o.b$(Je),u_fog_range:new o.b_(Je),u_fog_color:new o.cO(Je),u_fog_horizon_blend:new o.bZ(Je),u_fog_vertical_limit:new o.b_(Je),u_fog_temporal_offset:new o.bZ(Je),u_frustum_tl:new o.bY(Je),u_frustum_tr:new o.bY(Je),u_frustum_br:new o.bY(Je),u_frustum_bl:new o.bY(Je),u_globe_pos:new o.bY(Je),u_globe_radius:new o.bZ(Je),u_globe_transition:new o.bZ(Je),u_is_globe:new o.bX(Je),u_viewport:new o.b_(Je)}))(y)),Z.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(Je=>({u_cutoff_params:new o.cO(Je)}))(y)),Z.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(Je=>({u_lighting_ambient_color:new o.bY(Je),u_lighting_directional_dir:new o.bY(Je),u_lighting_directional_color:new o.bY(Je),u_ground_radiance:new o.bY(Je)}))(y)),Z.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(Je=>({u_light_matrix_0:new o.b$(Je),u_light_matrix_1:new o.b$(Je),u_fade_range:new o.b_(Je),u_shadow_normal_offset:new o.bY(Je),u_shadow_intensity:new o.bZ(Je),u_shadow_texel_size:new o.bZ(Je),u_shadow_map_resolution:new o.bZ(Je),u_shadow_direction:new o.bY(Je),u_shadow_bias:new o.bY(Je),u_shadowmap_0:new o.bX(Je),u_shadowmap_1:new o.bX(Je)}))(y)))}getAttributeLocation(y,C){let R=this.attributes[C];return R===void 0&&(R=this.attributes[C]=y.getAttribLocation(this.program,C)),R}setTerrainUniformValues(y,C){if(!this.terrainUniforms)return;const R=this.terrainUniforms;if(!this.failedToCreate){y.program.set(this.program);for(const $ in C)R[$]&&R[$].set(this.program,$,C[$])}}setGlobeUniformValues(y,C){if(!this.globeUniforms)return;const R=this.globeUniforms;if(!this.failedToCreate){y.program.set(this.program);for(const $ in C)R[$]&&R[$].set(this.program,$,C[$])}}setFogUniformValues(y,C){if(!this.fogUniforms)return;const R=this.fogUniforms;if(!this.failedToCreate){y.program.set(this.program);for(const $ in C)R[$].set(this.program,$,C[$])}}setCutoffUniformValues(y,C){if(!this.cutoffUniforms)return;const R=this.cutoffUniforms;if(!this.failedToCreate){y.program.set(this.program);for(const $ in C)R[$].set(this.program,$,C[$])}}setLightsUniformValues(y,C){if(!this.lightsUniforms)return;const R=this.lightsUniforms;if(!this.failedToCreate){y.program.set(this.program);for(const $ in C)R[$].set(this.program,$,C[$])}}setShadowUniformValues(y,C){if(this.failedToCreate||!this.shadowUniforms)return;const R=this.shadowUniforms;y.program.set(this.program);for(const $ in C)R[$].set(this.program,$,C[$])}_drawDebugWireframe(y,C,R,$,G,Z,te,de,xe,we){const Re=y.options.wireframe;if(Re.terrain===!1&&Re.layers2D===!1&&Re.layers3D===!1)return;const Le=y.context;if(!(!(!Re.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!Re.layers2D||y._terrain&&y._terrain.renderingToTexture||!CC.includes(this.name))||!(!Re.layers3D||!r_.includes(this.name))))return;const Ue=Le.gl,st=y.wireframeDebugCache.getLinesFromTrianglesBuffer(y.frameCounter,G,Le);if(!st)return;const Je=[...this.fixedDefines,"DEBUG_WIREFRAME"],mt=y.getOrCreateProgram(this.name,{config:this.configuration,defines:Je});Le.program.set(mt.program);const ht=(xt,es,Ft)=>{if(es[xt]&&Ft[xt])for(const Qt in es[xt])Ft[xt][Qt]&&Ft[xt][Qt].set(Ft.program,Qt,es[xt][Qt].current)};xe&&xe.setUniforms(mt.program,Le,mt.binderUniforms,te,{zoom:de}),ht("fixedUniforms",this,mt),ht("terrainUniforms",this,mt),ht("globeUniforms",this,mt),ht("fogUniforms",this,mt),ht("lightsUniforms",this,mt),ht("shadowUniforms",this,mt),st.bind(),Le.setColorMode(new sa([Ue.ONE,Ue.ONE_MINUS_SRC_ALPHA,Ue.ZERO,Ue.ONE],o.aq.transparent,[!0,!0,!0,!1])),Le.setDepthMode(new ar(C.func===Ue.LESS?Ue.LEQUAL:C.func,ar.ReadOnly,C.range)),Le.setStencilMode(oa.disabled);const kt=3*Z.primitiveLength*2,Tt=3*Z.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const xt=we||1;for(let es=0;es1?Ue.drawElementsInstanced(Ue.LINES,kt,Ue.UNSIGNED_SHORT,Tt,we):Ue.drawElements(Ue.LINES,kt,Ue.UNSIGNED_SHORT,Tt);G.bind(),Le.program.set(this.program),Le.setDepthMode(C),Le.setStencilMode(R),Le.setColorMode($)}checkUniforms(y,C,R){if(this.fixedDefines.includes(C)){for(const $ of Object.keys(R))if(!R[$].initialized)throw new Error(`Program '${this.name}', from draw '${y}': uniform ${$} not set but required by ${C} being defined`)}}draw(y,C,R,$,G,Z,te,de,xe,we,Re,Le,Ue,st,Je,mt){const ht=y.context,kt=ht.gl;if(this.failedToCreate)return;ht.program.set(this.program),ht.setDepthMode(R),ht.setStencilMode($),ht.setColorMode(G),ht.setCullFace(Z);for(const[At,Dt]of this.fixedUniformsEntries)Dt.set(this.program,At,te[At]);st&&st.setUniforms(this.program,ht,this.binderUniforms,Le,{zoom:Ue});const Tt={[kt.POINTS]:1,[kt.LINES]:2,[kt.TRIANGLES]:3,[kt.LINE_STRIP]:1}[C];this.checkUniforms(de,"RENDER_SHADOWS",this.shadowUniforms);const xt=Je||[],es=st?st.getPaintVertexBuffers():[],Ft=C===kt.TRIANGLES&&we,Qt=mt&&mt>0?1:void 0;for(const At of Re.get()){const Dt=At.vaos||(At.vaos={});if((Dt[de]||(Dt[de]=new bC)).bind(ht,this,xe,es,we,At.vertexOffset,xt,Qt),this.forceManualRenderingForInstanceIDShaders){const Gt=mt||1;for(let gs=0;gs1?kt.drawElementsInstanced(C,At.primitiveLength*Tt,kt.UNSIGNED_SHORT,At.primitiveOffset*Tt*2,mt):we?kt.drawElements(C,At.primitiveLength*Tt,kt.UNSIGNED_SHORT,At.primitiveOffset*Tt*2):kt.drawArrays(C,At.vertexOffset,At.vertexLength);Ft&&this._drawDebugWireframe(y,R,$,G,we,At,Le,Ue,st,mt)}}}function b6(I,y,C=0){const R=Math.pow(2,y.tileID.overscaledZ),$=y.tileSize*Math.pow(2,I.transform.tileZoom)/R,G=$*(y.tileID.canonical.x+y.tileID.wrap*R),Z=$*y.tileID.canonical.y;return{u_image:0,u_texsize:y.imageAtlasTexture?y.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/o.aA(y,1,I.transform.tileZoom),u_pixel_coord_upper:[G>>16,Z>>16],u_pixel_coord_lower:[65535&G,65535&Z],u_pattern_transition:C}}const HN={terrain:0,flat:1},GN=o.bb(),vh=(I,y,C,R,$,G,Z,te,de,xe,we,Re,Le,Ue,st,Je,mt,ht,kt=[0,0,1])=>{const Tt=y.style.light,xt=Tt.properties.get("position"),es=[xt.x,xt.y,xt.z],Ft=o.dE();Tt.properties.get("anchor")==="viewport"&&(o.dF(Ft,-y.transform.angle),o.dG(es,es,Ft));const Qt=Tt.properties.get("color").toPremultipliedRenderColor(null),At=y.transform,Dt={u_matrix:I,u_lightpos:es,u_lightintensity:Tt.properties.get("intensity"),u_lightcolor:[Qt.r,Qt.g,Qt.b],u_vertical_gradient:+C,u_opacity:R,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:GN,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:HN[xe],u_base_type:HN[we],u_ao:$,u_edge_radius:G,u_width_scale:Z,u_flood_light_color:st,u_vertical_scale:Je,u_flood_light_intensity:mt,u_ground_shadow_factor:ht,u_front_cutoff_params:kt};return At.projection.name==="globe"&&(Dt.u_tile_id=[te.canonical.x,te.canonical.y,1<({u_matrix:I,u_edge_radius:y,u_width_scale:C,u_vertical_scale:R,u_height_type:HN[$],u_base_type:HN[G]}),$a=(I,y,C,R,$,G,Z,te,de,xe,we,Re,Le,Ue,st,Je,mt,ht)=>{const kt=vh(I,y,C,R,$,G,Z,te,xe,we,Re,Le,Ue,st,Je,mt,1,[0,0,0]),Tt={u_height_factor:-Math.pow(2,te.overscaledZ)/de.tileSize/8};return Object.assign(kt,b6(y,de,ht),Tt)},g0=(I,y,C)=>({u_matrix:I,u_emissive_strength:y,u_ground_shadow_factor:C}),a_=(I,y,C,R,$,G=0)=>Object.assign(g0(I,y,$),b6(C,R,G)),TC=(I,y,C,R)=>({u_matrix:I,u_world:C,u_emissive_strength:y,u_ground_shadow_factor:R}),i_=(I,y,C,R,$,G,Z=0)=>Object.assign(a_(I,y,C,R,G,Z),{u_world:$}),o_=(I,y)=>({u_matrix:I,u_depth_bias:y}),Ej=(I,y)=>({u_matrix:I,u_ground_shadow_factor:y}),_1=(I,y,C,R,$)=>({u_matrix:I,u_camera_pos:[y[0],y[1],y[2]],u_depth_bias:C,u_height_scale:R,u_reset_depth:$}),Aj=(I,y,C)=>({u_image:I,u_opacity:y,u_blend_mode:C}),y0=(I,y,C,R,$,G,Z,te,de,xe=[0,0,1])=>({u_matrix:I,u_normal_matrix:y,u_opacity:C,u_faux_facade_ao_intensity:R,u_camera_pos:$,u_tile_to_meter:G,u_facade_emissive_chance:Z,u_flood_light_color:te,u_flood_light_intensity:de,u_front_cutoff_params:xe}),Mj=I=>({u_matrix:I}),l_=I=>({u_matrix:I}),WN=(I,y,C,R,$,G,Z,te)=>{const de=o.an/G.tileSize;return{u_matrix:I,u_inv_rot_matrix:y,u_camera_to_center_distance:C.getCameraToCenterDistance(te),u_extrude_scale:[C.pixelsToGLUnits[0]/de,C.pixelsToGLUnits[1]/de],u_zoom_transition:R,u_tile_id:Z,u_merc_center:$}},$c=(I,y,C,R)=>({u_matrix:I,u_inv_matrix:y,u_camera_to_center_distance:C.getCameraToCenterDistance(R),u_viewport_size:[C.width,C.height]}),wm=(I,y,C=1)=>({u_matrix:I,u_color:y,u_overlay:0,u_overlay_scale:C}),Up=o.bb(),KN=(I,y,C,R,$,G,Z)=>{const te=I.transform,de=te.projection.name==="globe",xe=de?o.dH(te.zoom,y.canonical)*te._pixelsPerMercatorPixel:o.aA(C,1,G),we={u_matrix:y.projMatrix,u_extrude_scale:xe,u_intensity:Z,u_inv_rot_matrix:Up,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(de){we.u_inv_rot_matrix=R,we.u_merc_center=$,we.u_tile_id=[y.canonical.x,y.canonical.y,1<({u_matrix:y,u_normalize_matrix:C,u_globe_matrix:R,u_merc_matrix:$,u_grid_matrix:G,u_tl_parent:Z,u_scale_parent:we,u_fade_t:Re.mix,u_opacity:Re.opacity*Le.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:Le.paint.get("raster-brightness-min"),u_brightness_high:Le.paint.get("raster-brightness-max"),u_saturation_factor:o.dJ(Le.paint.get("raster-saturation")),u_contrast_factor:o.dI(Le.paint.get("raster-contrast")),u_spin_weights:_6(Le.paint.get("raster-hue-rotate")),u_perspective_transform:Ue,u_raster_elevation:st,u_zoom_transition:te,u_merc_center:de,u_cutoff_params:xe,u_colorization_mix:YN(o.dK,mt,kt),u_colorization_offset:lp(o.dK,ht,kt),u_color_ramp:Je,u_texture_offset:[xt/(Tt+2*xt),Tt/(Tt+2*xt)],u_texture_res:[Tt+2*xt,Tt+2*xt],u_emissive_strength:es,u_zbias_factor:ZN(I)});function _6(I){I*=Math.PI/180;const y=Math.sin(I),C=Math.cos(I);return[(2*C+1)/3,(-Math.sqrt(3)*y-C+1)/3,(Math.sqrt(3)*y-C+1)/3]}const _x=.05,w6=(I,y,C,R,$,G,Z,te,de,xe,we,Re)=>({u_matrix:I,u_normalize_matrix:y,u_globe_matrix:C,u_merc_matrix:R,u_grid_matrix:$,u_tl_parent:G,u_scale_parent:xe,u_fade_t:we.mix,u_opacity:we.opacity,u_image0:0,u_image1:1,u_raster_elevation:Re,u_zoom_transition:Z,u_merc_center:te,u_cutoff_params:de}),j6=(I,y,C,R,$,G,Z,te,de,xe)=>({u_particle_texture:I,u_particle_texture_side_len:y,u_tile_offset:C,u_velocity:R,u_color_ramp:G,u_velocity_res:$,u_max_speed:Z,u_uv_offset:te,u_data_scale:[255*de[0],255*de[1]],u_data_offset:xe,u_particle_pos_scale:1.1,u_particle_pos_offset:[_x,_x]}),EC=(I,y,C,R,$,G,Z,te,de,xe)=>({u_particle_texture:I,u_particle_texture_side_len:y,u_velocity:C,u_velocity_res:R,u_max_speed:$,u_speed_factor:G,u_reset_rate:Z,u_rand_seed:Math.random(),u_uv_offset:te,u_data_scale:[255*de[0],255*de[1]],u_data_offset:xe,u_particle_pos_scale:1.1,u_particle_pos_offset:[_x,_x]}),Ij=o.bb(),w1=(I,y,C,R,$,G,Z,te,de,xe,we,Re,Le,Ue,st,Je,mt,ht,kt,Tt,xt,es,Ft,Qt)=>{const At=$.transform,Dt={u_is_size_zoom_constant:+(I==="constant"||I==="source"),u_is_size_feature_constant:+(I==="constant"||I==="camera"),u_size_t:y?y.uSizeT:0,u_size:y?y.uSize:0,u_camera_to_center_distance:At.getCameraToCenterDistance(kt),u_rotate_symbol:+C,u_aspect_ratio:At.width/At.height,u_fade_change:$.options.fadeDuration?$.symbolFadeChange:1,u_matrix:G,u_label_plane_matrix:Z,u_coord_matrix:te,u_is_text:+xe,u_elevation_from_sea:de?1:0,u_pitch_with_map:+R,u_texsize:we,u_texsize_icon:Re,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Ij,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:Ij,u_up_vector:[0,-1,0],u_color_adj_mat:es,u_icon_transition:Ft||0,u_gamma_scale:R?$.transform.getCameraToCenterDistance(kt)*Math.cos($.terrain?0:$.transform._pitch):1,u_device_pixel_ratio:o.o.devicePixelRatio,u_is_halo:1,u_scale_factor:Qt||1,u_ground_shadow_factor:Tt,u_inv_matrix:o.b7(o.bb(),Z),u_normal_scale:xt,u_lutTexture:10,u_zoom:At.zoom-Math.floor(At.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 kt.name==="globe"&&(Dt.u_tile_id=[Ue.canonical.x,Ue.canonical.y,1<({u_matrix:I,u_emissive_strength:y,u_opacity:C,u_color:R}),wx=(I,y,C,R,$,G,Z,te,de)=>Object.assign(function(xe,we,Re,Le,Ue,st){const{width:Je,height:mt}=Le.imageManager.getPixelSize(we),ht=Math.pow(2,st.tileID.overscaledZ),kt=st.tileSize*Math.pow(2,Le.transform.tileZoom)/ht,Tt=kt*(st.tileID.canonical.x+st.tileID.wrap*ht),xt=kt*st.tileID.canonical.y;return{u_image:0,u_pattern_tl:Re.tl,u_pattern_br:Re.br,u_texsize:[Je,mt],u_pattern_size:Re.displaySize,u_pattern_units_to_pixels:Ue?[Le.transform.width,-1*Le.transform.height]:[1/o.aA(st,1,Le.transform.tileZoom),1/o.aA(st,1,Le.transform.tileZoom)],u_pixel_coord_upper:[Tt>>16,xt>>16],u_pixel_coord_lower:[65535&Tt,65535&xt]}}(0,G,Z,R,te,de),{u_matrix:I,u_emissive_strength:y,u_opacity:C}),v0=new Float32Array(o.b9([])),jx=(I,y,C,R,$,G,Z,te,de,xe,we,Re,Le,Ue=[0,0,0],st,Je,mt)=>{const ht=$.style.light,kt=ht.properties.get("position"),Tt=[-kt.x,-kt.y,kt.z],xt=o.dE();ht.properties.get("anchor")==="viewport"&&(o.dF(xt,-$.transform.angle),o.dG(Tt,Tt,xt));const es=we.alphaMode==="MASK",Ft=ht.properties.get("color").toNonPremultipliedRenderColor(null),Qt=Le.paint.get("model-ambient-occlusion-intensity"),At=Le.paint.get("model-color").constantOr(o.aq.white).toNonPremultipliedRenderColor(null);return At.a=Le.paint.get("model-color-mix-intensity").constantOr(0),mt&&(At.r=mt[0],At.g=mt[1],At.b=mt[2],At.a=mt[3]),Je&&(At.r=Je.color.r,At.g=Je.color.g,At.b=Je.color.b,At.a=Je.colorMix,Re=Je.emissionStrength,G*=Je.opacity),{u_matrix:I,u_lighting_matrix:y,u_normal_matrix:C,u_node_matrix:R||v0,u_lightpos:Tt,u_lightintensity:ht.properties.get("intensity"),u_lightcolor:[Ft.r,Ft.g,Ft.b],u_camera_pos:Ue,u_opacity:G,u_baseTextureIsAlpha:0,u_alphaMask:+es,u_alphaCutoff:we.alphaCutoff,u_baseColorFactor:Z.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:te.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:de,u_roughnessFactor:xe,u_baseColorTexture:5,u_metallicRoughnessTexture:6,u_normalTexture:7,u_occlusionTexture:8,u_emissionTexture:9,u_lutTexture:10,u_color_mix:At.toArray01(),u_aoIntensity:Qt,u_emissive_strength:Re,u_occlusionTextureTransform:st||[0,0,0,0]}},Pj=(I,y=v0,C=v0)=>({u_matrix:I,u_instance:y,u_node_matrix:C}),c_={fillExtrusion:I=>({u_matrix:new o.b$(I),u_lightpos:new o.bY(I),u_lightintensity:new o.bZ(I),u_lightcolor:new o.bY(I),u_vertical_gradient:new o.bZ(I),u_opacity:new o.bZ(I),u_edge_radius:new o.bZ(I),u_width_scale:new o.bZ(I),u_ao:new o.b_(I),u_height_type:new o.bX(I),u_base_type:new o.bX(I),u_tile_id:new o.bY(I),u_zoom_transition:new o.bZ(I),u_inv_rot_matrix:new o.b$(I),u_merc_center:new o.b_(I),u_up_dir:new o.bY(I),u_height_lift:new o.bZ(I),u_flood_light_color:new o.bY(I),u_vertical_scale:new o.bZ(I),u_flood_light_intensity:new o.bZ(I),u_ground_shadow_factor:new o.bY(I),u_front_cutoff_params:new o.bY(I)}),fillExtrusionDepth:I=>({u_matrix:new o.b$(I),u_edge_radius:new o.bZ(I),u_width_scale:new o.bZ(I),u_vertical_scale:new o.bZ(I),u_height_type:new o.bX(I),u_base_type:new o.bX(I)}),fillExtrusionPattern:I=>({u_matrix:new o.b$(I),u_lightpos:new o.bY(I),u_lightintensity:new o.bZ(I),u_lightcolor:new o.bY(I),u_vertical_gradient:new o.bZ(I),u_height_factor:new o.bZ(I),u_edge_radius:new o.bZ(I),u_width_scale:new o.bZ(I),u_ao:new o.b_(I),u_height_type:new o.bX(I),u_base_type:new o.bX(I),u_tile_id:new o.bY(I),u_zoom_transition:new o.bZ(I),u_inv_rot_matrix:new o.b$(I),u_merc_center:new o.b_(I),u_up_dir:new o.bY(I),u_height_lift:new o.bZ(I),u_image:new o.bX(I),u_texsize:new o.b_(I),u_pixel_coord_upper:new o.b_(I),u_pixel_coord_lower:new o.b_(I),u_tile_units_to_pixels:new o.bZ(I),u_opacity:new o.bZ(I),u_pattern_transition:new o.bZ(I)}),fillExtrusionGroundEffect:I=>({u_matrix:new o.b$(I),u_opacity:new o.bZ(I),u_ao_pass:new o.bZ(I),u_meter_to_tile:new o.bZ(I),u_ao:new o.b_(I),u_flood_light_intensity:new o.bZ(I),u_flood_light_color:new o.bY(I),u_attenuation:new o.bZ(I),u_edge_radius:new o.bZ(I),u_fb:new o.bX(I),u_fb_size:new o.bZ(I),u_dynamic_offset:new o.bZ(I)}),fill:I=>({u_matrix:new o.b$(I),u_emissive_strength:new o.bZ(I),u_ground_shadow_factor:new o.bY(I)}),fillPattern:I=>({u_matrix:new o.b$(I),u_emissive_strength:new o.bZ(I),u_image:new o.bX(I),u_texsize:new o.b_(I),u_pixel_coord_upper:new o.b_(I),u_pixel_coord_lower:new o.b_(I),u_tile_units_to_pixels:new o.bZ(I),u_ground_shadow_factor:new o.bY(I),u_pattern_transition:new o.bZ(I)}),fillOutline:I=>({u_matrix:new o.b$(I),u_emissive_strength:new o.bZ(I),u_world:new o.b_(I),u_ground_shadow_factor:new o.bY(I)}),fillOutlinePattern:I=>({u_matrix:new o.b$(I),u_emissive_strength:new o.bZ(I),u_world:new o.b_(I),u_image:new o.bX(I),u_texsize:new o.b_(I),u_pixel_coord_upper:new o.b_(I),u_pixel_coord_lower:new o.b_(I),u_tile_units_to_pixels:new o.bZ(I),u_ground_shadow_factor:new o.bY(I),u_pattern_transition:new o.bZ(I)}),lineBlendComposite:I=>({u_image:new o.bX(I),u_opacity:new o.bZ(I),u_blend_mode:new o.bX(I)}),building:I=>({u_matrix:new o.b$(I),u_normal_matrix:new o.b$(I),u_opacity:new o.bZ(I),u_faux_facade_ao_intensity:new o.bZ(I),u_camera_pos:new o.bY(I),u_tile_to_meter:new o.bZ(I),u_facade_emissive_chance:new o.bZ(I),u_flood_light_color:new o.bY(I),u_flood_light_intensity:new o.bZ(I),u_front_cutoff_params:new o.bY(I)}),buildingBloom:I=>({u_matrix:new o.b$(I)}),buildingDepth:I=>({u_matrix:new o.b$(I)}),elevatedStructuresDepth:I=>({u_matrix:new o.b$(I),u_depth_bias:new o.bZ(I)}),elevatedStructures:I=>({u_matrix:new o.b$(I),u_ground_shadow_factor:new o.bY(I)}),elevatedStructuresDepthReconstruct:I=>({u_matrix:new o.b$(I),u_camera_pos:new o.bY(I),u_depth_bias:new o.bZ(I),u_height_scale:new o.bZ(I),u_reset_depth:new o.bZ(I)}),circle:o.dO,collisionBox:I=>({u_matrix:new o.b$(I),u_inv_rot_matrix:new o.b$(I),u_camera_to_center_distance:new o.bZ(I),u_extrude_scale:new o.b_(I),u_zoom_transition:new o.bZ(I),u_merc_center:new o.b_(I),u_tile_id:new o.bY(I)}),collisionCircle:I=>({u_matrix:new o.b$(I),u_inv_matrix:new o.b$(I),u_camera_to_center_distance:new o.bZ(I),u_viewport_size:new o.b_(I)}),debug:I=>({u_color:new o.dl(I),u_matrix:new o.b$(I),u_overlay:new o.bX(I),u_overlay_scale:new o.bZ(I)}),clippingMask:I=>({u_matrix:new o.b$(I)}),heatmap:I=>({u_extrude_scale:new o.bZ(I),u_intensity:new o.bZ(I),u_matrix:new o.b$(I),u_inv_rot_matrix:new o.b$(I),u_merc_center:new o.b_(I),u_tile_id:new o.bY(I),u_zoom_transition:new o.bZ(I),u_up_dir:new o.bY(I)}),heatmapTexture:I=>({u_image:new o.bX(I),u_color_ramp:new o.bX(I),u_opacity:new o.bZ(I)}),hillshade:I=>({u_matrix:new o.b$(I),u_image:new o.bX(I),u_latrange:new o.b_(I),u_light:new o.b_(I),u_shadow:new o.dl(I),u_highlight:new o.dl(I),u_emissive_strength:new o.bZ(I),u_accent:new o.dl(I)}),hillshadePrepare:I=>({u_matrix:new o.b$(I),u_image:new o.bX(I),u_dimension:new o.b_(I),u_zoom:new o.bZ(I)}),line:o.dN,linePattern:o.dM,raster:I=>({u_matrix:new o.b$(I),u_normalize_matrix:new o.b$(I),u_globe_matrix:new o.b$(I),u_merc_matrix:new o.b$(I),u_grid_matrix:new o.dm(I),u_tl_parent:new o.b_(I),u_scale_parent:new o.bZ(I),u_fade_t:new o.bZ(I),u_opacity:new o.bZ(I),u_image0:new o.bX(I),u_image1:new o.bX(I),u_brightness_low:new o.bZ(I),u_brightness_high:new o.bZ(I),u_saturation_factor:new o.bZ(I),u_contrast_factor:new o.bZ(I),u_spin_weights:new o.bY(I),u_perspective_transform:new o.b_(I),u_raster_elevation:new o.bZ(I),u_zoom_transition:new o.bZ(I),u_merc_center:new o.b_(I),u_cutoff_params:new o.cO(I),u_colorization_mix:new o.cO(I),u_colorization_offset:new o.bZ(I),u_color_ramp:new o.bX(I),u_texture_offset:new o.b_(I),u_texture_res:new o.b_(I),u_emissive_strength:new o.bZ(I),u_zbias_factor:new o.bZ(I)}),rasterParticle:I=>({u_matrix:new o.b$(I),u_normalize_matrix:new o.b$(I),u_globe_matrix:new o.b$(I),u_merc_matrix:new o.b$(I),u_grid_matrix:new o.dm(I),u_tl_parent:new o.b_(I),u_scale_parent:new o.bZ(I),u_fade_t:new o.bZ(I),u_opacity:new o.bZ(I),u_image0:new o.bX(I),u_image1:new o.bX(I),u_raster_elevation:new o.bZ(I),u_zoom_transition:new o.bZ(I),u_merc_center:new o.b_(I),u_cutoff_params:new o.cO(I)}),rasterParticleTexture:I=>({u_texture:new o.bX(I),u_opacity:new o.bZ(I)}),rasterParticleDraw:I=>({u_particle_texture:new o.bX(I),u_particle_texture_side_len:new o.bZ(I),u_tile_offset:new o.b_(I),u_velocity:new o.bX(I),u_color_ramp:new o.bX(I),u_velocity_res:new o.b_(I),u_max_speed:new o.bZ(I),u_uv_offset:new o.b_(I),u_data_scale:new o.b_(I),u_data_offset:new o.bZ(I),u_particle_pos_scale:new o.bZ(I),u_particle_pos_offset:new o.b_(I)}),rasterParticleUpdate:I=>({u_particle_texture:new o.bX(I),u_particle_texture_side_len:new o.bZ(I),u_velocity:new o.bX(I),u_velocity_res:new o.b_(I),u_max_speed:new o.bZ(I),u_speed_factor:new o.bZ(I),u_reset_rate:new o.bZ(I),u_rand_seed:new o.bZ(I),u_uv_offset:new o.b_(I),u_data_scale:new o.b_(I),u_data_offset:new o.bZ(I),u_particle_pos_scale:new o.bZ(I),u_particle_pos_offset:new o.b_(I)}),symbol:I=>({u_is_size_zoom_constant:new o.bX(I),u_is_size_feature_constant:new o.bX(I),u_size_t:new o.bZ(I),u_size:new o.bZ(I),u_camera_to_center_distance:new o.bZ(I),u_rotate_symbol:new o.bX(I),u_aspect_ratio:new o.bZ(I),u_fade_change:new o.bZ(I),u_matrix:new o.b$(I),u_label_plane_matrix:new o.b$(I),u_coord_matrix:new o.b$(I),u_is_text:new o.bX(I),u_elevation_from_sea:new o.bX(I),u_pitch_with_map:new o.bX(I),u_texsize:new o.b_(I),u_texsize_icon:new o.b_(I),u_texture:new o.bX(I),u_texture_icon:new o.bX(I),u_gamma_scale:new o.bZ(I),u_device_pixel_ratio:new o.bZ(I),u_tile_id:new o.bY(I),u_zoom_transition:new o.bZ(I),u_inv_rot_matrix:new o.b$(I),u_merc_center:new o.b_(I),u_camera_forward:new o.bY(I),u_tile_matrix:new o.b$(I),u_up_vector:new o.bY(I),u_ecef_origin:new o.bY(I),u_is_halo:new o.bX(I),u_icon_transition:new o.bZ(I),u_color_adj_mat:new o.b$(I),u_scale_factor:new o.bZ(I),u_ground_shadow_factor:new o.bY(I),u_inv_matrix:new o.b$(I),u_normal_scale:new o.bZ(I),u_lutTexture:new o.bX(I),u_zoom:new o.bZ(I),u_spp_fill_np_color:new o.cO(I),u_spp_halo_np_color:new o.cO(I),u_spp_opacity:new o.bZ(I),u_spp_halo_width:new o.bZ(I),u_spp_halo_blur:new o.bZ(I),u_spp_emissive_strength:new o.bZ(I),u_spp_occlusion_opacity:new o.bZ(I),u_spp_z_offset:new o.bZ(I),u_spp_translate_rotation:new o.b_(I)}),background:I=>({u_matrix:new o.b$(I),u_emissive_strength:new o.bZ(I),u_opacity:new o.bZ(I),u_color:new o.dl(I)}),backgroundPattern:I=>({u_matrix:new o.b$(I),u_emissive_strength:new o.bZ(I),u_opacity:new o.bZ(I),u_image:new o.bX(I),u_pattern_tl:new o.b_(I),u_pattern_br:new o.b_(I),u_texsize:new o.b_(I),u_pattern_size:new o.b_(I),u_pixel_coord_upper:new o.b_(I),u_pixel_coord_lower:new o.b_(I),u_pattern_units_to_pixels:new o.b_(I)}),terrainRaster:I=>({u_matrix:new o.b$(I),u_image0:new o.bX(I),u_image1:new o.bX(I),u_skirt_height:new o.bZ(I),u_ground_shadow_factor:new o.bY(I),u_emissive_texture_available:new o.bZ(I)}),skybox:I=>({u_matrix:new o.b$(I),u_sun_direction:new o.bY(I),u_cubemap:new o.bX(I),u_opacity:new o.bZ(I),u_temporal_offset:new o.bZ(I)}),skyboxGradient:I=>({u_matrix:new o.b$(I),u_color_ramp:new o.bX(I),u_center_direction:new o.bY(I),u_radius:new o.bZ(I),u_opacity:new o.bZ(I),u_temporal_offset:new o.bZ(I)}),skyboxCapture:I=>({u_matrix_3f:new o.dm(I),u_sun_direction:new o.bY(I),u_sun_intensity:new o.bZ(I),u_color_tint_r:new o.cO(I),u_color_tint_m:new o.cO(I),u_luminance:new o.bZ(I)}),globeRaster:I=>({u_proj_matrix:new o.b$(I),u_globe_matrix:new o.b$(I),u_normalize_matrix:new o.b$(I),u_merc_matrix:new o.b$(I),u_zoom_transition:new o.bZ(I),u_merc_center:new o.b_(I),u_image0:new o.bX(I),u_image1:new o.bX(I),u_grid_matrix:new o.dm(I),u_skirt_height:new o.bZ(I),u_far_z_cutoff:new o.bZ(I),u_frustum_tl:new o.bY(I),u_frustum_tr:new o.bY(I),u_frustum_br:new o.bY(I),u_frustum_bl:new o.bY(I),u_globe_pos:new o.bY(I),u_globe_radius:new o.bZ(I),u_viewport:new o.b_(I),u_emissive_texture_available:new o.bZ(I)}),globeAtmosphere:I=>({u_frustum_tl:new o.bY(I),u_frustum_tr:new o.bY(I),u_frustum_br:new o.bY(I),u_frustum_bl:new o.bY(I),u_horizon:new o.bZ(I),u_transition:new o.bZ(I),u_fadeout_range:new o.bZ(I),u_atmosphere_fog_color:new o.cO(I),u_high_color:new o.cO(I),u_space_color:new o.cO(I),u_temporal_offset:new o.bZ(I),u_horizon_angle:new o.bZ(I)}),model:I=>({u_matrix:new o.b$(I),u_lighting_matrix:new o.b$(I),u_normal_matrix:new o.b$(I),u_node_matrix:new o.b$(I),u_lightpos:new o.bY(I),u_lightintensity:new o.bZ(I),u_lightcolor:new o.bY(I),u_camera_pos:new o.bY(I),u_opacity:new o.bZ(I),u_baseColorFactor:new o.cO(I),u_emissiveFactor:new o.cO(I),u_metallicFactor:new o.bZ(I),u_roughnessFactor:new o.bZ(I),u_baseTextureIsAlpha:new o.bX(I),u_alphaMask:new o.bX(I),u_alphaCutoff:new o.bZ(I),u_baseColorTexture:new o.bX(I),u_metallicRoughnessTexture:new o.bX(I),u_normalTexture:new o.bX(I),u_occlusionTexture:new o.bX(I),u_emissionTexture:new o.bX(I),u_lutTexture:new o.bX(I),u_color_mix:new o.cO(I),u_aoIntensity:new o.bZ(I),u_emissive_strength:new o.bZ(I),u_occlusionTextureTransform:new o.cO(I)}),modelDepth:I=>({u_matrix:new o.b$(I),u_instance:new o.b$(I),u_node_matrix:new o.b$(I)}),groundShadow:I=>({u_matrix:new o.b$(I),u_ground_shadow_factor:new o.bY(I)}),stars:I=>({u_matrix:new o.b$(I),u_up:new o.bY(I),u_right:new o.bY(I),u_intensity_multiplier:new o.bZ(I)}),snowParticle:I=>({u_modelview:new o.b$(I),u_projection:new o.b$(I),u_time:new o.bZ(I),u_cam_pos:new o.bY(I),u_velocityConeAperture:new o.bZ(I),u_velocity:new o.bZ(I),u_horizontalOscillationRadius:new o.bZ(I),u_horizontalOscillationRate:new o.bZ(I),u_boxSize:new o.bZ(I),u_billboardSize:new o.bZ(I),u_simpleShapeParameters:new o.b_(I),u_screenSize:new o.b_(I),u_thinningCenterPos:new o.b_(I),u_thinningShape:new o.bY(I),u_thinningAffectedRatio:new o.bZ(I),u_thinningParticleOffset:new o.bZ(I),u_particleColor:new o.cO(I),u_direction:new o.bY(I)}),rainParticle:I=>({u_modelview:new o.b$(I),u_projection:new o.b$(I),u_time:new o.bZ(I),u_cam_pos:new o.bY(I),u_texScreen:new o.bX(I),u_velocityConeAperture:new o.bZ(I),u_velocity:new o.bZ(I),u_boxSize:new o.bZ(I),u_rainDropletSize:new o.b_(I),u_distortionStrength:new o.bZ(I),u_rainDirection:new o.bY(I),u_color:new o.cO(I),u_screenSize:new o.b_(I),u_thinningCenterPos:new o.b_(I),u_thinningShape:new o.bY(I),u_thinningAffectedRatio:new o.bZ(I),u_thinningParticleOffset:new o.bZ(I),u_shapeDirectionalPower:new o.bZ(I),u_shapeNormalPower:new o.bZ(I),u_mode:new o.bZ(I)}),vignette:I=>({u_vignetteShape:new o.bY(I),u_vignetteColor:new o.cO(I)}),occlusion:I=>({u_matrix:new o.b$(I),u_anchorPos:new o.bY(I),u_screenSizePx:new o.b_(I),u_occluderSizePx:new o.b_(I),u_color:new o.cO(I)})};class qp{constructor(y,C,R,$){this.id=qp.uniqueIdxCounter,qp.uniqueIdxCounter++,this.context=y;const G=y.gl;this.buffer=G.createBuffer(),this.dynamicDraw=!!R,this.context.unbindVAO(),y.bindElementBuffer.set(this.buffer),G.bufferData(G.ELEMENT_ARRAY_BUFFER,C.arrayBuffer,this.dynamicDraw?G.DYNAMIC_DRAW:G.STATIC_DRAW),this.dynamicDraw||$||C.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(y){this.id=qp.uniqueIdxCounter,qp.uniqueIdxCounter++;const C=this.context.gl;this.context.unbindVAO(),this.bind(),C.bufferSubData(C.ELEMENT_ARRAY_BUFFER,0,y.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}qp.uniqueIdxCounter=0;const QN={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class XN{constructor(y,C,R,$,G,Z){this.length=C.length,this.attributes=R,this.itemSize=C.bytesPerElement,this.dynamicDraw=$,this.instanceCount=Z,this.context=y;const te=y.gl;this.buffer=te.createBuffer(),y.bindVertexBuffer.set(this.buffer),te.bufferData(te.ARRAY_BUFFER,C.arrayBuffer,this.dynamicDraw?te.DYNAMIC_DRAW:te.STATIC_DRAW),this.dynamicDraw||G||C.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(y){const C=this.context.gl;this.bind(),C.bufferSubData(C.ARRAY_BUFFER,0,y.arrayBuffer)}enableAttributes(y,C){for(const R of this.attributes){const $=C.getAttributeLocation(y,R.name);$!==-1&&y.enableVertexAttribArray($)}}setVertexAttribPointers(y,C,R){for(const $ of this.attributes){const G=C.getAttributeLocation(y,$.name);if(G!==-1){const Z=$.offset+this.itemSize*(R||0);$.type==="Float32"?y.vertexAttribPointer(G,$.components,y.FLOAT,!1,this.itemSize,Z):y.vertexAttribIPointer(G,$.components,y[QN[$.type]],this.itemSize,Z)}}}setVertexAttribDivisor(y,C,R){for(let $=0;$0&&y.vertexAttribDivisor(G,R)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class Lj{constructor(y,C,R,$,G){this.context=y,this.width=C,this.height=R;const Z=this.framebuffer=y.gl.createFramebuffer();$>0&&(this.colorAttachment0=new g1(y,Z,0)),$>1&&(this.colorAttachment1=new g1(y,Z,1)),G&&(this.depthAttachmentType=G,this.depthAttachment=G==="renderbuffer"?new Sj(y,Z):new VN(y,Z))}static createWithTexture(y,C,R,$,G){const Z=y.gl;if(y.activeTexture.set(Z.TEXTURE1),y.viewport.set([0,0,R,$]),C&&C.width===R&&C.height===$)return Z.bindTexture(Z.TEXTURE_2D,C.colorAttachment0.get()),y.bindFramebuffer.set(C.framebuffer),C;C&&C.destroy();const te=new o.T(y,{width:R,height:$,data:null},y.extRenderToTextureHalfFloat?y.gl.RGBA16F:y.gl.RGBA8);te.bind(Z.LINEAR,Z.CLAMP_TO_EDGE);const de=y.createFramebuffer(R,$,1,null);if(de.colorAttachment0.set(te.texture),G){const xe=y.createRenderbuffer(Z.DEPTH24_STENCIL8,R,$);y.bindFramebuffer.set(de.framebuffer),Z.framebufferRenderbuffer(Z.FRAMEBUFFER,Z.DEPTH_STENCIL_ATTACHMENT,Z.RENDERBUFFER,xe),de._stencilRbo=xe}return de}createColorAttachment(y,C){C===0?this.colorAttachment0=new g1(y,this.framebuffer,0):C===1&&(this.colorAttachment1=new g1(y,this.framebuffer,1))}removeColorAttachment(y,C){const R=this.context.gl;let $;C===0?($=this.colorAttachment0.get(),this.colorAttachment0=void 0):C===1&&($=this.colorAttachment1.get(),this.colorAttachment1=void 0),$&&R.deleteTexture($)}destroy(){const y=this.context.gl;if(this.colorAttachment0){const C=this.colorAttachment0.get();C&&y.deleteTexture(C)}if(this.colorAttachment1){const C=this.colorAttachment1.get();C&&y.deleteTexture(C)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const C=this.depthAttachment.get();C&&y.deleteRenderbuffer(C)}else{const C=this.depthAttachment.get();C&&y.deleteTexture(C)}this._stencilRbo&&(y.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),y.deleteFramebuffer(this.framebuffer)}}class b0{constructor(y,C){this.gl=y,this.clearColor=new yj(this),this.clearDepth=new BR(this),this.clearStencil=new zN(this),this.colorMask=new $R(this),this.depthMask=new Ff(this),this.stencilMask=new vj(this),this.stencilFunc=new p1(this),this.stencilOp=new BN(this),this.stencilTest=new By(this),this.depthRange=new $y(this),this.depthTest=new Uy(this),this.depthFunc=new bm(this),this.blend=new $N(this),this.blendFunc=new bj(this),this.blendColor=new x6(this),this.blendEquation=new f1(this),this.cullFace=new _j(this),this.cullFaceSide=new wj(this),this.frontFace=new UN(this),this.program=new jj(this),this.activeTexture=new Nj(this),this.viewport=new _m(this),this.bindFramebuffer=new $h(this),this.bindRenderbuffer=new jC(this),this.bindTexture=new x1(this),this.bindVertexBuffer=new NC(this),this.bindElementBuffer=new g6(this),this.bindVertexArrayOES=new y6(this),this.pixelStoreUnpack=new kC(this),this.pixelStoreUnpackPremultiplyAlpha=new qN(this),this.pixelStoreUnpackFlipY=new kj(this),this.options=C?Object.assign({},C):{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=y.getExtension("EXT_texture_filter_anisotropic")||y.getExtension("MOZ_EXT_texture_filter_anisotropic")||y.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=y.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=y.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=y.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=y.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=C&&!!C.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.indexOf("PowerVR")!==-1,this.disableSymbolUBO=C&&!!C.forceDisableSymbolUBO,this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=y.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=y.getExtension("EXT_color_buffer_half_float"),this.extTimerQuery=y.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=y.getParameter(y.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(y.getParameter(y.MAX_UNIFORM_BLOCK_SIZE),32768),this.maxUniformBufferBindings=y.getParameter(y.MAX_UNIFORM_BUFFER_BINDINGS),this.extBlendFuncExtended=y.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(y,C,R){return new qp(this,y,C,R)}createVertexBuffer(y,C,R,$,G){return new XN(this,y,C,R,$,G)}createRenderbuffer(y,C,R){const $=this.gl,G=$.createRenderbuffer();return this.bindRenderbuffer.set(G),$.renderbufferStorage($.RENDERBUFFER,y,C,R),this.bindRenderbuffer.set(null),G}createFramebuffer(y,C,R,$){return new Lj(this,y,C,R,$)}clear({color:y,depth:C,stencil:R,colorMask:$}){const G=this.gl;let Z=0;y&&(Z|=G.COLOR_BUFFER_BIT,this.clearColor.set(y.toNonPremultipliedRenderColor(null)),this.colorMask.set($||[!0,!0,!0,!0])),C!==void 0&&(Z|=G.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(C),this.depthMask.set(!0)),R!==void 0&&(Z|=G.STENCIL_BUFFER_BIT,this.clearStencil.set(R),this.stencilMask.set(255)),G.clear(Z)}setCullFace(y){y.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(y.mode),this.frontFace.set(y.frontFace))}setDepthMode(y){y.func!==this.gl.ALWAYS||y.mask?(this.depthTest.set(!0),this.depthFunc.set(y.func),this.depthMask.set(y.mask),this.depthRange.set(y.range)):this.depthTest.set(!1)}setStencilMode(y){y.test.func!==this.gl.ALWAYS||y.mask?(this.stencilTest.set(!0),this.stencilMask.set(y.mask),this.stencilOp.set([y.fail,y.depthFail,y.pass]),this.stencilFunc.set({func:y.test.func,ref:y.ref,mask:y.test.mask})):this.stencilTest.set(!1)}setColorMode(y){o.b6(y.blendFunction,sa.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(y.blendFunction),this.blendColor.set(y.blendColor),y.blendEquation?this.blendEquation.set(y.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(y.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}let _0;function Kn(I,y,C,R,$,G,Z){const te=I.context,de=te.gl,xe=I.transform,we=[o.aH(xe.center.lng),o.aL(xe.center.lat)],Re=C.layout.get("symbol-placement"),Le=C.layout.get("text-variable-anchor"),Ue=C.layout.get("icon-rotation-alignment")==="map",st=C.layout.get("text-rotation-alignment")==="map",Je=Re!=="point",mt=[];let ht=0,kt=0;for(let At=0;At0){const Cr=o.bb(),ir=Sn;o.cz(Cr,gs.placementInvProjMatrix,xe.glCoordMatrix),o.cz(Cr,Cr,gs.placementViewportMatrix),mt.push({circleArray:dn,circleOffset:kt,transform:ir,invTransform:Cr,projection:gs.getProjection()}),ht+=dn.length/4,kt=ht}if(!Cn)continue;I.terrain&&I.terrain.setupElevationDraw(Gt,Rn);const mr=Us?[Dt.canonical.x,Dt.canonical.y,1<=0&&(Ue[Tt.associatedIconIndex]={x:ns,y:$s,z:Ps,angle:zs})}else ii(Ft,Re)}if(xe){Le.clear();const kt=I.icon.placedSymbolArray;for(let Tt=0;Tt{let Ca=[0,0,0];if(Hi){const dl=I.style.directionalLight,_o=I.style.ambientLight;dl&&_o&&(Ca=zp(I.style,dl,_o))}return Ca},Wa=Hi=>{if(I.context.disableSymbolUBO)return;Hi.push("USE_PAINT_PROPERTIES_UBO");const Ca=Math.floor(I.context.maxUniformBlockSize/4),dl=Math.floor(Ca/4);Hi.push(`MAX_UBO_SIZE_VEC4 ${dl}u`)},va=Hi=>{Dt.depthOcclusionForSymbolsAndCircles&&(C.hasOcclusionOpacityProperties||I.terrain)&&(Hi.push("DEPTH_D24"),Hi.push("DEPTH_OCCLUSION"))},Ii=Hi=>{C.lut&&!Ft&&(C.lut.texture||(C.lut.texture=new o.dR(I.context,C.lut.image,[C.lut.image.height,C.lut.image.height,C.lut.image.height],Qt.gl.RGBA8)),Qt.activeTexture.set(Qt.gl.TEXTURE0+10),C.lut.texture&&C.lut.texture.bind(Qt.gl.LINEAR,Qt.gl.CLAMP_TO_EDGE),Hi.push("APPLY_LUT_ON_GPU"))},bo=()=>{const Hi=Gt&&C.layout.get("symbol-placement")!=="point",Ca=[];va(Ca),Ii(Ca);const dl=Hi||wa,_o=dn.elevationType==="road",kc=I.shadowRenderer,oi=_o&&ns&&!!kc&&kc.enabled,ko=Gr(oi),Xc=_o&&ns&&!I.terrain?Ns:mn,wh=C.paint.get("icon-image-cross-fade");I.terrainRenderModeElevated()&&ns&&Ca.push("PITCH_WITH_MAP_TERRAIN"),mr&&(Ca.push("PROJECTION_GLOBE_VIEW"),dl&&Ca.push("PROJECTED_POS_ON_VIEWPORT")),wh>0&&dn.hasAnySecondaryIcon&&Ca.push("ICON_TRANSITION"),!dn.icon.zOffsetVertexBuffer||_o&&I.terrain||Ca.push("Z_OFFSET"),ht===0&&kt===0&&Tt===0&&xt===1||Ca.push("COLOR_ADJUSTMENT"),dn.sdfIcons&&Ca.push("RENDER_SDF"),oi&&Ca.push("RENDER_SHADOWS","NORMAL_OFFSET"),_o&&ns&&!I.terrain&&dn.icon.orientationVertexBuffer&&Ca.push("ELEVATED_ROADS"),Wa(Ca);const hd=Qt.disableSymbolUBO?dn.icon.programConfigurations.get(C.id):null,yu=I.getOrCreateProgram("symbol",{config:hd,defines:Ca}),$f=Cn.imageAtlasTexture?Cn.imageAtlasTexture.size:[0,0],so=dn.iconSizeData,Cx=o.bj(so,Dt.zoom),Tx=ns||!Dt.isOrthographic,Bo=Sd(ir,Cn.tileID.canonical,ns,Gt,Dt,dn.getProjection(),hr),Ko=tp(ir,Cn.tileID.canonical,ns,Gt,Dt,dn.getProjection(),hr),co=dn.icon.uboBinder&&dn.icon.uboBinder.cachedHeader&&256&dn.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:te,pc=I.translatePosMatrix(Ko,Cn,co,xe,!0),Hh=I.translatePosMatrix(ir,Cn,co,xe),Rl=dl?xo:Bo,Uf=Gt&&!ns&&!Hi;let x_=Rn;!Us&&!Dt.mercatorFromTransition||Gt||(x_=mc(Dt));const Gj=mr?x_:Rn,Wj=C.getColorAdjustmentMatrix(ht,kt,Tt,xt),lk=w1(so.kind,Cx,Uf,ns,I,Hh,Rl,pc,es,!1,$f,[0,0],0,Sn,Cr,hs,ya,Gj,dn.getProjection(),ko,Ga,Wj,wh,null),T1=Cn.imageAtlasTexture?Cn.imageAtlasTexture:null,Qy=C.layout.get("icon-size").constantOr(0)!==1||dn.iconsNeedLinear,ck=dn.sdfIcons||I.options.rotating||I.options.zooming||Qy||Tx?At.LINEAR:At.NEAREST,Kp=dn.sdfIcons&&C.paint.get("icon-halo-width").constantOr(1)!==0,g_=I.terrain&&ns&&Hi?o.b7(o.bb(),Bo):xo;if(Hi&&dn.icon){const y_=o.bu.getAtTileOffsetFunc(Sn,Dt.center.lat,Dt.worldSize,dn.getProjection()),v_=zc(ir,Cn.tileID.canonical,ns,Gt,Dt,dn.getProjection(),hr),F6=C.layout.get("icon-size-scale-range"),dk=o.aC(I.scaleFactor,F6[0],F6[1]);Lt(dn,ir,I,!1,v_,Ko,ns,Je,y_,Sn,dk)}return{program:yu,buffers:dn.icon,uniformValues:lk,atlasTexture:T1,atlasTextureIcon:null,atlasInterpolation:ck,atlasInterpolationIcon:null,isSDF:dn.sdfIcons,hasHalo:Kp,depthMode:Xc,tile:Cn,renderWithShadows:oi,labelPlaneMatrixInv:g_}},vl=()=>{const Hi=gs&&C.layout.get("symbol-placement")!=="point",Ca=[],dl=Hi||zs||wa,_o=dn.elevationType==="road",kc=I.shadowRenderer,oi=_o&&$s&&!!kc&&kc.enabled,ko=Gr(oi),Xc=_o&&$s&&!I.terrain?Ns:mn;I.terrainRenderModeElevated()&&$s&&Ca.push("PITCH_WITH_MAP_TERRAIN"),mr&&(Ca.push("PROJECTION_GLOBE_VIEW"),dl&&Ca.push("PROJECTED_POS_ON_VIEWPORT")),!dn.text.zOffsetVertexBuffer||_o&&I.terrain||Ca.push("Z_OFFSET"),dn.iconsInText&&Ca.push("RENDER_TEXT_AND_SYMBOL"),Ca.push("RENDER_SDF"),oi&&Ca.push("RENDER_SHADOWS","NORMAL_OFFSET"),_o&&$s&&!I.terrain&&dn.text.orientationVertexBuffer&&Ca.push("ELEVATED_ROADS"),va(Ca),Wa(Ca);const wh=Qt.disableSymbolUBO?dn.text.programConfigurations.get(C.id):null,hd=I.getOrCreateProgram("symbol",{config:wh,defines:Ca});let yu,$f=[0,0],so=null;const Cx=dn.textSizeData;dn.iconsInText&&($f=Cn.imageAtlasTexture?Cn.imageAtlasTexture.size:[0,0],so=Cn.imageAtlasTexture?Cn.imageAtlasTexture:null,yu=$s||!Dt.isOrthographic||I.options.rotating||I.options.zooming||Cx.kind==="composite"||Cx.kind==="camera"?At.LINEAR:At.NEAREST);const Tx=Cn.glyphAtlasTexture?Cn.glyphAtlasTexture.size:[0,0],Bo=C.layout.get("text-size-scale-range"),Ko=o.aC(I.scaleFactor,Bo[0],Bo[1]),co=o.bj(Cx,Dt.zoom,Ko),pc=Sd(ir,Cn.tileID.canonical,$s,gs,Dt,dn.getProjection(),hr),Hh=tp(ir,Cn.tileID.canonical,$s,gs,Dt,dn.getProjection(),hr),Rl=dn.text.uboBinder&&dn.text.uboBinder.cachedHeader&&256&dn.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:de,Uf=I.translatePosMatrix(Hh,Cn,Rl,we,!0),x_=I.translatePosMatrix(ir,Cn,Rl,we),Gj=dl?xo:pc,Wj=gs&&!$s&&!Hi;let lk=Rn;!Us&&!Dt.mercatorFromTransition||gs||(lk=mc(Dt));const T1=w1(Cx.kind,co,Wj,$s,I,x_,Gj,Uf,es,!0,Tx,$f,0,Sn,Cr,hs,ya,mr?lk:Rn,dn.getProjection(),ko,Ga,null,null,Ko),Qy=Cn.glyphAtlasTexture?Cn.glyphAtlasTexture:null,ck=At.LINEAR,Kp=C.paint.get("text-halo-width").constantOr(1)!==0,g_=I.terrain&&$s&&Hi?o.b7(o.bb(),pc):xo;if(Hi&&dn.text){const y_=o.bu.getAtTileOffsetFunc(Sn,Dt.center.lat,Dt.worldSize,dn.getProjection()),v_=zc(ir,Cn.tileID.canonical,$s,gs,Dt,dn.getProjection(),hr);Lt(dn,ir,I,!0,v_,Hh,$s,mt,y_,Sn,Ko)}return{program:hd,buffers:dn.text,uniformValues:T1,atlasTexture:Qy,atlasTextureIcon:so,atlasInterpolation:ck,atlasInterpolationIcon:yu,isSDF:!0,hasHalo:Kp,depthMode:Xc,tile:Cn,renderWithShadows:oi,labelPlaneMatrixInv:g_}},Lo=dn.icon.segments.get().length,Vi=dn.text.segments.get().length,Fa=Lo&&!Z.onlyText?bo():null,za=Vi&&!Z.onlyIcons?vl():null,Do=C.paint.get("icon-opacity").constantOr(1),Nl=C.paint.get("text-opacity").constantOr(1);if(Ps&&dn.canOverlap){an=!0;const Hi=Do&&!Z.onlyText?dn.icon.segments.get():[],Ca=Nl&&!Z.onlyIcons?dn.text.segments.get():[];for(const dl of Hi)Ys.push({segments:new o.dy([dl]),sortKey:dl.sortKey,state:Fa});for(const dl of Ca)Ys.push({segments:new o.dy([dl]),sortKey:dl.sortKey,state:za})}else Z.onlyText||Ys.push({segments:Do?dn.icon.segments:new o.dy([]),sortKey:0,state:Fa}),Z.onlyIcons||Ys.push({segments:Nl?dn.text.segments:new o.dy([]),sortKey:0,state:za})}an&&Ys.sort((Sn,Cn)=>Sn.sortKey-Cn.sortKey);for(const Sn of Ys){const Cn=Sn.state;if(Cn)if(I.terrain?I.terrain.setupElevationDraw(Cn.tile,Cn.program,{useDepthForOcclusion:Dt.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:Cn.labelPlaneMatrixInv}):I.setupDepthForOcclusion(Dt.depthOcclusionForSymbolsAndCircles,Cn.program),Qt.activeTexture.set(At.TEXTURE0),Cn.atlasTexture&&Cn.atlasTexture.bind(Cn.atlasInterpolation,At.CLAMP_TO_EDGE,!0),Cn.atlasTextureIcon&&(Qt.activeTexture.set(At.TEXTURE1),Cn.atlasTextureIcon&&Cn.atlasTextureIcon.bind(Cn.atlasInterpolationIcon,At.CLAMP_TO_EDGE,!0)),Cn.renderWithShadows&&I.shadowRenderer.setupShadows(Cn.tile.tileID.toUnwrapped(),Cn.program,"vector-tile"),I.uploadCommonLightUniforms(I.context,Cn.program),Cn.hasHalo){const dn=Cn.uniformValues;dn.u_is_halo=1,w0(Cn.buffers,Sn.segments,C,I,Cn.program,Cn.depthMode,$,G,dn,2),dn.u_is_halo=0}else{if(Cn.isSDF){const dn=Cn.uniformValues;Cn.hasHalo&&(dn.u_is_halo=1,w0(Cn.buffers,Sn.segments,C,I,Cn.program,Cn.depthMode,$,G,dn,1)),dn.u_is_halo=0}w0(Cn.buffers,Sn.segments,C,I,Cn.program,Cn.depthMode,$,G,Cn.uniformValues,1)}}}function w0(I,y,C,R,$,G,Z,te,de,xe){const we=R.context,Re=we.gl,Le=[I.dynamicLayoutVertexBuffer,I.opacityVertexBuffer,I.iconTransitioningVertexBuffer,I.globeExtVertexBuffer,I.zOffsetVertexBuffer,I.orientationVertexBuffer];I.featureIdBuffer&&Le.push(I.featureIdBuffer);const Ue=I.uboBinder?null:I.programConfigurations.get(C.id);if(I.uboBinder){I.uboBinder.layer=C;const mt=R.transform.zoom,ht=R.style.getBrightness?R.style.getBrightness():null,kt=I.uboBinder.getConstantUniformValues(mt,ht);de.u_spp_fill_np_color=kt.fill_np_color,de.u_spp_halo_np_color=kt.halo_np_color,de.u_spp_opacity=kt.opacity,de.u_spp_halo_width=kt.halo_width,de.u_spp_halo_blur=kt.halo_blur,de.u_spp_emissive_strength=kt.emissive_strength,de.u_spp_occlusion_opacity=kt.occlusion_opacity,de.u_spp_z_offset=kt.z_offset;const Tt=C.paint.get(I.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),xt=I.uboBinder.cachedHeader&&256&I.uboBinder.cachedHeader.dataDrivenMask&&Tt==="map"?R.transform.angle:0;de.u_spp_translate_rotation=[Math.cos(xt),Math.sin(xt)]}const{batchIndices:st,batchSegments:Je}=I.getBatchGrouping(y);for(const mt of st){const ht=Je.get(mt);I.uboBinder&&I.uboBinder.bind(we,$.program,mt),$.draw(R,Re.TRIANGLES,G,Z,te,Rr.disabled,de,C.id,I.layoutVertexBuffer,I.indexBuffer,ht,C.paint,R.transform.zoom,Ue,Le,xe)}}function dd(I,y,C,R,$,G){const Z=C.paint.get("line-width"),te=C.paint.get("line-emissive-strength").isConstant(),de=C.paint.get("line-emissive-strength").constantOr(0),xe=C.paint.get("line-occlusion-opacity"),we=C.layout.get("line-elevation-reference"),Re=C.layout.get("line-width-unit")==="meters",Le=we==="sea",Ue=!(!I.terrain||!I.terrain.enabled),st=I.context,Je=st.gl;if(C.hasElevatedBuckets&&I.transform.projection.name==="globe")return;const mt=C.layout.get("line-cross-slope"),ht=mt!==void 0,kt=mt<1,Tt=$||I.colorModeForDrapableLayerRenderPass(te?de:null),xt=I.terrain&&I.terrain.renderingToTexture||G,es=xt?1:o.o.devicePixelRatio,Ft=C.paint.get("line-dasharray"),Qt=Ft.constantOr(1),At=C.layout.get("line-cap"),Dt=Ft.constantOr(null),Gt=At.constantOr(null),gs=C.paint.get("line-pattern"),ns=gs.constantOr(1),$s=C.paint.get("line-pattern-cross-fade"),Ps=gs.constantOr(null),an=C.paint.get("line-opacity").constantOr(1);let mn=!ns&&an!==1||I.depthOcclusion&&xe>0&&xe<1;const Ns=C.paint.get("line-gradient"),hs=ns?"linePattern":"line",zs=o.dU(C);let Us;if(xt&&I.terrain&&I.terrain.clipOrMaskOverlapStencilType()&&(mn=!1),xe!==0&&I.depthOcclusion){const dn=C.paint._values["line-opacity"];dn&&dn.value&&dn.value.kind==="constant"?Us=dn.value:o.w(`Occlusion opacity for layer ${C.id} is supported only when line-opacity isn't data-driven.`)}Z.value.kind!=="constant"&&Z.value.isLineProgressConstant===!1&&zs.push("VARIABLE_LINE_WIDTH"),xt&&(I.emissiveMode!=="dual-source-blending"||te?I.emissiveMode==="mrt-fallback"&&zs.push("USE_MRT1"):zs.push("DUAL_SOURCE_BLENDING"));const Ys={},Rn=(dn,mr,Cr,ir,hr,na)=>{for(const wa of dn){const ya=y.getTile(wa);if(ns&&!ya.patternsLoaded())continue;const Ga=ya.getBucket(C);if(!Ga||Ga.elevationType!=="none"&&!hr||Ga.elevationType==="none"&&hr)continue;I.prepareDrawTile();const Gr=[...mr],Wa=I.shadowRenderer,va=Ga.elevationType==="road"&&!!Wa&&Wa.enabled;let Ii=[0,0,0];if(va){const oi=I.style.directionalLight,ko=I.style.ambientLight;oi&&ko&&(Ii=zp(I.style,oi,ko)),Gr.push("RENDER_SHADOWS","NORMAL_OFFSET")}const bo=Ga.programConfigurations.get(C.id);let vl=!1;if(Ps&&ya.imageAtlas){const oi=o.dV.from(Ps),ko=oi.getPrimary().scaleSelf(es).toString(),Xc=ya.imageAtlas.patternPositions.get(ko),wh=oi.getSecondary(),hd=wh?ya.imageAtlas.patternPositions.get(wh.scaleSelf(es).toString()):null;vl=!!Xc&&!!hd,Xc&&bo.setConstantPatternPositions(Xc,hd)}$s>0&&(vl||bo.getPatternTransitionVertexBuffer("line-pattern"))&&Gr.push("LINE_PATTERN_TRANSITION"),Ga.elevationGroundScaleVertexBuffer&&Gr.push("ELEVATION_GROUND_SCALE");const Lo=I.isTileAffectedByFog(wa),Vi=I.getOrCreateProgram(hs,{config:bo,defines:Gr,overrideFog:Lo});if(!ns&&Dt&&Gt&&ya.lineAtlas){const oi=ya.lineAtlas.getDash(Dt,Gt);oi&&bo.setConstantPatternPositions(oi)}va&&Wa.setupShadows(ya.tileID.toUnwrapped(),Vi,"vector-tile");let[Fa,za]=C.paint.get("line-trim-offset");(Gt==="round"||Gt==="square")&&Fa!==za&&(Fa===0&&(Fa-=1),za===1&&(za+=1));const Do=xt?wa.projMatrix:null,Nl=Re?1/Ga.tileToMeter/o.aA(ya,1,I.transform.zoom):1,Hi=Re?1/Ga.tileToMeter/o.aA(ya,1,Math.floor(I.transform.zoom)):1,Ca=Qt?C.paint._values["line-floorwidth"]:null;let dl;if(Ca&&Ca.value.kind==="constant"){const oi=Ga.zoom;oi in Ys||(Ys[oi]=Math.max(.01,C.widthExpression().evaluate({zoom:oi}))),dl=Ca.value.value;const ko=Math.floor(I.transform.zoom);Ca.value.value=Ys[oi]*Math.pow(2,ko-ya.tileID.overscaledZ)}const _o=ns?o.dW(I,ya,C,Do,es,Nl,Hi,[Fa,za],Ii,$s):o.dX(I,ya,C,Do,Ga.lineClipsArray.length,es,Nl,Hi,[Fa,za],Ii);if(Ns){const oi=Ga.gradients[C.id];let ko=oi.texture;if(C.gradientVersion!==oi.version){let Xc=256;if(C.stepInterpolant){const wh=y.getSource().maxzoom,hd=wa.canonical.z===wh?Math.ceil(1<{Us!=null&&(Us.value=an*xe),Vi.draw(I,Je.TRIANGLES,Cr,oi,Tt,Rr.disabled,_o,C.id,Ga.layoutVertexBuffer,Ga.indexBuffer,Ga.segments,C.paint,I.transform.zoom,bo,[Ga.layoutVertexBuffer2,Ga.patternVertexBuffer,Ga.zOffsetVertexBuffer,Ga.elevationGroundScaleVertexBuffer]),Us!=null&&(Us.value=an)};if(mn&&!hr){const oi=I.stencilModeForClipping(wa).ref;oi===0&&xt&&st.clear({stencil:0});const ko={func:Je.EQUAL,mask:255};_o.u_alpha_discard_threshold=.8,kc(new oa(ko,oi,255,Je.KEEP,Je.KEEP,Je.INVERT)),_o.u_alpha_discard_threshold=0,kc(new oa(ko,oi,255,Je.KEEP,Je.KEEP,Je.KEEP))}else _o.u_alpha_discard_threshold=mn&&hr&&na?.8:0,kc(hr?ir:I.stencilModeForClipping(wa));dl!==void 0&&(Ca.value.value=dl)}};let Sn=I.depthModeForSublayer(0,ar.ReadOnly);const Cn=new ar(I.depthOcclusion?Je.GREATER:Je.LEQUAL,ar.ReadOnly,I.depthRangeFor3D);if(C.hasNonElevatedBuckets){const dn=!xt&&I.terrain;xe!==0&&dn?o.w(`Occlusion opacity for layer ${C.id} is supported on terrain only if the layer has line-z-offset enabled.`):dn?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${C.id}.`):Rn(R,zs,Sn,oa.disabled,!1,!0)}if(C.hasElevatedBuckets){we==="hd-road-markup"?Ue||(Sn=Cn,zs.push("ELEVATED_ROADS")):(zs.push("ELEVATED"),Sn=Cn,ht&&zs.push(kt?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),Le&&zs.push("ELEVATION_REFERENCE_SEA"));const dn=mn?I.stencilModeFor3D():oa.disabled;I.forceTerrainMode=!0,Rn(R,zs,Sn,dn,!0,!0),mn&&Rn(R,zs,Sn,dn,!0,!1),I.forceTerrainMode=!1}mn&&(I.resetStencilClippingMasks(),xt&&st.clear({stencil:0})),xe===0||I.depthOcclusion||xt||I.layersWithOcclusionOpacity.push(I.currentLayer)}const Vp={additive:{clearColor:new o.aq(0,0,0,0),colorMode:sa.additive,compositeUniformValue:1},multiply:{clearColor:new o.aq(1,1,1,1),colorMode:sa.multiply,compositeUniformValue:0}};function j0(I,y){const C=1<=Df?1:Ue.pitch/Df))),2*st}(I.transform),xe=I.transform.getFreeCameraOptions().position,we="elevatedStructuresDepthReconstruct",Re=I.getOrCreateProgram(we,{defines:["DEPTH_RECONSTRUCTION"]}),Le=I.getOrCreateProgram(we);for(const Ue of R){const st=y.getTile(Ue),Je=st.getBucket(C);if(!Je)continue;const mt=Je.elevatedStructures;if(!mt)continue;const ht=Je.elevationBufferData.heightRange,kt=j0(Ue.toUnwrapped(),xe),Tt=I.translatePosMatrix(Ue.projMatrix,st,C.paint.get("fill-translate"),C.paint.get("fill-translate-anchor"));let xt,es,Ft,Qt;if($==="initialize"){if(!ht||ht.min>=1||mt.depthSegments.segments[0].primitiveLength===0)continue;xt=_1(Tt,kt,de,1,0),es=Z,Ft=mt.depthSegments,Qt=Re}else if($==="reset"){if(!ht||ht.min>=0||mt.maskSegments.segments[0].primitiveLength===0)continue;xt=_1(Tt,kt,0,0,1),es=te,Ft=mt.maskSegments,Qt=Re}else if($==="geometry"){if(mt.depthSegments.segments[0].primitiveLength===0)continue;xt=_1(Tt,kt,de,1,0),es=Z,Ft=mt.depthSegments,Qt=Le}Qt.draw(I,G.TRIANGLES,es,oa.disabled,sa.disabled,Rr.disabled,xt,C.id,mt.vertexBuffer,mt.indexBuffer,Ft,C.paint,I.transform.zoom)}}function j1(I,y,C,R){const{painter:$,sourceCache:G,layer:Z,coords:te,colorMode:de,elevationType:xe,terrainEnabled:we,pass:Re}=I,Le=$.context.gl,Ue=Z.paint.get("fill-pattern"),st=Z.paint.get("fill-pattern-cross-fade"),Je=Ue.constantOr(null);let mt=xe;xe!=="road"||y&&!we||(mt="none");const ht=mt==="road",kt=I.painter.shadowRenderer,Tt=ht&&!!kt&&kt.enabled,xt=new ar($.context.gl.LEQUAL,ar.ReadOnly,$.depthRangeFor3D);let es=[0,0,0];if(Tt){const Dt=$.style.directionalLight,Gt=$.style.ambientLight;Dt&&Gt&&(es=zp($.style,Dt,Gt))}const Ft=Ue&&Ue.constantOr(1),Qt=$.terrain&&$.terrain.renderingToTexture,At=(Dt,Gt)=>{let gs,ns,$s,Ps,an;Gt?(gs=Ft&&!Z.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",$s=Le.LINES):(gs=Ft?"fillPattern":"fill",$s=Le.TRIANGLES);for(const mn of te){const Ns=G.getTile(mn);if(Ft&&!Ns.patternsLoaded())continue;const hs=Ns.getBucket(Z);if(!hs)continue;const zs=y?hs.elevationBufferData:hs.bufferData;if(zs.isEmpty())continue;$.prepareDrawTile();const Us=zs.programConfigurations.get(Z.id),Ys=$.isTileAffectedByFog(mn),Rn=[],Sn=[];ht&&(Rn.push("ELEVATED_ROADS"),Sn.push(zs.elevatedLayoutVertexBuffer)),Tt&&Rn.push("RENDER_SHADOWS","NORMAL_OFFSET"),Qt&&C&&Rn.push("USE_MRT1"),Ft&&($.context.activeTexture.set(Le.TEXTURE0),Ns.imageAtlasTexture&&Ns.imageAtlasTexture.bind(Le.LINEAR,Le.CLAMP_TO_EDGE),Us.updatePaintBuffers());let Cn=!1;if(Je&&Ns.imageAtlas){const hr=Ns.imageAtlas,na=o.dV.from(Je),wa=na.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),ya=na.getSecondary(),Ga=hr.patternPositions.get(wa),Gr=ya?hr.patternPositions.get(ya.scaleSelf(o.o.devicePixelRatio).toString()):null;Cn=!!Ga&&!!Gr,Ga&&Us.setConstantPatternPositions(Ga,Gr)}st>0&&(Cn||Us.getPatternTransitionVertexBuffer("fill-pattern"))&&Rn.push("FILL_PATTERN_TRANSITION");const dn=$.getOrCreateProgram(gs,{config:Us,overrideFog:Ys,defines:Rn}),mr=$.translatePosMatrix(mn.projMatrix,Ns,Z.paint.get("fill-translate"),Z.paint.get("fill-translate-anchor"));Tt&&kt.setupShadows(Ns.tileID.toUnwrapped(),dn,"vector-tile");const Cr=Z.paint.get("fill-emissive-strength");if(Gt){Ps=zs.lineIndexBuffer,an=zs.lineSegments;const hr=$.terrain&&$.terrain.renderingToTexture?$.terrain.drapeBufferSize:[Le.drawingBufferWidth,Le.drawingBufferHeight];ns=gs==="fillOutlinePattern"&&Ft?i_(mr,Cr,$,Ns,hr,es,st):TC(mr,Cr,hr,es)}else Ps=zs.indexBuffer,an=zs.triangleSegments,ns=Ft?a_(mr,Cr,$,Ns,es,st):g0(mr,Cr,es);$.uploadCommonUniforms($.context,dn,mn.toUnwrapped());let ir=Dt;(xe==="road"&&!we||xe==="offset")&&(ir=xt),dn.draw($,$s,ir,R||$.stencilModeForClipping(mn),de,Rr.disabled,ns,Z.id,zs.layoutVertexBuffer,Ps,an,Z.paint,$.transform.zoom,Us,Sn)}};$.renderPass===Re&&At($.depthModeForSublayer(1,$.renderPass==="opaque"?ar.ReadWrite:ar.ReadOnly),!1),mt==="none"&&$.renderPass==="translucent"&&Z.paint.get("fill-antialias")&&At($.depthModeForSublayer(Z.getPaintProperty("fill-outline-color")?2:0,ar.ReadOnly),!0)}function Nx(I,y,C,R,$,G,Z,te){C.resetLayerRenderingStats(I);const de=I.context,xe=de.gl,we=I.transform,Re=C.paint.get("fill-extrusion-pattern"),Le=C.paint.get("fill-extrusion-pattern-cross-fade"),Ue=Re.constantOr(null),st=Re.constantOr(1),Je=C.paint.get("fill-extrusion-opacity"),mt=I.style.enable3dLights(),ht=C.paint.get(mt&&!st?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),kt=[C.paint.get("fill-extrusion-ambient-occlusion-intensity"),ht],Tt=C.layout.get("fill-extrusion-edge-radius"),xt=Tt>0&&!C.paint.get("fill-extrusion-rounded-roof"),es=xt?0:Tt,Ft=we.projection.name==="globe"?o.e1():0,Qt=we.projection.name==="globe",At=Qt?o.al(we.zoom):0,Dt=[o.aH(we.center.lng),o.aL(we.center.lat)],Gt=C.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",gs=C.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Gt?null:C.lut).toArray01().slice(0,3),ns=C.paint.get("fill-extrusion-flood-light-intensity"),$s=C.paint.get("fill-extrusion-vertical-scale"),Ps=C.paint.get("fill-extrusion-line-width").constantOr(1)!==0,an=C.paint.get("fill-extrusion-height-alignment"),mn=C.paint.get("fill-extrusion-base-alignment"),Ns=Bc(I,C.paint.get("fill-extrusion-cutoff-fade-range")),hs=C.paint.get("fill-extrusion-front-cutoff"),zs=d_(we.pitch,hs,!!I.terrain),Us=zs[2]<1;Us&&(I.maxFrontCutoffRawStart=Math.max(I.maxFrontCutoffRawStart,hs[0]));const Ys=[];let Rn;Qt&&Ys.push("PROJECTION_GLOBE_VIEW"),kt[0]>0&&Ys.push("FAUX_AO"),xt&&Ys.push("ZERO_ROOF_RADIUS"),te&&Ys.push("HAS_CENTROID"),ns>0&&Ys.push("FLOOD_LIGHT"),Ns.shouldRenderCutoff&&Ys.push("RENDER_CUTOFF"),Us&&Ys.push("RENDER_FRONT_CUTOFF"),Ps&&Ys.push("RENDER_WALL_MODE");const Sn=I.renderPass==="shadow",Cn=I.shadowRenderer,dn=Sn&&!!Cn,mr=Sn?Rr.disabled:Rr.backCCW;I.shadowRenderer&&(I.shadowRenderer.useNormalOffset=!0);let Cr=[0,0,0];if(Cn){const na=I.style.directionalLight,wa=I.style.ambientLight;na&&wa&&(Cr=zp(I.style,na,wa)),Sn||(Ys.push("RENDER_SHADOWS"),Cn.useNormalOffset&&Ys.push("NORMAL_OFFSET")),Rn=Ys.concat(["SHADOWS_SINGLE_CASCADE"])}const ir=dn?"fillExtrusionDepth":st?"fillExtrusionPattern":"fillExtrusion",hr=C.getLayerRenderingStats();for(const na of R){const wa=y.getTile(na),ya=wa.getBucket(C);if(!ya||ya.projection.name!==we.projection.name)continue;let Ga=!1;Cn&&(Ga=Cn.getMaxCascadeForTile(na.toUnwrapped())===0);const Gr=I.isTileAffectedByFog(na),Wa=ya.programConfigurations.get(C.id);let va=!1;if(Ue&&wa.imageAtlas){const za=wa.imageAtlas,Do=o.dV.from(Ue),Nl=Do.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),Hi=Do.getSecondary(),Ca=za.patternPositions.get(Nl),dl=Hi?za.patternPositions.get(Hi.scaleSelf(o.o.devicePixelRatio).toString()):null;va=!!Ca&&!!dl,Ca&&Wa.setConstantPatternPositions(Ca,dl)}Le>0&&(va||Wa.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&Ys.push("FILL_EXTRUSION_PATTERN_TRANSITION");const Ii=I.getOrCreateProgram(ir,{config:Wa,defines:Ga?Rn:Ys,overrideFog:Gr});if(I.terrain&&I.terrain.setupElevationDraw(wa,Ii,{useMeterToDem:!0}),!ya.centroidVertexBuffer){const za=Ii.getAttributeLocation(xe,"a_centroid_pos");za!==-1&&xe.vertexAttribI4ui(za,0,0,0,0)}!Sn&&Cn&&Cn.setupShadows(wa.tileID.toUnwrapped(),Ii,"vector-tile"),st&&(I.context.activeTexture.set(xe.TEXTURE0),wa.imageAtlasTexture&&wa.imageAtlasTexture.bind(xe.LINEAR,xe.CLAMP_TO_EDGE),Wa.updatePaintBuffers());const bo=C.paint.get("fill-extrusion-vertical-gradient"),vl=1/ya.tileToMeter;let Lo;if(Sn&&Cn){if(kx(wa.tileID,ya.maxHeight,I))continue;const za=Cn.calculateShadowPassMatrixFromTile(wa.tileID.toUnwrapped());Lo=UR(za,es,vl,$s,an,mn)}else{const za=I.translatePosMatrix(na.expandedProjMatrix,wa,C.paint.get("fill-extrusion-translate"),C.paint.get("fill-extrusion-translate-anchor")),Do=we.projection.createInversionMatrix(we,na.canonical);Lo=st?$a(za,I,bo,Je,kt,es,vl,na,wa,Ft,an,mn,At,Dt,Do,gs,$s,Le):vh(za,I,bo,Je,kt,es,vl,na,Ft,an,mn,At,Dt,Do,gs,$s,ns,Cr,zs)}I.uploadCommonUniforms(de,Ii,na.toUnwrapped(),null,Ns);let Vi=ya.segments;if(we.projection.name==="mercator"&&!Sn&&(Vi=ya.getVisibleSegments(wa.tileID,I.terrain,I.transform.getFrustum(0)),!Vi.get().length))continue;if(hr)if(Sn)for(const za of Vi.get())hr.numRenderedVerticesInShadowPass+=za.primitiveLength;else for(const za of Vi.get())hr.numRenderedVerticesInTransparentPass+=za.primitiveLength;const Fa=[];(I.terrain||te)&&Fa.push(ya.centroidVertexBuffer),Qt&&Fa.push(ya.layoutVertexExtBuffer),Ps&&Fa.push(ya.wallVertexBuffer),Ii.draw(I,de.gl.TRIANGLES,$,G,Z,mr,Lo,C.id,ya.layoutVertexBuffer,ya.indexBuffer,Vi,C.paint,I.transform.zoom,Wa,Fa)}I.shadowRenderer&&(I.shadowRenderer.useNormalOffset=!1)}class qh{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function d_(I,y,C){if(!(y[2]<1)||C)return[0,0,1];const R=180*I/Math.PI;if(R<15)return[-.5,y[1],y[2]];const $=Math.min(1,Math.max(0,(R-15)/5)),G=$*$*(3-2*$);return[-.5*(1-G)+y[0]*G,y[1],y[2]]}function zf(I,y,C,R,$,G,Z,te,de,xe,we,Re,Le,Ue,st,Je,mt,ht,kt,Tt,xt){const es=y.context,Ft=es.gl,Qt=y.transform,At=y.transform.zoom,Dt=[],Gt=I.translate,gs=I.translateAnchor,ns=I.edgeRadius,$s=Bc(y,I.cutoffFadeRange);we==="clear"?(Dt.push("CLEAR_SUBPASS"),Tt&&(Dt.push("CLEAR_FROM_TEXTURE"),es.activeTexture.set(Ft.TEXTURE0),Tt.bind(Ft.LINEAR,Ft.CLAMP_TO_EDGE))):we==="sdf"?Dt.push("SDF_SUBPASS"):we==="emissive"&&(Dt.push("USE_MRT1"),es.activeTexture.set(Ft.TEXTURE0),Tt.bind(Ft.LINEAR,Ft.CLAMP_TO_EDGE)),ht&&Dt.push("HAS_CENTROID"),$s.shouldRenderCutoff&&Dt.push("RENDER_CUTOFF");const Ps=(an,mn,Ns,hs,zs)=>{let Us=Dt;mn.groundRadiusBuffer!=null&&(Us=Dt.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const Ys=mn.programConfigurations.get(R.id),Rn=y.isTileAffectedByFog(an),Sn=y.getOrCreateProgram("fillExtrusionGroundEffect",{config:Ys,defines:Us,overrideFog:Rn}),Cn=((mr,Cr,ir,hr,na,wa,ya,Ga,Gr,Wa,va)=>({u_matrix:Cr,u_opacity:ir,u_ao_pass:hr?1:0,u_meter_to_tile:na,u_ao:wa,u_flood_light_intensity:ya,u_flood_light_color:Ga,u_attenuation:Gr,u_edge_radius:Wa,u_fb:0,u_fb_size:va,u_dynamic_offset:1}))(0,hs,Re,xe,zs,[Le,Ue*zs],st,Je,mt,At>=17?0:ns*zs,Tt?Tt.size[0]:0),dn=[];ht&&dn.push(mn.hiddenByLandmarkVertexBuffer),mn.groundRadiusBuffer!=null&&dn.push(mn.groundRadiusBuffer),y.uploadCommonUniforms(es,Sn,an.toUnwrapped(),null,$s),Sn.draw(y,es.gl.TRIANGLES,G,Z,te,de,Cn,R.id,mn.vertexBuffer,mn.indexBuffer,Ns,R.paint,At,Ys,dn)};for(const an of $){const mn=C.getTile(an),Ns=mn.getBucket(R);if(!Ns||Ns.projection.name!==Qt.projection.name||!Ns.groundEffect||Ns.groundEffect&&!Ns.groundEffect.hasData())continue;const hs=Ns.groundEffect,zs=1/Ns.tileToMeter;{const Us=y.translatePosMatrix(an.projMatrix,mn,Gt,gs),Ys=hs.getDefaultSegment();Ps(an,hs,Ys,Us,zs)}if(kt)for(let Us=0;Us<4;Us++){const Ys=o.d$[Us](an),Rn=C.getTile(Ys);if(!Rn)continue;const Sn=Rn.getBucket(R);if(!Sn||Sn.projection.name!==Qt.projection.name||!Sn.groundEffect||Sn.groundEffect&&!Sn.groundEffect.hasData())continue;const Cn=Sn.groundEffect;let dn,mr;Us===0?(dn=[-o.an,0,0],mr=1):Us===1?(dn=[o.an,0,0],mr=0):Us===2?(dn=[0,-o.an,0],mr=3):(dn=[0,o.an,0],mr=2);const Cr=Cn.regionSegments[mr];if(!Cr)continue;const ir=new Float32Array(16);o.bx(ir,an.projMatrix,dn),Ps(an,Cn,Cr,y.translatePosMatrix(ir,mn,Gt,gs),zs)}}}function pg(I,y,C,R,$,G,Z){R.centroidVertexArray.length===0&&R.createCentroidsBuffer();const te=G?G.findDEMTileFor(C):null;if(!(te&&te.dem||Z))return;G&&te&&te.dem&&R.selfDEMTileTimestamp!==te.dem._timestamp&&(R.borderDoneWithNeighborZ=[-1,-1,-1,-1],R.selfDEMTileTimestamp=te.dem._timestamp);const de=(ht,kt)=>{(ht.flags|kt.flags)&o.e3?(ht.flags|=o.e3,kt.flags|=o.e3):(ht.flags&=~o.e3,kt.flags&=~o.e3)},xe=ht=>new o.P(Math.ceil((ht+o.e4)*o.e5),0),we=(ht,kt,Tt)=>{const xt=Math.ceil((ht+o.e4)*o.e5),es=Math.floor(Math.max(0,Math.min(o.an-1,Tt))/4);return new o.P(xt,es<<5|(3&kt)<<3|7)},Re=ht=>{const kt=y.getSource().minzoom,Tt=es=>{const Ft=y.getTileByID(es);if(Ft&&Ft.hasData())return Ft.getBucket($)},xt=[0,-1,1];for(const es of xt){if(ht.overscaledZ+es(Le[0]=Math.min(ht.min.y,kt.min.y),Le[1]=Math.max(ht.max.y,kt.max.y),Le[2]=o.an-kt.min.x>ht.max.x?kt.min.x-o.an:ht.max.x,Le),st=(ht,kt)=>(Le[0]=Math.min(ht.min.x,kt.min.x),Le[1]=Math.max(ht.max.x,kt.max.x),Le[2]=o.an-kt.min.y>ht.max.y?kt.min.y-o.an:ht.max.y,Le),Je=[(ht,kt)=>Ue(ht,kt),(ht,kt)=>Ue(kt,ht),(ht,kt)=>st(ht,kt),(ht,kt)=>st(kt,ht)],mt=(ht,kt,Tt,xt,es,Ft,Qt)=>{if(!G)return 0;const At=[[Ft?Tt:ht,Ft?ht:Tt,0],[Ft?Tt:kt,Ft?kt:Tt,0]],Dt=Qt<0?o.an+Qt:Qt,Gt=[Ft?Dt:(ht+kt)/2,Ft?(ht+kt)/2:Dt,0];return Tt===0&&Qt<0||Tt!==0&&Qt>0?G.getForTilePoints(es,[Gt],!0,xt):At.push(Gt),G.getForTilePoints(C,At,!0,te),Math.max(At[0][2],At[1][2],Gt[2])/G.exaggeration()};for(let ht=0;ht<4;ht++){const kt=R.borderFeatureIndices[ht];if(kt.length===0)continue;const Tt=o.d$[ht](C),xt=Re(Tt);if(!(xt&&xt instanceof o.e0))continue;const es=G?G.findDEMTileFor(Tt):null;if(!(es&&es.dem||Z)||(G&&es&&es.dem&&R.borderDEMTileTimestamp[ht]!==es.dem._timestamp&&(R.borderDoneWithNeighborZ[ht]=-1,R.borderDEMTileTimestamp[ht]=es.dem._timestamp),R.borderDoneWithNeighborZ[ht]===xt.canonical.z))continue;xt.centroidVertexArray.length===0&&xt.createCentroidsBuffer();const Ft=(ht<2?1:5)-ht,Qt=xt.borderDoneWithNeighborZ[Ft]!==R.canonical.z,At=xt.borderFeatureIndices[Ft];let Dt=0;if(R.canonical.z!==xt.canonical.z){for(const $s of kt)R.showCentroid(R.featuresOnBorder[$s]);if(Qt)for(const $s of At)xt.showCentroid(xt.featuresOnBorder[$s]);R.borderDoneWithNeighborZ[ht]=xt.canonical.z,xt.borderDoneWithNeighborZ[Ft]=R.canonical.z;continue}const Gt=new Map,gs=new Set,ns=new Set;for(let $s=0;$s1||Ns.intersectsCount()>1;{let Sn=0;if(es&&es.dem&&!Rn){const Cn=Je[ht](an,hs),dn=ht%2?o.an-1:0;Sn=mt(Cn[0],Math.min(o.an-1,Cn[1]),dn,es,Tt,ht<2,Cn[2])}an.centroidXY=we(Sn,ht,Ys),hs.centroidXY=we(Sn,Ft,Ys)}if(R.writeCentroidToBuffer(an),xt.writeCentroidToBuffer(hs),Ps.buildingId!==void 0){for(const Sn of R.centroidData)Sn.buildingId===Ps.buildingId&&Sn!==an&&(Sn.centroidXY=an.centroidXY,R.writeCentroidToBuffer(Sn));for(const Sn of xt.centroidData)Sn.buildingId===Ps.buildingId&&Sn!==hs&&(Sn.centroidXY=hs.centroidXY,xt.writeCentroidToBuffer(Sn))}}for(const $s of kt){if(gs.has($s))continue;const Ps=R.featuresOnBorder[$s],an=R.centroidData[Ps.centroidDataIndex],mn=Ps.borders[ht];let Ns;for(;Dtmn[0]+3||hs[0]>mn[0]-3)break;xt.showCentroid(Ns),Dt++}if(Ns&&Dtmn[1]-3||(zs++,++Dt===At.length))break;Ns=xt.featuresOnBorder[At[Dt]]}for(;hs=At.length){R.showCentroid(Ps);continue}Ns=xt.featuresOnBorder[At[hs]];let Us=!1;if(zs>=1){const Sn=Ns.borders[Ft];Math.abs(mn[0]-Sn[0])<3&&Math.abs(mn[1]-Sn[1])<3&&(zs=1,Us=!0,Dt=hs+1)}else if(zs===0){R.showCentroid(Ps);continue}const Ys=xt.centroidData[Ns.centroidDataIndex];Z&&Us&&de(an,Ys);const Rn=Ps.intersectsCount()>1||Ns.intersectsCount()>1;if(zs>1)Dt=hs,an.centroidXY=Ys.centroidXY=new o.P(0,0);else if(es&&es.dem&&!Rn){const Sn=Je[ht](an,Ys),Cn=ht%2?o.an-1:0,dn=mt(Sn[0],Math.min(o.an-1,Sn[1]),Cn,es,Tt,ht<2,Sn[2]);an.centroidXY=Ys.centroidXY=xe(dn)}else Rn?an.centroidXY=Ys.centroidXY=new o.P(0,0):(an.centroidXY=R.encodeBorderCentroid(Ps),Ys.centroidXY=xt.encodeBorderCentroid(Ns));R.writeCentroidToBuffer(an),xt.writeCentroidToBuffer(Ys)}else R.showCentroid(Ps)}R.borderDoneWithNeighborZ[ht]=xt.canonical.z,xt.borderDoneWithNeighborZ[Ft]=R.canonical.z}(R.needsCentroidUpdate||!R.centroidVertexBuffer&&R.centroidVertexArray.length!==0)&&R.uploadCentroid(I)}const N1=[1,0,0],Dj=[0,1,0],Rj=[0,0,1];function kx(I,y,C){const R=C.transform,$=C.shadowRenderer;if(!$)return!0;const G=I.toUnwrapped(),Z=R.tileSize*$._cascades[C.currentShadowCascade].scale;let te=y;if(R.elevation){const st=R.elevation.getMinMaxForTile(I);st&&(te+=st.max)}const de=R.scaleZoom(Z);te/=o.e2(R.center.lat,de);const xe=[...$.shadowDirection];xe[2]=-xe[2];const we=$.computeSimplifiedTileShadowVolume(G,te,Z,xe);if(!we)return!1;const Re=[N1,Dj,Rj,xe,[xe[0],0,xe[2]],[0,xe[1],xe[2]]],Le=o.cl.fromInvProjectionMatrix(R.invProjMatrix,R.worldSize,de,R.projection.name!=="globe"),Ue=$.getCurrentCascadeFrustum();return Le.intersectsPrecise(we.vertices,we.planes,Re)===0||Ue.intersectsPrecise(we.vertices,we.planes,Re)===0}function Wy(I){const{painter:y,source:C,layer:R,coords:$}=I;let G=I.defines;const Z=y.context,te=y.renderPass==="shadow",de=y.renderPass==="light-beam",xe=y.shadowRenderer,we=o.e2(y.transform.center.lat,y.transform.zoom),Re=Bc(y,R.paint.get("building-cutoff-fade-range"));Re.shouldRenderCutoff&&(G=G.concat("RENDER_CUTOFF"));const Le=R.paint.get("building-front-cutoff"),Ue=Le[2]<1&&!y.terrain,st=d_(y.transform.pitch,Le,!!y.terrain);Ue&&(G=G.concat("RENDER_FRONT_CUTOFF"),y.maxFrontCutoffRawStart=Math.max(y.maxFrontCutoffRawStart,Le[0])),I.floodLightIntensity>0&&(G=G.concat("FLOOD_LIGHT"));for(const Je of $){const mt=C.getTile(Je),ht=mt.getBucket(R);if(!ht)continue;xe&&xe.getMaxCascadeForTile(Je.toUnwrapped())===0&&(G=G.concat("SHADOWS_SINGLE_CASCADE"));const kt=ht.programConfigurations.get(R.id);let Tt,xt,es,Ft=y.translatePosMatrix(Je.expandedProjMatrix,mt,[0,0],"map");if(Ft=o.cC(o.bb(),Ft,[1,1,I.verticalScale]),te&&xe){if(kx(mt.tileID,ht.maxHeight*we,y))continue;let At=xe.calculateShadowPassMatrixFromTile(mt.tileID.toUnwrapped());At=o.cC(o.bb(),At,[1,1,I.verticalScale]),es=l_(At),Tt=xt=y.getOrCreateProgram("buildingDepth",{config:kt,defines:G,overrideFog:!1})}else if(de)Tt=xt=y.getOrCreateProgram("buildingBloom",{config:kt,defines:G,overrideFog:!1}),es=Mj(Ft);else{const At=y.transform.calculatePosMatrix(Je.toUnwrapped(),y.transform.worldSize);o.cC(At,At,[1,1,I.verticalScale]);const Dt=o.bb();o.cC(Dt,At,[1,-1,1/we]),o.b7(Dt,Dt),o.e6(Dt,Dt);const Gt=y.transform.getFreeCameraOptions().position,gs=1<{if(de){const Gt=At.entranceBloom;Dt.draw(y,Z.gl.TRIANGLES,I.depthMode,oa.disabled,I.blendMode,Rr.disabled,es,R.id,Gt.layoutVertexBuffer,Gt.indexBuffer,Gt.segmentsBucket,R.paint,y.transform.zoom,kt,[Gt.layoutAttenuationBuffer,Gt.layoutColorBuffer])}else{const Gt=At.segmentsBucket;let gs=[At.layoutNormalBuffer,At.layoutCentroidBuffer,At.layoutColorBuffer,At.layoutFloodLightDataBuffer];At.layoutFacadePaintBuffer&&(gs=gs.concat([At.layoutFacadeDataBuffer,At.layoutFacadeVerticalRangeBuffer,At.layoutFacadePaintBuffer])),Dt.draw(y,Z.gl.TRIANGLES,I.depthMode,oa.disabled,I.blendMode,te?Rr.disabled:Rr.backCW,es,R.id,At.layoutVertexBuffer,At.indexBuffer,Gt,R.paint,y.transform.zoom,kt,gs)}};y.uploadCommonUniforms(Z,xt,Je.toUnwrapped(),null,Re),ht.buildingWithoutFacade&&Qt(ht.buildingWithoutFacade,xt),ht.buildingWithFacade&&(Tt!==xt&&y.uploadCommonUniforms(Z,Tt,Je.toUnwrapped(),null,Re),Qt(ht.buildingWithFacade,Tt))}}function fg(I,y,C,R,$,G,Z,te,de,xe,we,Re,Le,Ue){const st=I.context.gl,Je=I.depthModeForSublayer(1,ar.ReadOnly,st.LEQUAL,!0),mt=.1*(1-(ht=we))+3*ht;var ht;const kt=I._showOverdrawInspector,Tt=Re,xt=new qh;kt||zf(xt,I,y,C,R,Je,new oa({func:st.ALWAYS,mask:255},255,255,st.KEEP,st.KEEP,st.REPLACE),new sa([st.ONE,st.ONE,st.ONE,st.ONE],o.aq.transparent,[!1,!1,!1,!0],st.MIN),Rr.disabled,$,"sdf",G,Z,te,de,xe,mt,Tt,!1,void 0);{const es=kt?oa.disabled:new oa({func:st.EQUAL,mask:255},255,255,st.KEEP,st.DECR,st.DECR),Ft=kt?I.colorModeForRenderPass():new sa([st.ONE_MINUS_DST_ALPHA,st.DST_ALPHA,st.ONE,st.ONE],o.aq.transparent,[!0,!0,!0,!0]);zf(xt,I,y,C,R,Je,es,Ft,Rr.disabled,$,"color",G,Z,te,de,xe,mt,Tt,!1,void 0)}}function u_(I){return[I[0]*o.e7,I[1]*o.e7,I[2]*o.e7,0]}function Ky(I,y,C,R,$,G,Z,te,de){const xe=R.getSource(),we=C.globeSharedBuffers;if(!we)return;let Re,Le,Ue;if(y&&(Re=R.getTile(y)),xe instanceof o.aV?(Le=xe.texture,Ue=o.dw(0,0,C.transform)):Re&&y&&(Le=Re.texture,Ue=o.dw(y.canonical.z,y.canonical.x,C.transform)),!Le||!Ue)return;I||(Ue=o.cC(o.bb(),Ue,[1,-1,1]));const st=C.context,Je=st.gl,mt=$.paint.get("raster-resampling")==="nearest"?Je.NEAREST:Je.LINEAR,ht=C.colorModeForDrapableLayerRenderPass(G),kt=Z.defines;kt.push("GLOBE_POLES");const Tt=new ar(Je.LEQUAL,ar.ReadWrite,C.depthRangeFor3D),xt=Float32Array.from(C.transform.expandedFarZProjMatrix),es=Float32Array.from(o.du(o.dv(new o.cn(0,0,0))));C.terrain&&C.terrain.prepareDrawTile(),st.activeTexture.set(Je.TEXTURE0),Le.bind(mt,Je.CLAMP_TO_EDGE),st.activeTexture.set(Je.TEXTURE1),Le.bind(mt,Je.CLAMP_TO_EDGE),"useMipmap"in Le&&st.extTextureFilterAnisotropic&&C.transform.pitch>20&&Je.texParameterf(Je.TEXTURE_2D,st.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,st.extTextureFilterAnisotropicMax);const[Ft,Qt,At,Dt]=y?we.getPoleBuffers(y.canonical.z,!1):we.getPoleBuffers(0,!0),Gt=$.paint.get("raster-elevation");let gs;I?(gs=Ft,C.renderDefaultNorthPole=Gt!==0):(gs=Qt,C.renderDefaultSouthPole=Gt!==0);const ns=u_(Z.mix),$s=((an,mn,Ns,hs,zs,Us,Ys,Rn,Sn,Cn,dn,mr,Cr,ir)=>bx(an,mn,Ns,hs,new Float32Array(16),new Float32Array(9),[0,0],zs,[0,0],[0,0,0,0],1,{opacity:1,mix:0},Ys,[0,0],Sn,2,dn,mr,Cr,1,0,ir))(C,xt,es,Ue,o.al(C.transform.zoom),0,$,0,Gt,0,ns,Z.offset,Z.range,G),Ps=C.getOrCreateProgram("raster",{defines:kt});C.uploadCommonUniforms(st,Ps,null),Ps.draw(C,Je.TRIANGLES,Tt,de,ht,te,$s,$.id,gs,At,Dt)}function Oj(I){if(I.isOrthographic)return[0,0,0,0];const y=I._nearZ,C=I.projection.farthestPixelDistance(I),R=C-y,$=.2*I.height,G=y+$;return[y,C,(G-$-y)/R,(G-y)/R]}function Fj(I,y,C,R){if(I)return y instanceof fm&&I instanceof Fh?y.getTextureDescriptor(I,C,!0):{texture:I.texture,mix:u_(R.mix),offset:R.offset,buffer:0,tileSize:1}}var h_=o.e8([{name:"a_index",type:"Int16",components:1}]);class bh{constructor(y,C,R,$){const G={width:R[0],height:R[1],data:null},Z=y.gl;this.targetColorTexture=new o.T(y,G,Z.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new o.T(y,G,Z.RGBA8,{useMipmap:!1}),this.context=y,this.updateParticleTexture(C,$),this.lastInvalidatedAt=0}updateParticleTexture(y,C){if(this.particleTextureDimension===C.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const R=this.context.gl,$=C.width*C.height;this.particleTexture0=new o.T(this.context,C,R.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new o.T(this.context,C,R.RGBA8,{premultiply:!1,useMipmap:!1});const G=new o.e9;G.reserve($);for(let Z=0;Z<$;Z++)G.emplaceBack(Z);this.particleIndexBuffer=this.context.createVertexBuffer(G,h_.members,!0),this.particleSegment=o.dy.simpleSegment(0,0,this.particleIndexBuffer.length,0),this.particleTextureDimension=C.width}update(y){return!(this.lastInvalidatedAt0){const ns=o.ec(C.canonical,de),$s=o.ed(ns);Le=o.aD(new Float32Array(16),de.globeMatrix,$s),o.aD(Le,de.projMatrix,Le)}const Ue=o.bb();Ue[12]+=2*$/(o.o.devicePixelRatio*de.width),Ue[13]+=2*G/(o.o.devicePixelRatio*de.height),o.aD(Le,Ue,Le);const st=I.getOrCreateProgram("debug",{defines:Re}),Je=y.getTileByID(C.key);I.terrain&&I.terrain.setupElevationDraw(Je,st);const mt=ar.disabled,ht=oa.disabled,kt=I.colorModeForRenderPass(),Tt="$debug";te.activeTexture.set(xe.TEXTURE0),I.emptyTexture.bind(xe.LINEAR,xe.CLAMP_TO_EDGE),we?Je._makeGlobeTileDebugBuffers(I.context,de):Je._makeDebugTileBoundsBuffers(I.context,de.projection);const xt=Je._tileDebugBuffer||I.debugBuffer,es=Je._tileDebugIndexBuffer||I.debugIndexBuffer,Ft=Je._tileDebugSegments||I.debugSegments;if(st.draw(I,xe.LINE_STRIP,mt,ht,kt,Rr.disabled,wm(Le,R.toPremultipliedRenderColor(null)),Tt,xt,es,Ft,null,null,null,[Je._globeTileDebugBorderBuffer]),Z){const ns=Je.latestRawTileData,$s=Math.floor((ns&&ns.byteLength||0)/1024);let Ps=C.canonical.toString();C.overscaledZ!==C.canonical.z&&(Ps+=` => ${C.overscaledZ}`),Ps+=` ${Je.state}`,Ps+=` ${$s}kb`,function(an,mn){an.initDebugOverlayCanvas();const Ns=an.debugOverlayCanvas,hs=an.context.gl,zs=an.debugOverlayCanvas.getContext("2d");zs.clearRect(0,0,Ns.width,Ns.height),zs.shadowColor="white",zs.shadowBlur=2,zs.lineWidth=1.5,zs.strokeStyle="white",zs.textBaseline="top",zs.font="bold 36px Open Sans, sans-serif",zs.fillText(mn,5,5),zs.strokeText(mn,5,5),an.debugOverlayTexture.update(Ns),an.debugOverlayTexture.bind(hs.LINEAR,hs.CLAMP_TO_EDGE)}(I,Ps)}const Qt=y.getTile(C).tileSize,At=512/Math.min(Qt,512)*(C.overscaledZ/de.zoom)*.5,Dt=Je._tileDebugTextBuffer||I.debugBuffer,Gt=Je._tileDebugTextIndexBuffer||I.quadTriangleIndexBuffer,gs=Je._tileDebugTextSegments||I.debugSegments;st.draw(I,xe.TRIANGLES,mt,ht,sa.alphaBlended,Rr.disabled,wm(Le,o.aq.transparent.toPremultipliedRenderColor(null),At),Tt,Dt,Gt,gs,null,null,null,[Je._globeTileDebugTextBuffer])}function PC(I,y,C,R){gg(I,0,y+C/2,I.transform.width,C,R)}function zj(I,y,C,R){gg(I,y-C/2,0,C,I.transform.height,R)}function gg(I,y,C,R,$,G){const Z=I.context,te=Z.gl;te.enable(te.SCISSOR_TEST),te.scissor(y*o.o.devicePixelRatio,C*o.o.devicePixelRatio,R*o.o.devicePixelRatio,$*o.o.devicePixelRatio),Z.clear({color:G}),te.disable(te.SCISSOR_TEST)}const k6=o.e8([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:jm}=k6;function Bf(I,y,C,R){I.emplaceBack(y,C,R)}class Wd{constructor(y){this.vertexArray=new o.ee,this.indices=new o.dC,Bf(this.vertexArray,-1,-1,1),Bf(this.vertexArray,1,-1,1),Bf(this.vertexArray,-1,1,1),Bf(this.vertexArray,1,1,1),Bf(this.vertexArray,-1,-1,-1),Bf(this.vertexArray,1,-1,-1),Bf(this.vertexArray,-1,1,-1),Bf(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=y.createVertexBuffer(this.vertexArray,jm),this.indexBuffer=y.createIndexBuffer(this.indices),this.segment=o.dy.simpleSegment(0,0,36,12)}}function Hp(I,y,C,R,$,G){const Z=I.context.gl,te=y.paint.get("sky-atmosphere-color"),de=y.paint.get("sky-atmosphere-halo-color"),xe=y.paint.get("sky-atmosphere-sun-intensity"),we=((Re,Le,Ue,st,Je)=>({u_matrix_3f:Re,u_sun_direction:Le,u_sun_intensity:Ue,u_color_tint_r:[st.r,st.g,st.b,st.a],u_color_tint_m:[Je.r,Je.g,Je.b,Je.a],u_luminance:5e-5}))(o.eg(o.dE(),R),$,xe,te.toPremultipliedRenderColor(null),de.toPremultipliedRenderColor(null));Z.framebufferTexture2D(Z.FRAMEBUFFER,Z.COLOR_ATTACHMENT0,Z.TEXTURE_CUBE_MAP_POSITIVE_X+G,y.skyboxTexture,0),C.draw(I,Z.TRIANGLES,ar.disabled,oa.disabled,sa.unblended,Rr.frontCW,we,"skyboxCapture",y.skyboxGeometry.vertexBuffer,y.skyboxGeometry.indexBuffer,y.skyboxGeometry.segment)}const S6=o.e8([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class JN{constructor(y){const C=new o.eh;C.emplaceBack(-1,1,1,0,0),C.emplaceBack(1,1,1,1,0),C.emplaceBack(1,-1,1,1,1),C.emplaceBack(-1,-1,1,0,1);const R=new o.dC;R.emplaceBack(0,1,2),R.emplaceBack(2,3,0),this.vertexBuffer=y.createVertexBuffer(C,S6.members),this.indexBuffer=y.createIndexBuffer(R),this.segments=o.dy.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const ek=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 k0{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class C6{constructor(y){this.colorModeAlphaBlendedWriteRGB=new sa([1,Ml,1,Ml],o.aq.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new sa([1,0,1,0],o.aq.transparent,[!1,!1,!1,!0]),this.params=new k0,this.updateNeeded=!0}update(y){const C=y.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new JN(C);const R=this.params.sizeRange,$=this.params.intensityRange,G=function(we){const Re=o.em(30),Le=[];for(let Ue=0;Ue{const At=G.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Qt&&At.push("ALPHA_PASS");const Dt=y.getOrCreateProgram("globeAtmosphere",{defines:At}),Gt=((ns,$s,Ps,an,mn,Ns,hs,zs,Us,Ys,Rn,Sn)=>({u_frustum_tl:ns,u_frustum_tr:$s,u_frustum_br:Ps,u_frustum_bl:an,u_horizon:mn,u_transition:Ns,u_fadeout_range:hs,u_atmosphere_fog_color:zs.toArray01(),u_high_color:Us.toArray01(),u_space_color:Ys.toArray01(),u_temporal_offset:Rn,u_horizon_angle:Sn}))(G.frustumCorners.TL,G.frustumCorners.TR,G.frustumCorners.BR,G.frustumCorners.BL,G.frustumCorners.horizon,te,mt,we,Le,st,kt,es);y.uploadCommonUniforms(R,Dt);const gs=this.atmosphereBuffer;gs&&Dt.draw(y,$.TRIANGLES,Z,oa.disabled,Qt?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,Rr.backCW,Gt,Qt?"atmosphere_glow_alpha":"atmosphere_glow",gs.vertexBuffer,gs.indexBuffer,gs.segments)};Ft(!1),Ft(!0)}drawStars(y,C){const R=o.aC(C.properties.get("star-intensity"),0,1);if(R===0)return;const $=y.context,G=$.gl,Z=y.transform,te=y.getOrCreateProgram("stars"),de=o.bL([]);o.bN(de,de,-Z._pitch),o.bM(de,de,-Z.angle),o.bN(de,de,o.ap(Z._center.lat)),o.ek(de,de,-o.ap(Z._center.lng));const xe=o.bR(new Float32Array(16),de),we=o.aD([],Z.starsProjMatrix,xe),Re=o.eg([],xe),Le=o.el([],Re),Ue=[0,1,0];o.dG(Ue,Ue,Le),o.bJ(Ue,Ue,this.params.sizeMultiplier);const st=[1,0,0];o.dG(st,st,Le),o.bJ(st,st,this.params.sizeMultiplier);const Je=(mt=Ue,ht=st,kt=R,{u_matrix:Float32Array.from(we),u_up:mt,u_right:ht,u_intensity_multiplier:kt});var mt,ht,kt;y.uploadCommonUniforms($,te),this.starsVx&&this.starsIdx&&te.draw(y,G.TRIANGLES,ar.disabled,oa.disabled,this.colorModeAlphaBlendedWriteRGB,Rr.disabled,Je,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class Nm{constructor(){this.visibleTiles=[]}updateBorders(y,C){const R=[],$=[],G=y._getRenderableCoordinates(!1,!0);for(const de of G){const xe=y.getTile(de);if(!xe.hasData())continue;const we=xe.getBucket(C);we&&(we.isEmpty()||(R.push(de.key),$.push({bucket:we,tileID:de.canonical})))}let Z=R.length!==this.visibleTiles.length;if(!Z){R.sort();for(let de=0;dede.tileID.z-xe.tileID.z||de.tileID.x-xe.tileID.x||de.tileID.y-xe.tileID.y);for(const de of $){const xe=new Array,we=new Array,Re=de.bucket;for(const Le of Re.featuresOnBorder)te.has(Le.featureId)?we.push(Le.footprintIndex):(te.add(Le.featureId),xe.push(Le.footprintIndex));Re.updateFootprintHiddenFlags(xe,o.en,!1),Re.updateFootprintHiddenFlags(we,o.en,!0)}}}function LC(I,y){const C=[...I],R=y.cameraWorldSizeForFog/y.worldSize,$=o.b9([]);return o.cC($,$,[R,R,1]),o.aD(C,$,C),o.aD(C,y.worldToFogMatrix,C),C}function La(I,y,C,R,$){const G=C.material,Z=R.context,{baseColorTexture:te,metallicRoughnessTexture:de}=G.pbrMetallicRoughness,{normalTexture:xe,occlusionTexture:we,emissionTexture:Re}=G;function Le(st,Je,mt){if(st&&(I.push(Je),Z.activeTexture.set(Z.gl.TEXTURE0+mt),st.gfxTexture)){const{minFilter:ht,magFilter:kt,wrapS:Tt,wrapT:xt}=st.sampler;st.gfxTexture.bindExtraParam(ht,kt,Tt,xt)}}Le(te,"HAS_TEXTURE_u_baseColorTexture",5),Le(de,"HAS_TEXTURE_u_metallicRoughnessTexture",6),Le(xe,"HAS_TEXTURE_u_normalTexture",7),Le(we,"HAS_TEXTURE_u_occlusionTexture",8),Le(Re,"HAS_TEXTURE_u_emissionTexture",9),$&&($.texture||($.texture=new o.dR(R.context,$.image,[$.image.height,$.image.height,$.image.height],Z.gl.RGBA8)),Z.activeTexture.set(Z.gl.TEXTURE0+10),$.texture&&$.texture.bind(Z.gl.LINEAR,Z.gl.CLAMP_TO_EDGE),I.push("APPLY_LUT_ON_GPU")),C.texcoordBuffer&&(I.push("HAS_ATTRIBUTE_a_uv_2f"),y.push(C.texcoordBuffer)),C.colorBuffer&&(I.push(C.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),y.push(C.colorBuffer)),C.normalBuffer&&(I.push("HAS_ATTRIBUTE_a_normal_3f"),y.push(C.normalBuffer)),C.pbrBuffer&&(I.push("HAS_ATTRIBUTE_a_pbr"),I.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),y.push(C.pbrBuffer)),G.alphaMode!=="OPAQUE"&&G.alphaMode!=="MASK"||I.push("UNPREMULT_TEXTURE_IN_SHADER"),G.defined||I.push("DIFFUSE_SHADED");const Ue=R.shadowRenderer;Ue&&(I.push("RENDER_SHADOWS"),Ue.useNormalOffset&&I.push("NORMAL_OFFSET"))}function m_(I,y,C,R,$,G){const Z=I.modelOpacity,te=y.context,de=new ar(y.context.gl.LEQUAL,I.isLightMesh?ar.ReadOnly:ar.ReadWrite,y.depthRangeFor3D),xe=y.transform,we=I.mesh,Re=we.material,Le=Re.pbrMetallicRoughness,Ue=y.style.fog;let st;st=y.transform.projection.zAxisUnit==="pixels"?[...I.nodeModelMatrix]:o.aD([],R.zScaleMatrix,I.nodeModelMatrix),o.aD(st,R.negCameraPosMatrix,st);const Je=o.b7([],st);o.e6(Je,Je);const mt=C.paint.get("model-color-use-theme").constantOr("default")==="none",ht=C.paint.get("model-emissive-strength").constantOr(0),kt=jx(new Float32Array(I.worldViewProjection),new Float32Array(st),new Float32Array(Je),null,y,Z,Le.baseColorFactor,Re.emissiveFactor,Le.metallicFactor,Le.roughnessFactor,Re,ht,C,void 0,void 0,I.materialOverride,I.modelColor),Tt={defines:[]},xt=[],es=y.shadowRenderer;es&&(es.useNormalOffset=!1),La(Tt.defines,xt,we,y,mt?null:C.lut);let Ft=null;if(Ue){const Dt=LC(I.nodeModelMatrix,y.transform);if(Ft=new Float32Array(Dt),xe.projection.name!=="globe"){const Gt=we.aabb.min,gs=we.aabb.max,[ns,$s]=Ue.getOpacityForBounds(Dt,Gt[0],Gt[1],gs[0],gs[1]);Tt.overrideFog=ns>=sr||$s>=sr}}const Qt=Bc(y,C.paint.get("model-cutoff-fade-range"));Qt.shouldRenderCutoff&&Tt.defines.push("RENDER_CUTOFF");const At=y.getOrCreateProgram("model",Tt);y.uploadCommonUniforms(te,At,null,Ft,Qt),y.renderPass!=="shadow"&&es&&es.setupShadowsFromMatrix(I.nodeModelMatrix,At),At.draw(y,te.gl.TRIANGLES,de,$,G,we.material.doubleSided?Rr.disabled:Rr.backCCW,kt,C.id,we.vertexBuffer,we.indexBuffer,we.segments,C.paint,y.transform.zoom,void 0,xt)}function Bj(I,y){return I.style._importedAsBasemap?"basemap":y.scope}function tk(I,y,C,R,$,G,Z,te,de,xe){const we=I.transform,Re=!!y.isGeometryBloom&&y.isGeometryBloom;if(Re&&I.renderPass==="shadow")return;const Le=we.projection.name==="globe"?o.ev(C,we):[...C];o.aD(Le,Le,y.globalMatrix);const Ue=o.aD([],R,Le);if(y.meshes)for(const st of y.meshes){const Je=te.get(st.material.name);if(Je&&Je.opacity<=0)continue;if(st.material.alphaMode!=="BLEND"){Z.push({mesh:st,depth:0,modelIndex:$,worldViewProjection:Ue,nodeModelMatrix:Le,isLightMesh:Re,materialOverride:Je,modelOpacity:de,modelColor:xe,node:y,modelMatrix:C});continue}const mt=o.ah([],st.centroid,Ue);!we.isOrthographic&&mt[2]<=0||G.push({mesh:st,depth:mt[2],modelIndex:$,worldViewProjection:Ue,nodeModelMatrix:Le,isLightMesh:Re,materialOverride:Je,modelOpacity:de,modelColor:xe,node:y,modelMatrix:C})}if(y.children)for(const st of y.children)tk(I,st,C,R,$,G,Z,te,de,xe)}function p_(I,y,C,R){const $=C.shadowRenderer;if(!$)return;const G=$.getShadowPassDepthMode(),Z=$.calculateShadowPassMatrixFromMatrix(y),te=Pj(Z);C.getOrCreateProgram("modelDepth").draw(C,C.context.gl.TRIANGLES,G,oa.disabled,sa.disabled,Rr.disabled,te,R.id,I.vertexBuffer,I.indexBuffer,I.segments,R.paint,C.transform.zoom,void 0,void 0)}function sk(I,y,C,R){const $=function(we,Re){if(Re.footprintDebugMesh)return Re.footprintDebugMesh;if(!Re.footprint)return null;const Le=we.context,Ue=Re.footprint.vertices,st=Re.footprint.indices,Je=new o.dB;Je.reserve(Ue.length);for(const Gt of Ue)Je.emplaceBack(Gt.x,Gt.y);const mt=new o.dC;mt.reserve(st.length);for(let Gt=0;Gt0){const Le=G.terrain,Ue=Le.findDEMTileFor(te);Ue&&Ue.dem?de=o.ex.create(Le,te,Ue):Re=0}if(Re===0&&(Z.terrainElevationMin=0,Z.terrainElevationMax=0),Re===Z.validForExaggeration&&(Re===0||de&&de._demTile&&de._demTile.tileID===Z.validForDEMTile.id&&de._dem._timestamp===Z.validForDEMTile.timestamp))return!1;for(const Le in Z.instancesPerModel){const Ue=Z.instancesPerModel[Le];for(let st=0;stxe&&(xe=Ue.max)}const we=o.aC(R.x,G,Z)-R.x,Re=o.aC(R.y,te,de)-R.y,Le=o.bU(xe,y.center.lat)-R.z;return y._zoomFromMercatorZ(Math.sqrt(we*we+Re*Re+Le*Le))}function Wo(I,y,C,R,$,G,Z){const te=I.context,de=I.renderPass==="shadow",xe=I.shadowRenderer,we=de&&xe?xe.getShadowPassDepthMode():new ar(te.gl.LEQUAL,ar.ReadWrite,I.depthRangeFor3D),Re=I.isTileAffectedByFog(G),Le=I.transform.projection.name==="globe";if(C.meshes)for(const Ue of C.meshes){const st=Le?[]:["MODEL_POSITION_ON_GPU"],Je=[];let mt,ht,kt;const Tt=!Le&&R.instancedDataArray.length>20;Tt&&st.push("INSTANCED_ARRAYS");const xt=Bc(I,y.paint.get("model-cutoff-fade-range"));if(xt.shouldRenderCutoff&&st.push("RENDER_CUTOFF"),de&&xe)mt=I.getOrCreateProgram("modelDepth",{defines:st}),ht=Pj(Z.shadowTileMatrix,Z.shadowTileMatrix,Float32Array.from(C.globalMatrix)),kt=sa.disabled;else{La(st,Je,Ue,I,y.paint.get("model-color-use-theme").constantOr("default")==="none"?null:y.lut),mt=I.getOrCreateProgram("model",{defines:st,overrideFog:Re});const Ft=Ue.material,Qt=Ft.pbrMetallicRoughness,At=y.paint.get("model-opacity").constantOr(1),Dt=y.paint.get("model-emissive-strength").constantOr(0);ht=jx(G.expandedProjMatrix,Float32Array.from(C.globalMatrix),new Float32Array(16),null,I,At,Qt.baseColorFactor,Ft.emissiveFactor,Qt.metallicFactor,Qt.roughnessFactor,Ft,Dt,y,$),xe&&(Z.shadowUniformsInitialized?mt.setShadowUniformValues(te,xe.getShadowUniformValues()):(xe.setupShadows(G.toUnwrapped(),mt,"model-tile"),Z.shadowUniformsInitialized=!0)),kt=xt.shouldRenderCutoff||At<1||Ft.alphaMode!=="OPAQUE"?sa.alphaBlended:sa.unblended}I.uploadCommonUniforms(te,mt,G.toUnwrapped(),null,xt);const es=Ue.material.doubleSided?Rr.disabled:Rr.backCCW;if(Tt)Je.push(R.instancedDataBuffer),mt.draw(I,te.gl.TRIANGLES,we,oa.disabled,kt,es,ht,y.id,Ue.vertexBuffer,Ue.indexBuffer,Ue.segments,y.paint,I.transform.zoom,void 0,Je,R.instancedDataArray.length);else{const Ft=de?"u_instance":"u_normal_matrix";for(let Qt=0;Qtde[1]?Z:de,G[0]=C.max[0],Z=o.aE(o.bE(),G,$),te=Z[1]de[1]?Z:de,G[1]=C.min[1],Z=o.aE(o.bE(),G,$),te=Z[1]de[1]?Z:de;const xe=o.aC(R[0],0,1),we=100*y.pixelsPerMeter*o.aC(R[1],0,1),Re=o.aC(R[2],0,1),Le=o.ey(o.bE(),te,de,xe),Ue=Math.tan(.5*y.fovX),st=-Le[2]*Ue;if(we===0)return Le[1]<-Math.abs(st)?Re:1;const Je=(-Math.abs(st)-Le[1])/we,mt=(kt,Tt,xt)=>(1-xt)*kt+xt*Tt,ht=o.aC(mt(1,Re,Je),Re,1);return mt(1,ht,o.aC((y.pitch-20)/20,0,1))}class rk{}class DC{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(y,C,R){{const Re=this._storage.get(C.id);if(Re)return Re.lastUsedFrameIdx=y,Re.buf}const $=R.gl,G=$.getBufferParameter($.ELEMENT_ARRAY_BUFFER,$.BUFFER_SIZE),Z=new ArrayBuffer(G),te=new Int16Array(Z);$.getBufferSubData($.ELEMENT_ARRAY_BUFFER,0,new Int16Array(Z));const de=new o.eA;for(let Re=0;Re30&&(R.buf.destroy(),this._storage.delete(C))}destroy(){for(const[y,C]of this._storage)C.buf.destroy(),this._storage.delete(y)}}class RC{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const S1=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 OC{constructor(y){this.revealStart=11,this.revealRange=2}}const ak=o.e8([{type:"Float32",name:"a_pos_2f",components:2}]);class T6{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(y,C){const R=y.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const Z=new o.eB,te=new o.dC;Z.emplaceBack(-1,-1),Z.emplaceBack(1,-1),Z.emplaceBack(1,1),Z.emplaceBack(-1,1),te.emplaceBack(0,1,2),te.emplaceBack(0,2,3),this.vignetteVx=y.context.createVertexBuffer(Z,ak.members),this.vignetteIdx=y.context.createIndexBuffer(te)}const $=o.dy.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){y.uploadCommonUniforms(y.context,R);const Z={u_vignetteShape:(G={vignetteShape:[C.start,C.range,Math.pow(10,C.fadePower)],vignetteColor:[C.color.r,C.color.g,C.color.b,C.color.a*C.strength]}).vignetteShape,u_vignetteColor:G.vignetteColor};R.draw(y,y.context.gl.TRIANGLES,ar.disabled,oa.disabled,sa.alphaBlended,Rr.disabled,Z,"vignette",this.vignetteVx,this.vignetteIdx,$)}var G}}class ik{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(y,C){const R=y.getFreeCameraOptions().position,$=R.toAltitude(),G=R.toLngLat(),Z=o.ap(G.lng),te=o.ap(G.lat),de=y.pixelsPerMeter/C,xe=Z*o.eD,we=o.eD*Math.log(Math.tan(Math.PI/4+te/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 Re=-this._offsetYPrev+we,Le=-this._elevationPrev+$;this._accumulatedOffsetX+=(-this._offsetXPrev+xe)*de,this._accumulatedOffsetY+=Re*de,this._accumulatedElevation+=Le*de,this._offsetXPrev=xe,this._offsetYPrev=we,this._elevationPrev=$}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function Q(I,y){return[-(I[0]-Math.floor(I[0]/y)*y),-(I[1]-Math.floor(I[1]/y)*y),-(I[2]-Math.floor(I[2]/y)*y)]}function ee(I){const y=o.em(1323123451230),C=[];for(let R=0;R Rain"),this._vignetteParams={strength:1,start:.7,range:1,fadePower:.4,color:{r:.27,g:.27,b:.27,a:1}},this.particlesCount=16e3}update(y){const C=y.context;if(!this.particlesVx){const R=ee(this.particlesCount),$=new o.eE,G=new o.dC;let Z=0;const te=o.em(1323123451230);for(let de=0;deR)return;const $=ke(0,1,C.revealStart,C.revealStart+C.revealRange,R);if(!this.particlesVx||!this.particlesIdx)return;const G=structuredClone(this._params);let Z=[-G.direction.x,G.direction.y,-100];o.ay(Z,Z);const te=structuredClone(this._vignetteParams);te.strength*=$,G.overrideStyleParameters||(G.intensity=y.style.rain.state.density,G.timeFactor=y.style.rain.state.intensity,G.color=structuredClone(y.style.rain.state.color),Z=structuredClone(y.style.rain.state.direction),G.screenThinning.intensity=y.style.rain.state.centerThinning,G.dropletSizeX=y.style.rain.state.dropletSize[0],G.dropletSizeYScale=y.style.rain.state.dropletSize[1]/y.style.rain.state.dropletSize[0],G.distortionStrength=100*y.style.rain.state.distortionStrength,te.strength=1,te.color=structuredClone(y.style.rain.state.vignetteColor));const de=this.updateOnRender(y,G.timeFactor),xe=y.context,we=xe.gl,Re=y.transform;this.screenTexture&&this.screenTexture.size[0]===y.width&&this.screenTexture.size[1]===y.height||(this.screenTexture=new o.T(xe,{width:y.width,height:y.height,data:null},we.RGBA8)),G.distortionStrength>0&&(xe.activeTexture.set(we.TEXTURE0),this.screenTexture.bind(we.LINEAR,we.CLAMP_TO_EDGE),we.copyTexSubImage2D(we.TEXTURE_2D,0,0,0,0,0,y.width,y.height));const Le=y.getOrCreateProgram("rainParticle");y.uploadCommonUniforms(xe,Le),xe.activeTexture.set(we.TEXTURE0),this.screenTexture.bind(we.LINEAR,we.CLAMP_TO_EDGE);const Ue=[G.color.r,G.color.g,G.color.b,G.color.a],st=(Je,mt)=>{const ht=Q(this._movement.getPosition(),Je),kt=G.dropletSizeX,Tt=G.dropletSizeX*G.dropletSizeYScale,xt=y.width/2,es=y.height/2,Ft=ke(0,G.screenThinning.start,0,1,G.screenThinning.intensity),Qt=ke(.001,G.screenThinning.range,0,1,G.screenThinning.intensity),At=ke(0,G.screenThinning.particleOffset,0,1,G.screenThinning.intensity),Dt=(Gt={modelview:de.modelviewMatrix,projection:de.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:ht,velocityConeAperture:G.velocityConeAperture,velocity:G.velocity,boxSize:Je,rainDropletSize:[kt,Tt],distortionStrength:G.distortionStrength,rainDirection:Z,color:Ue,screenSize:[Re.width,Re.height],thinningCenterPos:[xt,es],thinningShape:[Ft,Qt,Math.pow(10,G.screenThinning.fadePower)],thinningAffectedRatio:G.screenThinning.affectedRatio,thinningParticleOffset:At,shapeDirectionalPower:G.shapeDirPower,shapeNormalPower:G.shapeNormalPower,mode:mt?0:1},{u_modelview:Float32Array.from(Gt.modelview),u_projection:Float32Array.from(Gt.projection),u_time:Gt.time,u_cam_pos:Gt.camPos,u_texScreen:0,u_velocityConeAperture:Gt.velocityConeAperture,u_velocity:Gt.velocity,u_boxSize:Gt.boxSize,u_rainDropletSize:Gt.rainDropletSize,u_distortionStrength:Gt.distortionStrength,u_rainDirection:Gt.rainDirection,u_color:Gt.color,u_screenSize:Gt.screenSize,u_thinningCenterPos:Gt.thinningCenterPos,u_thinningShape:Gt.thinningShape,u_thinningAffectedRatio:Gt.thinningAffectedRatio,u_thinningParticleOffset:Gt.thinningParticleOffset,u_shapeDirectionalPower:Gt.shapeDirectionalPower,u_shapeNormalPower:Gt.shapeNormalPower,u_mode:Gt.mode});var Gt;const gs=Math.round(G.intensity*this.particlesCount),ns=o.dy.simpleSegment(0,0,4*gs,2*gs);Le.draw(y,we.TRIANGLES,ar.disabled,oa.disabled,sa.alphaBlended,Rr.disabled,Dt,"rain_particles",this.particlesVx,this.particlesIdx,ns)};G.distortionStrength>0&&st(G.boxSize,!0),st(G.boxSize,!1),this._vignette.draw(y,te)}}const yt=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 Ve{constructor(y){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 OC("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(y){const C=y.context;if(!this.particlesVx){const R=ee(this.particlesCount),$=new o.eF,G=new o.dC;let Z=0;const te=o.em(1323123451230);for(let de=0;deZ)return;const te=ke(0,1,G.revealStart,G.revealStart+G.revealRange,Z);$.strength*=te,C.overrideStyleParameters||(C.intensity=y.style.snow.state.density,C.timeFactor=y.style.snow.state.intensity,C.color=structuredClone(y.style.snow.state.color),R=structuredClone(y.style.snow.state.direction),C.screenThinning.intensity=y.style.snow.state.centerThinning,C.billboardSize=2.79*y.style.snow.state.flakeSize,$.strength=1,$.color=structuredClone(y.style.snow.state.vignetteColor));const de=this.updateOnRender(y,C.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const xe=y.context,we=xe.gl,Re=y.transform,Le=y.getOrCreateProgram("snowParticle");y.uploadCommonUniforms(xe,Le),((Ue,st,Je)=>{const mt=Q(this._movement.getPosition(),Ue),ht=Re.width/2,kt=Re.height/2,Tt=ke(0,Je.screenThinning.start,0,1,Je.screenThinning.intensity),xt=ke(.001,Je.screenThinning.range,0,1,Je.screenThinning.intensity),es=ke(0,Je.screenThinning.particleOffset,0,1,Je.screenThinning.intensity),Ft=(Qt={modelview:de.modelviewMatrix,projection:de.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:mt,velocityConeAperture:Je.velocityConeAperture,velocity:Je.velocity,horizontalOscillationRadius:Je.horizontalOscillationRadius,horizontalOscillationRate:Je.horizontalOscillationRate,boxSize:Ue,billboardSize:1*Je.billboardSize,simpleShapeParameters:[Je.shapeFadeStart,Je.shapeFadePower],screenSize:[Re.width,Re.height],thinningCenterPos:[ht,kt],thinningShape:[Tt,xt,Math.pow(10,Je.screenThinning.fadePower)],thinningAffectedRatio:Je.screenThinning.affectedRatio,thinningParticleOffset:es,color:[Je.color.r,Je.color.g,Je.color.b,Je.color.a],direction:R},{u_modelview:Float32Array.from(Qt.modelview),u_projection:Float32Array.from(Qt.projection),u_time:Qt.time,u_cam_pos:Qt.camPos,u_velocityConeAperture:Qt.velocityConeAperture,u_velocity:Qt.velocity,u_horizontalOscillationRadius:Qt.horizontalOscillationRadius,u_horizontalOscillationRate:Qt.horizontalOscillationRate,u_boxSize:Qt.boxSize,u_billboardSize:Qt.billboardSize,u_simpleShapeParameters:Qt.simpleShapeParameters,u_screenSize:Qt.screenSize,u_thinningCenterPos:Qt.thinningCenterPos,u_thinningShape:Qt.thinningShape,u_thinningAffectedRatio:Qt.thinningAffectedRatio,u_thinningParticleOffset:Qt.thinningParticleOffset,u_particleColor:Qt.color,u_direction:Qt.direction});var Qt;const At=Math.round(Je.intensity*this.particlesCount),Dt=o.dy.simpleSegment(0,0,4*At,2*At);this.particlesVx&&this.particlesIdx&&Le.draw(y,we.TRIANGLES,ar.disabled,oa.disabled,sa.alphaBlended,Rr.disabled,Ft,"snow_particles",this.particlesVx,this.particlesIdx,Dt)})(C.boxSize,0,C),this._vignette.draw(y,$)}}const pn={symbol:function(I,y,C,R,$){if(I.renderPass!=="translucent")return;const G=oa.disabled,Z=I.colorModeForRenderPass(),te=C.layout.get("text-variable-anchor"),de=C.layout.get("text-size-scale-range"),xe=o.aC(I.scaleFactor,de[0],de[1]);te&&function(Le,Ue,st,Je,mt,ht,kt,Tt){const xt=Ue.transform,es=mt==="map",Ft=ht==="map";for(const Qt of Le){const At=Je.getTile(Qt),Dt=At.getBucket(st);if(!Dt||!Dt.text||!Dt.text.segments.get().length)continue;const Gt=o.bj(Dt.textSizeData,xt.zoom,Tt),gs=ep(Qt,Dt.getProjection(),xt),ns=xt.calculatePixelsToTileUnitsMatrix(At),$s=Sd(gs,At.tileID.canonical,Ft,es,xt,Dt.getProjection(),ns),Ps=Dt.hasIconTextFit()&&Dt.hasIconData();Gt&&Zu(Dt,es,Ft,kt,xt,$s,Qt,Math.pow(2,xt.zoom-At.tileID.overscaledZ),Gt,Ps)}}(R,I,C,y,C.layout.get("text-rotation-alignment"),C.layout.get("text-pitch-alignment"),$,xe);const we=C.paint.get("icon-opacity").constantOr(1)!==0,Re=C.paint.get("text-opacity").constantOr(1)!==0;C.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(we||Re)?Uh(I,y,C,R,G,Z):(we&&Uh(I,y,C,R,G,Z,{onlyIcons:!0}),Re&&Uh(I,y,C,R,G,Z,{onlyText:!0})),y.map.showCollisionBoxes&&(Kn(I,y,C,R,C.paint.get("text-translate"),C.paint.get("text-translate-anchor"),!0),Kn(I,y,C,R,C.paint.get("icon-translate"),C.paint.get("icon-translate-anchor"),!1))},circle:function(I,y,C,R){if(I.renderPass!=="translucent")return;const $=C.paint.get("circle-opacity"),G=C.paint.get("circle-stroke-width"),Z=C.paint.get("circle-stroke-opacity"),te=C.layout.get("circle-sort-key").constantOr(1)!==void 0,de=C.paint.get("circle-emissive-strength");if($.constantOr(1)===0&&(G.constantOr(1)===0||Z.constantOr(1)===0))return;const xe=I.context,we=xe.gl,Re=I.transform,Le=!(!I.terrain||!I.terrain.enabled),Ue=C.layout.get("circle-elevation-reference"),st=I.depthModeForSublayer(0,ar.ReadOnly),Je=new ar(I.context.gl.LEQUAL,ar.ReadOnly,I.depthRangeFor3D),mt=Ue==="none"||Le?st:Je,ht=oa.disabled,kt=I.colorModeForDrapableLayerRenderPass(de),Tt=Re.projection.name==="globe",xt=[o.aH(Re.center.lng),o.aL(Re.center.lat)],es=[];for(let Qt=0;QtQt.sortKey-At.sortKey);const Ft={useDepthForOcclusion:Re.depthOcclusionForSymbolsAndCircles};for(const Qt of es){const{programConfiguration:At,program:Dt,layoutVertexBuffer:Gt,dynamicBuffers:gs,indexBuffer:ns,uniformValues:$s,tile:Ps}=Qt.state,an=Qt.segments;I.terrain&&I.terrain.setupElevationDraw(Ps,Dt,Ft),I.uploadCommonUniforms(xe,Dt,Ps.tileID.toUnwrapped()),Dt.draw(I,we.TRIANGLES,mt,ht,kt,Rr.disabled,$s,C.id,Gt,ns,an,C.paint,Re.zoom,At,gs)}},heatmap:function(I,y,C,R){if(C.paint.get("heatmap-opacity")!==0)if(I.renderPass==="offscreen"){const $=I.context,G=$.gl,Z=oa.disabled,te=new sa([G.ONE,G.ONE,G.ONE,G.ONE],o.aq.transparent,[!0,!0,!0,!0]),de=I.transform.projection.name==="globe"?.5:.25;C.heatmapFbo=Lj.createWithTexture($,C.heatmapFbo,I.width*de,I.height*de),$.clear({color:o.aq.transparent});const xe=I.transform,we=xe.projection.name==="globe",Re=we?["PROJECTION_GLOBE_VIEW"]:[],Le=we?Rr.frontCCW:Rr.disabled,Ue=[o.aH(xe.center.lng),o.aL(xe.center.lat)];for(let st=0;st({u_image:0,u_color_ramp:1,u_opacity:Re.paint.get("heatmap-opacity")}))(0,G),G.id,$.viewportBuffer,$.quadTriangleIndexBuffer,$.viewportSegments,G.paint,$.transform.zoom)}(I,C))},line:function(I,y,C,R){const $=C.paint.get("line-opacity"),G=C.paint.get("line-width");if($.constantOr(1)===0||G.constantOr(1)===0)return;const Z=C.paint.get("line-blend-mode");if(Z!=="default"&&I.transform.projection.name!=="globe")return I.terrain&&I.terrain.renderingToTexture?void function(te,de,xe,we,Re){if(te.renderPass!=="translucent")return;const Le=te.context,Ue=Le.gl,st=te.terrain;if(!st)return;const Je=Le.bindFramebuffer.current,mt=te.emissiveMode==="mrt-fallback";xe.lineBlendDrapeFbo=Lj.createWithTexture(Le,xe.lineBlendDrapeFbo,st.drapeBufferSize[0],st.drapeBufferSize[1],!0),xe.lineBlendDrapeStencil=xe.lineBlendDrapeFbo._stencilRbo,mt&&Ue.drawBuffers([Ue.COLOR_ATTACHMENT0]),Le.clear({color:Vp[Re].clearColor,depth:1,stencil:0});const ht=te.currentStencilSource,kt=te._tileClippingMaskIDs,Tt=te.nextStencilID;te.currentStencilSource=void 0,te._tileClippingMaskIDs={},te.nextStencilID=1;const xt=te._terrain;te._terrain=null,te._renderTileClippingMasks(xe,de,we),dd(te,de,xe,we,Vp[Re].colorMode,!0),te._terrain=xt,te.currentStencilSource=ht,te._tileClippingMaskIDs=kt,te.nextStencilID=Tt,Le.bindFramebuffer.set(Je),mt&&Ue.drawBuffers([Ue.COLOR_ATTACHMENT0,Ue.COLOR_ATTACHMENT1]);const es=st.drapeBufferSize;Le.viewport.set([0,0,es[0],es[1]]);const Ft=xe.lineBlendDrapeFbo;if(!Ft)return;Le.activeTexture.set(Ue.TEXTURE0),Ue.bindTexture(Ue.TEXTURE_2D,Ft.colorAttachment0.get());const Qt=Re==="additive"?1:xe.paint.get("line-opacity").constantOr(1),At=xe.paint.get("line-emissive-strength").constantOr(0),Dt=Re==="additive"?te.colorModeForDrapableLayerRenderPass(At):Vp[Re].colorMode;te.getOrCreateProgram("lineBlendComposite").draw(te,Ue.TRIANGLES,ar.disabled,oa.disabled,Dt,Rr.disabled,Aj(0,Qt,Vp[Re].compositeUniformValue),xe.id,te.viewportBuffer,te.quadTriangleIndexBuffer,te.viewportSegments,xe.paint,te.transform.zoom)}(I,y,C,R,Z):I.renderPass==="offscreen"?void function(te,de,xe,we,Re){const Le=te.context,Ue=Math.ceil(te.width),st=Math.ceil(te.height);xe.lineBlendFbo=Lj.createWithTexture(Le,xe.lineBlendFbo,Ue,st,!0),xe.lineBlendStencil=xe.lineBlendFbo._stencilRbo,Le.clear({color:Vp[Re].clearColor,depth:1,stencil:0});const Je=te.currentStencilSource,mt=te._tileClippingMaskIDs,ht=te.nextStencilID;te.currentStencilSource=void 0,te._tileClippingMaskIDs={},te.nextStencilID=1,te._renderTileClippingMasks(xe,de,we);const kt=te.renderPass;te.renderPass="translucent",dd(te,de,xe,we,Vp[Re].colorMode),te.renderPass=kt,te.currentStencilSource=Je,te._tileClippingMaskIDs=mt,te.nextStencilID=ht,Le.viewport.set([0,0,te.width,te.height])}(I,y,C,R,Z):I.renderPass==="translucent"?void function(te,de,xe){const we=te.context,Re=we.gl,Le=de.lineBlendFbo;if(!Le)return;we.activeTexture.set(Re.TEXTURE0),Re.bindTexture(Re.TEXTURE_2D,Le.colorAttachment0.get());const Ue=xe==="additive"?1:de.paint.get("line-opacity").constantOr(1),st=xe==="additive"?te.colorModeForDrapableLayerRenderPass(de.paint.get("line-emissive-strength").constantOr(0)):Vp[xe].colorMode;te.getOrCreateProgram("lineBlendComposite").draw(te,Re.TRIANGLES,ar.disabled,oa.disabled,st,Rr.disabled,Aj(0,Ue,Vp[xe].compositeUniformValue),de.id,te.viewportBuffer,te.quadTriangleIndexBuffer,te.viewportSegments,de.paint,te.transform.zoom)}(I,C,Z):void 0;I.renderPass==="translucent"&&dd(I,y,C,R)},fill:function(I,y,C,R){const $=C.paint.get("fill-color"),G=C.paint.get("fill-opacity");if(G.constantOr(1)===0)return;const Z=C.paint.get("fill-emissive-strength"),te=I.colorModeForDrapableLayerRenderPass(Z),de=C.paint.get("fill-pattern"),xe=I.opaquePassEnabledForLayer()&&!de.constantOr(1)&&$.constantOr(o.aq.transparent).a===1&&G.constantOr(0)===1?"opaque":"translucent";let we="none";C.layout.get("fill-elevation-reference")!=="none"?we="road":C.paint.get("fill-z-offset").constantOr(1)!==0&&(we="offset");const Re=!(!I.terrain||!I.terrain.enabled),Le={painter:I,sourceCache:y,layer:C,coords:R,colorMode:te,elevationType:we,terrainEnabled:Re,pass:xe};if(I.renderPass==="shadow")return void(I.shadowRenderer&&we==="road"&&!Re&&function(st){const{painter:Je,sourceCache:mt,layer:ht,coords:kt}=st,Tt=Je.context.gl,xt=st.painter.shadowRenderer;for(const es of kt){const Ft=mt.getTile(es),Qt=Ft.getBucket(ht);if(!Qt)continue;const At=Qt.elevatedStructures;if(!At||!At.shadowCasterSegments||At.shadowCasterSegments.segments[0].primitiveLength===0)continue;Je.prepareDrawTile();const Dt=Qt.bufferData.programConfigurations.get(ht.id),Gt=Je.isTileAffectedByFog(es),gs=Je.getOrCreateProgram("elevatedStructuresDepth",{config:Dt,overrideFog:Gt}),ns=xt.calculateShadowPassMatrixFromTile(Ft.tileID.toUnwrapped());Je.uploadCommonUniforms(Je.context,gs,es.toUnwrapped());const $s=o_(ns,0);gs.draw(Je,Tt.TRIANGLES,xt.getShadowPassDepthMode(),oa.disabled,sa.disabled,Rr.disabled,$s,ht.id,At.vertexBuffer,At.indexBuffer,At.shadowCasterSegments,ht.paint,Je.transform.zoom,Dt)}}(Le));const Ue=I.emissiveMode==="mrt-fallback";if(we!=="offset"){if(j1(Le,!1,Ue),we==="road"){const st=!Re&&I.renderPass==="translucent";st&&Gy(I,y,C,R,"geometry"),j1(Le,!0,Ue,oa.disabled),st&&function(Je){const{painter:mt,sourceCache:ht,layer:kt,coords:Tt,colorMode:xt}=Je,es=mt.context.gl,Ft=Je.painter.shadowRenderer,Qt=!!Ft&&Ft.enabled,At=new ar(mt.context.gl.LEQUAL,ar.ReadOnly,mt.depthRangeFor3D);let Dt=[0,0,0];if(Qt){const gs=mt.style.directionalLight,ns=mt.style.ambientLight;gs&&ns&&(Dt=zp(mt.style,gs,ns))}const Gt=gs=>{for(const ns of Tt){const $s=ht.getTile(ns),Ps=$s.getBucket(kt);if(!Ps)continue;const an=Ps.elevatedStructures;if(!an)continue;let mn,Ns;if(gs?(mn=an.renderableBridgeSegments,Ns=an.bridgeProgramConfigurations.get(kt.id)):(mn=an.renderableTunnelSegments,Ns=an.tunnelProgramConfigurations.get(kt.id)),!mn||mn.segments[0].primitiveLength===0)continue;Ns.updatePaintBuffers(),mt.prepareDrawTile();const hs=mt.isTileAffectedByFog(ns),zs=[];Qt&&zs.push("RENDER_SHADOWS","NORMAL_OFFSET");const Us=mt.getOrCreateProgram("elevatedStructures",{config:Ns,overrideFog:hs,defines:zs}),Ys=mt.translatePosMatrix(ns.projMatrix,$s,kt.paint.get("fill-translate"),kt.paint.get("fill-translate-anchor"));Qt&&Ft.setupShadows($s.tileID.toUnwrapped(),Us,"vector-tile");const Rn=Ej(Ys,Dt);mt.uploadCommonUniforms(mt.context,Us,ns.toUnwrapped()),Us.draw(mt,es.TRIANGLES,At,oa.disabled,xt,Rr.backCCW,Rn,kt.id,an.vertexBuffer,an.indexBuffer,mn,kt.paint,mt.transform.zoom,Ns,[an.vertexBufferNormal])}};Gt(!0),Gt(!1)}(Le)}}else j1(Le,!1,Ue,I.stencilModeFor3D())},"fill-extrusion":function(I,y,C,R){const $=C.paint.get("fill-extrusion-opacity"),G=I.context,Z=G.gl,te=I.terrain,de=te&&te.renderingToTexture;if($===0)return;const xe=I.emissiveMode==="mrt-fallback",we=I.conflationActive&&I.style.isLayerClipped(C,y.getSource()),Re=I.style.order.indexOf(C.fqid);if(we&&function(Le,Ue,st,Je,mt){for(const ht of Je){const kt=Ue.getTile(ht).getBucket(st);kt&&(kt.updateReplacement(ht,Le.replacementSource,mt),kt.uploadCentroid(Le.context))}}(I,y,C,R,Re),te||we)for(const Le of R){const Ue=y.getTile(Le).getBucket(C);Ue&&pg(I.context,y,Le,Ue,C,te,we)}if(I.renderPass==="shadow"&&I.shadowRenderer){if(te&&$<.65&&C._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.af)return;const Le=I.shadowRenderer.getShadowPassDepthMode();Nx(I,y,C,R,Le,oa.disabled,sa.disabled,we)}else if(I.renderPass==="translucent"){const Le=!C.paint.get("fill-extrusion-pattern").constantOr(1),Ue=C.paint.get("fill-extrusion-color").constantOr(o.aq.white);if(!de&&Ue.a!==0){const st=new ar(I.context.gl.LEQUAL,ar.ReadWrite,I.depthRangeFor3D);$===1&&Le?Nx(I,y,C,R,st,oa.disabled,sa.unblended,we):(Nx(I,y,C,R,st,oa.disabled,sa.disabled,we),Nx(I,y,C,R,st,I.stencilModeFor3D(),I.colorModeForRenderPass(),we),I.resetStencilClippingMasks())}if(I.style.enable3dLights()&&Le&&(!te&&I.transform.projection.name!=="globe"||de)){const st=C.paint.get("fill-extrusion-opacity"),Je=C.paint.get("fill-extrusion-ambient-occlusion-intensity"),mt=C.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),ht=C.paint.get("fill-extrusion-flood-light-intensity"),kt=C.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Tt=C.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(kt?null:C.lut).toArray01().slice(0,3),xt=Je>0&&mt>0,es=ht>0,Ft=(Dt,Gt,gs)=>(1-gs)*Dt+gs*Gt,Qt=new qh;Qt.translate=C.paint.get("fill-extrusion-translate"),Qt.translateAnchor=C.paint.get("fill-extrusion-translate-anchor"),Qt.edgeRadius=C.layout.get("fill-extrusion-edge-radius"),Qt.cutoffFadeRange=C.paint.get("fill-extrusion-cutoff-fade-range");const At=Dt=>{const Gt=I.depthModeForSublayer(1,ar.ReadOnly,Z.LEQUAL,!0),gs=C.paint.get(Dt?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),ns=Ft(.1,3,gs),$s=I._showOverdrawInspector;if(!$s){const Ps=new oa({func:Z.ALWAYS,mask:255},255,255,Z.KEEP,Z.KEEP,Z.REPLACE),an=new sa([Z.ONE,Z.ONE,Z.ONE,Z.ONE],o.aq.transparent,[!1,!1,!1,!0],Z.MIN);zf(Qt,I,y,C,R,Gt,Ps,an,Rr.disabled,Dt,"sdf",st,Je,mt,ht,Tt,ns,we,!1)}{const Ps=$s?oa.disabled:new oa({func:Z.EQUAL,mask:255},255,255,Z.KEEP,Z.DECR,Z.DECR),an=$s?I.colorModeForRenderPass():new sa([Z.ONE_MINUS_DST_ALPHA,Z.DST_ALPHA,Z.ONE,Z.ONE],o.aq.transparent,[!0,!0,!0,!0]);zf(Qt,I,y,C,R,Gt,Ps,an,Rr.disabled,Dt,"color",st,Je,mt,ht,Tt,ns,we,!1)}};if(de){const Dt=()=>{const gs=te.drapeBufferSize[0],ns=te.drapeBufferSize[1];let $s=te.framebufferCopyTexture;return $s&&(!$s||$s.size[0]===gs&&$s.size[1]===ns)||($s&&$s.destroy(),$s=te.framebufferCopyTexture=new o.T(G,new o.q({width:gs,height:ns}),Z.RGBA8)),$s.bind(Z.LINEAR,Z.CLAMP_TO_EDGE),Z.copyTexSubImage2D(Z.TEXTURE_2D,0,0,0,0,0,gs,ns),$s},Gt=(gs,ns,$s)=>{const Ps=I.depthModeForSublayer(1,ar.ReadOnly,Z.LEQUAL,!1),an=C.paint.get(gs?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),mn=Ft(.1,3,an);{const Ns=new sa([Z.ONE,Z.ONE,Z.ONE,Z.ONE],o.aq.transparent,[!1,!1,!1,!0]);zf(Qt,I,y,C,R,Ps,oa.disabled,Ns,Rr.disabled,gs,"clear",st,Je,mt,ht,Tt,mn,we,ns)}{const Ns=new oa({func:Z.ALWAYS,mask:255},255,255,Z.KEEP,Z.KEEP,Z.REPLACE),hs=new sa([Z.ONE,Z.ONE,Z.ONE,Z.ONE],o.aq.transparent,[!1,!1,!1,!0],Z.MIN);zf(Qt,I,y,C,R,Ps,Ns,hs,Rr.disabled,gs,"sdf",st,Je,mt,ht,Tt,mn,we,ns)}xe&&!gs&&($s=Dt());{const Ns=gs?Z.ZERO:Z.ONE_MINUS_DST_ALPHA,hs=new oa({func:Z.EQUAL,mask:255},255,255,Z.KEEP,Z.DECR,Z.DECR),zs=new sa([Ns,Z.DST_ALPHA,Z.ONE_MINUS_DST_ALPHA,Z.ZERO],o.aq.transparent,[!0,!0,!0,!0]);zf(Qt,I,y,C,R,Ps,hs,zs,Rr.disabled,gs,"color",st,Je,mt,ht,Tt,mn,we,ns)}if(!xe||gs){const Ns=new sa([Z.ONE,Z.ONE,Z.ONE,gs?Z.ZERO:Z.ONE],o.aq.transparent,[!1,!1,!1,!0],gs?Z.FUNC_ADD:Z.MAX);zf(Qt,I,y,C,R,Ps,oa.disabled,Ns,Rr.disabled,gs,"clear",st,Je,mt,ht,Tt,mn,we,ns,$s)}else{Z.drawBuffers([Z.NONE,Z.COLOR_ATTACHMENT1]);const Ns=new oa({func:Z.EQUAL,mask:255},254,255,Z.KEEP,Z.DECR,Z.DECR),hs=new sa([Z.ONE,Z.ONE,Z.ONE,Z.ONE],o.aq.transparent,[!0,!1,!1,!1],Z.MAX);zf(Qt,I,y,C,R,Ps,Ns,hs,Rr.disabled,gs,"emissive",st,Je,mt,ht,Tt,mn,we,ns,$s),Z.drawBuffers([Z.COLOR_ATTACHMENT0])}};if(xt||es){let gs;I.prepareDrawTile(),xe&&!xt||(gs=Dt()),xt&&Gt(!0,!1,gs),es&&Gt(!1,!0,gs)}}else xt&&At(!0),es&&At(!1),(xt||es)&&I.resetStencilClippingMasks()}}},building:function(I,y,C,R){I.currentLayer0&&G>0,xe=!0;const we=C.paint.get("building-vertical-scale");if(we<=0)return;I.shadowRenderer||(xe=!1);const Re=I.conflationActive&&I.style.isLayerClipped(C,y.getSource()),Le=I.style.order.indexOf(C.fqid);if(function(Ue,st,Je,mt,ht,kt){for(const Tt of kt){const xt=st.getTile(Tt).getBucket(Je);xt&&(ht&&xt.updateReplacement(Tt,Ue.replacementSource,mt),xt.uploadUpdatedIndexBuffer(Ue.context))}}(I,y,C,Le,Re,R),function(Ue,st,Je,mt){for(const ht of mt){const kt=st.getTile(ht).getBucket(Je);kt&&kt.needsEvaluation()&&kt.uploadUpdatedColorBuffer(Ue.context)}}(I,y,C,R),C.resetLayerRenderingStats(I),I.shadowRenderer&&(I.shadowRenderer.useNormalOffset=!0),I.renderPass==="shadow"&&I.shadowRenderer){const Ue=[],st=I.shadowRenderer.getShadowPassDepthMode();Wy({painter:I,source:y,layer:C,coords:R,defines:Ue,blendMode:sa.disabled,depthMode:st,opacity:te,verticalScale:we,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(I.renderPass==="translucent"){let Ue=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];xe&&(Ue=Ue.concat("RENDER_SHADOWS")),I.shadowRenderer&&I.shadowRenderer.useNormalOffset&&(Ue=Ue.concat("NORMAL_OFFSET"));const st=C.paint.get("building-facade-emissive-chance"),Je=C.paint.get("building-ambient-occlusion-intensity"),mt=C.paint.get("building-flood-light-intensity"),ht=C.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",kt=C.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(ht?null:C.lut).toArray01().slice(0,3),Tt=C.paint.get("building-flood-light-ground-attenuation"),xt=mt>0,es=new ar(I.context.gl.LEQUAL,ar.ReadWrite,I.depthRangeFor3D);te<1&&Wy({painter:I,source:y,layer:C,coords:R,defines:Ue,blendMode:sa.disabled,depthMode:es,opacity:te,verticalScale:we,facadeEmissiveChance:st,facadeAOIntensity:Je,floodLightIntensity:mt,floodLightColor:kt,depthOnly:!0});const Ft=I.colorModeForRenderPass();Wy({painter:I,source:y,layer:C,coords:R,defines:Ue,blendMode:Ft,depthMode:es,opacity:te,verticalScale:we,facadeEmissiveChance:st,facadeAOIntensity:Je,floodLightIntensity:mt,floodLightColor:kt});const Qt=C.paint.get("building-front-cutoff");d_(I.transform.pitch,Qt,!!I.terrain),de&&fg(I,y,C,R,!0,te,$,G,mt,kt,Z,Re),xt&&fg(I,y,C,R,!1,te,$,G,mt,kt,Tt,Re)}else if(I.renderPass==="light-beam"){const Ue=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],st=new ar(I.context.gl.LEQUAL,ar.ReadOnly,I.depthRangeFor3D);Wy({painter:I,source:y,layer:C,coords:R,defines:Ue,blendMode:sa.alphaBlended,depthMode:st,opacity:te,verticalScale:we,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}I.shadowRenderer&&(I.shadowRenderer.useNormalOffset=!1),I.resetStencilClippingMasks()},hillshade:function(I,y,C,R){if(I.renderPass!=="offscreen"&&I.renderPass!=="translucent"||I.style.disableElevatedTerrain)return;const $=I.context,G=I.terrain&&I.terrain.renderingToTexture,[Z,te]=I.renderPass!=="translucent"||G?[{},R]:I.stencilConfigForOverlap(R);for(const de of te){const xe=y.getTile(de);if(xe.needsHillshadePrepare&&I.renderPass==="offscreen")f6(I,xe,C);else if(I.renderPass==="translucent"){const we=I.depthModeForSublayer(0,ar.ReadOnly),Re=C.paint.get("hillshade-emissive-strength"),Le=I.colorModeForDrapableLayerRenderPass(Re),Ue=G&&I.terrain?I.terrain.stencilModeForRTTOverlap(de):Z[de.overscaledZ];zR(I,de,xe,C,we,Ue,Le)}}$.viewport.set([0,0,I.width,I.height]),I.resetStencilClippingMasks()},raster:function(I,y,C,R,$,G){if(I.renderPass!=="translucent")return;const Z=C.paint.get("raster-opacity");if(Z===0)return;const te=I.transform.projection.name==="globe",de=C.paint.get("raster-elevation")!==0,xe=de&&te,we=I.terrain&&I.terrain.exaggeration()>0&&de&&C.paint.get("raster-elevation-reference")==="ground",Re=!te&&we;if(I.renderElevatedRasterBackface&&!xe)return;const Le=I.context,Ue=Le.gl,st=y.getSource(),Je=function(Dt,Gt,gs,ns,$s){const Ps=Gt.paint.get("raster-color"),an=Dt.type==="raster-array",mn=[],Ns=Gt.paint.get("raster-resampling"),hs=Gt.paint.get("raster-color-mix");let zs=Gt.paint.get("raster-color-range");const Us=[hs[0],hs[1],hs[2],0],Ys=hs[3];let Rn=Ns==="nearest"?ns.NEAREST:ns.LINEAR;if(an&&(mn.push("RASTER_ARRAY"),Ps||mn.push("RASTER_COLOR"),Ns==="linear"&&mn.push("RASTER_ARRAY_LINEAR"),Rn=ns.NEAREST,!zs&&Dt.rasterLayers)){const Sn=Dt.rasterLayers.find(({id:Cn})=>Cn===Gt.sourceLayer);Sn&&Sn.fields&&Sn.fields.range&&(zs=Sn.fields.range)}if(zs=zs||[0,1],Ps){mn.push("RASTER_COLOR"),gs.activeTexture.set(ns.TEXTURE2),Gt.updateColorRamp(zs);let Sn=Gt.colorRampTexture;Sn||(Sn=Gt.colorRampTexture=new o.T(gs,Gt.colorRamp,ns.RGBA8)),Sn.bind(Rn,ns.CLAMP_TO_EDGE)}return $s&&mn.push("USE_MRT1"),{mix:Us,range:zs,offset:Ys,defines:mn,resampling:Rn}}(st,C,Le,Ue,I.terrain&&I.terrain.renderingToTexture&&I.emissiveMode==="mrt-fallback");if(st instanceof o.aV&&!R.length&&!te)return;const mt=C.paint.get("raster-emissive-strength"),ht=I.colorModeForDrapableLayerRenderPass(mt),kt=I.terrain&&I.terrain.renderingToTexture,Tt=!I.options.moving,xt=C.paint.get("raster-resampling")==="nearest"?Ue.NEAREST:Ue.LINEAR;if(st instanceof o.aV&&!R.length&&(st.onNorthPole||st.onSouthPole)){const Dt=de?I.stencilModeFor3D():oa.disabled;return void Ky(!!st.onNorthPole,null,I,y,C,mt,Je,Rr.disabled,Dt)}if(!R.length)return;const[es,Ft]=st instanceof o.aV||kt?[{},R]:I.stencilConfigForOverlap(R),Qt=Ft[Ft.length-1].overscaledZ;xe&&Je.defines.push("PROJECTION_GLOBE_VIEW"),de&&Je.defines.push("RENDER_CUTOFF","ELEVATED"),we&&Je.defines.push("ELEVATION_REFERENCE_GROUND");const At=(Dt,Gt,gs)=>{for(const ns of Dt){const $s=ns.toUnwrapped(),Ps=y.getTile(ns);if(kt&&(!Ps||!Ps.hasData()))continue;Le.activeTexture.set(Ue.TEXTURE0);const an=Fj(Ps,st,C,Je);if(!an||!an.texture)continue;const{texture:mn,mix:Ns,offset:hs,tileSize:zs,buffer:Us}=an;let Ys,Rn;kt?(Ys=ar.disabled,Rn=ns.projMatrix):de?(Ys=new ar(Ue.LEQUAL,ar.ReadWrite,I.depthRangeFor3D),Rn=te?Float32Array.from(I.transform.expandedFarZProjMatrix):I.transform.calculateProjMatrix($s,Tt)):(Ys=I.depthModeForSublayer(ns.overscaledZ-Qt,Z===1?ar.ReadWrite:ar.ReadOnly,Ue.LESS),Rn=I.transform.calculateProjMatrix($s,Tt));const Sn=I.terrain&&kt?I.terrain.stencilModeForRTTOverlap(ns):es[ns.overscaledZ],Cn=G?0:C.paint.get("raster-fade-duration");Ps.registerFadeDuration(Cn);const dn=y.findLoadedParent(ns,0),mr=op(Ps,dn,y,I.transform,Cn);let Cr,ir;!mr.isFading&&Ps.refreshedUponExpiration&&(Ps.refreshedUponExpiration=!1),I.terrain&&I.terrain.prepareDrawTile(),Le.activeTexture.set(Ue.TEXTURE0),mn.bind(xt,Ue.CLAMP_TO_EDGE),Le.activeTexture.set(Ue.TEXTURE1),dn?(dn.texture&&dn.texture.bind(xt,Ue.CLAMP_TO_EDGE),Cr=Math.pow(2,dn.tileID.overscaledZ-Ps.tileID.overscaledZ),ir=[Ps.tileID.canonical.x*Cr%1,Ps.tileID.canonical.y*Cr%1]):mn.bind(xt,Ue.CLAMP_TO_EDGE),"useMipmap"in mn&&Le.extTextureFilterAnisotropic&&I.transform.pitch>20&&Ue.texParameterf(Ue.TEXTURE_2D,Le.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,Le.extTextureFilterAnisotropicMax);const hr=I.transform;let na;const wa=de?Oj(hr):[0,0,0,0];let ya,Ga,Gr,Wa,va,Ii=0;if(xe&&st instanceof o.aV&&st.coordinates.length>3)ya=Float32Array.from(o.du(o.dv(new o.cn(0,0,0)))),Ga=Float32Array.from(hr.globeMatrix),Gr=Float32Array.from(o.dq(hr)),Wa=[o.aH(hr.center.lng),o.aL(hr.center.lat)],na=st.elevatedGlobePerspectiveTransform,va=st.elevatedGlobeGridMatrix||new Float32Array(9);else if(xe){const Vi=o.dr(ns.canonical);Ii=o.ds(Vi.getCenter().lat),ya=Float32Array.from(o.du(o.dv(ns.canonical))),Ga=Float32Array.from(hr.globeMatrix),Gr=Float32Array.from(o.dq(hr)),Wa=[o.aH(hr.center.lng),o.aL(hr.center.lat)],na=[0,0],va=Float32Array.from(o.dt(ns.canonical,Vi,Ii,hr.worldSize/hr._pixelsPerMercatorPixel))}else na=st instanceof o.aV?st.perspectiveTransform:[0,0],ya=new Float32Array(16),Ga=new Float32Array(9),Gr=new Float32Array(16),Wa=[0,0],va=new Float32Array(9);const bo=bx(I,Rn,ya,Ga,Gr,va,ir||[0,0],o.al(I.transform.zoom),Wa,wa,Cr||1,mr,C,na,de?C.paint.get("raster-elevation"):0,2,Ns,hs,Je.range,zs,Us,mt),vl=I.isTileAffectedByFog(ns),Lo=I.getOrCreateProgram("raster",{defines:Je.defines,overrideFog:vl});if(I.uploadCommonUniforms(Le,Lo,$s),st instanceof o.aV){const Vi=st.elevatedGlobeVertexBuffer,Fa=st.elevatedGlobeIndexBuffer;if(kt||!te)st.boundsBuffer&&st.boundsSegments&&Lo.draw(I,Ue.TRIANGLES,Ys,oa.disabled,ht,Rr.disabled,bo,C.id,st.boundsBuffer,I.quadTriangleIndexBuffer,st.boundsSegments);else if(Vi&&Fa){const za=hr.zoom<=o.cJ?st.elevatedGlobeSegments:st.getSegmentsForLongitude(hr.center.lng);za&&Lo.draw(I,Ue.TRIANGLES,Ys,oa.disabled,ht,Gt,bo,C.id,Vi,Fa,za)}}else if(xe){Ys=new ar(Ue.LEQUAL,ar.ReadOnly,I.depthRangeFor3D);const Vi=I.globeSharedBuffers;if(Vi){we&&(I.terrain.setupElevationDraw(Ps,Lo),I.uploadCommonUniforms(Le,Lo,Ps.tileID.toUnwrapped()));const[Fa,za,Do]=Vi.getGridBuffers(Ii,!1),Nl=Lo.getAttributeLocation(Ue,"a_texture_pos");Nl!==-1&&Ue.vertexAttribI4ui(Nl,0,0,0,0),Lo.draw(I,Ue.TRIANGLES,Ys,gs||Sn,I.colorModeForRenderPass(),Gt,bo,C.id,Fa,za,Do)}}else if(Re)Ys=new ar(Ue.LEQUAL,ar.ReadWrite,I.depthRangeFor3D),I.terrain.setupElevationDraw(Ps,Lo),I.uploadCommonUniforms(Le,Lo,Ps.tileID.toUnwrapped()),hr.pitch>20&&Lo.draw(I,Ue.TRIANGLES,Ys,oa.disabled,sa.disabled,Rr.frontCCW,bo,C.id,I.terrain.gridBuffer,I.terrain.gridIndexBuffer,I.terrain.gridSegments),Lo.draw(I,Ue.TRIANGLES,Ys,Sn,ht,Rr.backCCW,bo,C.id,I.terrain.gridBuffer,I.terrain.gridIndexBuffer,I.terrain.gridSegments);else{const{tileBoundsBuffer:Vi,tileBoundsIndexBuffer:Fa,tileBoundsSegments:za}=I.getTileBoundsBuffers(Ps);Lo.draw(I,Ue.TRIANGLES,Ys,Sn,ht,Rr.disabled,bo,C.id,Vi,Fa,za)}}if(!(st instanceof o.aV)&&xe)for(const ns of Dt){const $s=ns.canonical.y===(1<o.d$[Us]($s));Ns.push($s);const hs=$s.canonical.x,zs=$s.canonical.y;for(const Us of Ns){const Ys=xt.getTile(Gt?Us.wrapped():Us);if(!Ys)continue;const Rn=Ys.rasterParticleState;if(!Rn)continue;const Sn=Us.canonical.x+(1<Qt.tileID)),Ue&&(xe.activeTexture.set(we.TEXTURE0),I.imageManager.bind(I.context,C.scope));const Ft=[];if(I.terrain&&I.terrain.renderingToTexture&&I.emissiveMode==="mrt-fallback"&&Ft.push("USE_MRT1"),de){const Qt=I.getOrCreateProgram(Tt,{overrideFog:!1,overrideRtt:!0,defines:Ft}),At=new Float32Array(o.b9([])),Dt=new o.aR(0,0,0,0,0),Gt=Ue?wx(At,te,Z,I,0,C.scope,st,de,{tileID:Dt,tileSize:Le}):Hy(At,te,Z,$.toPremultipliedRenderColor(G?null:C.lut));return void Qt.draw(I,we.TRIANGLES,ht,mt,kt,Rr.disabled,Gt,C.id,I.viewportBuffer,I.quadTriangleIndexBuffer,I.viewportSegments)}for(const Qt of es){const At=I.isTileAffectedByFog(Qt),Dt=I.getOrCreateProgram(Tt,{overrideFog:At,defines:Ft}),Gt=Qt.toUnwrapped(),gs=R?Qt.projMatrix:I.transform.calculateProjMatrix(Gt);I.prepareDrawTile();const ns=y?y.getTile(Qt):xt?xt[Qt.key]:new o.b0(Qt,Le,Re.zoom,I),$s=Ue?wx(gs,te,Z,I,0,C.scope,st,de,{tileID:Qt,tileSize:Le}):Hy(gs,te,Z,$.toPremultipliedRenderColor(G?null:C.lut));I.uploadCommonUniforms(xe,Dt,Gt);const{tileBoundsBuffer:Ps,tileBoundsIndexBuffer:an,tileBoundsSegments:mn}=I.getTileBoundsBuffers(ns);Dt.draw(I,we.TRIANGLES,ht,mt,kt,Rr.disabled,$s,C.id,Ps,an,mn)}},sky:function(I,y,C){const R=I._atmosphere?o.al(I.transform.zoom):1,$=C.paint.get("sky-opacity")*R;if($===0)return;const G=I.context,Z=C.paint.get("sky-type"),te=new ar(G.gl.LEQUAL,ar.ReadOnly,[0,1]),de=I.frameCounter/1e3%1;Z==="atmosphere"?I.renderPass==="offscreen"?C.needsSkyboxCapture(I)&&(function(xe,we){const Re=xe.context,Le=Re.gl;let Ue=we.skyboxFbo;if(!Ue){Ue=we.skyboxFbo=Re.createFramebuffer(32,32,1,null),we.skyboxGeometry=new Wd(Re),we.skyboxTexture=Re.gl.createTexture(),Le.bindTexture(Le.TEXTURE_CUBE_MAP,we.skyboxTexture),Le.texParameteri(Le.TEXTURE_CUBE_MAP,Le.TEXTURE_WRAP_S,Le.CLAMP_TO_EDGE),Le.texParameteri(Le.TEXTURE_CUBE_MAP,Le.TEXTURE_WRAP_T,Le.CLAMP_TO_EDGE),Le.texParameteri(Le.TEXTURE_CUBE_MAP,Le.TEXTURE_MIN_FILTER,Le.LINEAR),Le.texParameteri(Le.TEXTURE_CUBE_MAP,Le.TEXTURE_MAG_FILTER,Le.LINEAR);for(let ht=0;ht<6;++ht)Le.texImage2D(Le.TEXTURE_CUBE_MAP_POSITIVE_X+ht,0,Le.RGBA,32,32,0,Le.RGBA,Le.UNSIGNED_BYTE,null)}Re.bindFramebuffer.set(Ue.framebuffer),Re.viewport.set([0,0,32,32]);const st=we.getCenter(xe,!0),Je=xe.getOrCreateProgram("skyboxCapture"),mt=new Float64Array(16);o.b9(mt),o.ef(mt,mt,.5*-Math.PI),Hp(xe,we,Je,mt,st,0),o.b9(mt),o.ef(mt,mt,.5*Math.PI),Hp(xe,we,Je,mt,st,1),o.b9(mt),o.cE(mt,mt,.5*-Math.PI),Hp(xe,we,Je,mt,st,2),o.b9(mt),o.cE(mt,mt,.5*Math.PI),Hp(xe,we,Je,mt,st,3),o.b9(mt),Hp(xe,we,Je,mt,st,4),o.b9(mt),o.ef(mt,mt,Math.PI),Hp(xe,we,Je,mt,st,5),Re.viewport.set([0,0,xe.width,xe.height])}(I,C),C.markSkyboxValid(I)):I.renderPass==="sky"&&function(xe,we,Re,Le,Ue){const st=xe.context,Je=st.gl,mt=xe.transform,ht=xe.getOrCreateProgram("skybox");st.activeTexture.set(Je.TEXTURE0),Je.bindTexture(Je.TEXTURE_CUBE_MAP,we.skyboxTexture);const kt=((Tt,xt,es,Ft,Qt)=>({u_matrix:Tt,u_sun_direction:xt,u_cubemap:0,u_opacity:Ft,u_temporal_offset:Qt}))(mt.skyboxMatrix,we.getCenter(xe,!1),0,Le,Ue);xe.uploadCommonUniforms(st,ht),ht.draw(xe,Je.TRIANGLES,Re,oa.disabled,xe.colorModeForRenderPass(),Rr.backCW,kt,"skybox",we.skyboxGeometry.vertexBuffer,we.skyboxGeometry.indexBuffer,we.skyboxGeometry.segment)}(I,C,te,$,de):Z==="gradient"&&I.renderPass==="sky"&&function(xe,we,Re,Le,Ue){const st=xe.context,Je=st.gl,mt=xe.transform,ht=xe.getOrCreateProgram("skyboxGradient");we.skyboxGeometry||(we.skyboxGeometry=new Wd(st)),st.activeTexture.set(Je.TEXTURE0);let kt=we.colorRampTexture;kt||(kt=we.colorRampTexture=new o.T(st,we.colorRamp,Je.RGBA8)),kt.bind(Je.LINEAR,Je.CLAMP_TO_EDGE);const Tt=((xt,es,Ft,Qt,At)=>({u_matrix:xt,u_color_ramp:0,u_center_direction:es,u_radius:o.ap(Ft),u_opacity:Qt,u_temporal_offset:At}))(mt.skyboxMatrix,we.getCenter(xe,!1),we.paint.get("sky-gradient-radius"),Le,Ue);xe.uploadCommonUniforms(st,ht),ht.draw(xe,Je.TRIANGLES,Re,oa.disabled,xe.colorModeForRenderPass(),Rr.backCW,Tt,"skyboxGradient",we.skyboxGeometry.vertexBuffer,we.skyboxGeometry.indexBuffer,we.skyboxGeometry.segment)}(I,C,te,$,de)},custom:function(I,y,C,R){const $=I.context,G=C.implementation;if(!I.transform.projection.unsupportedLayers||!I.transform.projection.unsupportedLayers.includes("custom")||I.terrain&&(I.terrain.renderingToTexture||I.renderPass==="offscreen")&&C.isDraped(y)){if(I.renderPass==="offscreen"){const Z=G.prerender;if(Z){if(I.setCustomLayerDefaults(),$.setColorMode(I.colorModeForRenderPass()),I.transform.projection.name==="globe"){const te=I.transform.pointMerc;Z.call(G,$.gl,I.transform.customLayerMatrix(),I.transform.getProjection(),I.transform.globeToMercatorMatrix(),o.al(I.transform.zoom),[te.x,te.y],I.transform.pixelsPerMeterRatio)}else Z.call(G,$.gl,I.transform.customLayerMatrix());$.setDirty(),I.setBaseState()}}else if(I.renderPass==="translucent"){if(I.terrain&&I.terrain.renderingToTexture){const te=G.renderToTile;if(te){const de=R[0].canonical,xe={x:de.x+R[0].wrap*(G.wrapTileId?0:1<{xe&&(xe.useNormalOffset=!0,we||(xe.enabled=!0))},Le=y.getSource();if(I.renderPass==="light-beam"&&Le.type!=="batched-model")return;if(Le.type==="vector"||Le.type==="geojson")return function(xt,es,Ft,Qt,At){const Dt=xt.transform,Gt=Dt.projection.name==="globe",gs=Dt.getFreeCameraOptions().position;if(!xt.modelManager)return;const ns=xt.modelManager;Ft.modelManager=ns;const $s=xt.shadowRenderer;if(!Ft._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const Ps=Ft._unevaluatedLayout._values["model-id"],an=Object.assign({},Ft.layout.get("model-id").parameters),mn=xt.style.order.indexOf(Ft.fqid),Ns=Ft.paint.get("model-opacity").constantOr(1);for(const hs of Qt){const zs=es.getTile(hs).getBucket(Ft);if(!zs||zs.projection.name!==Dt.projection.name)continue;const Us=zs.getModelUris();if(Us&&!zs.modelsRequested&&(ns.addModelsFromBucket(Us,At),zs.modelsRequested=!0),Gt)an.zoom=hs.overscaledZ;else{const ir=Gp(hs,Dt);an.zoom=ir}const Ys=Ps.possiblyEvaluate(an);if(kn(xt,zs,hs),jn.shadowUniformsInitialized=!1,jn.useSingleShadowCascade=!!$s&&$s.getMaxCascadeForTile(hs.toUnwrapped())===0,xt.renderPass==="shadow"&&$s){if(xt.currentShadowCascade===1&&zs.isInsideFirstShadowMapFrustum)continue;const ir=Dt.calculatePosMatrix(hs.toUnwrapped(),Dt.worldSize);if(jn.tileMatrix.set(ir),jn.shadowTileMatrix=Float32Array.from($s.calculateShadowPassMatrixFromMatrix(ir)),jn.aabb.min=[0,0,0],jn.aabb.max[0]=jn.aabb.max[1]=o.an,jn.aabb.max[2]=0,$j(zs,jn,xt,Ft.scope))continue}const Rn=1<0&&xt.style.isLayerClipped(Ft,es.getSource())&&zs.updateReplacement(hs,xt.replacementSource,mn,Ft.scope)&&(zs.uploaded=!1,zs.upload(xt.context));let Cn=0;const dn=new Array,mr=new Array,Cr=new Array;for(let ir in zs.instancesPerModel){const hr=zs.instancesPerModel[ir];hr.features.length>0&&!Gt&&(ir=Ys.evaluate(hr.features[0].feature,{}));const na=ns.getModel(ir,At);if(na||ns.hasURLBeenRequested(ir)||zs.modelUris.includes(ir)||(zs.modelUris.push(ir),zs.modelsRequested=!1),na&&na.uploaded)if(Gt){const wa=o.bJ([],[gs.x,gs.y,gs.z],xt.transform.worldSize);o.eo(wa,wa);for(let ya=0;ya0&&Wa.elevationUpdate(ir.terrain,ya,Gr,na.source),Wa.needsReEvaluation(ir,Ga,na)&&Wa.evaluate(na))}})(xt,es,Ft,Qt),function(){const ir=new Map;let hr,na,wa;dn?(hr=Qt.length-1,na=-1,wa=-1):(hr=0,na=Qt.length,wa=1);const ya=new Float64Array(16),Ga=o.ce(),Gr=new o.P(0,0);for(let Wa=hr;Wa!==na;Wa+=wa){const va=Qt[Wa],Ii=es.getTile(va).getBucket(Ft);if(!Ii||!Ii.uploaded)continue;let bo=!1;gs&&(bo=gs.getMaxCascadeForTile(va.toUnwrapped())===0);const vl=Dt.calculatePosMatrix(va.toUnwrapped(),Dt.worldSize),Lo=Ii.modelTraits;!Rn&&dn&&(o.b7(ya,vl),o.ah(Ga,$s,ya),Gr.x=Ga[0],Gr.y=Ga[1]);const Vi=[];Ii.setFilter(Ft.filter);for(const Fa of Ii.getNodesInfo()){if(Fa.hiddenByReplacement||!Fa.node.meshes)continue;const za=Fa.node;let Do=0;xt.terrain&&za.elevation&&(Do=za.elevation*xt.terrain.exaggeration());const Nl=(()=>{const yu=Fa.aabb;return Ys.min=[...yu.min],Ys.max=[...yu.max],Ys.min[2]+=Do,Ys.max[2]+=Do,o.ah(Ys.min,Ys.min,vl),o.ah(Ys.max,Ys.max,vl),Ys})(),Hi=Fa.evaluatedScale;if(Hi[0]<=1&&Hi[1]<=1&&Hi[2]<=1&&Nl.intersects(Sn)===0)continue;if(!Rn&&dn){const yu=.16666666666666666;Fa.cameraCollisionOpacity=$s[0]>Nl.min[0]&&$s[0]Nl.min[1]&&$s[1]!dn||Fa.opacity===1&&za.opacity===1?Fa.depthza.depth?-1:1);for(const Fa of Vi){const za=Fa.nodeInfo,Do=za.node;if(xt._debugParams.show3DModelFootprints&&Do.footprint){const oi=Do.id||Do.name||"footprint";ir.has(oi)||ir.set(oi,{node:Do,mvp:Fa.wvpForTile})}let Nl=o.aD([],Ns,Fa.tileModelMatrix);o.aD(Nl,an,Nl);const Hi=o.b7([],Nl);o.e6(Hi,Hi),o.cC(Hi,Hi,fs),Nl=o.aD(Nl,Nl,Do.globalMatrix);const Ca=xt.renderPass==="light-beam",dl=Ft.paint.get("model-color-use-theme").constantOr("default")==="none",_o=Lo&o.ez.HasMapboxMeshFeatures,kc=_o?0:za.evaluatedRMEA[0][2];for(let oi=0;oi=sr||Uf>=sr}}const so=ko.material;let Cx;so.occlusionTexture&&so.occlusionTexture.offsetScale&&(Cx=so.occlusionTexture.offsetScale,hd.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const Tx=xt.getOrCreateProgram("model",hd);!Rn&&gs&&gs.setupShadowsFromMatrix(Fa.tileModelMatrix,Tx,gs.useNormalOffset),xt.uploadCommonUniforms(At,Tx,null,$f);const Bo=so.pbrMetallicRoughness;Bo.metallicFactor=.9,Bo.roughnessFactor=.5;const Ko=jx(new Float32Array(wh),new Float32Array(Nl),new Float32Array(Hi),new Float32Array(Do.globalMatrix),xt,Fa.opacity,Bo.baseColorFactor,so.emissiveFactor,Bo.metallicFactor,Bo.roughnessFactor,so,kc,Ft,[0,0,0],Cx);!Xc&&(za.hasTranslucentParts||Fa.opacity<1)&&Tx.draw(xt,At.gl.TRIANGLES,zs,oa.disabled,sa.disabled,Rr.backCCW,Ko,Ft.id,ko.vertexBuffer,ko.indexBuffer,ko.segments,Ft.paint,xt.transform.zoom,void 0,yu),Tx.draw(xt,At.gl.TRIANGLES,Xc?Us:zs,oa.disabled,Xc||Fa.opacity<1||za.hasTranslucentParts?sa.alphaBlended:sa.unblended,Rr.backCCW,Ko,Ft.id,ko.vertexBuffer,ko.indexBuffer,ko.segments,Ft.paint,xt.transform.zoom,void 0,yu)}}}if(xt._debugParams.show3DModelFootprints&&ir.size>0){const Wa=Array.from(ir.keys()).sort();for(const va of Wa){const{node:Ii,mvp:bo}=ir.get(va);sk(xt,0,Ii,bo)}}}()}(I,y,C,R),void Re();if(Le.type!=="model")return;const Ue=Le.getModels(),st=[],Je=I.transform.getFreeCameraOptions().position,mt=o.bJ([],[Je.x,Je.y,Je.z],I.transform.worldSize);o.eo(mt,mt);const ht=[],kt=[];let Tt=0;for(const xt of Ue){const es=y.getFeatureState("",xt.id),Ft={type:"Unknown",id:xt.id,properties:xt.featureProperties},Qt=C.paint.get("model-rotation").evaluate(Ft,es),At=C.paint.get("model-scale").evaluate(Ft,es),Dt=C.paint.get("model-translation").evaluate(Ft,es),Gt=C.paint.get("model-opacity").evaluate(Ft,es);nk(C,xt.id,es,xt.featureProperties,xt.nodeOverrideNames,xt.nodeOverrides),k1(C,xt.id,es,xt.featureProperties,xt.materialOverrideNames,xt.materialOverrides),xt.nodeOverrides.size>0&&xt.computeBoundsAndApplyParent(),xt.computeModelMatrix(I,Qt,At,Dt,te,Z,!1);const gs=o.b9([]),ns=o.e2(xt.position.lat,I.transform.zoom),$s=o.bP([],[1,1,1/ns]);o.bx(gs,gs,mt),st.push({zScaleMatrix:$s,negCameraPosMatrix:gs});for(const Ps of xt.nodes)tk(I,Ps,xt.matrix,I.transform.expandedFarZProjMatrix,Tt,ht,kt,xt.materialOverrides,Gt);Tt++}if(ht.sort((xt,es)=>es.depth-xt.depth),I.renderPass!=="shadow"){if(I._debugParams.show3DModelFootprints){const xt=I.transform.projMatrix,es=new Map,Ft=(At,Dt)=>{if(At.footprint){const Gt=At.id||At.name||"footprint";if(!es.has(Gt)){const gs=o.aD([],xt,Dt);es.set(Gt,{node:At,mvp:gs})}}};for(const At of kt)Ft(At.node,At.modelMatrix);for(const At of ht)Ft(At.node,At.modelMatrix);const Qt=Array.from(es.keys()).sort();for(const At of Qt){const{node:Dt,mvp:Gt}=es.get(At);sk(I,0,Dt,Gt)}}Kd(I,C,ht,kt,st),Re()}else{for(const xt of kt)p_(xt.mesh,xt.nodeModelMatrix,I,C);for(const xt of ht)p_(xt.mesh,xt.nodeModelMatrix,I,C);Re()}}},Wn={line:function(I,y,C){if(I.hasElevatedBuckets=!1,I.hasNonElevatedBuckets=!1,I._unevaluatedLayout.getValue("line-elevation-reference")!==void 0||I._unevaluatedLayout.getValue("line-z-offset")!==void 0){if(y){const R=y.getVisibleCoordinates();for(const $ of R){const G=y.getTile($).getBucket(I);if(G&&(G.elevationType!=="none"?I.hasElevatedBuckets=!0:I.hasNonElevatedBuckets=!0,I.hasElevatedBuckets&&I.hasNonElevatedBuckets))break}}}else I.hasNonElevatedBuckets=!0},model:function(I,y,C){const R=y.getSource();if(!R.loaded())return;if(R.type==="vector"||R.type==="geojson")return void(C.modelManager&&C.modelManager.upload(C,Bj(C,I)));if(R.type==="batched-model"||R.type!=="model")return;const $=R.getModels();for(const G of $)G.upload(C.context)},raster:function(I,y,C){const R=y.getSource();if(!(R instanceof fm&&R.loaded()))return;const $=I.sourceLayer||R.rasterLayerIds&&R.rasterLayerIds[0];if(!$)return;const G=I.paint.get("raster-array-band")||R.getInitialBand($);if(G==null)return;const Z=y.getIds().map(te=>y.getTileByID(te));for(const te of Z)te.updateNeeded(I.id,G)&&R.prepareTile(te,$,I.id,G)},"raster-particle":function(I,y,C){const R=y.getSource();if(!(R instanceof fm&&R.loaded()))return;const $=I.sourceLayer||R.rasterLayerIds&&R.rasterLayerIds[0];if(!$)return;const G=I.paint.get("raster-particle-array-band")||R.getInitialBand($);if(G==null)return;const Z=y.getIds().map(te=>y.getTileByID(te));for(const te of Z)te.updateNeeded(I.id,G)&&R.prepareTile(te,$,I.id,G)}},Ur={fill:Gy},Ua={fill:function(I,y,C,R){if(!C.layout||C.layout.get("fill-elevation-reference")==="none"||C.paint.get("fill-opacity").constantOr(1)===0)return;const $=I.context.gl,G=new ar($.LEQUAL,ar.ReadOnly,I.depthRangeFor3D),Z=new oa({func:$.ALWAYS,mask:255},255,255,$.KEEP,$.KEEP,$.REPLACE),te=I.transform.getFreeCameraOptions().position,de=I.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const xe of R){const we=y.getTile(xe),Re=we.getBucket(C);if(!Re)continue;const Le=Re.elevatedStructures;if(!Le||Le.depthSegments.segments[0].primitiveLength===0)continue;const Ue=j0(xe.toUnwrapped(),te),st=I.translatePosMatrix(xe.projMatrix,we,C.paint.get("fill-translate"),C.paint.get("fill-translate-anchor")),Je=_1(st,Ue,0,1,0);de.draw(I,$.TRIANGLES,G,Z,sa.disabled,Rr.disabled,Je,C.id,Le.vertexBuffer,Le.indexBuffer,Le.depthSegments,C.paint,I.transform.zoom)}}};class oo{constructor(y,C,R,$,G){this.context=new b0(y,C),this.transform=R,this._tileTextures={},this.frameCopies=[],this.loadTimeStamps=[],this._timeStamp=o.o.now(),this._averageFPS=0,this._fpsHistory=[],this._dt=0,this._debugParams={forceEnablePrecipitation:!1,showTerrainProxyTiles:!1,fpsWindow:30,continousRedraw:!1,show3DModelFootprints:!1,enabledLayers:{}};const Z=["fill","line","symbol","circle","heatmap","fill-extrusion","building","raster","raster-particle","hillshade","model","background","sky"];for(const de of Z)this._debugParams.enabledLayers[de]=!0;for(const de of Z);this.occlusionParams=new RC,this.setup(),this.numSublayers=al.maxUnderzooming+al.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 ec(this),this._wireframeDebugCache=new DC,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const te=new o.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,te,y.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=$,this.maxFrontCutoffRawStart=0,this.worldview=G,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(y,C){const R=!!y&&!!y.terrain&&this.transform.projection.supportsTerrain;if(!(R||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new Vy(this,y));const $=this._terrain;this.transform.elevation=R?$:null,$.update(y,this.transform,C),this.transform.elevation&&!$.enabled&&(this.transform.elevation=null)}_updateFog(y){const C=y.fog;if(!C||this.transform.projection.name==="globe"||C.getOpacity(this.transform.pitch)<1||C.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[R,$]=C.getFovAdjustedRange(this.transform._fov);if(R>$)return void(this.transform.fogCullDistSq=null);const G=R+.78*($-R);this.transform.fogCullDistSq=G*G}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(y){y&&!this._terrain&&(this._terrain=new Vy(this,this.style)),this._forceTerrainMode=y}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(y,C){if(this.width=y*o.o.devicePixelRatio,this.height=C*o.o.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const R of this.style.order)this.style._mergedLayers[R].resize()}setup(){const y=this.context,C=new o.dB;C.emplaceBack(0,0),C.emplaceBack(o.an,0),C.emplaceBack(0,o.an),C.emplaceBack(o.an,o.an),this.tileExtentBuffer=y.createVertexBuffer(C,o.dx.members),this.tileExtentSegments=o.dy.simpleSegment(0,0,4,2);const R=new o.dB;R.emplaceBack(0,0),R.emplaceBack(o.an,0),R.emplaceBack(0,o.an),R.emplaceBack(o.an,o.an),this.debugBuffer=y.createVertexBuffer(R,o.dx.members),this.debugSegments=o.dy.simpleSegment(0,0,4,5);const $=new o.dB;$.emplaceBack(-1,-1),$.emplaceBack(1,-1),$.emplaceBack(-1,1),$.emplaceBack(1,1),this.viewportBuffer=y.createVertexBuffer($,o.dx.members),this.viewportSegments=o.dy.simpleSegment(0,0,4,2);const G=new o.eH;G.emplaceBack(0,0,0,0),G.emplaceBack(o.an,0,o.an,0),G.emplaceBack(0,o.an,0,o.an),G.emplaceBack(o.an,o.an,o.an,o.an),this.mercatorBoundsBuffer=y.createVertexBuffer(G,o.eI.members),this.mercatorBoundsSegments=o.dy.simpleSegment(0,0,4,2);const Z=new o.dC;Z.emplaceBack(0,1,2),Z.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=y.createIndexBuffer(Z);const te=new o.eJ;for(const xe of[0,1,3,2,0])te.emplaceBack(xe);this.debugIndexBuffer=y.createIndexBuffer(te),this.emptyTexture=new o.T(y,new o.q({width:1,height:1},Uint8Array.of(0,0,0,0)),y.gl.RGBA8),this.identityMat=o.bb();const de=this.context.gl;this.stencilClearMode=new oa({func:de.ALWAYS,mask:0},0,255,de.ZERO,de.ZERO,de.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(y){return y._makeTileBoundsBuffers(this.context,this.transform.projection),y._tileBoundsBuffer?{tileBoundsBuffer:y._tileBoundsBuffer,tileBoundsIndexBuffer:y._tileBoundsIndexBuffer,tileBoundsSegments:y._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const y=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram("clippingMask").draw(this,y.TRIANGLES,ar.disabled,this.stencilClearMode,sa.disabled,Rr.disabled,Cj(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(y,C,R){if(!C||this.currentStencilSource===C.id||!y.isTileClipped()||!R||R.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let te=!1;for(const de of R)if(this._tileClippingMaskIDs[de.key]===void 0){te=!0;break}if(!te)return}this.currentStencilSource=C.id;const $=this.context,G=$.gl;this.nextStencilID+R.length>256&&this.clearStencil(),$.setColorMode(sa.disabled),$.setDepthMode(ar.disabled);const Z=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const te of R){const de=C.getTile(te),xe=this._tileClippingMaskIDs[te.key]=this.nextStencilID++,{tileBoundsBuffer:we,tileBoundsIndexBuffer:Re,tileBoundsSegments:Le}=this.getTileBoundsBuffers(de);Z.draw(this,G.TRIANGLES,ar.disabled,new oa({func:G.ALWAYS,mask:0},xe,255,G.KEEP,G.KEEP,G.REPLACE),sa.disabled,Rr.disabled,Cj(te.projMatrix),"$clipping",we,Re,Le)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const y=this.nextStencilID++,C=this.context.gl;return new oa({func:C.NOTEQUAL,mask:255},y,255,C.KEEP,C.KEEP,C.REPLACE)}stencilModeForClipping(y){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(y);const C=this.context.gl;return new oa({func:C.EQUAL,mask:255},this._tileClippingMaskIDs[y.key],0,C.KEEP,C.KEEP,C.REPLACE)}stencilConfigForOverlap(y){const C=this.context.gl,R=y.sort((Z,te)=>te.overscaledZ-Z.overscaledZ),$=R[R.length-1].overscaledZ,G=R[0].overscaledZ-$+1;if(G>1){this.currentStencilSource=void 0,this.nextStencilID+G>256&&this.clearStencil();const Z={};for(let te=0;tethis._debugParams.fpsWindow&&this._fpsHistory.splice(0,this._fpsHistory.length-this._debugParams.fpsWindow),this._averageFPS=Math.round(this._fpsHistory.reduce((y,C)=>y+C/this._fpsHistory.length,0))}render(y,C){const R=o.o.now();this._dt=R-this._timeStamp,this._timeStamp=R,this._wireframeDebugCache.update(this.frameCounter),this._debugParams.continousRedraw=y.map.repaint,this.style=y,this.options=C;const $=this.style._mergedLayers,G=!(!this.terrain||!this.terrain.enabled),Z=()=>this.style._getOrder(G).filter(Ns=>{const hs=$[Ns];return!(hs.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[hs.type]});let te=Z(),de=!1,xe=!1,we=null,Re=0,Le=!1;for(const Ns of te){const hs=$[Ns];hs.visibility!=="none"&&(hs.type==="circle"?de=!0:hs.type==="building"?(we=hs,++Re):hs.type==="symbol"&&(hs.hasOcclusionOpacityProperties?xe=!0:de=!0))}this.updateEmissiveMode();let Ue=te.map(Ns=>$[Ns]);const st=this.style._mergedSourceCaches;this.imageManager=y.imageManager,this.modelManager=y.modelManager,this.symbolFadeChange=y.placement.symbolFadeChange(o.o.now()),this.imageManager.beginFrame();for(const Ns in st){const hs=st[Ns];hs.used&&(hs.prepare(this.context),hs.getSource().usedInConflation&&++Re)}let Je=!1;for(const Ns of Ue)Ns.isHidden(this.transform.zoom)||(Ns.type==="clip"&&(Je=!0),this.prepareLayer(Ns));const mt={},ht={},kt={},Tt={},xt={};for(const Ns in st){const hs=st[Ns];mt[Ns]=hs.getVisibleCoordinates(),ht[Ns]=mt[Ns].slice().reverse(),kt[Ns]=hs.getVisibleCoordinates(!0).reverse(),Tt[Ns]=hs.getShadowCasterCoordinates(),xt[Ns]=hs.sortCoordinatesByDistance(mt[Ns])}const es=Ns=>{const hs=this.style.getLayerSourceCache(Ns);return hs&&hs.used?hs.getSource():null};if(Re||Je||this._clippingActiveLastFrame){const Ns=[],hs=[];let zs=0;for(const Us of Ue)this.isSourceForClippingOrConflation(Us,es(Us))&&(Ns.push(Us),hs.push(zs)),zs++;if(Ns&&(Je||Ns.length>1)||this._clippingActiveLastFrame){Je=!1;const Us=[];for(let Ys=0;Ys0){const Us=es(hs);Us&&(this.minCutoffZoom=Math.max(Us.minzoom,this.minCutoffZoom)),hs.minzoom&&(this.minCutoffZoom=Math.max(hs.minzoom,this.minCutoffZoom))}hs.is3D(G)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=Ns),this._lastOcclusionLayer=Ns)}const Ft=this.style&&this.style.fog;Ft?(this._fogVisible=Ft.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=Ft.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(kt),this.opaquePassCutoff=0,te=Z(),Ue=te.map(Ns=>$[Ns]));const Qt=this._shadowRenderer;if(Qt){Qt.updateShadowParameters(this.transform,this.style.directionalLight);for(const Ns in st)for(const hs of mt[Ns]){let zs={min:0,max:0};this.terrain&&(zs=this.terrain.getMinMaxForTile(hs)||zs),Qt.addShadowReceiver(hs.toUnwrapped(),zs.min,zs.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 C6(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const At=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),Dt=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if(At&&!this._snow&&(this._snow=new ps(this)),!At&&this._snow&&(this._snow.destroy(),delete this._snow),Dt&&!this._rain&&(this._rain=new et(this)),!Dt&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),we){this.buildingTileBorderManager||(this.buildingTileBorderManager=new Nm);const Ns=this.style.getLayerSourceCache(we);this.buildingTileBorderManager.updateBorders(Ns,we)}if(!Ge.has(this.context.gl))return;this.renderPass="offscreen";for(const Ns of Ue){const hs=y.getLayerSourceCache(Ns);if(!Ns.hasOffscreenPass()||Ns.isHidden(this.transform.zoom))continue;const zs=hs?ht[hs.id]:void 0;(Ns.type==="custom"||Ns.type==="raster"||Ns.type==="raster-particle"||Ns.isSky()||zs&&zs.length)&&this.renderLayer(this,hs,Ns,zs)}this.depthRangeFor3D=[0,1-(Ue.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,Tt)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const Gt=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),gs=(()=>{if(C.showOverdrawInspector)return o.aq.black;const Ns=this.style.fog;if(Ns&&this.transform.projection.supportsFog){const hs=this.style.getLut(Ns.scope);if(!Gt){const zs=Ns.properties.get("color-use-theme")==="none",Us=Ns.properties.get("color").toNonPremultipliedRenderColor(zs?null:hs).toArray01();return new o.aq(...Us)}if(Gt){const zs=Ns.properties.get("space-color-use-theme")==="none",Us=Ns.properties.get("space-color").toNonPremultipliedRenderColor(zs?null:hs).toArray01();return new o.aq(...Us)}}return o.aq.transparent})();if(this.context.clear({color:gs,depth:1}),this.clearStencil(),this._showOverdrawInspector=C.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Gt&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=te.length-1;this.currentLayer>=0;this.currentLayer--){const Ns=Ue[this.currentLayer],hs=y.getLayerSourceCache(Ns);if(Ns.isSky())continue;const zs=hs?(Ns.is3D(G)?xt:ht)[hs.id]:void 0;this._renderTileClippingMasks(Ns,hs,zs),this.renderLayer(this,hs,Ns,zs)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Gt&&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 zs=this.currentLayer;this.depthOcclusion=!0;for(const Us of this.layersWithOcclusionOpacity){this.currentLayer=Us;const Ys=Ue[this.currentLayer],Rn=y.getLayerSourceCache(Ys),Sn=Rn?ht[Rn.id]:void 0;this.terrain||this._renderTileClippingMasks(Ys,Rn,Rn?mt[Rn.id]:void 0),this.renderLayer(this,Rn,Ys,Sn)}this.depthOcclusion=!1,this.currentLayer=zs,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 Ns=null;Ue.forEach(hs=>{const zs=y.getLayerSourceCache(hs);zs&&!hs.isHidden(this.transform.zoom)&&zs.getVisibleCoordinates().length&&(!Ns||Ns.getSource().maxzoom0?C.pop():null}terrainRenderModeElevated(){return this.style&&!!this.style.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(y,C,R){const $=R===void 0?this.terrain&&this.terrain.renderingToTexture:R,G=[];return this.style&&this.style.enable3dLights()&&(y==="globeRaster"||y==="terrainRaster"?(G.push("LIGHTING_3D_MODE"),G.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):$||G.push("LIGHTING_3D_MODE")),this.terrainRenderModeElevated()&&(G.push("TERRAIN"),this.linearFloatFilteringSupported()&&G.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&G.push("GLOBE"),!this._fogVisible||$||C!==void 0&&!C||G.push("FOG"),$&&G.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&G.push("OVERDRAW_INSPECTOR"),G}getOrCreateProgram(y,C){this.cache=this.cache||{};const R=C&&C.defines||[],$=C&&C.config,G=this.currentGlobalDefines(y,C&&C.overrideFog,C&&C.overrideRtt).concat(R),Z=cd.cacheKey(yC[y],y,G,$);return this.cache[Z]||(this.cache[Z]=new cd(this.context,y,yC[y],$,c_[y],G)),this.cache[Z]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.frontFace.setDefault(),this.context.cullFaceSide.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault()}setBaseState(){const y=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(y.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(y,C){if(this.style.enable3dLights()){const R=this.style.directionalLight,$=this.style.ambientLight;if(R&&$){const G=((Z,te,de)=>{const xe=Z.properties.get("direction"),we=Z.properties.get("color-use-theme")==="none",Re=Z.properties.get("color").toNonPremultipliedRenderColor(we?null:de.getLut(Z.scope)).toArray01(),Le=Z.properties.get("intensity"),Ue=te.properties.get("color-use-theme")==="none",st=te.properties.get("color").toNonPremultipliedRenderColor(Ue?null:de.getLut(te.scope)).toArray01(),Je=te.properties.get("intensity"),mt=[xe.x,xe.y,xe.z],ht=o.dD(st,Je),kt=o.dD(Re,Le);return{u_lighting_ambient_color:ht,u_lighting_directional_dir:mt,u_lighting_directional_color:kt,u_ground_radiance:n_(mt,kt,ht)}})(R,$,this.style);C.setLightsUniformValues(y,G)}}}uploadCommonUniforms(y,C,R,$,G){if(this.uploadCommonLightUniforms(y,C),this.terrain&&this.terrain.renderingToTexture)return;const Z=this.style.fog;if(Z){const te=Z.getOpacity(this.transform.pitch),de=((xe,we,Re,Le,Ue,st,Je,mt,ht,kt,Tt,xt)=>{const es=xe.transform,Ft=we.properties.get("color-use-theme")==="none",Qt=we.properties.get("color").toNonPremultipliedRenderColor(Ft?null:xe.style.getLut(we.scope)).toArray01();Qt[3]=Le;const At=xe.frameCounter/1e3%1,[Dt,Gt]=we.properties.get("vertical-range");return{u_fog_matrix:Re?es.calculateFogTileMatrix(Re):xt||xe.identityMat,u_fog_range:we.getFovAdjustedRange(es._fov),u_fog_color:Qt,u_fog_horizon_blend:we.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(Dt,Gt),Gt],u_fog_temporal_offset:At,u_frustum_tl:Ue,u_frustum_tr:st,u_frustum_br:Je,u_frustum_bl:mt,u_globe_pos:ht,u_globe_radius:kt,u_viewport:Tt,u_globe_transition:o.al(es.zoom),u_is_globe:+(es.projection.name==="globe")}})(this,Z,R,te,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],$);C.setFogUniformValues(y,de)}G&&C.setCutoffUniformValues(y,G.uniformValues)}setTileLoadedFlag(y){this.tileLoaded=y}saveCanvasCopy(){const y=this.canvasCopy();y&&(this.frameCopies.push(y),this.tileLoaded=!1)}canvasCopy(){const y=this.context.gl,C=y.createTexture();return y.bindTexture(y.TEXTURE_2D,C),y.copyTexImage2D(y.TEXTURE_2D,0,y.RGBA,0,0,y.drawingBufferWidth,y.drawingBufferHeight,0),C}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const y=this.style&&this.style.fog;return!!y&&y.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const y=this._backgroundTiles,C=this._backgroundTiles={},R=this.transform.coveringTiles({tileSize:512});for(const $ of R)C[$.key]=y[$.key]||new o.b0($,512,this.transform.tileZoom,this,void 0,this.worldview);return C}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(y,C){return!(!y.is3D(!(!this.terrain||!this.terrain.enabled))||y.type!=="clip"&&y.type!=="building"&&(y.minzoom&&y.minzoom>this.transform.zoom||(this.style._clipLayerPresent||y.sourceLayer!=="building"&&y.sourceLayer!=="procedural_buildings")&&(!C||C.type!=="batched-model")))}isTileAffectedByFog(y){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let C=this._cachedTileFogOpacities[y.key];return C||(this._cachedTileFogOpacities[y.key]=C=this.style.fog.getOpacityForTile(y)),C[0]>=sr||C[1]>=sr}setupDepthForOcclusion(y,C,R){const $=this.context,G=$.gl,Z=!!R;var te;R||(R={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}),$.activeTexture.set(G.TEXTURE3),y&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(G.NEAREST,G.CLAMP_TO_EDGE),R.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],R.u_depth_range_unpack=[2/((te=this.depthRangeFor3D)[1]-te[0]),-1-2*te[0]/(te[1]-te[0])],R.u_occluder_half_size=.5*this.occlusionParams.occluderSize,R.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(G.NEAREST,G.CLAMP_TO_EDGE),$.activeTexture.set(G.TEXTURE0),Z||C.setTerrainUniformValues($,R)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const y=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=y?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function Sa(I,y){let C=!1,R=null;const $=()=>{R=null,C&&(I(),R=setTimeout($,y),C=!1)};return()=>(C=!0,R||$(),R)}class Nc{constructor(y){this._hashName=y&&encodeURIComponent(y),o.aZ(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=Sa(this._updateHashUnthrottled.bind(this),300)}addTo(y){return this._map=y,window.addEventListener("hashchange",this._onHashChange,!1),y.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 y=this._map;if(!y)return"";const C=lo(y);if(this._hashName){const R=this._hashName;let $=!1;const G=location.hash.slice(1).split("&").map(Z=>{const te=Z.split("=")[0];return te===R?($=!0,`${te}=${C}`):Z}).filter(Z=>Z);return $||G.push(`${R}=${C}`),`#${G.join("&")}`}return`#${C}`}_getCurrentHash(){const y=location.hash.replace("#","");if(this._hashName){let C;return y.split("&").map(R=>R.split("=")).forEach(R=>{R[0]===this._hashName&&(C=R)}),(C&&C[1]||"").split("/")}return y.split("/")}_onHashChange(){const y=this._map;if(!y)return!1;const C=this._getCurrentHash();if(C.length>=3&&!C.some(R=>isNaN(Number(R)))){const R=y.dragRotate.isEnabled()&&y.touchZoomRotate.isEnabled()?+(C[3]||0):y.getBearing();return y.jumpTo({center:[+C[2],+C[1]],zoom:+C[0],bearing:R,pitch:+(C[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(/(#.+)?$/,this.getHashString()))}}function lo(I,y){const C=I.getCenter(),R=Math.round(100*I.getZoom())/100,$=Math.ceil((R*Math.LN2+Math.log(512/360/.5))/Math.LN10),G=Math.pow(10,$),Z=Math.round(C.lng*G)/G,te=Math.round(C.lat*G)/G,de=I.getBearing(),xe=I.getPitch();let we=y?`/${Z}/${te}/${R}`:`${R}/${te}/${Z}`;return(de||xe)&&(we+="/"+Math.round(10*de)/10),xe&&(we+=`/${Math.round(xe)}`),we}const _h={linearity:.3,easing:o.eN(0,0,.3,1)},Wp=Object.assign({deceleration:2500,maxSpeed:1400},_h),qn=Object.assign({deceleration:20,maxSpeed:1400},_h),Ks=Object.assign({deceleration:1e3,maxSpeed:360},_h),cn=Object.assign({deceleration:1e3,maxSpeed:90},_h);class Da{constructor(y){this._map=y,this.clear()}clear(){this._inertiaBuffer=[]}record(y){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:o.o.now(),settings:y})}_drainInertiaBuffer(){const y=this._inertiaBuffer,C=o.o.now();for(;y.length>0&&C-y[0].time>160;)y.shift()}_onMoveEnd(y){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const C={zoom:0,bearing:0,pitch:0,pan:new o.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:G}of this._inertiaBuffer)C.zoom+=G.zoomDelta||0,C.bearing+=G.bearingDelta||0,C.pitch+=G.pitchDelta||0,G.panDelta&&C.pan._add(G.panDelta),G.around&&(C.around=G.around),G.pinchAround&&(C.pinchAround=G.pinchAround);const R=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,$={};if(C.pan.mag()){const G=$i(C.pan.mag(),R,Object.assign({},Wp,y||{}));$.offset=C.pan.mult(G.amount/C.pan.mag()),$.center=this._map.transform.center,Ha($,G)}if(C.zoom){const G=$i(C.zoom,R,qn);$.zoom=this._map.transform.zoom+G.amount,Ha($,G)}if(C.bearing){const G=$i(C.bearing,R,Ks);$.bearing=this._map.transform.bearing+o.aC(G.amount,-179,179),Ha($,G)}if(C.pitch){const G=$i(C.pitch,R,cn);$.pitch=this._map.transform.pitch+G.amount,Ha($,G)}if($.zoom||$.bearing){const G=C.pinchAround===void 0?C.around:C.pinchAround;$.around=G?this._map.unproject(G):this._map.getCenter()}return this.clear(),$.noMoveStart=!0,$}}function Ha(I,y){(!I.duration||I.durationC.unproject(de)),te=G.reduce((de,xe,we,Re)=>de.add(xe.div(Re.length)),new o.P(0,0));super(y,{points:G,point:te,lngLats:Z,lngLat:C.unproject(te),originalEvent:R}),this._defaultPrevented=!1}}class Yd extends o.C{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(y,C){super("wheel",{originalEvent:C}),this._defaultPrevented=!1}}class il{constructor(y,C){this._map=y,this._clickTolerance=C.clickTolerance}reset(){this._mousedownPos=void 0}wheel(y){return this._firePreventable(new Yd(this._map,y))}mousedown(y,C){return this._mousedownPos=C,this._firePreventable(new ri(y.type,this._map,y))}mouseup(y){this._map.fire(new ri(y.type,this._map,y))}preclick(y){const C=new MouseEvent("preclick",y);this._map.fire(new ri(C.type,this._map,C))}click(y,C){this._mousedownPos&&this._mousedownPos.dist(C)>=this._clickTolerance||(this.preclick(y),this._map.fire(new ri(y.type,this._map,y)))}dblclick(y){return this._firePreventable(new ri(y.type,this._map,y))}mouseover(y){this._map.fire(new ri(y.type,this._map,y))}mouseout(y){this._map.fire(new ri(y.type,this._map,y))}touchstart(y){return this._firePreventable(new ro(y.type,this._map,y))}touchmove(y){this._map.fire(new ro(y.type,this._map,y))}touchend(y){this._map.fire(new ro(y.type,this._map,y))}touchcancel(y){this._map.fire(new ro(y.type,this._map,y))}_firePreventable(y){if(this._map.fire(y),y.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class yg{constructor(y){this._map=y}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(y){this._map.fire(new ri(y.type,this._map,y))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new ri("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(y){this._delayContextMenu?this._contextMenuEvent=y:this._map.fire(new ri(y.type,this._map,y)),this._map.listens("contextmenu")&&y.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class FC{constructor(y,C){this._map=y,this._el=y.getCanvasContainer(),this._container=y.getContainer(),this._clickTolerance=C.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(y,C){this.isEnabled()&&y.shiftKey&&y.button===0&&(A(),this._startPos=this._lastPos=C,this._active=!0)}mousemoveWindow(y,C){if(!this._active)return;const R=C,$=this._startPos,G=this._lastPos;if(!$||!G||G.equals(R)||!this._box&&R.dist($){this._box&&(this._box.style.transform=`translate(${Z}px,${de}px)`,this._box.style.width=te-Z+"px",this._box.style.height=xe-de+"px")})}mouseupWindow(y,C){if(!this._active)return;const R=this._startPos,$=C;if(R&&y.button===0){if(this.reset(),D(),R.x!==$.x||R.y!==$.y)return this._map.fire(new o.C("boxzoomend",{originalEvent:y})),{cameraAnimation:G=>G.fitScreenCoordinates(R,$,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",y)}}keydown(y){this._active&&y.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",y))}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(y,C){return this._map.fire(new o.C(y,{originalEvent:C}))}}function zC(I,y){const C={};for(let R=0;Rthis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=y.timeStamp),R.length===this.numTouches&&(this.centroid=function($){const G=new o.P(0,0);for(const Z of $)G._add(Z);return G.div($.length)}(C),this.touches=zC(R,C)))}touchmove(y,C,R){if(this.aborted||!this.centroid)return;const $=zC(R,C);for(const G in this.touches){const Z=$[G];(!Z||Z.dist(this.touches[G])>30)&&(this.aborted=!0)}}touchend(y,C,R){if((!this.centroid||y.timeStamp-this.startTime>500)&&(this.aborted=!0),R.length===0){const $=!this.aborted&&this.centroid;if(this.reset(),$)return $}}}class Zy{constructor(y){this.singleTap=new vg(y),this.numTaps=y.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(y,C,R){this.singleTap.touchstart(y,C,R)}touchmove(y,C,R){this.singleTap.touchmove(y,C,R)}touchend(y,C,R){const $=this.singleTap.touchend(y,C,R);if($){const G=y.timeStamp-this.lastTime<500,Z=!this.lastTap||this.lastTap.dist($)<30;if(G&&Z||this.reset(),this.count++,this.lastTime=y.timeStamp,this.lastTap=$,this.count===this.numTaps)return this.reset(),$}}}class ok{constructor(){this._zoomIn=new Zy({numTouches:1,numTaps:2}),this._zoomOut=new Zy({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(y,C,R){this._zoomIn.touchstart(y,C,R),this._zoomOut.touchstart(y,C,R)}touchmove(y,C,R){this._zoomIn.touchmove(y,C,R),this._zoomOut.touchmove(y,C,R)}touchend(y,C,R){const $=this._zoomIn.touchend(y,C,R),G=this._zoomOut.touchend(y,C,R);return $?(this._active=!0,y.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:Z=>Z.easeTo({duration:300,zoom:Z.getZoom()+1,around:Z.unproject($)},{originalEvent:y})}):G?(this._active=!0,y.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:Z=>Z.easeTo({duration:300,zoom:Z.getZoom()-1,around:Z.unproject(G)},{originalEvent:y})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const E6=0,qR=2,VR={[E6]:1,[qR]:2},C1={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class BC{constructor(y){this.reset(),this._clickTolerance=y.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(y,C){return!1}_move(y,C){return{}}mousedown(y,C){if(this._lastPoint)return;const R=z(y);this._correctButton(y,R)&&(this._lastPoint=C,this._eventButton=R)}mousemoveWindow(y,C){const R=this._lastPoint;if(R){if(y.preventDefault(),this._eventButton!=null&&function($,G){const Z=VR[G];return $.buttons===void 0||($.buttons&Z)!==Z}(y,this._eventButton))this.reset();else if(this._moved||!(C.dist(R)0&&(this._active=!0);const $=zC(R,C),G=new o.P(0,0),Z=new o.P(0,0);let te=0;for(const xe in $){const we=$[xe],Re=this._touches[xe];Re&&(G._add(we),Z._add(we.sub(Re)),te++,$[xe]=we)}if(this._touches=$,te{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class UC{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(y){}_move(y,C,R){return{}}touchstart(y,C,R){this._firstTwoTouches||R.length<2||(this._firstTwoTouches=[R[0].identifier,R[1].identifier],this._start([C[0],C[1]]))}touchmove(y,C,R){const $=this._firstTwoTouches;if(!$)return;y.preventDefault();const[G,Z]=$,te=sc(R,C,G),de=sc(R,C,Z);if(!te||!de)return;const xe=this._aroundCenter?null:te.add(de).div(2);return this._move([te,de],xe,y)}touchend(y,C,R){if(!this._firstTwoTouches)return;const[$,G]=this._firstTwoTouches,Z=sc(R,C,$),te=sc(R,C,G);Z&&te||(this._active&&D(),this.reset())}touchcancel(){this.reset()}enable(y){this._enabled=!0,this._aroundCenter=!!y&&y.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function sc(I,y,C){for(let R=0;RMath.abs(I.x)}class WR extends UC{constructor(y){super(),this._map=y}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(y){this._lastPoints=y,qC(y[0].sub(y[1]))&&(this._valid=!1)}_move(y,C,R){const $=this._lastPoints;if(!$)return;const G=y[0].sub($[0]),Z=y[1].sub($[1]);return this._map._cooperativeGestures&&!o.eO()&&R.touches.length<3||(this._valid=this.gestureBeginsVertically(G,Z,R.timeStamp),!this._valid)?void 0:(this._lastPoints=y,this._active=!0,{pitchDelta:(G.y+Z.y)/2*-.5})}gestureBeginsVertically(y,C,R){if(this._valid!==void 0)return this._valid;const $=y.mag()>=2,G=C.mag()>=2;if(!$&&!G)return;if(!$||!G)return this._firstMove==null&&(this._firstMove=R),R-this._firstMove<100&&void 0;const Z=y.y>0==C.y>0;return qC(y)&&qC(C)&&Z}}const KR={panStep:100,bearingStep:15,pitchStep:10};class Vj{constructor(){const y=KR;this._panStep=y.panStep,this._bearingStep=y.bearingStep,this._pitchStep=y.pitchStep,this._rotationDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(y){if(y.altKey||y.ctrlKey||y.metaKey)return;let C=0,R=0,$=0,G=0,Z=0;switch(y.keyCode){case 61:case 107:case 171:case 187:C=1;break;case 189:case 109:case 173:C=-1;break;case 37:y.shiftKey?R=-1:(y.preventDefault(),G=-1);break;case 39:y.shiftKey?R=1:(y.preventDefault(),G=1);break;case 38:y.shiftKey?$=1:(y.preventDefault(),Z=-1);break;case 40:y.shiftKey?$=-1:(y.preventDefault(),Z=1);break;default:return}return this._rotationDisabled&&(R=0,$=0),{cameraAnimation:te=>{const de=te.getZoom();te.easeTo({duration:300,easeId:"keyboardHandler",easing:YR,zoom:C?Math.round(de)+C*(y.shiftKey?2:1):de,bearing:te.getBearing()+R*this._bearingStep,pitch:te.getPitch()+$*this._pitchStep,offset:[-G*this._panStep,-Z*this._panStep],center:te.getCenter()},{originalEvent:y})}}}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 YR(I){return I*(2-I)}const Hj=4.000244140625,ZR=1/450;class P6{constructor(y,C){this._map=y,this._el=y.getCanvasContainer(),this._handler=C,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=ZR,o.aZ(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}setZoomRate(y){this._defaultZoomRate=y}setWheelZoomRate(y){this._wheelZoomRate=y}isEnabled(){return!!this._enabled}isActive(){return this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(y){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!y&&y.around==="center",this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(y){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(y.ctrlKey||y.metaKey||this.isZooming()||o.eO()))return void this._showBlockerAlert();this._alertContainer.style.visibility!=="hidden"&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let C=y.deltaMode===WheelEvent.DOM_DELTA_LINE?40*y.deltaY:y.deltaY;const R=o.o.now(),$=R-(this._lastWheelEventTime||0);this._lastWheelEventTime=R,C!==0&&C%Hj===0?this._type="wheel":C!==0&&Math.abs(C)<4?this._type="trackpad":$>400?(this._type=null,this._lastValue=C,this._timeout=window.setTimeout(this._onTimeout,40,y)):this._type||(this._type=Math.abs($*C)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,C+=this._lastValue)),y.shiftKey&&C&&(C/=4),this._type&&(this._lastWheelEvent=y,this._delta-=C,this._active||this._start(y)),y.preventDefault()}_onTimeout(y){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(y)}_start(y){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const C=M(this._el,y);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:C,this._aroundCoord=this._map.transform.pointCoordinate3D(this._aroundPoint),this._targetZoom=void 0,this._frameId||(this._frameId=!0,this._handler._triggerRenderFrame())}renderFrame(){if(!this._frameId||(this._frameId=null,!this.isActive()))return;const y=this._map.transform;this._type==="wheel"&&y.projection.wrap&&(y._center.lng>=180||y._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const C=()=>y._terrainEnabled()&&this._aroundCoord?y.computeZoomRelativeTo(this._aroundCoord):y.zoom;if(this._delta!==0){const xe=this._type==="wheel"&&Math.abs(this._delta)>Hj?this._wheelZoomRate:this._defaultZoomRate;let we=2/(1+Math.exp(-Math.abs(this._delta*xe)));this._delta<0&&we!==0&&(we=1/we);const Re=C(),Le=Math.pow(2,Re),Ue=typeof this._targetZoom=="number"?y.zoomScale(this._targetZoom):Le;this._targetZoom=Math.min(y.maxZoom,Math.max(y.minZoom,y.scaleZoom(Ue*we))),this._type==="wheel"&&(this._startZoom=Re,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const R=typeof this._targetZoom=="number"?this._targetZoom:C(),$=this._startZoom,G=this._easing;let Z,te=!1;if(this._type==="wheel"&&$&&G){const xe=Math.min((o.o.now()-this._lastWheelEventTime)/200,1),we=G(xe);Z=o.am($,R,we),xe<1?this._frameId||(this._frameId=!0):te=!0}else Z=R,te=!0;this._active=!0,te&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let de=Z-C();return de*this._lastDelta<0&&(de=0),{noInertia:!0,needsRenderFrame:!te,zoomDelta:de,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(y){let C=o.eP;if(this._prevEase){const R=this._prevEase,$=(o.o.now()-R.start)/R.duration,G=R.easing($+.01)-R.easing($),Z=.27/Math.sqrt(G*G+1e-4)*.01,te=Math.sqrt(.0729-Z*Z);C=o.eN(Z,te,.25,1)}return this._prevEase={start:o.o.now(),duration:y,easing:C},C}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=_("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 L6{constructor(y,C){this._clickZoom=y,this._tapZoom=C}enable(){this._clickZoom.enable(),this._tapZoom.enable()}disable(){this._clickZoom.disable(),this._tapZoom.disable()}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class D6{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(y,C){return y.preventDefault(),{cameraAnimation:R=>{R.easeTo({duration:300,zoom:R.getZoom()+(y.shiftKey?-1:1),around:R.unproject(C)},{originalEvent:y})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class nq{constructor(){this._tap=new Zy({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(y,C,R){this._swipePoint||(this._tapTime&&y.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?R.length>0&&(this._swipePoint=C[0],this._swipeTouch=R[0].identifier):this._tap.touchstart(y,C,R))}touchmove(y,C,R){if(this._tapTime){if(this._swipePoint){if(R[0].identifier!==this._swipeTouch)return;const $=C[0],G=$.y-this._swipePoint.y;return this._swipePoint=$,y.preventDefault(),this._active=!0,{zoomDelta:G/128}}}else this._tap.touchmove(y,C,R)}touchend(y,C,R){this._tapTime?this._swipePoint&&R.length===0&&this.reset():this._tap.touchend(y,C,R)&&(this._tapTime=y.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class QR{constructor(y,C,R){this._el=y,this._mousePan=C,this._touchPan=R}enable(y){this._inertiaOptions=y||{},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 rq{constructor(y,C,R){this._pitchWithRotate=y.pitchWithRotate,this._mouseRotate=C,this._mousePitch=R}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 aq{constructor(y,C,R,$){this._el=y,this._touchZoom=C,this._touchRotate=R,this._tapDragZoom=$,this._rotationDisabled=!1,this._enabled=!0}enable(y){this._touchZoom.enable(y),this._rotationDisabled||this._touchRotate.enable(y),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 VC=I=>I.zoom||I.drag||I.pitch||I.rotate;class iq extends o.C{}class oq{constructor(){this.constants=[1,1,.01],this.radius=0}setup(y,C){const R=o.ax([],C,y);this.radius=o.ai(R[2]<0?o.eR([],R,this.constants):[R[0],R[1],0])}projectRay(y){o.eR(y,y,this.constants),o.ay(y,y),o.eS(y,y,this.constants);const C=o.bJ([],y,this.radius);if(C[2]>0){const R=o.bJ([],[0,0,1],o.bi(C,[0,0,1])),$=o.bJ([],o.ay([],[C[0],C[1],0]),this.radius),G=o.cT([],C,o.bJ([],o.ax([],o.cT([],$,R),C),2));C[0]=G[0],C[1]=G[1]}return C}}function HC(I){return I.panDelta&&I.panDelta.mag()||I.zoomDelta||I.bearingDelta||I.pitchDelta}class lq{constructor(y,C){this._map=y,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Da(y),this._bearingSnap=C.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new oq,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(C),o.aZ(["handleEvent","handleWindowEvent"],this);const R=this._el;this._listeners=[[R,"touchstart",{passive:!0}],[R,"touchmove",{passive:!1}],[R,"touchend",void 0],[R,"touchcancel",void 0],[R,"mousedown",void 0],[R,"mousemove",void 0],[R,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[R,"mouseover",void 0],[R,"mouseout",void 0],[R,"dblclick",void 0],[R,"click",void 0],[R,"keydown",{capture:!1}],[R,"keyup",void 0],[R,"wheel",{passive:!1}],[R,"contextmenu",void 0],[window,"blur",void 0]];for(const[$,G,Z]of this._listeners){const te=$===document?this.handleWindowEvent:this.handleEvent;$.addEventListener(G,te,Z)}}destroy(){for(const[y,C,R]of this._listeners){const $=y===document?this.handleWindowEvent:this.handleEvent;y.removeEventListener(C,$,R)}}_addDefaultHandlers(y){const C=this._map,R=C.getCanvasContainer();this._add("mapEvent",new il(C,y));const $=C.boxZoom=new FC(C,y);this._add("boxZoom",$);const G=new ok,Z=new D6;C.doubleClickZoom=new L6(Z,G),this._add("tapZoom",G),this._add("clickZoom",Z);const te=new nq;this._add("tapDragZoom",te);const de=C.touchPitch=new WR(C);this._add("touchPitch",de);const xe=new A6(y),we=new $C(y);C.dragRotate=new rq(y,xe,we),this._add("mouseRotate",xe,["mousePitch"]),this._add("mousePitch",we,["mouseRotate"]);const Re=new bg(y),Le=new HR(C,y);C.dragPan=new QR(R,Re,Le),this._add("mousePan",Re),this._add("touchPan",Le,["touchZoom","touchRotate"]);const Ue=new qj,st=new GR;C.touchZoomRotate=new aq(R,st,Ue,te),this._add("touchRotate",Ue,["touchPan","touchZoom"]),this._add("touchZoom",st,["touchPan","touchRotate"]),this._add("blockableMapEvent",new yg(C));const Je=C.scrollZoom=new P6(C,this);this._add("scrollZoom",Je,["mousePan"]);const mt=C.keyboard=new Vj;this._add("keyboard",mt);for(const ht of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])y.interactive&&y[ht]&&C[ht].enable(y[ht])}_add(y,C,R){this._handlers.push({handlerName:y,handler:C,allowed:R}),this._handlersById[y]=C}stop(y){if(!this._updatingCamera){for(const{handler:C}of this._handlers)C.reset();this._inertia.clear(),this._fireEvents({},{},y),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:y}of this._handlers)if(y.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!VC(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(y,C,R){for(const $ in y)if($!==R&&(!C||C.indexOf($)<0))return!0;return!1}handleWindowEvent(y){this.handleEvent(y,`${y.type}Window`)}_getMapTouches(y){const C=[];for(const R of y)this._el.contains(R.target)&&C.push(R);return C}handleEvent(y,C){this._updatingCamera=!0;const R=y.type==="renderFrame",$=R?void 0:y,G={needsRenderFrame:!1},Z={},te={},de=y.touches?this._getMapTouches(y.touches):void 0,xe=de?F(this._el,de):R?void 0:M(this._el,y);for(const{handlerName:Le,handler:Ue,allowed:st}of this._handlers){if(!Ue.isEnabled())continue;let Je;this._blockedByActive(te,st,Le)?Ue.reset():Ue[C||y.type]&&(Je=Ue[C||y.type](y,xe,de),this.mergeHandlerResult(G,Z,Je,Le,$),Je&&Je.needsRenderFrame&&this._triggerRenderFrame()),(Je||Ue.isActive())&&(te[Le]=Ue)}const we={};for(const Le in this._previousActiveHandlers)te[Le]||(we[Le]=$);this._previousActiveHandlers=te,(Object.keys(we).length||HC(G))&&(this._changes.push([G,Z,we]),this._triggerRenderFrame()),(Object.keys(te).length||HC(G))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:Re}=G;Re&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],Re(this._map))}mergeHandlerResult(y,C,R,$,G){if(!R)return;Object.assign(y,R);const Z={handlerName:$,originalEvent:R.originalEvent||G};R.zoomDelta!==void 0&&(C.zoom=Z),R.panDelta!==void 0&&(C.drag=Z),R.pitchDelta!==void 0&&(C.pitch=Z),R.bearingDelta!==void 0&&(C.rotate=Z)}_applyChanges(){const y={},C={},R={};for(const[$,G,Z]of this._changes)$.panDelta&&(y.panDelta=(y.panDelta||new o.P(0,0))._add($.panDelta)),$.zoomDelta&&(y.zoomDelta=(y.zoomDelta||0)+$.zoomDelta),$.bearingDelta&&(y.bearingDelta=(y.bearingDelta||0)+$.bearingDelta),$.pitchDelta&&(y.pitchDelta=(y.pitchDelta||0)+$.pitchDelta),$.around!==void 0&&(y.around=$.around),$.aroundCoord!==void 0&&(y.aroundCoord=$.aroundCoord),$.pinchAround!==void 0&&(y.pinchAround=$.pinchAround),$.noInertia&&(y.noInertia=$.noInertia),Object.assign(C,G),Object.assign(R,Z);this._updateMapTransform(y,C,R),this._changes=[]}_updateMapTransform(y,C,R){const $=this._map,G=$.transform,Z=kt=>[kt.x,kt.y,kt.z];if((()=>{const kt=this._eventsInProgress.drag;return kt&&!this._handlersById[kt.handlerName].isActive()})()&&!HC(y)){const kt=G.zoom;G.cameraElevationReference="sea",this._originalZoom!=null&&G._orthographicProjectionAtLowPitch&&G.projection.name!=="globe"&&G.pitch===0?(G.cameraElevationReference="ground",G.zoom=this._originalZoom):(G.recenterOnTerrain(),G.cameraElevationReference="ground"),kt!==G.zoom&&this._map._update(!0)}if(G._isCameraConstrained&&$._stop(!0),!HC(y))return void this._fireEvents(C,R,!0);let{panDelta:te,zoomDelta:de,bearingDelta:xe,pitchDelta:we,around:Re,aroundCoord:Le,pinchAround:Ue}=y;G._isCameraConstrained&&(de>0&&(de=0),G._isCameraConstrained=!1),Ue!==void 0&&(Re=Ue),(de||(kt=>C[kt]&&!this._eventsInProgress[kt])("drag"))&&Re&&(this._dragOrigin=Z(G.pointCoordinate3D(Re)),this._originalZoom=G.zoom,this._trackingEllipsoid.setup(G._camera.position,this._dragOrigin)),G.cameraElevationReference="sea",$._stop(!0),Re=Re||$.transform.centerPoint,xe&&(G.bearing+=xe),we&&(G.pitch+=we),G._updateCameraState();const st=[0,0,0];if(te)if(G.projection.name==="mercator"){const kt=this._trackingEllipsoid.projectRay(G.screenPointToMercatorRay(Re).dir),Tt=this._trackingEllipsoid.projectRay(G.screenPointToMercatorRay(Re.sub(te)).dir);st[0]=Tt[0]-kt[0],st[1]=Tt[1]-kt[1]}else{const kt=G.pointCoordinate(Re);if(G.projection.name==="globe"){te=te.rotate(-G.angle);const Tt=G._pixelsPerMercatorPixel/G.worldSize;st[0]=-te.x*o.eQ(o.bV(kt.y))*Tt,st[1]=-te.y*o.eQ(G.center.lat)*Tt}else{const Tt=G.pointCoordinate(Re.sub(te));kt&&Tt&&(st[0]=Tt.x-kt.x,st[1]=Tt.y-kt.y)}}const Je=G.zoom,mt=[0,0,0];if(de){const kt=Z(Le||G.pointCoordinate3D(Re)),Tt={dir:o.ay([],o.ax([],kt,G._camera.position))};if(Tt.dir[2]<0){const xt=G.zoomDeltaToMovement(kt,de);o.bJ(mt,Tt.dir,xt)}}const ht=o.cT(st,st,mt);G._translateCameraConstrained(ht),de&&Math.abs(G.zoom-Je)>1e-4&&G.recenterOnTerrain(),G.cameraElevationReference="ground",this._map._update(),y.noInertia||this._inertia.record(y),this._fireEvents(C,R,!0)}_fireEvents(y,C,R){const $=VC(this._eventsInProgress),G=VC(y),Z={};for(const we in y){const{originalEvent:Re}=y[we];this._eventsInProgress[we]||(Z[`${we}start`]=Re),this._eventsInProgress[we]=y[we]}!$&&G&&this._fireEvent("movestart",G.originalEvent);for(const we in Z)this._fireEvent(we,Z[we]);G&&this._fireEvent("move",G.originalEvent);for(const we in y){const{originalEvent:Re}=y[we];this._fireEvent(we,Re)}const te={};let de;for(const we in this._eventsInProgress){const{handlerName:Re,originalEvent:Le}=this._eventsInProgress[we];this._handlersById[Re].isActive()||(delete this._eventsInProgress[we],de=C[Re]||Le,te[`${we}end`]=de)}for(const we in te)this._fireEvent(we,te[we]);const xe=VC(this._eventsInProgress);if(R&&($||G)&&!xe){this._updatingCamera=!0;const we=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),Re=Le=>Le!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new iq("renderFrame",{timeStamp:y})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const XR="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class cq extends o.E{constructor(y,C){super(),this._moving=!1,this._zooming=!1,this.transform=y,this._bearingSnap=C.bearingSnap,this._respectPrefersReducedMotion=C.respectPrefersReducedMotion!==!1,o.aZ(["_renderFrameCallback"],this)}getCenter(){return new o.aU(this.transform.center.lng,this.transform.center.lat)}setCenter(y,C){return this.jumpTo({center:y},C)}panBy(y,C,R){return y=o.P.convert(y).mult(-1),this.panTo(this.transform.center,Object.assign({offset:y},C),R)}panTo(y,C,R){return this.easeTo(Object.assign({center:y},C),R)}getZoom(){return this.transform.zoom}setZoom(y,C){return this.jumpTo({zoom:y},C),this}zoomTo(y,C,R){return this.easeTo(Object.assign({zoom:y},C),R)}zoomIn(y,C){return this.zoomTo(this.getZoom()+1,y,C),this}zoomOut(y,C){return this.zoomTo(this.getZoom()-1,y,C),this}getBearing(){return this.transform.bearing}setBearing(y,C){return this.jumpTo({bearing:y},C),this}getPadding(){return this.transform.padding}setPadding(y,C){return this.jumpTo({padding:y},C),this}rotateTo(y,C,R){return this.easeTo(Object.assign({bearing:y},C),R)}resetNorth(y,C){return this.rotateTo(0,Object.assign({duration:1e3},y),C),this}resetNorthPitch(y,C){return this.easeTo(Object.assign({bearing:0,pitch:0,duration:1e3},y),C),this}snapToNorth(y,C){return Math.abs(this.getBearing())y.aspect?R/(2*Math.tan(.5*y.fovX)*y.aspect):$/(2*Math.tan(.5*y.fovY)*y.aspect)}_cameraForBoundsOnGlobe(y,C,R,$,G,Z){const te=y.clone(),de=this._extendCameraOptions(Z);te.bearing=$,te.pitch=G;const xe=o.aU.convert(C),we=o.aU.convert(R),Re=.5*(xe.lat+we.lat),Le=.5*(xe.lng+we.lng),Ue=o.eT(Re,Le),st=o.ay([],Ue),Je=o.ay([],o.bh([],st,[0,1,0])),mt=o.bh([],Je,st),ht=[Je[0],Je[1],Je[2],0,mt[0],mt[1],mt[2],0,st[0],st[1],st[2],0,0,0,0,1],kt=[Ue,o.eT(xe.lat,xe.lng),o.eT(we.lat,xe.lng),o.eT(we.lat,we.lng),o.eT(xe.lat,we.lng),o.eT(Re,xe.lng),o.eT(Re,we.lng),o.eT(xe.lat,Le),o.eT(we.lat,Le)];let Tt=o.cU.fromPoints(kt.map(Us=>[o.bi(Je,Us),o.bi(mt,Us),o.bi(st,Us)]));const xt=o.ah([],Tt.center,ht);o.eU(xt)===0&&o.eV(xt,0,0,1),o.ay(xt,xt),o.bJ(xt,xt,o.aF),te.center=o.eW(xt);const es=te.getWorldToCameraMatrix(),Ft=o.b7(new Float64Array(16),es);Tt=o.cU.applyTransform(Tt,o.aD([],es,ht));const Qt=this._extendAABB(Tt,te,de,$);if(!Qt)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Tt=Qt,o.ah(xt,xt,es);const At=.5*(Tt.max[2]-Tt.min[2]),Dt=this._minimumAABBFrustumDistance(te,Tt),Gt=o.bJ([],[0,0,1],At),gs=o.cT(Gt,xt,Gt),ns=Dt+(te.pitch===0?0:o.bf(xt,gs)),$s=te.globeCenterInViewSpace,Ps=o.ax([],xt,[$s[0],$s[1],$s[2]]);o.ay(Ps,Ps),o.bJ(Ps,Ps,ns);const an=o.cT([],xt,Ps);o.ah(an,an,Ft);const mn=o.eD/o.aF,Ns=o.ai(an),hs=o.bU(Math.max(Ns*mn-o.eD,Number.EPSILON),0),zs=Math.min(te.zoomFromMercatorZAdjusted(hs),de.maxZoom);return zs>.5*(o.cJ+o.cv)?(te.setProjection({name:"mercator"}),te.zoom=zs,this._cameraForBounds(te,C,R,$,G,Z)):{center:te.center,zoom:zs,bearing:$,pitch:G}}_extendAABB(y,C,R,$){const G=.5*((R.padding.left||0)+(R.padding.right||0)),Z=.5*((R.padding.top||0)+(R.padding.bottom||0)),te=Z,de=G,xe=G,we=Z,Re=C.width-(de+xe),Le=C.height-(te+we),Ue=o.ax([],y.max,y.min),st=Math.min(Re/Ue[0],Le/Ue[1]),Je=Math.min(C.scaleZoom(C.scale*st),R.maxZoom);if(isNaN(Je))return null;const mt=C.scale/C.zoomScale(Je),ht=new o.cU([y.min[0]-de*mt,y.min[1]-we*mt,y.min[2]],[y.max[0]+xe*mt,y.max[1]+te*mt,y.max[2]]),kt=(typeof R.offset.x=="number"&&typeof R.offset.y=="number"?new o.P(R.offset.x,R.offset.y):o.P.convert(R.offset)).rotate(-o.ap($));return ht.center[0]-=kt.x*mt,ht.center[1]+=kt.y*mt,ht}queryTerrainElevation(y,C){const R=this.transform.elevation;return R?(C=Object.assign({},{exaggerated:!0},C),R.getAtPoint(o.ag.fromLngLat(y),null,C.exaggerated)):null}_cameraForBounds(y,C,R,$,G,Z){if(y.projection.name==="globe")return this._cameraForBoundsOnGlobe(y,C,R,$,G,Z);const te=y.clone(),de=this._extendCameraOptions(Z);te.bearing=$,te.pitch=G;const xe=o.aU.convert(C),we=o.aU.convert(R),Re=new o.aU(xe.lng,we.lat),Le=new o.aU(we.lng,xe.lat),Ue=te.project(xe),st=te.project(we),Je=this.queryTerrainElevation(xe),mt=this.queryTerrainElevation(we),ht=this.queryTerrainElevation(Re),kt=this.queryTerrainElevation(Le),Tt=[[Ue.x,Ue.y,Math.min(Je||0,mt||0,ht||0,kt||0)],[st.x,st.y,Math.max(Je||0,mt||0,ht||0,kt||0)]];let xt=o.cU.fromPoints(Tt);const es=te.getWorldToCameraMatrix(),Ft=o.b7(new Float64Array(16),es);xt=o.cU.applyTransform(xt,es);const Qt=this._extendAABB(xt,te,de,$);if(!Qt)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");xt=Qt;const At=.5*o.ax([],xt.max,xt.min)[2],Dt=this._minimumAABBFrustumDistance(te,xt),Gt=[0,0,1,0];o.aE(Gt,Gt,es),o.eX(Gt,Gt);const gs=o.bJ([],Gt,Dt+At),ns=o.cT([],xt.center,gs);o.ah(xt.center,xt.center,Ft),o.ah(ns,ns,Ft);const $s=te.unproject(new o.P(xt.center[0],xt.center[1])),Ps=o.eY(te.projection,$s),an=Math.pow(2,Ps),mn=Math.min(te._zoomFromMercatorZ(ns[2]*te.pixelsPerMeter*an/te.worldSize),de.maxZoom);return te.mercatorFromTransition&&mn<.5*(o.cJ+o.cv)?(te.setProjection({name:"globe"}),te.zoom=mn,this._cameraForBounds(te,C,R,$,G,Z)):{center:$s,zoom:mn,bearing:$,pitch:G}}fitBounds(y,C,R){const $=this.cameraForBounds(y,C);return this._fitInternal($,C,R)}fitScreenCoordinates(y,C,R,$,G){const Z=o.P.convert(y),te=o.P.convert(C),de=new o.P(Math.min(Z.x,te.x),Math.min(Z.y,te.y)),xe=new o.P(Math.max(Z.x,te.x),Math.max(Z.y,te.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(Z,te))return this;const we=this.transform.pointLocation3D(de),Re=this.transform.pointLocation3D(xe),Le=this.transform.pointLocation3D(new o.P(de.x,xe.y)),Ue=this.transform.pointLocation3D(new o.P(xe.x,de.y)),st=[Math.min(we.lng,Re.lng,Le.lng,Ue.lng),Math.min(we.lat,Re.lat,Le.lat,Ue.lat)],Je=[Math.max(we.lng,Re.lng,Le.lng,Ue.lng),Math.max(we.lat,Re.lat,Le.lat,Ue.lat)],mt=$&&$.pitch?$.pitch:this.getPitch(),ht=this._cameraForBounds(this.transform,st,Je,R,mt,$);return this._fitInternal(ht,$,G)}_fitInternal(y,C,R){return y?(C=Object.assign(y,C)).linear?this.easeTo(C,R):this.flyTo(C,R):this}jumpTo(y,C){this.stop();const R=y.preloadOnly?this.transform.clone():this.transform;let $=!1,G=!1,Z=!1;"zoom"in y&&R.zoom!==+y.zoom&&($=!0,R.zoom=+y.zoom),y.center!==void 0&&(R.center=o.aU.convert(y.center)),"bearing"in y&&R.bearing!==+y.bearing&&(G=!0,R.bearing=+y.bearing),"pitch"in y&&R.pitch!==+y.pitch&&(Z=!0,R.pitch=+y.pitch);const te=typeof y.padding=="number"?this._extendPadding(y.padding):y.padding;if(y.padding!=null&&!R.isPaddingEqual(te))if(y.retainPadding===!1){const de=R.clone();de.padding=te,R.setLocationAtPoint(R.center,de.centerPoint)}else R.padding=te;return y.preloadOnly?(this._preloadTiles(R),this):(this.fire(new o.C("movestart",C)).fire(new o.C("move",C)),$&&this.fire(new o.C("zoomstart",C)).fire(new o.C("zoom",C)).fire(new o.C("zoomend",C)),G&&this.fire(new o.C("rotatestart",C)).fire(new o.C("rotate",C)).fire(new o.C("rotateend",C)),Z&&this.fire(new o.C("pitchstart",C)).fire(new o.C("pitch",C)).fire(new o.C("pitchend",C)),this.fire(new o.C("moveend",C)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||o.w(XR),this.transform.getFreeCameraOptions()}setFreeCameraOptions(y,C){const R=this.transform;if(!R.projection.supportsFreeCamera)return o.w(XR),this;this.stop();const $=R.zoom,G=R.pitch,Z=R.bearing;R.setFreeCameraOptions(y);const te=$!==R.zoom,de=G!==R.pitch,xe=Z!==R.bearing;return this.fire(new o.C("movestart",C)).fire(new o.C("move",C)),te&&this.fire(new o.C("zoomstart",C)).fire(new o.C("zoom",C)).fire(new o.C("zoomend",C)),xe&&this.fire(new o.C("rotatestart",C)).fire(new o.C("rotate",C)).fire(new o.C("rotateend",C)),de&&this.fire(new o.C("pitchstart",C)).fire(new o.C("pitch",C)).fire(new o.C("pitchend",C)),this.fire(new o.C("moveend",C)),this}easeTo(y,C){this._stop(!1,y.easeId),((y=Object.assign({offset:[0,0],duration:500,easing:o.eP},y)).animate===!1||this._prefersReducedMotion(y))&&(y.duration=0);const R=this.transform,$=this.getZoom(),G=this.getBearing(),Z=this.getPitch(),te=this.getPadding(),de="zoom"in y?+y.zoom:$,xe="bearing"in y?this._normalizeBearing(y.bearing,G):G,we="pitch"in y?+y.pitch:Z,Re=this._extendPadding(y.padding),Le=o.P.convert(y.offset);let Ue,st,Je;if(R.projection.name==="globe"){const Gt=o.ag.fromLngLat(R.center),gs=Le.rotate(-R.angle);Gt.x+=gs.x/R.worldSize,Gt.y+=gs.y/R.worldSize;const ns=Gt.toLngLat(),$s=o.aU.convert(y.center||ns);this._normalizeCenter($s),Ue=R.centerPoint.add(gs),st=new o.P(Gt.x,Gt.y).mult(R.worldSize),Je=new o.P(o.aH($s.lng),o.aL($s.lat)).mult(R.worldSize).sub(st)}else{Ue=R.centerPoint.add(Le);const Gt=R.pointLocation(Ue),gs=o.aU.convert(y.center||Gt);this._normalizeCenter(gs),st=R.project(Gt),Je=R.project(gs).sub(st)}const mt=R.zoomScale(de-$);let ht,kt;y.around&&(ht=o.aU.convert(y.around),kt=R.locationPoint(ht));const Tt=this._zooming||de!==$,xt=this._rotating||G!==xe,es=this._pitching||we!==Z,Ft=!R.isPaddingEqual(Re),Qt=y.retainPadding===!1?R.clone():R,At=Gt=>gs=>{if(Tt&&(Gt.zoom=o.am($,de,gs)),xt&&(Gt.bearing=o.am(G,xe,gs)),es&&(Gt.pitch=o.am(Z,we,gs)),Ft&&(Qt.interpolatePadding(te,Re,gs),Ue=Qt.centerPoint.add(Le)),ht)Gt.setLocationAtPoint(ht,kt);else{const ns=Gt.zoomScale(Gt.zoom-$),$s=de>$?Math.min(2,mt):Math.max(.5,mt),Ps=Math.pow($s,1-gs),an=Gt.unproject(st.add(Je.mult(gs*Ps)).mult(ns));Gt.setLocationAtPoint(Gt.renderWorldCopies?an.wrap():an,Ue)}return y.preloadOnly||this._fireMoveEvents(C),Gt};if(y.preloadOnly){const Gt=this._emulate(At,y.duration,R);return this._preloadTiles(Gt),this}const Dt={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Tt,this._rotating=xt,this._pitching=es,this._padding=Ft,this._easeId=y.easeId,this._prepareEase(C,y.noMoveStart,Dt),this._ease(At(R),Gt=>{R.cameraElevationReference==="sea"&&R.recenterOnTerrain(),this._afterEase(C,Gt)},y),this}_prepareEase(y,C,R={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),C||R.moving||this.fire(new o.C("movestart",y)),this._zooming&&!R.zooming&&this.fire(new o.C("zoomstart",y)),this._rotating&&!R.rotating&&this.fire(new o.C("rotatestart",y)),this._pitching&&!R.pitching&&this.fire(new o.C("pitchstart",y))}_fireMoveEvents(y){this.fire(new o.C("move",y)),this._zooming&&this.fire(new o.C("zoom",y)),this._rotating&&this.fire(new o.C("rotate",y)),this._pitching&&this.fire(new o.C("pitch",y))}_afterEase(y,C){if(this._easeId&&C&&this._easeId===C)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const R=this._zooming,$=this._rotating,G=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,R&&this.fire(new o.C("zoomend",y)),$&&this.fire(new o.C("rotateend",y)),G&&this.fire(new o.C("pitchend",y)),this.fire(new o.C("moveend",y))}flyTo(y,C){if(this._prefersReducedMotion(y)){const Us=o.aJ(y,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(Us,C)}this.stop(),y=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:o.eP},y);const R=this.transform,$=this.getZoom(),G=this.getBearing(),Z=this.getPitch(),te=this.getPadding(),de="zoom"in y?o.aC(+y.zoom,R.minZoom,R.maxZoom):$,xe="bearing"in y?this._normalizeBearing(y.bearing,G):G,we="pitch"in y?+y.pitch:Z,Re=this._extendPadding(y.padding),Le=R.zoomScale(de-$),Ue=o.P.convert(y.offset);let st=R.centerPoint.add(Ue);const Je=R.pointLocation(st),mt=o.aU.convert(y.center||Je);this._normalizeCenter(mt);const ht=R.project(Je),kt=R.project(mt).sub(ht);let Tt=y.curve;const xt=Math.max(R.width,R.height),es=xt/Le,Ft=kt.mag();if("minZoom"in y){const Us=o.aC(Math.min(y.minZoom,$,de),R.minZoom,R.maxZoom),Ys=xt/R.zoomScale(Us-$);Tt=Math.sqrt(Ys/Ft*2)}const Qt=Tt*Tt;function At(Us){const Ys=(es*es-xt*xt+(Us?-1:1)*Qt*Qt*Ft*Ft)/(2*(Us?es:xt)*Qt*Ft);return Math.log(Math.sqrt(Ys*Ys+1)-Ys)}function Dt(Us){return(Math.exp(Us)-Math.exp(-Us))/2}function Gt(Us){return(Math.exp(Us)+Math.exp(-Us))/2}const gs=At(0);let ns=function(Us){return Gt(gs)/Gt(gs+Tt*Us)},$s=function(Us){return xt*((Gt(gs)*(Dt(Ys=gs+Tt*Us)/Gt(Ys))-Dt(gs))/Qt)/Ft;var Ys},Ps=(At(1)-gs)/Tt;if(Math.abs(Ft)<1e-6||!isFinite(Ps)){if(Math.abs(xt-es)<1e-6)return this.easeTo(y,C);const Us=esy.maxDuration&&(y.duration=0);const an=G!==xe,mn=we!==Z,Ns=!R.isPaddingEqual(Re),hs=y.retainPadding===!1?R.clone():R,zs=Us=>Ys=>{const Rn=Ys*Ps,Sn=1/ns(Rn);Us.zoom=Ys===1?de:$+Us.scaleZoom(Sn),an&&(Us.bearing=o.am(G,xe,Ys)),mn&&(Us.pitch=o.am(Z,we,Ys)),Ns&&(hs.interpolatePadding(te,Re,Ys),st=hs.centerPoint.add(Ue));const Cn=Ys===1?mt:Us.unproject(ht.add(kt.mult($s(Rn))).mult(Sn));return Us.setLocationAtPoint(Us.renderWorldCopies?Cn.wrap():Cn,st),Us._updateCameraOnTerrain(),y.preloadOnly||this._fireMoveEvents(C),Us};if(y.preloadOnly){const Us=this._emulate(zs,y.duration,R);return this._preloadTiles(Us),this}return this._zooming=!0,this._rotating=an,this._pitching=mn,this._padding=Ns,this._prepareEase(C,!1),this._ease(zs(R),()=>this._afterEase(C),y),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(y){}_cancelRenderFrame(y){}_stop(y,C){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const R=this._onEaseEnd;this._onEaseEnd=void 0,R.call(this,C)}if(!y){const R=this.handlers;R&&R.stop(!1)}return this}_ease(y,C,R){R.animate===!1||R.duration===0?(y(1),C()):(this._easeStart=o.o.now(),this._easeOptions=R,this._onEaseFrame=y,this._onEaseEnd=C,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const y=Math.min((o.o.now()-this._easeStart)/this._easeOptions.duration,1),C=this._onEaseFrame;C&&C(this._easeOptions.easing(y)),y<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(y,C){y=o.bs(y,-180,180);const R=Math.abs(y-C);return Math.abs(y-360-C)180?-360:R<-180?360:0}_prefersReducedMotion(y){return this._respectPrefersReducedMotion&&o.o.prefersReducedMotion&&!(y&&y.essential)}_emulate(y,C,R){const $=Math.ceil(15*C/1e3),G=[],Z=y(R.clone());for(let te=0;te<=$;te++){const de=Z(te/$);G.push(de.clone())}return G}_preloadTiles(y,C){}}class JR{constructor(y={}){this.options=y,o.aZ(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(y){const C=this.options&&this.options.compact,R=y._getUIString("AttributionControl.ToggleAttribution");this._map=y,this._container=_("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=_("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",R);const $=_("span","mapboxgl-ctrl-icon",this._compactButton);return $.setAttribute("aria-hidden","true"),$.setAttribute("title",R),this._innerContainer=_("div","mapboxgl-ctrl-attrib-inner",this._container),C&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),C===void 0&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0,this._attribHTML=void 0}_toggleAttribution(){this._container.classList.contains("mapboxgl-compact-show")?(this._container.classList.remove("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","false")):(this._container.classList.add("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","true"))}_updateEditLink(){let y=this._editLink;y||(y=this._editLink=this._container.querySelector(".mapbox-improve-map"));const C=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||o.g.ACCESS_TOKEN}];if(y){const R=C.reduce(($,G,Z)=>(G.value&&($+=`${G.key}=${G.value}${Z$.length-G.length),y=y.filter(($,G)=>{for(let Z=G+1;Z=0)return!1;return!0}),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?y=[...this.options.customAttribution,...y]:y.unshift(this.options.customAttribution));const R=y.map($=>function(G){const Z=new DOMParser().parseFromString(G,"text/html");return Array.from(Z.body.querySelectorAll("*")).reverse().forEach(te=>{const de=te.textContent||"";if(te.tagName!=="A")return void te.replaceWith(...te.childNodes);const xe=te.getAttribute("href");if(!xe||!/^(https?:|mailto:)/i.test(xe))return void te.replaceWith(Z.createTextNode(de));const we=Z.createElement("a");we.href=xe,we.textContent=de,we.rel="noopener nofollow";const Re=te.getAttribute("class");Re&&(we.className=Re),te.replaceWith(we)}),Z.body.innerHTML}($)).join(" | ");R!==this._attribHTML&&(this._attribHTML=R,y.length?(this._innerContainer.innerHTML=R,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 eO{constructor(){o.aZ(["_updateLogo","_updateCompact"],this)}onAdd(y){this._map=y,this._container=_("div","mapboxgl-ctrl");const C=_("a","mapboxgl-ctrl-logo");return C.target="_blank",C.rel="noopener nofollow",C.href="https://www.mapbox.com/",C.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),C.setAttribute("rel","noopener nofollow"),this._container.appendChild(C),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off("sourcedata",this._updateLogo),this._map.off("resize",this._updateCompact)}getDefaultPosition(){return"bottom-left"}_updateLogo(y){y&&y.sourceDataType!=="metadata"||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const y=this._map.style._sourceCaches;if(Object.entries(y).length===0)return!0;for(const C in y){const R=y[C].getSource();if(R.hasOwnProperty("mapbox_logo")&&!R.mapbox_logo)return!1}return!0}_updateCompact(){const y=this._container.children;if(y.length){const C=y[0];this._map.getCanvasContainer().offsetWidth<250?C.classList.add("mapboxgl-compact"):C.classList.remove("mapboxgl-compact")}}}class dq{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(y){const C=++this._id;return this._queue.push({callback:y,id:C,cancelled:!1}),C}remove(y){const C=this._currentlyRunning,R=C?this._queue.concat(C):this._queue;for(const $ of R)if($.id===y)return void($.cancelled=!0)}run(y=0){const C=this._currentlyRunning=this._queue;this._queue=[];for(const R of C)if(!R.cancelled&&(R.callback(y),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class wbe{constructor(y){this.jumpTo(y)}getValue(y){if(y<=this._startTime)return this._start;if(y>=this._endTime)return this._end;const C=o.dn((y-this._startTime)/(this._endTime-this._startTime));return this._start*(1-C)+this._end*C}isEasing(y){return y>=this._startTime&&y<=this._endTime}jumpTo(y){this._startTime=-1/0,this._endTime=-1/0,this._start=y,this._end=y}easeTo(y,C,R){this._start=this.getValue(C),this._end=y,this._startTime=C,this._endTime=C+R}}const jbe={"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 Po extends o.C{constructor(y,C,R,$){const{point:G,lngLat:Z,originalEvent:te,target:de}=y;super(y.type,{point:G,lngLat:Z,originalEvent:te,target:de}),this.preventDefault=()=>{y.preventDefault()},this.id=C,this.interaction=R,this.feature=$}}class R6{constructor(y){this.map=y,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(y,C){if(this.typeById.has(y))throw new Error(`Interaction id "${y}" already exists.`);const R=C.filter;let $=C.type;R&&this.filters.set(y,o.dg(R)),$==="mouseover"&&($="mouseenter"),$==="mouseout"&&($="mouseleave");const G=this.interactionsByType.get($)||new Map;$==="mouseenter"||$==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(y,C)):G.size===0&&this.map.on($,this.handleType),G.size===0&&this.interactionsByType.set($,G),G.set(y,C),this.typeById.set(y,$)}get(y){const C=this.typeById.get(y);if(!C)return;const R=this.interactionsByType.get(C);return R?R.get(y):void 0}remove(y){const C=this.typeById.get(y);if(!C)return;this.typeById.delete(y),this.filters.delete(y);const R=this.interactionsByType.get(C);R&&(R.delete(y),C==="mouseenter"||C==="mouseleave"?(this.delegatedInteractions.delete(y),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):R.size===0&&this.map.off(C,this.handleType))}queryTargets(y,C){const R=[];for(const[$,G]of C)G.target&&R.push({targetId:$,target:G.target,filter:this.filters.get($)});return this.map.style.queryRenderedTargets(y,R,this.map.transform)}handleMove(y){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const C=this.queryTargets(y.point,Array.from(this.delegatedInteractions).reverse());C.length&&(y.type="mouseenter",this.handleType(y,C));const R=new Map;for(const[$,{feature:G}]of this.prevHoveredFeatures)this.hoveredFeatures.has($)||R.set(G.id,G);R.size&&(y.type="mouseleave",this.handleType(y,Array.from(R.values())))}handleOut(y){const C=Array.from(this.hoveredFeatures.values()).map(({feature:R})=>R);C.length&&(y.type="mouseleave",this.handleType(y,C)),this.hoveredFeatures.clear()}handleType(y,C){const R=y.type==="mouseenter";if(R&&!this.interactionsByType.has(y.type))return void o.w("mouseenter interaction required for mouseleave to work.");const $=Array.from(this.interactionsByType.get(y.type)).reverse(),G=!!C;C=C||this.queryTargets(y.point,$);let Z=!1;const te=new Set;for(const de of C){for(const[xe,we]of $){if(!we.target)continue;const Re=de.variants?de.variants[xe]:null;if(Re){for(const Le of Re){if(yh(Le,de,te,xe))continue;const Ue=new o.di(de,Le),st=Ef(Le,de,xe);G&&Ue.id!==void 0&&(Ue.state=this.map.getFeatureState(Ue));const Je=R?this.prevHoveredFeatures.get(st):null,mt=new Po(y,xe,we,Ue),ht=Je?Je.stop:we.handler(mt);if(R&&this.hoveredFeatures.set(st,{feature:de,stop:ht}),ht!==!1){Z=!0;break}}if(Z)break}}if(Z)break}if(!Z)for(const[de,xe]of $){const{handler:we,target:Re}=xe;if(!Re&&we(new Po(y,de,xe,null))!==!1)break}}}function Nbe(I,y){if(Array.isArray(I)&&Array.isArray(y)){const C=new Set(I),R=new Set(y);return C.size===R.size&&I.every($=>R.has($))}return o.b6(I,y)}const kbe={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},Sbe={showCompass:!0,showZoom:!0,visualizePitch:!1};class GC{constructor(y,C,R=!1){this._clickTolerance=10,this.element=C,this.mouseRotate=new A6({clickTolerance:y.dragRotate._mouseRotate._clickTolerance}),this.map=y,R&&(this.mousePitch=new $C({clickTolerance:y.dragRotate._mousePitch._clickTolerance})),o.aZ(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),C.addEventListener("mousedown",this.mousedown),C.addEventListener("touchstart",this.touchstart,{passive:!1}),C.addEventListener("touchmove",this.touchmove),C.addEventListener("touchend",this.touchend),C.addEventListener("touchcancel",this.reset)}down(y,C){this.mouseRotate.mousedown(y,C),this.mousePitch&&this.mousePitch.mousedown(y,C),A()}move(y,C){const R=this.map,$=this.mouseRotate.mousemoveWindow(y,C),G=$&&$.bearingDelta;if(G&&R.setBearing(R.getBearing()+G),this.mousePitch){const Z=this.mousePitch.mousemoveWindow(y,C),te=Z&&Z.pitchDelta;te&&R.setPitch(R.getPitch()+te)}}off(){const y=this.element;y.removeEventListener("mousedown",this.mousedown),y.removeEventListener("touchstart",this.touchstart),y.removeEventListener("touchmove",this.touchmove),y.removeEventListener("touchend",this.touchend),y.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){T(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(y){this.down(Object.assign({},y,{button:y.button,type:y.type,ctrlKey:!0,preventDefault:()=>y.preventDefault()}),M(this.element,y)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(y){this.move(y,M(this.element,y))}mouseup(y){this.mouseRotate.mouseupWindow(y),this.mousePitch&&this.mousePitch.mouseupWindow(y),this.offTemp()}touchstart(y){y.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=F(this.element,y.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>y.preventDefault()},this._startPos))}touchmove(y){y.targetTouches.length!==1?this.reset():(this._lastPos=F(this.element,y.targetTouches)[0],this.move({buttons:1,preventDefault:()=>y.preventDefault()},this._lastPos))}touchend(y){y.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)C.width||y.y>C.height;C.locationPoint3D(R).distSqr(y)180;){const R=C.locationPoint3D(I);if(R.x>=0&&R.y>=0&&R.x<=C.width&&R.y<=C.height)break;I.lng>C.center.lng?I.lng-=360:I.lng+=360}return I}const WC={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%)"},Sx={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class _g extends o.E{constructor(y,C){super(),(y instanceof HTMLElement||C)&&(y=Object.assign({element:y},C)),o.aZ(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:R="center",color:$="#3FB1CE",scale:G=1,draggable:Z=!1,clickTolerance:te=0,rotation:de=Sx.rotation,rotationAlignment:xe=Sx.rotationAlignment,pitchAlignment:we=Sx.pitchAlignment,occludedOpacity:Re=Sx.occludedOpacity,altitude:Le=Sx.altitude}=y||{};this._anchor=R,this._color=$,this._scale=G,this._draggable=Z,this._clickTolerance=te,this._rotation=de,this._rotationAlignment=xe,this._pitchAlignment=we,this._occludedOpacity=Re,this._altitude=Le,this._state="inactive",this._isDragging=!1,this._updateMoving=()=>this._update(!0),y&&y.element?(this._element=y.element,this._offset=o.P.convert(y&&y.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=o.P.convert(y&&y.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",Je=>{Je.preventDefault()}),this._element.addEventListener("mousedown",Je=>{Je.preventDefault()});const Ue=this._element.classList;for(const Je in WC)Ue.remove(`mapboxgl-marker-anchor-${Je}`);Ue.add(`mapboxgl-marker-anchor-${this._anchor}`);const st=y&&y.className?y.className.trim().split(/\s+/):[];Ue.add(...st),this._popup=null}_createDefaultMarker(){const y=_("div"),C=v("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},y);if(this._altitude===0){const R=v("radialGradient",{id:"shadowGradient"},v("defs",{},C));v("stop",{offset:"10%","stop-opacity":.4},R),v("stop",{offset:"100%","stop-opacity":.05},R),v("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},C)}return v("path",{fill:this._color,d:"M27,13.5C27,19.07 20.25,27 14.75,34.5C14.02,35.5 12.98,35.5 12.25,34.5C6.75,27 0,19.22 0,13.5C0,6.04 6.04,0 13.5,0C20.96,0 27,6.04 27,13.5Z"},C),v("path",{opacity:.25,d:"M13.5,0C6.04,0 0,6.04 0,13.5C0,19.22 6.75,27 12.25,34.5C13,35.52 14.02,35.5 14.75,34.5C20.25,27 27,19.07 27,13.5C27,6.04 20.96,0 13.5,0ZM13.5,1C20.42,1 26,6.58 26,13.5C26,15.9 24.5,19.18 22.22,22.74C19.95,26.3 16.71,30.14 13.94,33.91C13.74,34.18 13.61,34.32 13.5,34.44C13.39,34.32 13.26,34.18 13.06,33.91C10.28,30.13 7.41,26.31 5.02,22.77C2.62,19.23 1,15.95 1,13.5C1,6.58 6.58,1 13.5,1Z"},C),v("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},C),y}addTo(y){return y===this._map||(this.remove(),this._map=y,y.getCanvasContainer().appendChild(this._element),y.on("move",this._updateMoving),y.on("moveend",this._update),y.on("remove",this._clearFadeTimer),y._addMarker(this),this.setDraggable(this._draggable),this._update(),y.on("click",this._onMapClick)),this}remove(){const y=this._map;return y&&(y.off("click",this._onMapClick),y.off("move",this._updateMoving),y.off("moveend",this._update),y.off("mousedown",this._addDragHandler),y.off("touchstart",this._addDragHandler),y.off("mouseup",this._onUp),y.off("touchend",this._onUp),y.off("mousemove",this._onMove),y.off("touchmove",this._onMove),y.off("remove",this._clearFadeTimer),y._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(y){return this._lngLat=o.aU.convert(y),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(y){return y===this._altitude||(this._defaultMarker&&(this._altitude===0&&y!==0||this._altitude!==0&&y===0)&&(this._element=this._createDefaultMarker()),this._altitude=y||Sx.altitude,this._update()),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(y){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")),y){if(!("offset"in y.options)){const $=Math.sqrt(Math.pow(13.5,2)/2);y.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[$,-1*(38.1-13.5+$)],"bottom-right":[-$,-1*(38.1-13.5+$)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=y,y._marker=this,y._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(y){const C=y.code,R=y.charCode||y.keyCode;C!=="Space"&&C!=="Enter"&&R!==32&&R!==13||this.togglePopup()}_onMapClick(y){const C=y.originalEvent.target,R=this._element;this._popup&&(C===R||R.contains(C))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const y=this._popup;return y?(y.isOpen()?(y.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(y.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const y=this._map,C=this._pos;if(!y||!C)return!1;const R=y.unproject(C,this._altitude),$=y.getFreeCameraOptions();if(!$.position)return!1;const G=$.position.toLngLat();return G.distanceTo(R)<.9*G.distanceTo(this._lngLat)}_evaluateOpacity(){const y=this._map;if(!y)return;const C=this._pos;if(!C||C.x<0||C.x>y.transform.width||C.y<0||C.y>y.transform.height)return void this._clearFadeTimer();const R=y.unproject(C,this._altitude);let $;y._showingGlobe()&&o.e$(y.transform,this._lngLat)?$=0:($=1-y._queryFogOpacity(R),y.transform._terrainEnabled()&&y.getTerrain()&&this._behindTerrain()&&($*=this._occludedOpacity)),this._element.style.opacity=`${$}`,this._element.style.pointerEvents=$>0?"auto":"none",this._popup&&this._popup._setOpacity($),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const y=this._pos;if(!y||!this._map)return;const C=this._offset.mult(this._scale);this._element.style.transform=` translate(${y.x}px,${y.y}px) ${WC[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${C.x}px,${C.y}px) `}_calculateXYTransform(){const y=this._pos,C=this._map,R=this.getPitchAlignment();if(!C||!y||R!=="map")return"";if(!C._showingGlobe()){const de=C.getPitch();return de?`rotateX(${de}deg)`:""}const $=o.cH(o.f0(C.transform,this._lngLat)),G=y.sub(o.f1(C.transform)),Z=Math.abs(G.x)+Math.abs(G.y);if(Z===0)return"";const te=$/Z;return`rotateX(${-G.y*te}deg) rotateY(${G.x*te}deg)`}_calculateZTransform(){const y=this._pos,C=this._map;if(!C||!y)return"";let R=0;const $=this.getRotationAlignment();if($==="map")if(C._showingGlobe()){const G=C.project(new o.aU(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),Z=C.project(new o.aU(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(G);R=o.cH(Math.atan2(Z.y,Z.x))-90}else R=-C.getBearing();else if($==="horizon"){const G=o.aj(4,6,C.getZoom()),Z=o.f1(C.transform);Z.y+=G*C.transform.height;const te=y.sub(Z),de=o.cH(Math.atan2(te.y,te.x));R=(de>90?de-270:de+90)*(1-G)}return R+=this._rotation,R?`rotateZ(${R}deg)`:""}_update(y){cancelAnimationFrame(this._updateFrameId);const C=this._map;C&&(C.transform.renderWorldCopies&&(this._lngLat=tO(this._lngLat,this._pos,C.transform)),this._pos=C.project(this._lngLat,this._altitude),y===!0?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),C._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(C._showingGlobe()||C.getTerrain()||C.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(y){return this._offset=o.P.convert(y),this._update(),this}addClassName(y){return this._element.classList.add(y),this}removeClassName(y){return this._element.classList.remove(y),this}toggleClassName(y){return this._element.classList.toggle(y)}_onMove(y){const C=this._map;if(!C)return;const R=this._pointerdownPos,$=this._positionDelta;if(R&&$){if(!this._isDragging){const G=this._clickTolerance||C._clickTolerance;if(y.point.dist(R)I.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(I.minPitch!=null&&I.maxPitch!=null&&I.minPitch>I.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(I.minPitch!=null&&I.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(I.maxPitch!=null&&I.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");I.antialias&&o.eZ(window)&&(I.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 ap(I.minZoom,I.maxZoom,I.minPitch,I.maxPitch,I.renderWorldCopies,null,null),I),this._repaint=!!I.repaint,this._interactive=I.interactive,this._minTileCacheSize=I.minTileCacheSize,this._maxTileCacheSize=I.maxTileCacheSize,this._failIfMajorPerformanceCaveat=I.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=I.preserveDrawingBuffer,this._antialias=I.antialias,this._trackResize=I.trackResize,this._bearingSnap=I.bearingSnap,this._refreshExpiredTiles=I.refreshExpiredTiles,this._fadeDuration=I.fadeDuration,this._isInitialLoad=!0,this._crossSourceCollisions=I.crossSourceCollisions,this._collectResourceTiming=I.collectResourceTiming,this._language=this._parseLanguage(I.language),this._worldview=I.worldview,this._renderTaskQueue=new dq,this._domRenderTaskQueue=new dq,this._controls=[],this._markers=[],this._popups=[],this._mapId=o.r(),this._locale=Object.assign({},jbe,I.locale),this._clickTolerance=I.clickTolerance,this._cooperativeGestures=I.cooperativeGestures,this._performanceMetricsCollection=I.performanceMetricsCollection,this._tessellationStep=I.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=I.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new wbe(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=I.scaleFactor,this._requestManager=new K(I.transformRequest,I.accessToken,I.testMode);const C=ce(I.accessToken||o.g.ACCESS_TOKEN);if(C&&"atlas"in C&&typeof C.atlas=="number"&&(this._tokenExpiration=C.atlas),this._silenceAuthErrors=!!I.testMode,this._contextCreateOptions=I.contextCreateOptions?Object.assign({},I.contextCreateOptions):{},typeof I.container=="string"){const R=document.getElementById(I.container);if(!R)throw new Error(`Container '${I.container.toString()}' not found.`);this._container=R}else{if(!(I.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=I.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."),I.maxBounds&&this.setMaxBounds(I.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 lq(this,I),this._localFontFamily=I.localFontFamily,this._localIdeographFontFamily=I.localIdeographFontFamily,this._useServerFontComposition=I.useServerFontComposition,(I.style||!I.testMode)&&this.setStyle(I.style||o.g.DEFAULT_STYLE,{config:I.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,useServerFontComposition:this._useServerFontComposition}),I.projection&&this.setProjection(I.projection),I.hash&&(this._hash=new Nc(typeof I.hash=="string"&&I.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){y.center==null&&y.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:I.center,zoom:I.zoom,bearing:I.bearing,pitch:I.pitch});const R=I.bounds;R&&(this.resize(),this.fitBounds(R,Object.assign({},I.fitBoundsOptions,{duration:0})))}this.resize(),I.attributionControl&&this.addControl(new JR({customAttribution:I.customAttribution})),this._logoControl=new eO,this.addControl(this._logoControl,I.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent()}),this.on("data",R=>{this._update(R.dataType==="style"),this.fire(new o.C(`${R.dataType}data`,R))}),this.on("dataloading",R=>{this.fire(new o.C(`${R.dataType}dataloading`,R))}),this._interactions=new R6(this)}_getMapId(){return this._mapId}addControl(I,y){if(y===void 0&&(y=I.getDefaultPosition?I.getDefaultPosition():"top-right"),!I||!I.onAdd)return this.fire(new o.B(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const C=I.onAdd(this);this._controls.push(I);const R=this._controlPositions[y];return y.indexOf("bottom")!==-1?R.insertBefore(C,R.firstChild):R.appendChild(C),this}removeControl(I){if(!I||!I.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 y=this._controls.indexOf(I);return y>-1&&this._controls.splice(y,1),I.onRemove(this),this}hasControl(I){return this._controls.indexOf(I)>-1}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(I){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 y=!this._moving;return y&&this.fire(new o.C("movestart",I)).fire(new o.C("move",I)),this.fire(new o.C("resize",I)),y&&this.fire(new o.C("moveend",I)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(I){return this.transform.setMaxBounds(o.aK.convert(I)),this._update()}setMinZoom(I){if((I=I??-2)>=-2&&I<=this.transform.maxZoom)return this.transform.minZoom=I,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=I,this._update(),this.getZoom()>I?this.setZoom(I):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(I){if((I=I??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(I>=0&&I<=this.transform.maxPitch)return this.transform.minPitch=I,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(I>=this.transform.minPitch)return this.transform.maxPitch=I,this._update(),this.getPitch()>I?this.setPitch(I):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(I){return this._scaleFactor=I,this.painter.scaleFactor=I,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(y=>y.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(I){return this.transform.renderWorldCopies=I,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(I){return I==="auto"?navigator.language:Array.isArray(I)?I.length===0?void 0:I.map(y=>y==="auto"?navigator.language:y):I}setLanguage(I){const y=this._parseLanguage(I);if(!this.style||y===this._language)return this;this._language=y,this.style.reloadSources();for(const C of this._controls)C._setLanguage&&C._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(I){return this.style&&I!==this._worldview?(this._worldview=I,this._styleDirty=!0,this.style.setWorldview(I),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(I){return this._lazyInitEmptyStyle(),I?typeof I=="string"&&(I={name:I}):I=null,this._useExplicitProjection=!!I,this._prioritizeAndUpdateProjection(I,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const I=this.transform,y=I.projection.name;let C;y==="globe"&&I.zoom>=o.cv?(I.setMercatorFromTransition(),C=!0):y==="mercator"&&I.zoom=o.cv?this.transform.setMercatorFromTransition():this.transform.setProjection(I),this.style.applyProjectionUpdate();const R=this.transform.getProjection().name==="mercator"&&C!==this.transform.mercatorFromTransition;return(y||R)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(I,y){return this.transform.locationPoint3D(o.aU.convert(I),y)}unproject(I,y){return this.transform.pointLocation3D(o.P.convert(I),y)}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(I,y,C){const R=$=>{let G=[];if(Array.isArray(y)){const Z=y.filter(te=>this.getLayer(te));G=Z.length?this.queryRenderedFeatures($,{layers:Z}):[]}else G=this.queryRenderedFeatures($,{target:y});return G};if(I==="mouseenter"||I==="mouseover"){let $=!1;return{listener:C,targets:y,delegates:{mousemove:Z=>{const te=R(Z.point);te.length?$||($=!0,C.call(this,new ri(I,this,Z.originalEvent,{features:te}))):$=!1},mouseout:()=>{$=!1}}}}if(I==="mouseleave"||I==="mouseout"){let $=!1;return{listener:C,targets:y,delegates:{mousemove:te=>{R(te.point).length?$=!0:$&&($=!1,C.call(this,new ri(I,this,te.originalEvent)))},mouseout:te=>{$&&($=!1,C.call(this,new ri(I,this,te.originalEvent)))}}}}{const $=G=>{const Z=R(G.point);Z.length&&(G.features=Z,C.call(this,G),delete G.features)};return{listener:C,targets:y,delegates:{[I]:$}}}}on(I,y,C){if(typeof y=="function"||C===void 0)return super.on(I,y);if(typeof y=="string"&&(y=[y]),!this._areTargetsValid(y))return this;const R=this._createDelegatedListener(I,y,C);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[I]=this._delegatedListeners[I]||[],this._delegatedListeners[I].push(R);for(const $ in R.delegates)this.on($,R.delegates[$]);return this}once(I,y,C){if(typeof y=="function"||C===void 0)return super.once(I,y);if(typeof y=="string"&&(y=[y]),!this._areTargetsValid(y))return this;const R=this._createDelegatedListener(I,y,C);for(const $ in R.delegates)this.once($,R.delegates[$]);return this}off(I,y,C){if(typeof y=="function"||C===void 0)return super.off(I,y);if(typeof y=="string"&&(y=[y]),!this._areTargetsValid(y))return this;const R=this._delegatedListeners?this._delegatedListeners[I]:void 0;return R&&($=>{for(let G=0;G<$.length;G++){const Z=$[G];if(Z.listener===C&&Nbe(Z.targets,y)){for(const te in Z.delegates)this.off(te,Z.delegates[te]);return $.splice(G,1),this}}})(R),this}queryRenderedFeatures(I,y){if(!this.style)return[];if(I===void 0||I instanceof o.P||Array.isArray(I)||y!==void 0||(y=I,I=void 0),I=I||[[0,0],[this.transform.width,this.transform.height]],!y){const G=this.style.queryRenderedFeatures(I,void 0,this.transform),Z=this.style.queryRenderedFeatureset(I,void 0,this.transform);return G.concat(Z)}let C=!0;if(y.target&&(C=this._isTargetValid(y.target),C&&!y.layers))return this.style.queryRenderedFeatureset(I,y,this.transform);let R=!0;if(y.layers&&Array.isArray(y.layers)){for(const G of y.layers)if(!this._isValidId(G)){R=!1;break}if(R&&!y.target)return this.style.queryRenderedFeatures(I,y,this.transform)}let $=[];return R&&($=$.concat(this.style.queryRenderedFeatures(I,y,this.transform))),C&&($=$.concat(this.style.queryRenderedFeatureset(I,y,this.transform))),$}querySourceFeatures(I,y){return!I||typeof I=="string"&&!this._isValidId(I)?[]:this.style.querySourceFeatures(I,y)}queryRasterValue(I,y,C){return this._isValidId(I)?this.style.queryRasterValue(I,y,C):Promise.resolve(null)}isPointOnSurface(I){const{name:y}=this.transform.projection;return y!=="globe"&&y!=="mercator"&&o.w(`${y} projection does not support isPointOnSurface, this API may behave unexpectedly.`),this.transform.isPointOnSurface(o.P.convert(I))}addInteraction(I,y){return this._interactions.add(I,y),this}removeInteraction(I){return this._interactions.remove(I),this}getCooperativeGestures(){return this._cooperativeGestures}setCooperativeGestures(I){return this._cooperativeGestures=I,this}setStyle(I,y){return y=Object.assign({},{localIdeographFontFamily:this._localIdeographFontFamily,localFontFamily:this._localFontFamily,useServerFontComposition:this._useServerFontComposition},y),this.style&&I&&y.diff!==!1&&y.localFontFamily===this._localFontFamily&&y.localIdeographFontFamily===this._localIdeographFontFamily&&!y.config?(this.style._diffStyle(I,(C,R)=>{if(C){const $=typeof C=="string"?C:C instanceof Error?C.message:C.error;o.w(`Unable to perform style diff: ${$}. Rebuilding the style from scratch.`),this._updateStyle(I,y)}else R&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=y.localIdeographFontFamily,this._localFontFamily=y.localFontFamily,this._updateStyle(I,y))}_getUIString(I){const y=this._locale[I];if(y==null)throw new Error(`Missing UI string '${I}'`);return y}_updateStyle(I,y){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),I){const C=Object.assign({},y);y&&y.config&&(C.initialConfig=y.config,delete C.config),this.style=new Qc(this,C).load(I),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new Qc(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(I){return I==null?(this.fire(new o.B(new Error("IDs can't be empty."))),!1):!o.db(I)||(this.fire(new o.B(new Error(`IDs can't contain special symbols: "${I}".`))),!1)}_isTargetValid(I){return"featuresetId"in I?this._isValidId("importId"in I?I.importId:I.featuresetId):"layerId"in I&&this._isValidId(I.layerId)}_areTargetsValid(I){if(Array.isArray(I)){for(const y of I)if(!this._isValidId(y))return!1;return!0}return this._isTargetValid(I)}addSource(I,y){return this._isValidId(I)?(this._lazyInitEmptyStyle(),this.style.addSource(I,y),this._update(!0)):this}isSourceLoaded(I){return!!this._isValidId(I)&&!!this.style&&this.style._isSourceCacheLoaded(I)}areTilesLoaded(){return this.style.areTilesLoaded()}addSourceType(I,y,C){this._lazyInitEmptyStyle(),this.style.addSourceType(I,y,C)}removeSource(I){return this._isValidId(I)?(this.style.removeSource(I),this._updateTerrain(),this._update(!0)):this}getSource(I){return this._isValidId(I)?this.style.getOwnSource(I):null}addImage(I,y,{pixelRatio:C=1,sdf:R=!1,stretchX:$,stretchY:G,content:Z}={}){this._lazyInitEmptyStyle();const te=o.I.from(I);if(y instanceof HTMLImageElement||ImageBitmap&&y instanceof ImageBitmap){const{width:de,height:xe,data:we}=o.o.getImageData(y);this.style.addImage(te,{data:new o.q({width:de,height:xe},we),pixelRatio:C,stretchX:$,stretchY:G,content:Z,sdf:R,version:0,usvg:!1})}else if(y.width===void 0||y.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:de,height:xe}=y,we=y;this.style.addImage(te,{data:new o.q({width:de,height:xe},new Uint8Array(we.data)),pixelRatio:C,stretchX:$,stretchY:G,content:Z,sdf:R,usvg:!1,version:0,userImage:we}),we.onAdd&&we.onAdd(this,I)}}updateImage(I,y){this._lazyInitEmptyStyle();const C=o.I.from(I),R=this.style.getImage(C);if(!R)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 $=y instanceof HTMLImageElement||ImageBitmap&&y instanceof ImageBitmap?o.o.getImageData(y):y,{width:G,height:Z,data:te}=$;if(G===void 0||Z===void 0)return void this.fire(new o.B(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(G!==(R.usvg?R.icon.usvg_tree.width:R.data.width)||Z!==(R.usvg?R.icon.usvg_tree.height:R.data.height))return void this.fire(new o.B(new Error(`The width and height of the updated image (${G}, ${Z}) must be that same as the previous version of the image (${R.data.width}, ${R.data.height})`)));const de=!(y instanceof HTMLImageElement||ImageBitmap&&y instanceof ImageBitmap);let xe=!1;R.usvg?(R.data=new o.q({width:G,height:Z},new Uint8Array(te)),R.usvg=!1,R.icon=void 0,xe=!0):R.data.replace(te,de),this.style.updateImage(C,R,xe)}hasImage(I){return I?!!this.style&&!!this.style.getImage(o.I.from(I)):(this.fire(new o.B(new Error("Missing required image id"))),!1)}removeImage(I){this.style.removeImage(o.I.from(I))}loadImage(I,y){o.n(this._requestManager.transformRequest(I,o.R.Image),(C,R)=>{y(C,R)})}listImages(){return this.style.listImages().map(I=>I.name)}addModel(I,y){this._lazyInitEmptyStyle(),this.style.addModel(I,y)}hasModel(I){return I?this.style.hasModel(I):(this.fire(new o.B(new Error("Missing required model id"))),!1)}removeModel(I){this.style.removeModel(I)}listModels(){return this.style.listModels()}addLayer(I,y){return this._isValidId(I.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(I,y),this._update(!0)):this}getSlot(I){const y=this.getLayer(I);return y&&y.slot||null}setSlot(I,y){return this.style.setSlot(I,y),this.style.mergeLayers(),this._update(!0)}addImport(I,y){return this.style.addImport(I,y).catch(C=>this.fire(new o.B(new Error("Failed to add import",C)))),this}updateImport(I,y){return typeof y!="string"&&y.id!==I?(this.removeImport(I),this.addImport(y)):(this.style.updateImport(I,y),this._update(!0))}removeImport(I){return this.style.removeImport(I),this}moveImport(I,y){return this.style.moveImport(I,y),this._update(!0)}moveLayer(I,y){return this._isValidId(I)?(this.style.moveLayer(I,y),this._update(!0)):this}removeLayer(I){return this._isValidId(I)?(this.style.removeLayer(I),this._update(!0)):this}getLayer(I){if(!this._isValidId(I))return null;const y=this.style.getOwnLayer(I);return y?y.type==="custom"?y.implementation:y.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(I,y,C){return this._isValidId(I)?(this.style.setLayerZoomRange(I,y,C),this._update(!0)):this}setFilter(I,y,C={}){return this._isValidId(I)?(this.style.setFilter(I,y,C),this._update(!0)):this}getFilter(I){return this._isValidId(I)?this.style.getFilter(I):null}setPaintProperty(I,y,C,R={}){return this._isValidId(I)?(this.style.setPaintProperty(I,y,C,R),this._update(!0)):this}getPaintProperty(I,y){return this._isValidId(I)?this.style.getPaintProperty(I,y):null}setLayoutProperty(I,y,C,R={}){return this._isValidId(I)?(this.style.setLayoutProperty(I,y,C,R),this._update(!0)):this}getLayoutProperty(I,y){return this._isValidId(I)?this.style.getLayoutProperty(I,y):null}setLayerProperty(I,y,C,R={}){return this._isValidId(I)?(y==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(I,y,C,R),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(I){return this.style.setGlyphsUrl(I),this._update(!0)}getSchema(I){return this.style.getSchema(I)}setSchema(I,y){return this.style.setSchema(I,y),this._update(!0)}getConfig(I){return this.style.getConfig(I)}setConfig(I,y){return this.style.setConfig(I,y),this._update(!0)}getConfigProperty(I,y){return this.style.getConfigProperty(I,y)}setConfigProperty(I,y,C){return this.style.setConfigProperty(I,y,C),this._update(!0)}getFeaturesetDescriptors(I){return this.style.getFeaturesetDescriptors(I)}setLights(I){if(this._lazyInitEmptyStyle(),I&&I.length===1&&I[0].type==="flat"){const y=I[0];y.properties?this.style.setFlatLight(y.properties,y.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(I),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const I=this.style.getLights()||[];return I.length===0&&I.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),I}setLight(I,y={}){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:I}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(I){return this._lazyInitEmptyStyle(),!I&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(I),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(I){return this._lazyInitEmptyStyle(),this.style.setFog(I),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(I){return this._lazyInitEmptyStyle(),this.style.setSnow(I),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(I){return this._lazyInitEmptyStyle(),this.style.setRain(I),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(I){return this._lazyInitEmptyStyle(),this.style.setColorTheme(I),this._update(!0)}setImportColorTheme(I,y){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(I,y),this._update(!0)}setCamera(I){return this.style.setCamera(I),this._triggerCameraUpdate(I)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(I){const y=this.transform.nearClipOffset!==I;return this.transform.nearClipOffset=I,this._update(y)}_triggerCameraUpdate(I){return this._update(this.transform.setOrthographicProjectionAtLowPitch(I["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(I){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(o.aU.convert(I),this.transform):0}setFeatureState(I,y){return I.source&&!this._isValidId(I.source)?this:(this.style.setFeatureState(I,y),this._update())}removeFeatureState(I,y){return I.source&&!this._isValidId(I.source)?this:(this.style.removeFeatureState(I,y),this._update())}getFeatureState(I){return I.source&&!this._isValidId(I.source)?null:this.style.getFeatureState(I)}_selectIndoorFloor(I){this.style.indoorManager.selectFloor(I)}_setIndoorActiveFloorsVisibility(I){this.style.indoorManager.setActiveFloorsVisibility(I)}getIndoorTileOptions(I,y){return this.style.isIndoorEnabled()?this.style.indoorManager.getIndoorTileOptions(I,y):null}_updateContainerDimensions(){if(!this._container)return;const I=this._container.getBoundingClientRect().width||400,y=this._container.getBoundingClientRect().height||300;let C,R,$,G=this._container;for(;G&&(!R||!$);){const Z=window.getComputedStyle(G).transform;Z&&Z!=="none"&&(C=Z.match(/matrix.*\((.+)\)/)[1].split(", "),C[0]&&C[0]!=="0"&&C[0]!=="1"&&(R=C[0]),C[3]&&C[3]!=="0"&&C[3]!=="1"&&($=C[3])),G=G.parentElement}this._containerWidth=R?Math.abs(I/R):I,this._containerHeight=$?Math.abs(y/$):y}_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 I=this._container;I.classList.add("mapboxgl-map"),(this._missingCSSCanary=_("div","mapboxgl-canary",I)).style.visibility="hidden",this._detectMissingCSS();const y=this._canvasContainer=_("div","mapboxgl-canvas-container",I);this._canvas=_("canvas","mapboxgl-canvas",y),this._interactive&&(y.classList.add("mapboxgl-interactive"),this._canvas.setAttribute("tabindex","0")),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region"),this._updateContainerDimensions(),this._resizeCanvas(this._containerWidth,this._containerHeight);const C=this._controlContainer=_("div","mapboxgl-control-container",I),R=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach($=>{R[$]=_("div",`mapboxgl-ctrl-${$}`,C)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(I,y){const C=o.o.devicePixelRatio||1;this._canvas.width=C*Math.ceil(I),this._canvas.height=C*Math.ceil(y),this._canvas.style.width=`${I}px`,this._canvas.style.height=`${y}px`}_addMarker(I){this._markers.push(I)}_removeMarker(I){const y=this._markers.indexOf(I);y!==-1&&this._markers.splice(y,1)}_addPopup(I){this._popups.push(I)}_removePopup(I){const y=this._popups.indexOf(I);y!==-1&&this._popups.splice(y,1)}_setupPainter(){const I=Object.assign({},g.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),y=this._canvas.getContext("webgl2",I);y?(Be(y,!0),this.painter=new oo(y,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",C=>{if(C.dataType==="source"){const R=this.transform.elevation?this.transform.elevation._source():null;R&&C.sourceCacheId===R.id&&this.style&&this.style._setLabelPlacementStale(),this.painter.setTileLoadedFlag(!0)}}),o.k.testSupport(y)):this.fire(new o.B(new Error("Failed to initialize WebGL")))}_contextLost(I){I.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new o.C("webglcontextlost",{originalEvent:I}))}_contextRestored(I){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:I}))}_onMapScroll(I){if(I.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(I){return this.style?(this._styleDirty=this._styleDirty||I,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(I){return this._update(),this._renderTaskQueue.add(I)}_cancelRenderFrame(I){this._renderTaskQueue.remove(I)}_requestDomTask(I){!this.loaded()||this.loaded()&&!this.isMoving()?I():this._domRenderTaskQueue.add(I)}_render(I){let y;this.fire(new o.C("renderstart")),++this._frameId;const C=this.painter.context.extTimerQuery,R=o.o.now(),$=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(y=$.createQuery(),$.beginQuery(C.TIME_ELAPSED_EXT,y)),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(I),this._domRenderTaskQueue.run(I),this._removed)return;this._updateProjectionTransition();const G=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const de=this.transform.zoom,xe=this.transform.pitch,we=o.o.now(),Re=new o.ae(de,{now:we,fadeDuration:G,pitch:xe,transition:this.style.transition,worldview:this._worldview});this.style.update(Re)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let Z=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),Z=this._updateAverageElevation(R),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):Z=this._updateAverageElevation(R),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,G,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:G,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(),y){const de=o.o.now()-R;$.endQuery(C.TIME_ELAPSED_EXT),setTimeout(()=>{const xe=$.getQueryParameter(y,$.QUERY_RESULT)/1e6;$.deleteQuery(y),this.fire(new o.C("gpu-timing-frame",{cpuTime:de,gpuTime:xe}))},50)}if(this.listens("gpu-timing-layer")){const de=this.painter.collectGpuTimers();setTimeout(()=>{const xe=this.painter.queryGpuTimers(de);this.fire(new o.C("gpu-timing-layer",{layerTimes:xe}))},50)}if(this.listens("gpu-timing-deferred-render")){const de=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const xe=this.painter.queryGpuTimeDeferredRender(de);this.fire(new o.C("gpu-timing-deferred-render",{gpuTime:xe}))},50)}const te=this._sourcesDirty||this._styleDirty||this._placementDirty||Z;if(te||this._repaint)this.triggerRepaint();else{const de=this.idle();if(de&&(Z=this._updateAverageElevation(R,!0)),Z)this.triggerRepaint();else if(this._triggerFrame(!1),de&&(this.fire(new o.C("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const xe=this._calculateSpeedIndex();this.fire(new o.C("speedindexcompleted",{speedIndex:xe})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||te||(this._fullyLoaded=!0,u.mark(d.fullLoad),this._performanceMetricsCollection&&Ne(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(I){for(const y of this._markers)I&&!this.getRenderWorldCopies()&&(y._lngLat=y._lngLat.wrap()),y._update();for(const y of this._popups)!I||this.getRenderWorldCopies()||y._trackPointer||(y._lngLat=y._lngLat.wrap()),y._update()}_updateAverageElevation(I,y=!1){const C=$=>(this.transform.averageElevation=$,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&C(0);const R=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(R||(y||I-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(I)){const $=this.transform.averageElevation;let G=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(G)?G=0:this._averageElevationLastSampledAt=I;const Z=Math.abs($-G);if(Z>1){if(this._isInitialLoad||R)return this._averageElevation.jumpTo(G),C(G);this._averageElevation.easeTo(G,I,300)}else if(Z>1e-4)return this._averageElevation.jumpTo(G),C(G)}return!!this._averageElevation.isEasing(I)&&C(this._averageElevation.getValue(I))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const I=this.painter.context.gl;Be(I,!1),this._logoControl instanceof eO&&this._logoControl._updateLogo(),I&&I.clear(I.DEPTH_BUFFER_BIT|I.COLOR_BUFFER_BIT|I.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(){je(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,I=>{I&&(I.message!==Y&&I.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),Ce(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&De(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&Fe(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){be(this._requestManager._customAccessToken)}_updateTerrain(){const I=this._isDragging();this.painter.updateTerrain(this.style,I)}_calculateSpeedIndex(){const I=this.painter.canvasCopy(),y=this.painter.getCanvasCopiesAndTimestamps();y.timeStamps.push(performance.now());const C=this.painter.context.gl,R=C.createFramebuffer();function $(G){C.framebufferTexture2D(C.FRAMEBUFFER,C.COLOR_ATTACHMENT0,C.TEXTURE_2D,G,0);const Z=new Uint8Array(C.drawingBufferWidth*C.drawingBufferHeight*4);return C.readPixels(0,0,C.drawingBufferWidth,C.drawingBufferHeight,C.RGBA,C.UNSIGNED_BYTE,Z),Z}return C.bindFramebuffer(C.FRAMEBUFFER,R),this._canvasPixelComparison($(I),y.canvasCopies.map($),y.timeStamps)}_canvasPixelComparison(I,y,C){let R=C[1]-C[0];const $=I.length/4;for(let G=0;G{const C=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,C&&this._render(y)}))}_preloadTiles(I){const y=this.style?this.style.getSourceCaches():[];return o.t(y,(C,R)=>C._preloadTiles(I,R),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(I){this._trackResize&&this.resize({originalEvent:I})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(I){this._showTileBoundaries!==I&&(this._showTileBoundaries=I,this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(I){this._showParseStatus!==I&&(this._showParseStatus=I,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(I){this._showTerrainWireframe!==I&&(this._showTerrainWireframe=I,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(I){this._showLayers2DWireframe!==I&&(this._showLayers2DWireframe=I,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(I){this._showLayers3DWireframe!==I&&(this._showLayers3DWireframe=I,this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(I){this._speedIndexTiming!==I&&(this._speedIndexTiming=I,this._update())}get showPadding(){return!!this._showPadding}set showPadding(I){this._showPadding!==I&&(this._showPadding=I,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(I){this._showCollisionBoxes!==I&&(this._showCollisionBoxes=I,this.style&&I?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(I){this._showOverdrawInspector!==I&&(this._showOverdrawInspector=I,this._update())}get repaint(){return!!this._repaint}set repaint(I){this._repaint!==I&&(this._repaint=I,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(I){this._vertices=I,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(I){this._showTileAABBs!==I&&(this._showTileAABBs=I,I&&this._update())}_setCacheLimits(I,y){o.e_(I,y)}get version(){return c}},NavigationControl:class{constructor(I={}){this.options=Object.assign({},Sbe,I),this._container=_("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",y=>y.preventDefault()),this.options.showZoom&&(o.aZ(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",y=>{this._map&&this._map.zoomIn({},{originalEvent:y})}),_("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",y=>{this._map&&this._map.zoomOut({},{originalEvent: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",y=>{const C=this._map;C&&(this.options.visualizePitch?C.resetNorthPitch({},{originalEvent:y}):C.resetNorth({},{originalEvent:y}))}),this._compassIcon=_("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const I=this._map;if(!I)return;const y=I.getZoom(),C=y===I.getMaxZoom(),R=y===I.getMinZoom();this._zoomInButton.disabled=C,this._zoomOutButton.disabled=R,this._zoomInButton.setAttribute("aria-disabled",C.toString()),this._zoomOutButton.setAttribute("aria-disabled",R.toString())}_rotateCompassArrow(){const I=this._map;if(!I)return;const y=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(I.transform.pitch*(Math.PI/180)),.5)}) rotateX(${I.transform.pitch}deg) rotateZ(${I.transform.angle*(180/Math.PI)}deg)`:`rotate(${I.transform.angle*(180/Math.PI)}deg)`;I._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=y)})}onAdd(I){return this._map=I,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),I.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&I.on("pitch",this._rotateCompassArrow),I.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new GC(I,this._compass,this.options.visualizePitch)),this._container}onRemove(){const I=this._map;I&&(this._container.remove(),this.options.showZoom&&I.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&I.off("pitch",this._rotateCompassArrow),I.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(I,y){const C=_("button",I,this._container);return C.type="button",C.addEventListener("click",y),C}_setButtonTitle(I,y){if(!this._map)return;const C=this._map._getUIString(`NavigationControl.${y}`);I.setAttribute("aria-label",C),I.firstElementChild&&I.firstElementChild.setAttribute("title",C)}},GeolocateControl:class extends o.E{constructor(I={}){super();const y=navigator.geolocation;this.options=Object.assign({geolocation:y},KC,I),o.aZ(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=Sa(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(I){return this._map=I,this._container=_("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(I){const y=(C=!!this.options.geolocation)=>{this._supportsGeolocation=C,I(C)};this._supportsGeolocation!==void 0?I(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(C=>y(C.state!=="denied")).catch(()=>y()):y()}_isOutOfMapMaxBounds(I){const y=this._map.getMaxBounds(),C=I.coords;return!!y&&(C.longitudey.getEast()||C.latitudey.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(I){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(I))return this._setErrorState(),this.fire(new o.C("outofmaxbounds",I)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=I,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(I),this.options.followUserLocation&&(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK")&&this._updateCamera(I),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.C("geolocate",Object.assign({coords:I.coords,timestamp:I.timestamp},I.toJSON?{toJSON:I.toJSON.bind(I)}:{}))),this._finish()}}_updateCamera(I){const y=new o.aU(I.coords.longitude,I.coords.latitude),C=I.coords.accuracy,R=this._map.getBearing(),$=Object.assign({bearing:R},this.options.fitBoundsOptions);this._map.fitBounds(y.toBounds(C),$,{geolocateSource:!0})}_updateMarker(I){if(I){const y=new o.aU(I.coords.longitude,I.coords.latitude);this._accuracyCircleMarker.setLngLat(y).addTo(this._map),this._userLocationDotMarker.setLngLat(y).addTo(this._map),this._accuracy=I.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const I=this._map.transform,y=o.bU(1,I._center.lat)*I.worldSize,C=Math.ceil(2*this._accuracy*y);this._circleElement.style.width=`${C}px`,this._circleElement.style.height=`${C}px`}_onZoom(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}_updateMarkerRotation(){this._userLocationDotMarker&&typeof this._heading=="number"?(this._userLocationDotMarker.setRotation(this._heading),this._userLocationDotMarker.addClassName("mapboxgl-user-location-show-heading")):(this._userLocationDotMarker.removeClassName("mapboxgl-user-location-show-heading"),this._userLocationDotMarker.setRotation(0))}_onError(I){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(I.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 y=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.setAttribute("aria-label",y),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",y),this._geolocationWatchID!==void 0&&this._clearWatch()}else{if(I.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:I.code,message:I.message,PERMISSION_DENIED:I.PERMISSION_DENIED,POSITION_UNAVAILABLE:I.POSITION_UNAVAILABLE,TIMEOUT:I.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const I=this.options.positionOptions.timeout;I&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},I))}_clearRequestTimeout(){this._requestTimeoutId!==void 0&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(I){if(this._map!==void 0){if(this._container.addEventListener("contextmenu",y=>y.preventDefault()),this._geolocateButton=_("button","mapboxgl-ctrl-geolocate",this._container),_("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",I===!1){o.w("Geolocation support is not available so the GeolocateControl will be disabled.");const y=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.setAttribute("aria-label",y),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",y)}else{const y=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.setAttribute("aria-label",y),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",y)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=_("div","mapboxgl-user-location"),this._dotElement.appendChild(_("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(_("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new _g({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=_("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new _g({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",y=>{y.geolocateSource||this._watchState!=="ACTIVE_LOCK"||y.originalEvent&&y.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(I){this._userLocationDotMarker&&(I.webkitCompassHeading?this._heading=I.webkitCompassHeading:I.absolute===!0&&(this._heading=-1*I.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 I;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(I={maximumAge:6e5,timeout:0},this._noTimeout=!0):(I=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,I),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(I){return this.options.followUserLocation=I??KC.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 I=()=>{const y="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(y,this._onDeviceOrientation)};typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(y=>{y==="granted"&&I()}).catch(console.error):I()}_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:JR,ScaleControl:class{constructor(I={}){this.options=Object.assign({},ud,I),o.aZ(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const I=this.options.maxWidth||100,y=this._map,C=y._containerHeight/2,R=y._containerWidth/2-I/2,$=y.unproject([R,C]),G=y.unproject([R+I,C]),Z=$.distanceTo(G);if(this.options.unit==="imperial"){const te=3.2808*Z;te>5280?this._setScale(I,te/5280,"mile"):this._setScale(I,te,"foot")}else this.options.unit==="nautical"?this._setScale(I,Z/1852,"nautical-mile"):Z>=1e3?this._setScale(I,Z/1e3,"kilometer"):this._setScale(I,Z,"meter")}_setScale(I,y,C){this._map._requestDomTask(()=>{const R=function(G){const Z=Math.pow(10,`${Math.floor(G)}`.length-1);let te=G/Z;return te=te>=10?10:te>=5?5:te>=3?3:te>=2?2:te>=1?1:function(de){const xe=Math.pow(10,Math.ceil(-Math.log(de)/Math.LN10));return Math.round(de*xe)/xe}(te),Z*te}(y),$=R/y;this._container.innerHTML=C!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:C}).format(R):`${R} ${wg[C]}`,this._container.style.width=I*$+"px"})}onAdd(I){return this._map=I,this._language=I.getLanguage(),this._container=_("div","mapboxgl-ctrl mapboxgl-ctrl-scale",I.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(I){this._language=I,this._update()}setUnit(I){this.options.unit=I,this._update()}},FullscreenControl:class{constructor(I={}){this._fullscreen=!1,I&&I.container&&(I.container instanceof HTMLElement?this._container=I.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(I){return this._map=I,this._container||(this._container=this._map.getContainer()),this._controlContainer=_("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 I=this._fullscreenButton=_("button","mapboxgl-ctrl-fullscreen",this._controlContainer);_("span","mapboxgl-ctrl-icon",I).setAttribute("aria-hidden","true"),I.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const I=this._getTitle();this._fullscreenButton.setAttribute("aria-label",I),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",I)}_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(I){return this._map=I,this._container=_("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 I=this._map.style.indoorManager;I.off("selector-update",this._onIndoorUpdate),I.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(I.getControlState())}}_createButton(I,y){const C=_("button",I,this._container);return C.type="button",C.addEventListener("click",y),C}_setButtonTitle(I,y){I.setAttribute("aria-label",y),I.textContent=y}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(I){if(!I||!I.floors||I.floors.length===0)return this._model=I,void(this._container.style.display="none");const y=this._model;this._model=I,this._container.style.display="inline-block";const C=!y||y.floors.length!==I.floors.length||y.floors.some((R,$)=>R.id!==I.floors[$].id);if(C&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),I.selectedFloorId){if(I.selectedFloorId!==this._lastSelectedFloorId||C){const R=I.floors.findIndex($=>$.id===I.selectedFloorId);if(R!==-1){const $=I.floors.length;let G,Z;$<=5?(G=0,Z=$-1):this._visibleFloorStart===0?(G=0,Z=3):this._visibleFloorStart>=$-3?(G=$-3-1,Z=$-1):(G=this._visibleFloorStart,Z=this._visibleFloorStart+3-1),RZ&&(this._visibleFloorStart=R-2)}}this._lastSelectedFloorId=I.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const I=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);_("span","mapboxgl-ctrl-icon",I).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||I.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(I);const y=this._model.floors,C=y.length;if(C<=5)return void y.forEach(Z=>this._createFloorButton(Z));const R=this._visibleFloorStart===0,$=this._visibleFloorStart>=C-3;if(R)this._createFloorButton(y[0]);else{const Z=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);_("span","mapboxgl-ctrl-icon",Z).setAttribute("aria-hidden","true"),this._container.appendChild(Z)}let G=[];if(G=R?y.slice(1,4):$?y.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):y.slice(this._visibleFloorStart,this._visibleFloorStart+3),G.forEach(Z=>this._createFloorButton(Z)),$)this._createFloorButton(y[C-1]);else{const Z=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);_("span","mapboxgl-ctrl-icon",Z).setAttribute("aria-hidden","true"),this._container.appendChild(Z)}}_createFloorButton(I){const y=this._createButton("mapboxgl-ctrl-level-button",()=>{const G=I.id;this._model&&this._model.selectedFloorId===G&&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(G))}),C=(I.name||"").trim(),R=I.zIndex.toString(),$=C?Array.from(C).slice(0,3).join(""):R;this._setButtonTitle(y,$),this._model&&this._model.activeFloorsVisible&&I.id===this._model.selectedFloorId&&y.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(y)}_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 I=this._model&&this._model.floors||[];if(I.length>3){const y=I.length-3;this._visibleFloorStart===y-1&&(this._visibleFloorStart=y-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const I=this._model.floors.length-3;this._visibleFloorStartI&&(this._visibleFloorStart=I),this._render())}}},Popup:class extends o.E{constructor(I){super(),this.options=Object.assign(Object.create(YC),I),this._altitude=this.options.altitude,o.aZ(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(I&&I.className?I.className.trim().split(/\s+/):[])}addTo(I){return this._map&&this.remove(),this._map=I,this.options.closeOnClick&&I.on("preclick",this._onClose),this.options.closeOnMove&&I.on("move",this._onClose),I.on("remove",this.remove),this._update(),I._addPopup(this),this._focusFirstElement(),this._trackPointer?(I.on("mousemove",this._onMouseEvent),I.on("mouseup",this._onMouseEvent),I._canvasContainer.classList.add("mapboxgl-track-pointer")):I.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 I=this._map;return I&&(I.off("move",this._update),I.off("move",this._onClose),I.off("preclick",this._onClose),I.off("click",this._onClose),I.off("remove",this.remove),I.off("mousemove",this._onMouseEvent),I.off("mouseup",this._onMouseEvent),I.off("drag",this._onMouseEvent),I._canvasContainer&&I._canvasContainer.classList.remove("mapboxgl-track-pointer"),I._removePopup(this),this._map=void 0),this.fire(new o.C("close")),this}getLngLat(){return this._lngLat}setLngLat(I){this._lngLat=o.aU.convert(I),this._pos=null,this._trackPointer=!1,this._update();const y=this._map;return y&&(y.on("move",this._update),y.off("mousemove",this._onMouseEvent),y._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(I){return this._altitude=I,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const I=this._map;return I&&(I.off("move",this._update),I.on("mousemove",this._onMouseEvent),I.on("drag",this._onMouseEvent),I._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(I){return this.setDOMContent(document.createTextNode(I))}setHTML(I){const y=document.createDocumentFragment(),C=document.createElement("body");let R;for(C.innerHTML=I;R=C.firstChild,R;)y.appendChild(R);return this.setDOMContent(y)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(I){return this.options.maxWidth=I,this._update(),this}setDOMContent(I){let y=this._content;if(y)for(;y.hasChildNodes();)y.firstChild&&y.removeChild(y.firstChild);else y=this._content=_("div","mapboxgl-popup-content",this._container||void 0);if(y.appendChild(I),this.options.closeButton){const C=this._closeButton=_("button","mapboxgl-popup-close-button",y);C.type="button",C.setAttribute("aria-label","Close popup"),C.innerHTML='',C.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(I){return this._classList.add(I),this._updateClassList(),this}removeClassName(I){return this._classList.delete(I),this._updateClassList(),this}setOffset(I){return this.options.offset=I,this._update(),this}toggleClassName(I){let y;return this._classList.delete(I)?y=!1:(this._classList.add(I),y=!0),this._updateClassList(),y}_onMouseEvent(I){this._update(I.point)}_getAnchor(I){if(this.options.anchor)return this.options.anchor;const y=this._map,C=this._container,R=this._pos;if(!y||!C||!R)return"bottom";const $=C.offsetWidth,G=C.offsetHeight,Z=R.x<$/2,te=R.x>y.transform.width-$/2;if(R.y+Iy.transform.height-G){if(Z)return"bottom-left";if(te)return"bottom-right"}return Z?"left":te?"right":"bottom"}_updateClassList(){const I=this._container;if(!I)return;const y=[...this._classList];y.push("mapboxgl-popup"),this._anchor&&y.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&y.push("mapboxgl-popup-track-pointer"),I.className=y.join(" ")}_update(I){const y=this._map,C=this._content;if(!y||!this._lngLat&&!this._trackPointer||!C)return;let R=this._container;if(R||(R=this._container=_("div","mapboxgl-popup",y.getContainer()),this._tip=_("div","mapboxgl-popup-tip",R),R.appendChild(C)),this.options.maxWidth&&R.style.maxWidth!==this.options.maxWidth&&(R.style.maxWidth=this.options.maxWidth),y.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=tO(this._lngLat,this._pos,y.transform)),!this._trackPointer||I){const $=this._pos=this._trackPointer&&I instanceof o.P?I:y.project(this._lngLat,this._altitude),G=O6(this.options.offset),Z=this._anchor=this._getAnchor(G.y),te=O6(this.options.offset,Z),de=$.add(te).round();y._requestDomTask(()=>{this._container&&Z&&(this._container.style.transform=`${WC[Z]} translate(${de.x}px,${de.y}px)`)})}if(!this._marker&&y._showingGlobe()){const $=o.e$(y.transform,this._lngLat)?0:1;this._setOpacity($)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const I=this._container.querySelector(Cbe);I&&I.focus()}_onClose(){this.remove()}_setOpacity(I){this._container&&(this._container.style.opacity=`${I}`),this._content&&(this._content.style.pointerEvents=I?"auto":"none")}},Marker:_g,Style:Qc,LngLat:o.aU,LngLatBounds:o.aK,Point:o.P,MercatorCoordinate:o.ag,FreeCameraOptions:Yb,Evented:o.E,config:o.g,prewarm:function(){Bt().acquire(at)},clearPrewarmedResources:function(){const I=bt;I&&(I.isPreloaded()&&I.numActive()===1?(I.release(at),bt=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"))},get accessToken(){return o.g.ACCESS_TOKEN},set accessToken(I){o.g.ACCESS_TOKEN=I},get baseApiUrl(){return o.g.API_URL},set baseApiUrl(I){o.g.API_URL=I},get workerCount(){return He.workerCount},set workerCount(I){He.workerCount=I},get maxParallelImageRequests(){return o.g.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(I){o.g.MAX_PARALLEL_IMAGE_REQUESTS=I},clearStorage(I){o.f7(I)},get workerUrl(){return rt.workerUrl},set workerUrl(I){rt.workerUrl=I},get workerClass(){return rt.workerClass},set workerClass(I){rt.workerClass=I},get workerParams(){return rt.workerParams},set workerParams(I){rt.workerParams=I},get dracoUrl(){return o.f6()},set dracoUrl(I){o.g.DRACO_URL=o.o.resolveURL(I)},get meshoptUrl(){return o.f5()},set meshoptUrl(I){const y=o.o.resolveURL(I);o.g.MESHOPT_URL=y,o.g.MESHOPT_SIMD_URL=y},get buildingGenUrl(){return o.f4()},set buildingGenUrl(I){o.g.BUILDING_GEN_URL=o.o.resolveURL(I)},setNow:o.o.setNow,restoreNow:o.o.restoreNow}});var l=a;return l})})(mct);var gzt=mct.exports;const hl=wl(gzt),oBe={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},lBe={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 yzt(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function vzt({listings:s,isLoading:t}){const n=Mn(),r=N.useRef(null),a=N.useRef(null),i=N.useRef([]),[l,o]=N.useState(""),[c,d]=N.useState(!0);return N.useEffect(()=>{(async()=>{d(!0);try{const{data:p}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();p!=null&&p.value&&o(p.value)}catch(p){console.error("Error fetching mapbox token:",p)}d(!1)})()},[]),N.useEffect(()=>{if(!r.current||!l||a.current)return;hl.accessToken=l;const h=s.filter(g=>g.latitude!=null&&g.longitude!=null);let p=[-98.5795,39.8283],f=4;if(h.length>0){const g=h.reduce((v,j)=>v+j.longitude,0)/h.length,_=h.reduce((v,j)=>v+j.latitude,0)/h.length;p=[g,_],f=h.length===1?12:10}return a.current=new hl.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:f,center:p}),a.current.addControl(new hl.NavigationControl,"top-right"),()=>{var g;(g=a.current)==null||g.remove(),a.current=null}},[l]),N.useEffect(()=>{if(!a.current||!l)return;i.current.forEach(p=>p.remove()),i.current=[];const h=s.filter(p=>p.latitude!=null&&p.longitude!=null);if(h.forEach(p=>{var A,T,L;const f=oBe[p.status]||"#10B981",g=((A=p.photos)==null?void 0:A.find(D=>D.is_primary))||((T=p.photos)==null?void 0:T[0]),v=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${p.slug||p.id}`:`/public/listing/${p.slug||p.id}`,j=document.createElement("div");j.className="cursor-pointer",j.innerHTML=`
`;const b=new hl.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${g!=null&&g.photo_url?``:""}
${yzt(p.price)}
${p.property_address||""}
${p.city}, ${p.state}
${lBe[p.status]||p.status} ${p.bedrooms?`${p.bedrooms} bed`:""} ${p.bathrooms?`${p.bathrooms} bath`:""}
${(L=p.agent)!=null&&L.name?`
Listed by ${p.agent.name}
`:""}
Click to view details →
`),S=new hl.Marker(j).setLngLat([p.longitude,p.latitude]).setPopup(b).addTo(a.current);i.current.push(S)}),h.length>1){const p=new hl.LngLatBounds;h.forEach(f=>p.extend([f.longitude,f.latitude])),a.current.fitBounds(p,{padding:60,maxZoom:13})}else h.length===1&&a.current.flyTo({center:[h[0].longitude,h[0].latitude],zoom:12})},[s,l]),N.useEffect(()=>(window.__navigateToPublicListing__=h=>{n(h)},()=>{delete window.__navigateToPublicListing__}),[n]),c||t?e.jsx(Ws,{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(oBe).map(([h,p])=>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:p}}),e.jsx("span",{className:"text-xs text-gray-600",children:lBe[h]})]},h))}),e.jsx("div",{ref:r,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const oje={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},bzt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},vI="#0d0d0d",cBe="#1a1a1a",bl="#c9a84c",Nk="#f0d78c";function fct(){const[s,t]=N.useState(""),[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(-1),u=N.useRef(null),[h,p]=N.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:f}=dzt(),g=N.useMemo(()=>{if(!f)return[];const V=s.trim().toLowerCase(),W=[...f.cities.map(K=>({label:K.label,value:K.city,type:"city",count:K.count})),...f.neighborhoods.map(K=>({label:K.label,value:K.neighborhood,type:"neighborhood",count:K.count})),...f.zips.map(K=>({label:`ZIP ${K.label}`,value:K.zip,type:"zip",count:K.count}))];return(V?W.filter(K=>K.label.toLowerCase().includes(V)||K.value.toLowerCase().includes(V)):W).slice(0,8)},[f,s]);N.useEffect(()=>{const V=W=>{u.current&&!u.current.contains(W.target)&&o(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[]);const{data:_,isLoading:v}=czt({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}),j=V=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(V),b=()=>{p({status:"",propertyType:"",minPrice:"",maxPrice:""}),t("")},S=s||h.status||h.propertyType||h.minPrice||h.maxPrice,A=typeof window<"u"&&(window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")),T=V=>A?`/${V.slug||V.id}`:`/public/listing/${V.slug||V.id}`,{featured:L,restListings:D,luxeCount:M,cities:F,activeCount:z}=N.useMemo(()=>{const V=_||[],W=V.filter(Te=>Te.status==="active"),Y=W.length>0?W:V,K=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[J,ne,ie]=K.split("-").map(Number),he=Math.floor(Date.UTC(J,ne-1,ie)/864e5),ce=Y.length>0?Y[he%Y.length]:void 0,pe=V.filter(Te=>!ce||Te.id!==ce.id),le=Array.from(new Set(V.map(Te=>Te.city).filter(Boolean))).slice(0,8),ve=V.filter(Te=>(Te.price||0)>=1e6).length,ge=W.length;return{featured:ce,restListings:pe,luxeCount:ve,cities:le,activeCount:ge}},[_]);return e.jsxs(e.Fragment,{children:[e.jsxs(Go,{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:vI,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: ${bl}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${bl}, 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(Ln,{to:"/",className:"flex items-center gap-3",children:[e.jsx("img",{src:lfe,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(Ln,{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 ${bl}`,color:bl},children:"About LevelUp"})]}),e.jsx("button",{type:"button",onClick:()=>i(V=>!V),className:"md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full",style:{border:`1px solid ${bl}`,color:bl},"aria-label":"Toggle menu","aria-expanded":a,children:a?e.jsx(Bn,{className:"w-5 h-5"}):e.jsx(s4,{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(Ln,{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 ${bl}`,color:bl},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:xzt,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:bl}}),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:Nk},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 ${bl}`,backdropFilter:"blur(12px)"},children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:bl}}),e.jsx(ye,{placeholder:"City, neighborhood, or ZIP",value:s,onChange:V=>{t(V.target.value),o(!0),d(-1)},onFocus:()=>o(!0),onKeyDown:V=>{if(!(!l||g.length===0))if(V.key==="ArrowDown")V.preventDefault(),d(W=>Math.min(W+1,g.length-1));else if(V.key==="ArrowUp")V.preventDefault(),d(W=>Math.max(W-1,0));else if(V.key==="Enter"&&c>=0){V.preventDefault();const W=g[c];t(W.value),o(!1)}else V.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(l4,{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:bl,color:vI},onClick:()=>o(!1),children:[e.jsx(vr,{className:"h-5 w-5"}),e.jsx("span",{className:"hidden md:inline",children:"Search"})]})]}),l&&g.length>0&&e.jsxs("div",{className:"mt-2 rounded-2xl overflow-hidden shadow-2xl animate-fade-in",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.35)",backdropFilter:"blur(12px)"},children:[e.jsx("div",{className:"px-5 pt-3 pb-2 text-[10px] tracking-[0.2em] uppercase",style:{color:bl},children:"Suggestions"}),e.jsx("ul",{className:"max-h-80 overflow-y-auto",children:g.map((V,W)=>e.jsx("li",{children:e.jsxs("button",{type:"button",onMouseEnter:()=>d(W),onClick:()=>{t(V.value),o(!1)},className:"w-full flex items-center justify-between gap-3 px-5 py-3 text-left transition",style:{background:c===W?"rgba(201,168,76,0.12)":"transparent"},children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[V.type==="city"&&e.jsx(ka,{className:"h-4 w-4 shrink-0",style:{color:bl}}),V.type==="neighborhood"&&e.jsx(Va,{className:"h-4 w-4 shrink-0",style:{color:bl}}),V.type==="zip"&&e.jsx(Or,{className:"h-4 w-4 shrink-0",style:{color:bl}}),e.jsx("span",{className:"text-white/90 truncate",children:V.label})]}),e.jsxs("span",{className:"text-xs text-white/50 shrink-0",children:[V.count," ",V.count===1?"listing":"listings"]})]})},`${V.type}-${V.value}-${W}`))})]}),l&&s.trim()&&g.length===0&&e.jsx("div",{className:"mt-2 rounded-2xl px-5 py-4 text-sm text-white/70",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.25)"},children:"No matches yet — try a nearby city or ZIP."}),n&&e.jsxs("div",{className:"mt-4 p-6 rounded-2xl grid sm:grid-cols-2 md:grid-cols-4 gap-4 animate-fade-in",style:{background:"rgba(26,26,26,0.9)",border:"1px solid rgba(201,168,76,0.25)"},children:[e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Status"}),e.jsxs(ds,{value:h.status||"all",onValueChange:V=>p({...h,status:V==="all"?"":V}),children:[e.jsx(ls,{className:"lu-input-dark",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"Any status"}),Object.entries(oje).map(([V,W])=>e.jsx(Qe,{value:V,children:W},V))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),e.jsxs(ds,{value:h.propertyType||"all",onValueChange:V=>p({...h,propertyType:V==="all"?"":V}),children:[e.jsx(ls,{className:"lu-input-dark",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"Any type"}),Object.entries(bzt).map(([V,W])=>e.jsx(Qe,{value:V,children:W},V))]})]})]}),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:V=>p({...h,minPrice:V.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:V=>p({...h,maxPrice:V.target.value}),className:"lu-input-dark"})]}),S&&e.jsx("div",{className:"sm:col-span-2 md:col-span-4 flex justify-end",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:b,className:"text-white/70 hover:text-white gap-1",children:[e.jsx(Bn,{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:((_==null?void 0:_.length)??0).toString()},{label:"Active Now",value:z.toString()},{label:"Luxury $1M+",value:M.toString()}].map(V=>e.jsxs("div",{children:[e.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:Nk},children:V.value}),e.jsx("div",{className:"lu-eyebrow text-white/60 mt-1",children:V.label})]},V.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(io,{className:"h-4 w-4 animate-bounce"})]})]})]}),F.length>0&&e.jsx("section",{className:"py-8 overflow-hidden",style:{background:cBe,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:[...F,...F,...F].map((V,W)=>e.jsxs("span",{className:"flex items-center gap-3 lu-serif text-2xl md:text-3xl text-white/40",children:[V,e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:bl}})]},W))})}),L&&e.jsx("section",{id:"featured",className:"py-20 md:py-28",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[e.jsxs("div",{className:"flex items-end justify-between mb-10 md:mb-14",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx(un,{className:"h-4 w-4",style:{color:bl}}),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:Nk},children:"standout"}),"."]})]}),e.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),e.jsx(Ln,{to:T(L),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 W,Y;const V=((W=L.photos)==null?void 0:W.find(K=>K.is_primary))||((Y=L.photos)==null?void 0:Y[0]);return V?e.jsx("img",{src:V.photo_url,alt:L.property_address||L.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(Or,{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:bl,color:vI},children:oje[L.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(ka,{className:"h-3.5 w-3.5",style:{color:bl}}),L.city,L.state?`, ${L.state}`:""]}),L.property_address&&e.jsx("h3",{className:"lu-serif text-3xl md:text-4xl mb-4 leading-tight",children:L.property_address}),e.jsx("div",{className:"lu-serif text-5xl md:text-6xl mb-6",style:{color:Nk},children:j(L.price)}),e.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[L.bedrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(sy,{className:"h-4 w-4",style:{color:bl}}),L.bedrooms," bd"]}),L.bathrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Cp,{className:"h-4 w-4",style:{color:bl}}),L.bathrooms," ba"]}),L.square_footage&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ly,{className:"h-4 w-4",style:{color:bl}}),L.square_footage.toLocaleString()," sf"]})]}),L.description&&e.jsx("p",{className:"text-white/60 leading-relaxed mb-8 line-clamp-4",children:L.description}),e.jsxs("div",{className:"inline-flex items-center gap-3 lu-eyebrow group-hover:gap-5 transition-all",style:{color:bl},children:["View Residence ",e.jsx(Oa,{className:"h-4 w-4"})]})]})]})})]})}),e.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:cBe},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:bl}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),e.jsx("span",{className:"h-px w-10",style:{background:bl}})]}),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:Nk},children:"carefully considered"}),"."]}),e.jsx("p",{className:"text-white/60 max-w-2xl mx-auto",children:"Browse the full catalogue of LevelUp-represented properties. Filter, refine, and find the one that feels like yours."})]}),v?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-8",children:[...Array(6)].map((V,W)=>e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ws,{className:"aspect-[4/5] bg-white/5"}),e.jsx(Ws,{className:"h-6 w-32 bg-white/5"}),e.jsx(Ws,{className:"h-4 w-full bg-white/5"})]},W))}):D.length>0?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-14",children:D.map(V=>{var Y,K,J,ne,ie;const W=((Y=V.photos)==null?void 0:Y.find(he=>he.is_primary))||((K=V.photos)==null?void 0:K[0]);return e.jsxs(Ln,{to:T(V),className:"group lu-card-hover block",children:[e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden bg-black mb-5 rounded-lg",children:[W?e.jsx("img",{src:W.photo_url,alt:V.property_address||V.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(Or,{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:bl,border:`1px solid ${bl}`},children:oje[V.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:[V.bedrooms&&e.jsxs("span",{children:[V.bedrooms," bd"]}),V.bathrooms&&e.jsxs("span",{children:[V.bathrooms," ba"]}),V.square_footage&&e.jsxs("span",{children:[V.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(ka,{className:"h-3 w-3",style:{color:bl}}),V.city,V.state?`, ${V.state}`:""]}),e.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:Nk},children:j(V.price)}),V.property_address&&e.jsx("p",{className:"text-white/70 text-sm truncate",children:V.property_address}),((J=V.agent)==null?void 0:J.name)&&e.jsxs("p",{className:"text-white/40 text-xs mt-3 flex items-center gap-2",children:[e.jsx(Va,{className:"h-3 w-3"}),V.agent.name,(((ne=V.agent.brokerage)==null?void 0:ne.name)||V.agent.brokerage_name)&&e.jsxs("span",{className:"truncate",children:["· ",((ie=V.agent.brokerage)==null?void 0:ie.name)||V.agent.brokerage_name]})]})]})]},V.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 ${bl}`},children:e.jsx(Or,{className:"h-8 w-8",style:{color:bl}})}),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."}),S&&e.jsx(B,{onClick:b,style:{background:bl,color:vI},className:"hover:brightness-110",children:"Clear filters"})]})]})}),_&&_.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:bl}}),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:Nk},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(vzt,{listings:_,isLoading:v})})]})}),e.jsxs("section",{className:"relative py-24 md:py-32 overflow-hidden lu-grain",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`radial-gradient(ellipse at center, rgba(201,168,76,0.15) 0%, ${vI} 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:bl}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),e.jsx("span",{className:"h-px w-10",style:{background:bl}})]}),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:Nk},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:bl,color:vI},children:["Explore LevelUp",e.jsx(Oa,{className:"h-4 w-4"})]})]})]}),e.jsx("footer",{className:"py-14",style:{background:"#080808",borderTop:"1px solid rgba(201,168,76,0.15)"},children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 flex flex-col md:flex-row items-center justify-between gap-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:lfe,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(d9t,{}),e.jsx(u9t,{})]})}const _zt=N.lazy(()=>yi(()=>import("./PublicHomeValue-DmIsARfF.js"),[]));function wzt(){const s=Jl(),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(fct,{}):r==="home-value"||r==="whats-my-home-worth"?e.jsx(N.Suspense,{fallback:e.jsx("div",{}),children:e.jsx(_zt,{})}):r.startsWith("public/")?null:e.jsx(hct,{slugOverride:r})}function cye({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 xct=s=>ct({queryKey:["agent-card-public",s],queryFn:async()=>{if(!s)throw new Error("No slug provided");const{data:t,error:n}=await q.from("agent_cards").select("*").eq("slug",s).eq("is_published",!0).single();if(n)throw n;const{data:r}=await q.from("profiles").select("name, email, phone, brokerage_id").eq("id",t.user_id).single();let a=null;if(r!=null&&r.brokerage_id){const{data:o}=await q.from("brokerages").select("name").eq("id",r.brokerage_id).single();a=(o==null?void 0:o.name)||null}let i=null;try{const{data:o}=await q.from("profiles").select("avatar_url").eq("id",t.user_id).single();if(o!=null&&o.avatar_url)i=o.avatar_url;else{const{data:c}=await q.storage.from("avatars").list(`${t.user_id}`);if(c&&c.length>0){const{data:d}=q.storage.from("avatars").getPublicUrl(`${t.user_id}/${c[0].name}`);i=`${d.publicUrl}?t=${Date.now()}`}}}catch{}const l={...r||{name:null,email:null,phone:null,brokerage_id:null},email:t.display_email||(r==null?void 0:r.email)||null};return{...t,social_links:t.social_links||[],profile:l,brokerage_name:t.brokerage_display_name||a,avatar_url:i}},enabled:!!s}),jzt=()=>ct({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:s,error:t}=await q.from("agent_cards").select("*").order("created_at",{ascending:!1});if(t)throw t;return s}}),Nzt=s=>ct({queryKey:["agent-card",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_cards").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),gct=()=>{const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("agent_cards").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),ae.success("Agent card created")},onError:t=>ae.error(t.message)})},yct=()=>{const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("agent_cards").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),ae.success("Agent card updated")},onError:t=>ae.error(t.message)})},ml=async(s,t,n,r)=>{const a=new URLSearchParams(window.location.search);await q.from("agent_card_interactions").insert({card_id:s,interaction_type:t,interaction_detail:n||null,referrer:document.referrer||null,user_agent:navigator.userAgent||null,utm_source:a.get("utm_source")||null,utm_medium:a.get("utm_medium")||null,utm_campaign:a.get("utm_campaign")||null,metadata:{}})},kzt=async(s,t)=>{const{error:n}=await q.from("agent_card_leads").insert({card_id:s,...t});if(n)throw n},vct=s=>ct({queryKey:["agent-card-analytics",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_card_interactions").select("interaction_type, interaction_detail, created_at").eq("card_id",s).order("created_at",{ascending:!1}).limit(500);if(n)throw n;const{data:r,error:a}=await q.from("agent_card_leads").select("*").eq("card_id",s).order("created_at",{ascending:!1});if(a)throw a;const i=(t==null?void 0:t.filter(c=>c.interaction_type==="card_view").length)||0,l=(t==null?void 0:t.filter(c=>c.interaction_type==="button_click").length)||0,o=(t==null?void 0:t.filter(c=>c.interaction_type==="contact_saved").length)||0;return{views:i,clicks:l,saves:o,leads:r||[],interactions:t||[]}},enabled:!!s});function dye({open:s,onOpenChange:t,cardId:n,type:r,agentName:a}){const[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(""),[_,v]=N.useState(!1),j=async b=>{if(b.preventDefault(),!i.trim()){ae.error("Please enter your name");return}v(!0);try{await kzt(n,{lead_type:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:f.trim()||void 0,intent:h||void 0}),ml(n,"lead_submitted",r),q.functions.invoke("card-lead-notify",{body:{cardId:n,leadType:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:f.trim()||void 0,intent:h||void 0}}).catch(S=>console.error("Card lead notify failed:",S)),ae.success(r==="booking"?"Request sent! They'll be in touch soon.":r==="connect"?"Info shared! They'll be in touch soon.":"Referral submitted! Thank you."),t(!1),l(""),c(""),u(""),p(""),g("")}catch{ae.error("Something went wrong. Please try again.")}finally{v(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:r==="booking"?"Book a Call":r==="connect"?"Connect with Me":"Refer a Friend"}),e.jsx(Qn,{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:j,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:b=>l(b.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:b=>u(b.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:b=>c(b.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(ds,{value:h,onValueChange:p,children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select one"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"buy",children:"Buy a home"}),e.jsx(Qe,{value:"sell",children:"Sell my home"}),e.jsx(Qe,{value:"both",children:"Buy & Sell"}),e.jsx(Qe,{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:f,onChange:b=>g(b.target.value),placeholder:r==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),e.jsx(B,{type:"submit",className:"w-full rounded-2xl",disabled:_,children:_?"Sending...":"Submit"})]})]})})}const Szt=s=>ct({queryKey:["card-blocks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("card_blocks").select("*").eq("card_id",s).eq("is_visible",!0).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),Czt=s=>ct({queryKey:["card-blocks-all",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("card_blocks").select("*").eq("card_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),Tzt=()=>{const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("card_blocks").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["card-blocks",n.card_id]}),s.invalidateQueries({queryKey:["card-blocks-all",n.card_id]}),ae.success("Block added")},onError:t=>ae.error(t.message)})},Ezt=()=>{const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("card_blocks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),ae.success("Block updated")},onError:t=>ae.error(t.message)})},Azt=()=>{const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("card_blocks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),ae.success("Block removed")},onError:t=>ae.error(t.message)})};function Mzt(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 Izt(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 Pzt={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 Lzt({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=Izt(n.video_url),i=r||!!a,l=r?Mzt(n.video_url):a||n.video_url;return e.jsx("div",{className:Pzt[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 Dzt={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 Rzt({block:s,variant:t}){const r=s.config.testimonials||[],[a,i]=N.useState(0);if(r.length===0)return null;const l=Dzt[t],o=r[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(gb,{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(pl,{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(xa,{className:"h-4 w-4"})})]})]})}const Ozt={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 Fzt({block:s,variant:t}){const r=s.config.tags||[];if(r.length===0)return null;const a=Ozt[t];return e.jsx("div",{className:a.container,children:r.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const zzt={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 Bzt({block:s,cardId:t,variant:n}){const a=s.config.links||[];if(a.length===0)return null;const i=zzt[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:()=>ml(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 P4e={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 $zt({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 Uzt={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 qzt({block:s,cardId:t,variant:n}){const a=s.config.platforms||[],i=Uzt[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=P4e[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>ml(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx($zt,{path:c.icon,color:c.color})},o)})})]})}function uye({cardId:s,variant:t}){const{data:n}=Szt(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(Lzt,{block:l,variant:t},l.id);case"testimonials":return e.jsx(Rzt,{block:l,variant:t},l.id);case"specialties":return e.jsx(Fzt,{block:l,variant:t},l.id);case"custom_links":return e.jsx(Bzt,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(qzt,{block:i,cardId:s,variant:t})]})}async function Vzt(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 Hzt(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 hye(s){const{first:t,last:n}=Hzt(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 Vzt(s.avatarUrl);if(o){const d={"image/jpeg":"JPEG","image/jpg":"JPEG","image/png":"PNG","image/gif":"GIF","image/webp":"JPEG"}[o.mimeType]||"JPEG";r.push(`PHOTO;ENCODING=b;TYPE=${d}:${o.base64}`)}}r.push("END:VCARD");const a=new Blob([r.join(`\r `)],{type:"text/vcard"}),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=`${s.name.replace(/\s+/g,"_")}.vcf`,l.click(),URL.revokeObjectURL(i),ae.success("Contact saved!")}function Gzt({card:s}){var j;const[t,n]=N.useState(!1),[r,a]=N.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,S)=>{ml(s.id,"button_click",b),S()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),ml(s.id,"button_click","book"))},p=()=>{var b,S;ml(s.id,"contact_saved"),hye({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(S=s.profile)==null?void 0:S.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},f=async()=>{ml(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,S="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:S,url:b})}catch{}else await navigator.clipboard.writeText(b),ae.success("Link copied!")},g=()=>{a("referral"),n(!0),ml(s.id,"button_click","refer")},_=()=>{a("connect"),n(!0),ml(s.id,"button_click","connect")},v={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-white to-slate-50",children:[e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(ra,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(ni,{src:s.avatar_url||void 0,alt:i}),e.jsx(aa,{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(Ar,{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(Ei,{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(Vs,{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(yr,{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(ca,{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(cye,{card:s,variant:"standard"}),e.jsx(uye,{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:p,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Pa,{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:()=>{ml(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(ca,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),s.show_refer_friend&&e.jsxs(B,{variant:"ghost",onClick:g,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Nn,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),e.jsxs(B,{variant:"ghost",onClick:_,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Fo,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),e.jsxs(B,{variant:"ghost",onClick:f,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Hl,{className:"h-4 w-4 mr-3 text-primary"}),"Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((b,S)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>ml(s.id,"button_click",`social_${b.platform}`),className:"h-10 w-10 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center text-lg transition-colors",children:v[b.platform.toLowerCase()]||"🔗"},S))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),e.jsx(dye,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function Wzt({card:s}){var j;const[t,n]=N.useState(!1),[r,a]=N.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,S)=>{ml(s.id,"button_click",b),S()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),ml(s.id,"button_click","book"))},p=()=>{var b,S;ml(s.id,"contact_saved"),hye({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(S=s.profile)==null?void 0:S.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},f=async()=>{ml(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,S="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:S,url:b})}catch{}else await navigator.clipboard.writeText(b),ae.success("Link copied!")},g=()=>{a("referral"),n(!0),ml(s.id,"button_click","refer")},_=()=>{a("connect"),n(!0),ml(s.id,"button_click","connect")},v={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-[#0f1419] via-[#1a1f2e] to-[#0f1419]",children:[e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsx("div",{className:"w-16 h-0.5 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] mx-auto mb-8"}),e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(ra,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[e.jsx(ni,{src:s.avatar_url||void 0,alt:i}),e.jsx(aa,{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:Ar,label:"Call",handler:c},{icon:Ei,label:"Text",handler:d},{icon:Vs,label:"Email",handler:u}].map(({icon:b,label:S,handler:A})=>e.jsxs("button",{onClick:A,className:"flex flex-col items-center gap-1.5 py-4 bg-[#1e2636] hover:bg-[#252d3f] border border-[#c9a84c]/20 rounded-xl transition-colors",children:[e.jsx(b,{className:"h-5 w-5 text-[#c9a84c]"}),e.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:S})]},S))}),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(yr,{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(ca,{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(cye,{card:s,variant:"luxury"}),e.jsx(uye,{cardId:s.id,variant:"luxury"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&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(Pa,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{ml(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(ca,{className:"h-4 w-4 text-[#c9a84c]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:g,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Nn,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a Friend"]}),e.jsxs("button",{onClick:_,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(Fo,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),e.jsxs("button",{onClick:f,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Hl,{className:"h-4 w-4 text-[#c9a84c]"})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((b,S)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>ml(s.id,"button_click",`social_${b.platform}`),className:"h-10 w-10 rounded-full bg-[#1e2636] border border-[#c9a84c]/20 hover:border-[#c9a84c]/50 flex items-center justify-center text-lg transition-colors",children:v[b.platform.toLowerCase()]||"🔗"},S))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),e.jsx(dye,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function Kzt({card:s}){var S,A,T,L;const[t,n]=N.useState(!1),[r,a]=N.useState("booking"),i=((S=s.profile)==null?void 0:S.name)||"Agent",l=i.split(" ").map(D=>D[0]).join("").toUpperCase().slice(0,2),o={accent:((A=s.bold_theme_colors)==null?void 0:A.accent)||"#ff5722",dark:((T=s.bold_theme_colors)==null?void 0:T.dark)||"#1a1a2e",button:((L=s.bold_theme_colors)==null?void 0:L.button)||"#ff5722"},c=(D,M)=>{const F=parseInt(D.replace("#",""),16),z=Math.max(0,(F>>16)-M),V=Math.max(0,(F>>8&255)-M),W=Math.max(0,(F&255)-M);return`#${(z<<16|V<<8|W).toString(16).padStart(6,"0")}`};c(o.accent,25),c(o.dark,-20),c(o.button,25);const d=(D,M)=>{ml(s.id,"button_click",D),M()},u=()=>d("call",()=>{var D;(D=s.profile)!=null&&D.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),h=()=>d("text",()=>{var D;(D=s.profile)!=null&&D.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),p=()=>d("email",()=>{var D;(D=s.profile)!=null&&D.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),f=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),ml(s.id,"button_click","book"))},g=()=>{var D,M;ml(s.id,"contact_saved"),hye({name:i,phone:(D=s.profile)==null?void 0:D.phone,email:(M=s.profile)==null?void 0:M.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},_=async()=>{ml(s.id,"share_event");const D=`https://cards.relevelup.com/${s.slug}`,M="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:M,url:D})}catch{}else await navigator.clipboard.writeText(D),ae.success("Link copied!")},v=()=>{a("referral"),n(!0),ml(s.id,"button_click","refer")},j=()=>{a("connect"),n(!0),ml(s.id,"button_click","connect")},b={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen",style:{backgroundColor:o.accent},children:[e.jsxs("div",{className:"px-5 pt-10 pb-14 text-center relative",style:{backgroundColor:o.dark},children:[s.show_photo&&e.jsxs(ra,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${o.accent}`},children:[e.jsx(ni,{src:s.avatar_url||void 0,alt:i}),e.jsx(aa,{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:Ar,label:"Call",handler:u},{icon:Ei,label:"Text",handler:h},{icon:Vs,label:"Email",handler:p}].map(({icon:D,label:M,handler:F})=>e.jsxs("button",{onClick:F,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(D,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:M})]},M))}),e.jsxs("button",{onClick:f,className:"w-full h-14 text-base font-black rounded-2xl mb-6 text-white transition-opacity hover:opacity-90 flex items-center justify-center gap-2 uppercase tracking-wide",style:{backgroundColor:o.button},children:[e.jsx(yr,{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(ca,{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(cye,{card:s,variant:"bold"}),e.jsx(uye,{cardId:s.id,variant:"bold"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:g,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Pa,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{ml(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(ca,{className:"h-4 w-4",style:{color:o.accent}})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:v,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Nn,{className:"h-4 w-4",style:{color:o.accent}})," Refer a Friend"]}),e.jsxs("button",{onClick:j,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(Fo,{className:"h-4 w-4",style:{color:o.accent}})," Connect with Me"]}),e.jsxs("button",{onClick:_,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Hl,{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((D,M)=>e.jsx("a",{href:D.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>ml(s.id,"button_click",`social_${D.platform}`),className:"h-10 w-10 rounded-full flex items-center justify-center text-lg transition-opacity hover:opacity-85",style:{backgroundColor:o.dark},children:b[D.platform.toLowerCase()]||"🔗"},M))})]}),e.jsx("div",{className:"text-center py-6",children:e.jsx("p",{className:"text-xs text-white/50",children:"Powered by LevelUp"})})]}),e.jsx(dye,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function Yzt({card:s}){var j;const[t,n]=N.useState(!1),[r,a]=N.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,S)=>{ml(s.id,"button_click",b),S()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),ml(s.id,"button_click","book"))},p=()=>{var b,S;ml(s.id,"contact_saved"),hye({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(S=s.profile)==null?void 0:S.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},f=async()=>{ml(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,S="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:S,url:b})}catch{}else await navigator.clipboard.writeText(b),ae.success("Link copied!")},g=()=>{a("referral"),n(!0),ml(s.id,"button_click","refer")},_=()=>{a("connect"),n(!0),ml(s.id,"button_click","connect")},v={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-[#f5f1eb]",children:[e.jsx("div",{className:"bg-[#1b3a4b] h-2"}),e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(ra,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(ni,{src:s.avatar_url||void 0,alt:i}),e.jsx(aa,{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:Ar,label:"Call",handler:c},{icon:Ei,label:"Text",handler:d},{icon:Vs,label:"Email",handler:u}].map(({icon:b,label:S,handler:A})=>e.jsxs("button",{onClick:A,className:"flex flex-col items-center gap-1.5 py-4 bg-white hover:bg-[#e8e3db] border border-[#d4cfc5] rounded-lg transition-colors shadow-sm",children:[e.jsx(b,{className:"h-5 w-5 text-[#1b3a4b]"}),e.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:S})]},S))}),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(yr,{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(ca,{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(cye,{card:s,variant:"classic"}),e.jsx(uye,{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: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(Pa,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{ml(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(ca,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:g,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Nn,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a Friend"]}),e.jsxs("button",{onClick:_,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(Fo,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),e.jsxs("button",{onClick:f,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Hl,{className:"h-4 w-4 text-[#5a7a6f]"})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((b,S)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>ml(s.id,"button_click",`social_${b.platform}`),className:"h-10 w-10 rounded-full bg-white border border-[#d4cfc5] hover:bg-[#e8e3db] flex items-center justify-center text-lg transition-colors shadow-sm",children:v[b.platform.toLowerCase()]||"🔗"},S))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),e.jsx(dye,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function tMe({card:s}){switch(s.theme){case"luxury":return e.jsx(Wzt,{card:s});case"bold":return e.jsx(Kzt,{card:s});case"classic":return e.jsx(Yzt,{card:s});case"standard":default:return e.jsx(Gzt,{card:s})}}function Zzt(){const s=Jl();N.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]);const t=s.pathname.slice(1);return!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Agent Cards"}),e.jsx("p",{className:"text-slate-500",children:"Visit a specific agent's card URL to view their digital business card."})]})}):e.jsx(Qzt,{slug:t})}function Qzt({slug:s}){return e.jsx(Xzt,{slug:s})}function Xzt({slug:s}){var i;const{data:t,isLoading:n,error:r}=xct(s);if(N.useEffect(()=>{t!=null&&t.id&&ml(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(Ws,{className:"h-28 w-28 rounded-full"}),e.jsx(Ws,{className:"h-6 w-48"}),e.jsx(Ws,{className:"h-4 w-36"})]}),e.jsx(Ws,{className:"h-12 w-full"}),e.jsx(Ws,{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(Go,{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(tMe,{card:t})]})}function bct({presentationId:s,ctaLabel:t,agentName:n,prefillName:r,prefillEmail:a,prefillPhone:i}){const[l,o]=N.useState(r||""),[c,d]=N.useState(a||""),[u,h]=N.useState(i||""),[p,f]=N.useState(""),[g,_]=N.useState(""),[v,j]=N.useState(!1),[b,S]=N.useState(!1),A=async T=>{if(T.preventDefault(),!l.trim()){ae.error("Please enter your name");return}j(!0);try{const{error:L}=await q.from("smart_presentation_leads").insert({presentation_id:s,name:l.trim(),email:c.trim()||null,phone:u.trim()||null,intent:p||null,message:g.trim()||null});if(L)throw L;try{await q.rpc("log_presentation_view",{p_presentation_id:s,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}q.functions.invoke("presentation-lead-notify",{body:{presentationId:s,name:l.trim(),email:c.trim()||void 0,phone:u.trim()||void 0,intent:p||void 0,message:g.trim()||void 0}}).catch(D=>console.error("Presentation lead notify failed:",D)),S(!0)}catch{ae.error("Something went wrong. Please try again.")}finally{j(!1)}};return b?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-4",children:e.jsx(Ir,{className:"h-8 w-8 text-emerald-600"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"Thank you!"}),e.jsx("p",{className:"text-gray-500",children:n?`${n} will be in touch soon.`:"We'll be in touch soon."})]}):e.jsxs("form",{onSubmit:A,className:"space-y-4 max-w-md mx-auto",children:[e.jsxs("div",{children:[e.jsx(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(ds,{value:p,onValueChange:f,children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select one"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"buy",children:"Buy a home"}),e.jsx(Qe,{value:"sell",children:"Sell my home"}),e.jsx(Qe,{value:"both",children:"Buy & Sell"}),e.jsx(Qe,{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:g,onChange:T=>_(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:v,children:v?"Sending...":t})]})}function Jzt(){const s=Jl();N.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]);const t=s.pathname.slice(1);return!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Smart Presentations"}),e.jsx("p",{className:"text-slate-500",children:"Visit a specific presentation URL to view it."})]})}):e.jsx(eBt,{shareToken:t})}function eBt({shareToken:s}){var g;const[t,n]=N.useState(null),[r,a]=N.useState(!0),[i,l]=N.useState(0),[o,c]=N.useState(!1);N.useEffect(()=>{d()},[s]);const d=async()=>{const{data:_,error:v}=await q.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(v||!_){c(!0),a(!1);return}const{data:j}=await q.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",_.owner_user_id).single();let b;if(j!=null&&j.brokerage_id){const{data:A}=await q.from("brokerages").select("name").eq("id",j.brokerage_id).single();b=(A==null?void 0:A.name)||void 0}let S=null;if(_.contact_id){const{data:A}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",_.contact_id).single();S=A}n({..._,owner_name:j==null?void 0:j.name,owner_email:j==null?void 0:j.email,owner_phone:j==null?void 0:j.phone,owner_avatar:j==null?void 0:j.avatar_url,owner_title:(j==null?void 0:j.title)||void 0,brokerage_name:b,contact_name:S?[S.first_name,S.last_name].filter(Boolean).join(" "):void 0,contact_email:(S==null?void 0:S.email)||void 0,contact_phone:(S==null?void 0:S.phone)||void 0}),a(!1);try{await q.rpc("log_presentation_view",{p_presentation_id:_.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await q.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}},h=_=>{const v=_.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(v)return`https://www.youtube.com/embed/${v[1]}?rel=0`;if(_.includes("iframe.mediadelivery.net/play/")){const S=_.replace("/play/","/embed/"),A=S.includes("?")?"&":"?";return`${S}${A}responsive=true`}if(_.includes("iframe.mediadelivery.net")){const S=_.includes("?")?"&":"?";return`${_}${S}responsive=true`}const j=_.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(j)return`https://www.loom.com/embed/${j[1]}`;const b=_.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return b?`https://iframe.mediadelivery.net/embed/${b[1]}/${b[2]}?responsive=true`:_};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(Ws,{className:"h-12 w-3/4 mx-auto"}),e.jsx(Ws,{className:"h-64 w-full"}),e.jsx(Ws,{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 p=t.sections.filter(_=>_.is_visible!==!1),f=p[i];return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:e.jsx("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-end",children:e.jsxs("div",{className:"flex items-center gap-3",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsx("p",{className:"font-semibold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.owner_title}),t.brokerage_name&&!t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.brokerage_name})]})]})})}),e.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:t.heading||(t.client_name?`Welcome, ${t.client_name}!`:t.title)}),t.property_address&&e.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",e.jsx("strong",{children:t.property_address}),"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[e.jsxs("div",{className:"md:col-span-3",children:[f!=null&&f.video_url?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:h(f.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):f!=null&&f.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:f.image_url,alt:f.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:f==null?void 0:f.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:f==null?void 0:f.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:f==null?void 0:f.description})]}),(f==null?void 0:f.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:f.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:p.map((_,v)=>e.jsx("button",{onClick:()=>l(v),className:Et("w-full text-left p-4 rounded-xl border transition-all",i===v?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(v+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:_.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:_.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:_.description})]})]})},v))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),(g=t.cta_url)!=null&&g.trim()?e.jsxs(B,{size:"lg",onClick:u,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[t.cta_label,e.jsx(tr,{className:"h-5 w-5 ml-2"})]}):e.jsx("div",{className:"max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6",children:e.jsx(bct,{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 Zv=()=>{const s=ma();return ct({queryKey:["user-team",s],queryFn:async()=>{const{data:t,error:n}=await q.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 q.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 tBt(){const{user:s}=ys(),t=ma(),{data:n}=Zv();return ct({queryKey:["open-houses",t,n==null?void 0:n.teamId,n==null?void 0:n.role],queryFn:async()=>{const{data:r,error:a}=await q.from("open_houses").select("*").eq("agent_id",t).order("event_date",{ascending:!1});if(a)throw a;let i=r||[];if((n==null?void 0:n.role)==="team_leader"&&n.teamId){const{data:l,error:o}=await q.rpc("get_team_open_houses",{_user_id:t});if(!o&&l){const c=[...new Set(l.map(h=>h.agent_id))],d={};if(c.length>0){const{data:h}=await q.from("profiles").select("id, name").in("id",c);h==null||h.forEach(p=>{p.name&&(d[p.id]=p.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 Txn(s){const{user:t}=ys();return ct({queryKey:["open-house",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_houses").select("*").eq("id",s).single();if(r)throw r;return n},enabled:!!t&&!!s})}function _ct(s){const{user:t}=ys(),n=Ht();return N.useEffect(()=>{if(!s)return;const r=`visitors-${s}-${Math.random().toString(36).slice(2,10)}`,a=q.channel(r).on("postgres_changes",{event:"*",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${s}`},()=>{n.invalidateQueries({queryKey:["open-house-visitors",s]}),n.invalidateQueries({queryKey:["open-houses"]})}).subscribe();return()=>{q.removeChannel(a)}},[s,n]),ct({queryKey:["open-house-visitors",s],queryFn:async()=>{const{data:r,error:a}=await q.from("open_house_visitors").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(a)throw a;return r},enabled:!!t&&!!s})}function sBt(){const s=Ht(),t=ma();return gt({mutationFn:async n=>{const{data:r,error:a}=await q.from("open_houses").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),Pr({title:"Open house created!"})},onError:n=>{Pr({title:"Error",description:n.message,variant:"destructive"})}})}function wct(){const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{error:r}=await q.from("open_houses").update(n).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-houses"]}),s.invalidateQueries({queryKey:["open-house",n.id]})}})}function nBt(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("open_houses").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),Pr({title:"Open house deleted"})}})}function rBt(s){return ct({queryKey:["public-open-house",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_houses").select("*, profiles:agent_id(name, avatar_url, title, email, phone)").eq("slug",s).eq("is_active",!0).single();if(n)throw n;let r=null;if(t.agent_id){const{data:a}=await q.from("agent_cards").select("slug").eq("user_id",t.agent_id).eq("is_published",!0).maybeSingle();a&&(r=a.slug)}return{...t,agent_card_slug:r}},enabled:!!s})}function aBt(s){const{user:t}=ys();return ct({queryKey:["survey-questions",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;return n},enabled:!!t&&!!s})}function iBt(s){return ct({queryKey:["public-survey-questions",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_house_survey_questions").select("*").eq("open_house_id",s).eq("is_active",!0).order("sort_order");if(n)throw n;return t},enabled:!!s})}function oBt(){return gt({mutationFn:async s=>{const{error:t}=await q.from("open_house_survey_responses").insert(s);if(t)throw t}})}function lBt(s){const{user:t}=ys();return ct({queryKey:["survey-responses",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;const a=(n||[]).map(o=>o.id);if(a.length===0)return{questions:[],responses:[]};const{data:i,error:l}=await q.from("open_house_survey_responses").select("*").in("question_id",a).order("created_at",{ascending:!1});if(l)throw l;return{questions:n,responses:i||[]}},enabled:!!t&&!!s})}function cBt(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("open_house_survey_questions").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function dBt(){const s=Ht();return gt({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await q.from("open_house_survey_questions").update(r).eq("id",t);if(a)throw a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function uBt(){const s=Ht();return gt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await q.from("open_house_survey_questions").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function hBt(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.rpc("seed_default_survey_questions",{_open_house_id:t});if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n]})}})}function mBt(){return gt({mutationFn:async s=>{const{data:t,error:n}=await q.from("open_house_visitors").insert(s).select("id").single();if(n)throw n;return t}})}function pBt(){return gt({mutationFn:async({visitor_id:s,...t})=>{const{error:n}=await q.from("open_house_visitors").update(t).eq("id",s);if(n)throw n}})}function fBt(){return gt({mutationFn:async s=>{await q.rpc("increment_open_house_scan",{_slug:s})}})}async function jct(s){const{data:t,error:n}=await q.from("open_house_rooms").select("*").eq("open_house_id",s).order("sort_order");if(n)throw n;const r=t||[];if(r.length===0)return[];const a=r.map(c=>c.id),{data:i,error:l}=await q.from("open_house_room_media").select("*").in("room_id",a).order("sort_order");if(l)throw l;const o={};return(i||[]).forEach(c=>{var u;const d=c;(o[u=d.room_id]||(o[u]=[])).push(d)}),r.map(c=>({...c,media:o[c.id]||[]}))}function xBt(s){const{user:t}=ys();return ct({queryKey:["open-house-rooms",s],queryFn:()=>jct(s),enabled:!!t&&!!s})}function gBt(s){return ct({queryKey:["public-open-house-rooms",s],queryFn:()=>jct(s),enabled:!!s})}function yBt(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("open_house_rooms").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function vBt(){const s=Ht();return gt({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await q.from("open_house_rooms").update(r).eq("id",t);if(a)throw a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function bBt(){const s=Ht();return gt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await q.from("open_house_rooms").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function _Bt(){const s=Ht();return gt({mutationFn:async({open_house_id:t,...n})=>{const{data:r,error:a}=await q.from("open_house_room_media").insert(n).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function wBt(){const s=Ht();return gt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await q.from("open_house_room_media").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function jBt(s){const{user:t}=ys();return ct({queryKey:["open-house-leads",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_leads").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(r)throw r;return n||[]},enabled:!!t&&!!s})}function NBt(){const s=Ht();return gt({mutationFn:async({id:t,status:n,open_house_id:r})=>{const{error:a}=await q.from("open_house_leads").update({status:n}).eq("id",t);if(a)throw a;return{open_house_id:r}},onSuccess:t=>{s.invalidateQueries({queryKey:["open-house-leads",t.open_house_id]})}})}var mye="Switch",[kBt,Exn]=pu(mye),[SBt,CBt]=kBt(mye),Nct=N.forwardRef((s,t)=>{const{__scopeSwitch:n,name:r,checked:a,defaultChecked:i,required:l,disabled:o,value:c="on",onCheckedChange:d,form:u,...h}=s,[p,f]=N.useState(null),g=Si(t,S=>f(S)),_=N.useRef(!1),v=p?u||!!p.closest("form"):!0,[j,b]=hm({prop:a,defaultProp:i??!1,onChange:d,caller:mye});return e.jsxs(SBt,{scope:n,checked:j,disabled:o,children:[e.jsx(Jr.button,{type:"button",role:"switch","aria-checked":j,"aria-required":l,"data-state":Tct(j),"data-disabled":o?"":void 0,disabled:o,value:c,...h,ref:g,onClick:_r(s.onClick,S=>{b(A=>!A),v&&(_.current=S.isPropagationStopped(),_.current||S.stopPropagation())})}),v&&e.jsx(Cct,{control:p,bubbles:!_.current,name:r,value:c,checked:j,required:l,disabled:o,form:u,style:{transform:"translateX(-100%)"}})]})});Nct.displayName=mye;var kct="SwitchThumb",Sct=N.forwardRef((s,t)=>{const{__scopeSwitch:n,...r}=s,a=CBt(kct,n);return e.jsx(Jr.span,{"data-state":Tct(a.checked),"data-disabled":a.disabled?"":void 0,...r,ref:t})});Sct.displayName=kct;var TBt="SwitchBubbleInput",Cct=N.forwardRef(({__scopeSwitch:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=N.useRef(null),o=Si(l,i),c=tU(n),d=B$(t);return N.useEffect(()=>{const u=l.current;if(!u)return;const h=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(h,"checked").set;if(c!==n&&f){const g=new Event("click",{bubbles:r});f.call(u,n),u.dispatchEvent(g)}},[c,n,r]),e.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...a,tabIndex:-1,ref:o,style:{...a.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Cct.displayName=TBt;function Tct(s){return s?"checked":"unchecked"}var Ect=Nct,EBt=Sct;const bn=N.forwardRef(({className:s,...t},n)=>e.jsx(Ect,{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(EBt,{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")})}));bn.displayName=Ect.displayName;function ei(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 Mc(s,t){return s instanceof Date?new s.constructor(t):new Date(t)}function Bl(s,t){const n=ei(s);return isNaN(t)?Mc(s,NaN):(t&&n.setDate(n.getDate()+t),n)}function Nf(s,t){const n=ei(s);if(isNaN(t))return Mc(s,NaN);if(!t)return n;const r=n.getDate(),a=Mc(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 Act(s,t){const n=+ei(s);return Mc(s,n+t)}const sMe=6048e5,ABt=864e5,pye=6e4,fye=36e5,MBt=1e3,tH=43200,dBe=1440;function uBe(s,t){return Act(s,t*fye)}let IBt={};function Z4(){return IBt}function Wm(s,t){var o,c,d,u;const n=Z4(),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=ei(s),i=a.getDay(),l=(i=a.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function kf(s){const t=ei(s);return t.setHours(0,0,0,0),t}function I4(s){const t=ei(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 Gx(s,t){const n=kf(s),r=kf(t),a=+n-I4(n),i=+r-I4(r);return Math.round((a-i)/ABt)}function PBt(s){const t=Mct(s),n=Mc(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),pN(n)}function kP(s,t){return Act(s,t*pye)}function O2(s,t){const n=t*7;return Bl(s,n)}function LBt(s,t){return Nf(s,t*12)}function DBt(s){let t;return s.forEach(function(n){const r=ei(n);(t===void 0||t{const r=ei(n);(!t||t>r||isNaN(+r))&&(t=r)}),t||new Date(NaN)}function Ime(s,t){const n=ei(s),r=ei(t),a=n.getTime()-r.getTime();return a<0?-1:a>0?1:a}function xye(s){return Mc(s,Date.now())}function Vl(s,t){const n=kf(s),r=kf(t);return+n==+r}function nMe(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function L4e(s){if(!nMe(s)&&typeof s!="number")return!1;const t=ei(s);return!isNaN(Number(t))}function _8(s,t){const n=ei(s),r=ei(t),a=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return a*12+i}function OBt(s,t,n){const r=Wm(s,n),a=Wm(t,n),i=+r-I4(r),l=+a-I4(a);return Math.round((i-l)/sMe)}function Wv(s,t){const n=ei(s),r=ei(t),a=hBe(n,r),i=Math.abs(Gx(n,r));n.setDate(n.getDate()-a*i);const l=+(hBe(n,r)===-a),o=a*(i-l);return o===0?0:o}function hBe(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 FBt(s){return t=>{const r=(s?Math[s]:Math.trunc)(t);return r===0?0:r}}function zBt(s,t){return+ei(s)-+ei(t)}function BBt(s){const t=ei(s);return t.setHours(23,59,59,999),t}function V0(s){const t=ei(s),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function $Bt(s){const t=ei(s);return+BBt(t)==+V0(t)}function UBt(s,t){const n=ei(s),r=ei(t),a=Ime(n,r),i=Math.abs(_8(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=Ime(n,r)===-a;$Bt(ei(s))&&i===1&&Ime(s,r)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function qBt(s,t,n){const r=zBt(s,t)/1e3;return FBt(n==null?void 0:n.roundingMethod)(r)}function D4e(s,t){const n=ei(s.start),r=ei(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(ei(l)),l.setDate(l.getDate()+o),l.setHours(0,0,0,0);return a?c.reverse():c}function Fd(s){const t=ei(s);return t.setDate(1),t.setHours(0,0,0,0),t}function Ict(s){const t=ei(s),n=Mc(s,0);return n.setFullYear(t.getFullYear(),0,1),n.setHours(0,0,0,0),n}function w8(s,t){var o,c,d,u;const n=Z4(),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=ei(s),i=a.getDay(),l=(i{let r;const a=VBt[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 lje(s){return(t={})=>{const n=t.width?String(t.width):s.defaultWidth;return s.formats[n]||s.formats[s.defaultWidth]}}const GBt={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},WBt={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},KBt={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},YBt={date:lje({formats:GBt,defaultWidth:"full"}),time:lje({formats:WBt,defaultWidth:"full"}),dateTime:lje({formats:KBt,defaultWidth:"full"})},ZBt={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},QBt=(s,t,n,r)=>ZBt[s];function aF(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 XBt={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},JBt={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},e$t={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"]},t$t={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"]},s$t={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"}},n$t={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"}},r$t=(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"},a$t={ordinalNumber:r$t,era:aF({values:XBt,defaultWidth:"wide"}),quarter:aF({values:JBt,defaultWidth:"wide",argumentCallback:s=>s-1}),month:aF({values:e$t,defaultWidth:"wide"}),day:aF({values:t$t,defaultWidth:"wide"}),dayPeriod:aF({values:s$t,defaultWidth:"wide",formattingValues:n$t,defaultFormattingWidth:"wide"})};function iF(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)?o$t(o,h=>h.test(l)):i$t(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 i$t(s,t){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n)&&t(s[n]))return n}function o$t(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 c$t=/^(\d+)(th|st|nd|rd)?/i,d$t=/\d+/i,u$t={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},h$t={any:[/^b/i,/^(a|c)/i]},m$t={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},p$t={any:[/1/i,/2/i,/3/i,/4/i]},f$t={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},x$t={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]},g$t={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},y$t={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]},v$t={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},b$t={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}},_$t={ordinalNumber:l$t({matchPattern:c$t,parsePattern:d$t,valueCallback:s=>parseInt(s,10)}),era:iF({matchPatterns:u$t,defaultMatchWidth:"wide",parsePatterns:h$t,defaultParseWidth:"any"}),quarter:iF({matchPatterns:m$t,defaultMatchWidth:"wide",parsePatterns:p$t,defaultParseWidth:"any",valueCallback:s=>s+1}),month:iF({matchPatterns:f$t,defaultMatchWidth:"wide",parsePatterns:x$t,defaultParseWidth:"any"}),day:iF({matchPatterns:g$t,defaultMatchWidth:"wide",parsePatterns:y$t,defaultParseWidth:"any"}),dayPeriod:iF({matchPatterns:v$t,defaultMatchWidth:"any",parsePatterns:b$t,defaultParseWidth:"any"})},gye={code:"en-US",formatDistance:HBt,formatLong:YBt,formatRelative:QBt,localize:a$t,match:_$t,options:{weekStartsOn:0,firstWeekContainsDate:1}};function w$t(s){const t=ei(s);return Gx(t,Ict(t))+1}function rMe(s){const t=ei(s),n=+pN(t)-+PBt(t);return Math.round(n/sMe)+1}function aMe(s,t){var u,h,p,f;const n=ei(s),r=n.getFullYear(),a=Z4(),i=(t==null?void 0:t.firstWeekContainsDate)??((h=(u=t==null?void 0:t.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??a.firstWeekContainsDate??((f=(p=a.locale)==null?void 0:p.options)==null?void 0:f.firstWeekContainsDate)??1,l=Mc(s,0);l.setFullYear(r+1,0,i),l.setHours(0,0,0,0);const o=Wm(l,t),c=Mc(s,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const d=Wm(c,t);return n.getTime()>=o.getTime()?r+1:n.getTime()>=d.getTime()?r:r-1}function j$t(s,t){var o,c,d,u;const n=Z4(),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=aMe(s,t),i=Mc(s,0);return i.setFullYear(a,0,r),i.setHours(0,0,0,0),Wm(i,t)}function iMe(s,t){const n=ei(s),r=+Wm(n,t)-+j$t(n,t);return Math.round(r/sMe)+1}function Cc(s,t){const n=s<0?"-":"",r=Math.abs(s).toString().padStart(t,"0");return n+r}const kk={y(s,t){const n=s.getFullYear(),r=n>0?n:1-n;return Cc(t==="yy"?r%100:r,t.length)},M(s,t){const n=s.getMonth();return t==="M"?String(n+1):Cc(n+1,2)},d(s,t){return Cc(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 Cc(s.getHours()%12||12,t.length)},H(s,t){return Cc(s.getHours(),t.length)},m(s,t){return Cc(s.getMinutes(),t.length)},s(s,t){return Cc(s.getSeconds(),t.length)},S(s,t){const n=t.length,r=s.getMilliseconds(),a=Math.trunc(r*Math.pow(10,n-3));return Cc(a,t.length)}},bI={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},mBe={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 kk.y(s,t)},Y:function(s,t,n,r){const a=aMe(s,r),i=a>0?a:1-a;if(t==="YY"){const l=i%100;return Cc(l,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):Cc(i,t.length)},R:function(s,t){const n=Mct(s);return Cc(n,t.length)},u:function(s,t){const n=s.getFullYear();return Cc(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 Cc(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 Cc(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 kk.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 Cc(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=iMe(s,r);return t==="wo"?n.ordinalNumber(a,{unit:"week"}):Cc(a,t.length)},I:function(s,t,n){const r=rMe(s);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):Cc(r,t.length)},d:function(s,t,n){return t==="do"?n.ordinalNumber(s.getDate(),{unit:"date"}):kk.d(s,t)},D:function(s,t,n){const r=w$t(s);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):Cc(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 Cc(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 Cc(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 Cc(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=bI.noon:r===0?a=bI.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=bI.evening:r>=12?a=bI.afternoon:r>=4?a=bI.morning:a=bI.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 kk.h(s,t)},H:function(s,t,n){return t==="Ho"?n.ordinalNumber(s.getHours(),{unit:"hour"}):kk.H(s,t)},K:function(s,t,n){const r=s.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):Cc(r,t.length)},k:function(s,t,n){let r=s.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):Cc(r,t.length)},m:function(s,t,n){return t==="mo"?n.ordinalNumber(s.getMinutes(),{unit:"minute"}):kk.m(s,t)},s:function(s,t,n){return t==="so"?n.ordinalNumber(s.getSeconds(),{unit:"second"}):kk.s(s,t)},S:function(s,t){return kk.S(s,t)},X:function(s,t,n){const r=s.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return fBe(r);case"XXXX":case"XX":return AE(r);case"XXXXX":case"XXX":default:return AE(r,":")}},x:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"x":return fBe(r);case"xxxx":case"xx":return AE(r);case"xxxxx":case"xxx":default:return AE(r,":")}},O:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+pBe(r,":");case"OOOO":default:return"GMT"+AE(r,":")}},z:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+pBe(r,":");case"zzzz":default:return"GMT"+AE(r,":")}},t:function(s,t,n){const r=Math.trunc(s.getTime()/1e3);return Cc(r,t.length)},T:function(s,t,n){const r=s.getTime();return Cc(r,t.length)}};function pBe(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+Cc(i,2)}function fBe(s,t){return s%60===0?(s>0?"-":"+")+Cc(Math.abs(s)/60,2):AE(s,t)}function AE(s,t=""){const n=s>0?"-":"+",r=Math.abs(s),a=Cc(Math.trunc(r/60),2),i=Cc(r%60,2);return n+a+t+i}const xBe=(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"})}},Lct=(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"})}},N$t=(s,t)=>{const n=s.match(/(P+)(p+)?/)||[],r=n[1],a=n[2];if(!a)return xBe(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}}",xBe(r,t)).replace("{{time}}",Lct(a,t))},R4e={p:Lct,P:N$t},k$t=/^D+$/,S$t=/^Y+$/,C$t=["D","DD","YY","YYYY"];function Dct(s){return k$t.test(s)}function Rct(s){return S$t.test(s)}function O4e(s,t,n){const r=T$t(s,t,n);if(console.warn(r),C$t.includes(s))throw new RangeError(r)}function T$t(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 E$t=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,A$t=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,M$t=/^'([^]*?)'?$/,I$t=/''/g,P$t=/[a-zA-Z]/;function Ss(s,t,n){var u,h,p,f,g,_,v,j;const r=Z4(),a=(n==null?void 0:n.locale)??r.locale??gye,i=(n==null?void 0:n.firstWeekContainsDate)??((h=(u=n==null?void 0:n.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??r.firstWeekContainsDate??((f=(p=r.locale)==null?void 0:p.options)==null?void 0:f.firstWeekContainsDate)??1,l=(n==null?void 0:n.weekStartsOn)??((_=(g=n==null?void 0:n.locale)==null?void 0:g.options)==null?void 0:_.weekStartsOn)??r.weekStartsOn??((j=(v=r.locale)==null?void 0:v.options)==null?void 0:j.weekStartsOn)??0,o=ei(s);if(!L4e(o))throw new RangeError("Invalid time value");let c=t.match(A$t).map(b=>{const S=b[0];if(S==="p"||S==="P"){const A=R4e[S];return A(b,a.formatLong)}return b}).join("").match(E$t).map(b=>{if(b==="''")return{isToken:!1,value:"'"};const S=b[0];if(S==="'")return{isToken:!1,value:L$t(b)};if(mBe[S])return{isToken:!0,value:b};if(S.match(P$t))throw new RangeError("Format string contains an unescaped latin alphabet character `"+S+"`");return{isToken:!1,value:b}});a.localize.preprocessor&&(c=a.localize.preprocessor(o,c));const d={firstWeekContainsDate:i,weekStartsOn:l,locale:a};return c.map(b=>{if(!b.isToken)return b.value;const S=b.value;(!(n!=null&&n.useAdditionalWeekYearTokens)&&Rct(S)||!(n!=null&&n.useAdditionalDayOfYearTokens)&&Dct(S))&&O4e(S,t,String(s));const A=mBe[S[0]];return A(o,S,a.localize,d)}).join("")}function L$t(s){const t=s.match(M$t);return t?t[1].replace(I$t,"'"):s}function D$t(s,t,n){const r=Z4(),a=(n==null?void 0:n.locale)??r.locale??gye,i=2520,l=Ime(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=ei(t),d=ei(s)):(c=ei(s),d=ei(t));const u=qBt(d,c),h=(I4(d)-I4(c))/1e3,p=Math.round((u-h)/60);let f;if(p<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):p===0?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",p,o);if(p<45)return a.formatDistance("xMinutes",p,o);if(p<90)return a.formatDistance("aboutXHours",1,o);if(pr.getTime()}function wb(s,t){const n=ei(s),r=ei(t);return+n<+r}function U$t(s){return+ei(s)>Date.now()}function q$t(s,t){const n=t instanceof Date?Mc(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 V$t=10;class Oct{constructor(){Ma(this,"subPriority",0)}validate(t,n){return!0}}class H$t extends Oct{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 G$t extends Oct{constructor(){super(...arguments);Ma(this,"priority",V$t);Ma(this,"subPriority",-1)}set(n,r){return r.timestampIsSet?n:Mc(n,q$t(n,Date))}}class dc{run(t,n,r,a){const i=this.parse(t,n,r,a);return i?{setter:new H$t(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,n,r){return!0}}class W$t extends dc{constructor(){super(...arguments);Ma(this,"priority",140);Ma(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 Mh={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}/},ew={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 Ih(s,t){return s&&{value:t(s.value),rest:s.rest}}function Iu(s,t){const n=t.match(s);return n?{value:parseInt(n[0],10),rest:t.slice(n[0].length)}:null}function tw(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*fye+i*pye+l*MBt),rest:t.slice(n[0].length)}}function Fct(s){return Iu(Mh.anyDigitsSigned,s)}function ph(s,t){switch(s){case 1:return Iu(Mh.singleDigit,t);case 2:return Iu(Mh.twoDigits,t);case 3:return Iu(Mh.threeDigits,t);case 4:return Iu(Mh.fourDigits,t);default:return Iu(new RegExp("^\\d{1,"+s+"}"),t)}}function cfe(s,t){switch(s){case 1:return Iu(Mh.singleDigitSigned,t);case 2:return Iu(Mh.twoDigitsSigned,t);case 3:return Iu(Mh.threeDigitsSigned,t);case 4:return Iu(Mh.fourDigitsSigned,t);default:return Iu(new RegExp("^-?\\d{1,"+s+"}"),t)}}function oMe(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 zct(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 Bct(s){return s%400===0||s%4===0&&s%100!==0}class K$t extends dc{constructor(){super(...arguments);Ma(this,"priority",130);Ma(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 Ih(ph(4,n),i);case"yo":return Ih(a.ordinalNumber(n,{unit:"year"}),i);default:return Ih(ph(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=zct(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 Y$t extends dc{constructor(){super(...arguments);Ma(this,"priority",130);Ma(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 Ih(ph(4,n),i);case"Yo":return Ih(a.ordinalNumber(n,{unit:"year"}),i);default:return Ih(ph(r.length,n),i)}}validate(n,r){return r.isTwoDigitYear||r.year>0}set(n,r,a,i){const l=aMe(n,i);if(a.isTwoDigitYear){const c=zct(a.year,l);return n.setFullYear(c,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),Wm(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),Wm(n,i)}}class Z$t extends dc{constructor(){super(...arguments);Ma(this,"priority",130);Ma(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(n,r){return cfe(r==="R"?4:r.length,n)}set(n,r,a){const i=Mc(n,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),pN(i)}}class Q$t extends dc{constructor(){super(...arguments);Ma(this,"priority",130);Ma(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(n,r){return cfe(r==="u"?4:r.length,n)}set(n,r,a){return n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}class X$t extends dc{constructor(){super(...arguments);Ma(this,"priority",120);Ma(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 ph(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 J$t extends dc{constructor(){super(...arguments);Ma(this,"priority",120);Ma(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 ph(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 eUt extends dc{constructor(){super(...arguments);Ma(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);Ma(this,"priority",110)}parse(n,r,a){const i=l=>l-1;switch(r){case"M":return Ih(Iu(Mh.month,n),i);case"MM":return Ih(ph(2,n),i);case"Mo":return Ih(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 tUt extends dc{constructor(){super(...arguments);Ma(this,"priority",110);Ma(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 Ih(Iu(Mh.month,n),i);case"LL":return Ih(ph(2,n),i);case"Lo":return Ih(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 sUt(s,t,n){const r=ei(s),a=iMe(r,n)-t;return r.setDate(r.getDate()-a*7),r}class nUt extends dc{constructor(){super(...arguments);Ma(this,"priority",100);Ma(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(n,r,a){switch(r){case"w":return Iu(Mh.week,n);case"wo":return a.ordinalNumber(n,{unit:"week"});default:return ph(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a,i){return Wm(sUt(n,a,i),i)}}function rUt(s,t){const n=ei(s),r=rMe(n)-t;return n.setDate(n.getDate()-r*7),n}class aUt extends dc{constructor(){super(...arguments);Ma(this,"priority",100);Ma(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 Iu(Mh.week,n);case"Io":return a.ordinalNumber(n,{unit:"week"});default:return ph(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a){return pN(rUt(n,a))}}const iUt=[31,28,31,30,31,30,31,31,30,31,30,31],oUt=[31,29,31,30,31,30,31,31,30,31,30,31];class lUt extends dc{constructor(){super(...arguments);Ma(this,"priority",90);Ma(this,"subPriority",1);Ma(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"d":return Iu(Mh.date,n);case"do":return a.ordinalNumber(n,{unit:"date"});default:return ph(r.length,n)}}validate(n,r){const a=n.getFullYear(),i=Bct(a),l=n.getMonth();return i?r>=1&&r<=oUt[l]:r>=1&&r<=iUt[l]}set(n,r,a){return n.setDate(a),n.setHours(0,0,0,0),n}}class cUt extends dc{constructor(){super(...arguments);Ma(this,"priority",90);Ma(this,"subpriority",1);Ma(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 Iu(Mh.dayOfYear,n);case"Do":return a.ordinalNumber(n,{unit:"date"});default:return ph(r.length,n)}}validate(n,r){const a=n.getFullYear();return Bct(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 lMe(s,t,n){var h,p,f,g;const r=Z4(),a=(n==null?void 0:n.weekStartsOn)??((p=(h=n==null?void 0:n.locale)==null?void 0:h.options)==null?void 0:p.weekStartsOn)??r.weekStartsOn??((g=(f=r.locale)==null?void 0:f.options)==null?void 0:g.weekStartsOn)??0,i=ei(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 Bl(i,u)}class dUt extends dc{constructor(){super(...arguments);Ma(this,"priority",90);Ma(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=lMe(n,a,i),n.setHours(0,0,0,0),n}}class uUt extends dc{constructor(){super(...arguments);Ma(this,"priority",90);Ma(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 Ih(ph(r.length,n),l);case"eo":return Ih(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=lMe(n,a,i),n.setHours(0,0,0,0),n}}class hUt extends dc{constructor(){super(...arguments);Ma(this,"priority",90);Ma(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 Ih(ph(r.length,n),l);case"co":return Ih(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=lMe(n,a,i),n.setHours(0,0,0,0),n}}function mUt(s,t){const n=ei(s),r=F$t(n),a=t-r;return Bl(n,a)}class pUt extends dc{constructor(){super(...arguments);Ma(this,"priority",90);Ma(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 ph(r.length,n);case"io":return a.ordinalNumber(n,{unit:"day"});case"iii":return Ih(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 Ih(a.day(n,{width:"narrow",context:"formatting"}),i);case"iiiiii":return Ih(a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i);case"iiii":default:return Ih(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=mUt(n,a),n.setHours(0,0,0,0),n}}class fUt extends dc{constructor(){super(...arguments);Ma(this,"priority",80);Ma(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(oMe(a),0,0,0),n}}class xUt extends dc{constructor(){super(...arguments);Ma(this,"priority",80);Ma(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(oMe(a),0,0,0),n}}class gUt extends dc{constructor(){super(...arguments);Ma(this,"priority",80);Ma(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(oMe(a),0,0,0),n}}class yUt extends dc{constructor(){super(...arguments);Ma(this,"priority",70);Ma(this,"incompatibleTokens",["H","K","k","t","T"])}parse(n,r,a){switch(r){case"h":return Iu(Mh.hour12h,n);case"ho":return a.ordinalNumber(n,{unit:"hour"});default:return ph(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 vUt extends dc{constructor(){super(...arguments);Ma(this,"priority",70);Ma(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(n,r,a){switch(r){case"H":return Iu(Mh.hour23h,n);case"Ho":return a.ordinalNumber(n,{unit:"hour"});default:return ph(r.length,n)}}validate(n,r){return r>=0&&r<=23}set(n,r,a){return n.setHours(a,0,0,0),n}}class bUt extends dc{constructor(){super(...arguments);Ma(this,"priority",70);Ma(this,"incompatibleTokens",["h","H","k","t","T"])}parse(n,r,a){switch(r){case"K":return Iu(Mh.hour11h,n);case"Ko":return a.ordinalNumber(n,{unit:"hour"});default:return ph(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 _Ut extends dc{constructor(){super(...arguments);Ma(this,"priority",70);Ma(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(n,r,a){switch(r){case"k":return Iu(Mh.hour24h,n);case"ko":return a.ordinalNumber(n,{unit:"hour"});default:return ph(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 wUt extends dc{constructor(){super(...arguments);Ma(this,"priority",60);Ma(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"m":return Iu(Mh.minute,n);case"mo":return a.ordinalNumber(n,{unit:"minute"});default:return ph(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setMinutes(a,0,0),n}}class jUt extends dc{constructor(){super(...arguments);Ma(this,"priority",50);Ma(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"s":return Iu(Mh.second,n);case"so":return a.ordinalNumber(n,{unit:"second"});default:return ph(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setSeconds(a,0),n}}class NUt extends dc{constructor(){super(...arguments);Ma(this,"priority",30);Ma(this,"incompatibleTokens",["t","T"])}parse(n,r){const a=i=>Math.trunc(i*Math.pow(10,-r.length+3));return Ih(ph(r.length,n),a)}set(n,r,a){return n.setMilliseconds(a),n}}class kUt extends dc{constructor(){super(...arguments);Ma(this,"priority",10);Ma(this,"incompatibleTokens",["t","T","x"])}parse(n,r){switch(r){case"X":return tw(ew.basicOptionalMinutes,n);case"XX":return tw(ew.basic,n);case"XXXX":return tw(ew.basicOptionalSeconds,n);case"XXXXX":return tw(ew.extendedOptionalSeconds,n);case"XXX":default:return tw(ew.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Mc(n,n.getTime()-I4(n)-a)}}class SUt extends dc{constructor(){super(...arguments);Ma(this,"priority",10);Ma(this,"incompatibleTokens",["t","T","X"])}parse(n,r){switch(r){case"x":return tw(ew.basicOptionalMinutes,n);case"xx":return tw(ew.basic,n);case"xxxx":return tw(ew.basicOptionalSeconds,n);case"xxxxx":return tw(ew.extendedOptionalSeconds,n);case"xxx":default:return tw(ew.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Mc(n,n.getTime()-I4(n)-a)}}class CUt extends dc{constructor(){super(...arguments);Ma(this,"priority",40);Ma(this,"incompatibleTokens","*")}parse(n){return Fct(n)}set(n,r,a){return[Mc(n,a*1e3),{timestampIsSet:!0}]}}class TUt extends dc{constructor(){super(...arguments);Ma(this,"priority",20);Ma(this,"incompatibleTokens","*")}parse(n){return Fct(n)}set(n,r,a){return[Mc(n,a),{timestampIsSet:!0}]}}const EUt={G:new W$t,y:new K$t,Y:new Y$t,R:new Z$t,u:new Q$t,Q:new X$t,q:new J$t,M:new eUt,L:new tUt,w:new nUt,I:new aUt,d:new lUt,D:new cUt,E:new dUt,e:new uUt,c:new hUt,i:new pUt,a:new fUt,b:new xUt,B:new gUt,h:new yUt,H:new vUt,K:new bUt,k:new _Ut,m:new wUt,s:new jUt,S:new NUt,X:new kUt,x:new SUt,t:new CUt,T:new TUt},AUt=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,MUt=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,IUt=/^'([^]*?)'?$/,PUt=/''/g,LUt=/\S/,DUt=/[a-zA-Z]/;function cMe(s,t,n,r){var _,v,j,b;const a=O$t(),i=a.locale??gye,l=a.firstWeekContainsDate??((v=(_=a.locale)==null?void 0:_.options)==null?void 0:v.firstWeekContainsDate)??1,o=a.weekStartsOn??((b=(j=a.locale)==null?void 0:j.options)==null?void 0:b.weekStartsOn)??0;if(t==="")return s===""?ei(n):Mc(n,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new G$t],u=t.match(MUt).map(S=>{const A=S[0];if(A in R4e){const T=R4e[A];return T(S,i.formatLong)}return S}).join("").match(AUt),h=[];for(let S of u){Rct(S)&&O4e(S,t,s),Dct(S)&&O4e(S,t,s);const A=S[0],T=EUt[A];if(T){const{incompatibleTokens:L}=T;if(Array.isArray(L)){const M=h.find(F=>L.includes(F.token)||F.token===A);if(M)throw new RangeError(`The format string mustn't contain \`${M.fullToken}\` and \`${S}\` at the same time`)}else if(T.incompatibleTokens==="*"&&h.length>0)throw new RangeError(`The format string mustn't contain \`${S}\` and any other token at the same time`);h.push({token:A,fullToken:S});const D=T.run(s,S,i.match,c);if(!D)return Mc(n,NaN);d.push(D.setter),s=D.rest}else{if(A.match(DUt))throw new RangeError("Format string contains an unescaped latin alphabet character `"+A+"`");if(S==="''"?S="'":A==="'"&&(S=RUt(S)),s.indexOf(S)===0)s=s.slice(S.length);else return Mc(n,NaN)}}if(s.length>0&&LUt.test(s))return Mc(n,NaN);const p=d.map(S=>S.priority).sort((S,A)=>A-S).filter((S,A,T)=>T.indexOf(S)===A).map(S=>d.filter(A=>A.priority===S).sort((A,T)=>T.subPriority-A.subPriority)).map(S=>S[0]);let f=ei(n);if(isNaN(f.getTime()))return Mc(n,NaN);const g={};for(const S of p){if(!S.validate(f,c))return Mc(n,NaN);const A=S.set(f,g,c);Array.isArray(A)?(f=A[0],Object.assign(g,A[1])):f=A}return Mc(n,f)}function RUt(s){return s.match(IUt)[1].replace(PUt,"'")}function ww(s){return+ei(s)i-l);return n>=r&&n<=a}function G9(s,t){return Bl(s,-t)}function Xh(s,t){const r=VUt(s);let a;if(r.date){const c=HUt(r.date,2);a=GUt(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=WUt(r.time),isNaN(l)))return new Date(NaN);if(r.timezone){if(o=KUt(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 sH={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},$Ut=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,UUt=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,qUt=/^([+-])(\d{2})(?::?(\d{2}))?$/;function VUt(s){const t={},n=s.split(sH.dateTimeDelimiter);let r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],sH.timeZoneDelimiter.test(t.date)&&(t.date=s.split(sH.timeZoneDelimiter)[0],r=s.substr(t.date.length,s.length))),r){const a=sH.timezone.exec(r);a?(t.time=r.replace(a[1],""),t.timezone=a[1]):t.time=r}return t}function HUt(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 GUt(s,t){if(t===null)return new Date(NaN);const n=s.match($Ut);if(!n)return new Date(NaN);const r=!!n[4],a=oF(n[1]),i=oF(n[2])-1,l=oF(n[3]),o=oF(n[4]),c=oF(n[5])-1;if(r)return JUt(t,o,c)?YUt(t,o,c):new Date(NaN);{const d=new Date(0);return!QUt(t,i,l)||!XUt(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function oF(s){return s?parseInt(s):1}function WUt(s){const t=s.match(UUt);if(!t)return NaN;const n=cje(t[1]),r=cje(t[2]),a=cje(t[3]);return eqt(n,r,a)?n*fye+r*pye+a*1e3:NaN}function cje(s){return s&&parseFloat(s.replace(",","."))||0}function KUt(s){if(s==="Z")return 0;const t=s.match(qUt);if(!t)return 0;const n=t[1]==="+"?-1:1,r=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return tqt(r,a)?n*(r*fye+a*pye):NaN}function YUt(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 ZUt=[31,null,31,30,31,30,31,31,30,31,30,31];function $ct(s){return s%400===0||s%4===0&&s%100!==0}function QUt(s,t,n){return t>=0&&t<=11&&n>=1&&n<=(ZUt[t]||($ct(s)?29:28))}function XUt(s,t){return t>=1&&t<=($ct(s)?366:365)}function JUt(s,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function eqt(s,t,n){return s===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&s>=0&&s<25}function tqt(s,t){return t>=0&&t<=59}function dje(s,t){const n=ei(s),r=n.getFullYear(),a=n.getDate(),i=Mc(s,0);i.setFullYear(r,t,15),i.setHours(0,0,0,0);const l=R$t(i);return n.setMonth(t,Math.min(a,l)),n}function W9(s,t){const n=ei(s);return n.setHours(t),n}function K9(s,t){const n=ei(s);return n.setMinutes(t),n}function yBe(s,t){const n=ei(s);return isNaN(+n)?Mc(s,NaN):(n.setFullYear(t),n)}function GE(s,t){return Nf(s,-t)}var vBe;function fr(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 ML extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Uct extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(vBe=globalThis).__zod_globalConfig??(vBe.__zod_globalConfig={});const dMe=globalThis.__zod_globalConfig;function yM(s){return dMe}function qct(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 F4e(s,t){return typeof t=="bigint"?t.toString():t}function uMe(s){return{get value(){{const t=s();return Object.defineProperty(this,"value",{value:t}),t}}}}function hMe(s){return s==null}function mMe(s){const t=s.startsWith("^")?1:0,n=s.endsWith("$")?s.length-1:s.length;return s.slice(t,n)}function sqt(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 dfe(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}const rqt=uMe(()=>{var s;if(dMe.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 dB(s){if(dfe(s)===!1)return!1;const t=s.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(dfe(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Hct(s){return dB(s)?{...s}:Array.isArray(s)?[...s]:s instanceof Map?new Map(s):s instanceof Set?new Set(s):s}const aqt=new Set(["string","number","symbol"]);function j8(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function X4(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 Li(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 iqt(s){return Object.keys(s).filter(t=>s[t]._zod.optin==="optional"&&s[t]._zod.optout==="optional")}const oqt={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 lqt(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=Q4(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 GM(this,"shape",l),l},checks:[]});return X4(s,i)}function cqt(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=Q4(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 GM(this,"shape",l),l},checks:[]});return X4(s,i)}function dqt(s,t){if(!dB(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=Q4(s._zod.def,{get shape(){const i={...s._zod.def.shape,...t};return GM(this,"shape",i),i}});return X4(s,a)}function uqt(s,t){if(!dB(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Q4(s._zod.def,{get shape(){const r={...s._zod.def.shape,...t};return GM(this,"shape",r),r}});return X4(s,n)}function hqt(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=Q4(s._zod.def,{get shape(){const a={...s._zod.def.shape,...t._zod.def.shape};return GM(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return X4(s,n)}function mqt(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=Q4(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 GM(this,"shape",c),c},checks:[]});return X4(t,l)}function pqt(s,t,n){const r=Q4(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 GM(this,"shape",i),i}});return X4(t,r)}function SP(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 nH(s){return typeof s=="string"?s:s==null?void 0:s.message}function vM(s,t,n){var c,d,u,h,p,f;const r=s.message?s.message:nH((u=(d=(c=s.inst)==null?void 0:c._zod.def)==null?void 0:d.error)==null?void 0:u.call(d,s))??nH((h=t==null?void 0:t.error)==null?void 0:h.call(t,s))??nH((p=n.customError)==null?void 0:p.call(n,s))??nH((f=n.localeError)==null?void 0:f.call(n,s))??"Invalid input",{inst:a,continue:i,input:l,...o}=s;return o.path??(o.path=[]),o.message=r,t!=null&&t.reportInput&&(o.input=l),o}function pMe(s){return Array.isArray(s)?"array":typeof s=="string"?"string":"unknown"}function uB(...s){const[t,n,r]=s;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const Wct=(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,F4e,2),Object.defineProperty(s,"toString",{value:()=>s.message,enumerable:!1})},Kct=fr("$ZodError",Wct),Yct=fr("$ZodError",Wct,{Parent:Error});function xqt(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 gqt(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 ML;if(l.issues.length){const o=new((a==null?void 0:a.Err)??s)(l.issues.map(c=>vM(c,i,yM())));throw Vct(o,a==null?void 0:a.callee),o}return l.value},xMe=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=>vM(c,i,yM())));throw Vct(o,a==null?void 0:a.callee),o}return l.value},yye=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 ML;return i.issues.length?{success:!1,error:new(s??Kct)(i.issues.map(l=>vM(l,a,yM())))}:{success:!0,data:i.value}},yqt=yye(Yct),vye=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=>vM(l,a,yM())))}:{success:!0,data:i.value}},vqt=vye(Yct),bqt=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return fMe(s)(t,n,a)},_qt=s=>(t,n,r)=>fMe(s)(t,n,r),wqt=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return xMe(s)(t,n,a)},jqt=s=>async(t,n,r)=>xMe(s)(t,n,r),Nqt=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return yye(s)(t,n,a)},kqt=s=>(t,n,r)=>yye(s)(t,n,r),Sqt=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return vye(s)(t,n,a)},Cqt=s=>async(t,n,r)=>vye(s)(t,n,r),Tqt=/^[cC][0-9a-z]{6,}$/,Eqt=/^[0-9a-z]+$/,Aqt=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Mqt=/^[0-9a-vA-V]{20}$/,Iqt=/^[A-Za-z0-9]{27}$/,Pqt=/^[a-zA-Z0-9_-]{21}$/,Lqt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Dqt=/^([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})$/,wBe=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)$/,Rqt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Oqt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Fqt(){return new RegExp(Oqt,"u")}const zqt=/^(?:(?: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])$/,Bqt=/^(([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}|:))$/,$qt=/^((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])$/,Uqt=/^(([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])$/,qqt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Zct=/^[A-Za-z0-9_-]*$/,Vqt=/^https?$/,Hqt=/^\+[1-9]\d{6,14}$/,Qct="(?:(?:\\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])))",Gqt=new RegExp(`^${Qct}$`);function Xct(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 Wqt(s){return new RegExp(`^${Xct(s)}$`)}function Kqt(s){const t=Xct({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(`^${Qct}T(?:${r})$`)}const Yqt=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}$`)},Zqt=/^-?\d+$/,Qqt=/^-?\d+(?:\.\d+)?$/,Xqt=/^(?:true|false)$/i,Jqt=/^[^A-Z]*$/,eVt=/^[^a-z]*$/,s0=fr("$ZodCheck",(s,t)=>{var n;s._zod??(s._zod={}),s._zod.def=t,(n=s._zod).onattach??(n.onattach=[])}),Jct={number:"number",bigint:"bigint",object:"date"},edt=fr("$ZodCheckLessThan",(s,t)=>{s0.init(s,t);const n=Jct[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{s0.init(s,t);const n=Jct[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})}}),tVt=fr("$ZodCheckMultipleOf",(s,t)=>{s0.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):sqt(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})}}),sVt=fr("$ZodCheckNumberFormat",(s,t)=>{var l;s0.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]=oqt[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=Zqt)}),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})}}),nVt=fr("$ZodCheckMaxLength",(s,t)=>{var n;s0.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!hMe(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=pMe(a);r.issues.push({origin:l,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),rVt=fr("$ZodCheckMinLength",(s,t)=>{var n;s0.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!hMe(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=pMe(a);r.issues.push({origin:l,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),aVt=fr("$ZodCheckLengthEquals",(s,t)=>{var n;s0.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!hMe(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=pMe(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})}}),bye=fr("$ZodCheckStringFormat",(s,t)=>{var n,r;s0.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=()=>{})}),iVt=fr("$ZodCheckRegex",(s,t)=>{bye.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})}}),oVt=fr("$ZodCheckLowerCase",(s,t)=>{t.pattern??(t.pattern=Jqt),bye.init(s,t)}),lVt=fr("$ZodCheckUpperCase",(s,t)=>{t.pattern??(t.pattern=eVt),bye.init(s,t)}),cVt=fr("$ZodCheckIncludes",(s,t)=>{s0.init(s,t);const n=j8(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})}}),dVt=fr("$ZodCheckStartsWith",(s,t)=>{s0.init(s,t);const n=new RegExp(`^${j8(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})}}),uVt=fr("$ZodCheckEndsWith",(s,t)=>{s0.init(s,t);const n=new RegExp(`.*${j8(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})}}),hVt=fr("$ZodCheckOverwrite",(s,t)=>{s0.init(s,t),s._zod.check=n=>{n.value=t.tx(n.value)}});class mVt{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 pVt={major:4,minor:4,patch:3},xh=fr("$ZodType",(s,t)=>{var a;var n;s??(s={}),s._zod.def=t,s._zod.bag=s._zod.bag||{},s._zod.version=pVt;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=SP(o),h;for(const p of c){if(p._zod.def.when){if(fqt(o)||!p._zod.def.when(o))continue}else if(u)continue;const f=o.issues.length,g=p._zod.check(o);if(g instanceof Promise&&(d==null?void 0:d.async)===!1)throw new ML;if(h||g instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await g,o.issues.length!==f&&(u||(u=SP(o,f)))});else{if(o.issues.length===f)continue;u||(u=SP(o,f))}}return h?h.then(()=>o):o},l=(o,c,d)=>{if(SP(o))return o.aborted=!0,o;const u=i(c,r,d);if(u instanceof Promise){if(d.async===!1)throw new ML;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 ML;return d.then(u=>i(u,r,c))}return i(d,r,c)}}Wc(s,"~standard",()=>({validate:i=>{var l;try{const o=yqt(s,i);return o.success?{value:o.data}:{issues:(l=o.error)==null?void 0:l.issues}}catch{return vqt(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}))}),gMe=fr("$ZodString",(s,t)=>{var n;xh.init(s,t),s._zod.pattern=[...((n=s==null?void 0:s._zod.bag)==null?void 0:n.patterns)??[]].pop()??Yqt(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}}),fu=fr("$ZodStringFormat",(s,t)=>{bye.init(s,t),gMe.init(s,t)}),fVt=fr("$ZodGUID",(s,t)=>{t.pattern??(t.pattern=Dqt),fu.init(s,t)}),xVt=fr("$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=wBe(r))}else t.pattern??(t.pattern=wBe());fu.init(s,t)}),gVt=fr("$ZodEmail",(s,t)=>{t.pattern??(t.pattern=Rqt),fu.init(s,t)}),yVt=fr("$ZodURL",(s,t)=>{fu.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)===Vqt.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})}}}),vVt=fr("$ZodEmoji",(s,t)=>{t.pattern??(t.pattern=Fqt()),fu.init(s,t)}),bVt=fr("$ZodNanoID",(s,t)=>{t.pattern??(t.pattern=Pqt),fu.init(s,t)}),_Vt=fr("$ZodCUID",(s,t)=>{t.pattern??(t.pattern=Tqt),fu.init(s,t)}),wVt=fr("$ZodCUID2",(s,t)=>{t.pattern??(t.pattern=Eqt),fu.init(s,t)}),jVt=fr("$ZodULID",(s,t)=>{t.pattern??(t.pattern=Aqt),fu.init(s,t)}),NVt=fr("$ZodXID",(s,t)=>{t.pattern??(t.pattern=Mqt),fu.init(s,t)}),kVt=fr("$ZodKSUID",(s,t)=>{t.pattern??(t.pattern=Iqt),fu.init(s,t)}),SVt=fr("$ZodISODateTime",(s,t)=>{t.pattern??(t.pattern=Kqt(t)),fu.init(s,t)}),CVt=fr("$ZodISODate",(s,t)=>{t.pattern??(t.pattern=Gqt),fu.init(s,t)}),TVt=fr("$ZodISOTime",(s,t)=>{t.pattern??(t.pattern=Wqt(t)),fu.init(s,t)}),EVt=fr("$ZodISODuration",(s,t)=>{t.pattern??(t.pattern=Lqt),fu.init(s,t)}),AVt=fr("$ZodIPv4",(s,t)=>{t.pattern??(t.pattern=zqt),fu.init(s,t),s._zod.bag.format="ipv4"}),MVt=fr("$ZodIPv6",(s,t)=>{t.pattern??(t.pattern=Bqt),fu.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})}}}),IVt=fr("$ZodCIDRv4",(s,t)=>{t.pattern??(t.pattern=$qt),fu.init(s,t)}),PVt=fr("$ZodCIDRv6",(s,t)=>{t.pattern??(t.pattern=Uqt),fu.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 sdt(s){if(s==="")return!0;if(/\s/.test(s)||s.length%4!==0)return!1;try{return atob(s),!0}catch{return!1}}const LVt=fr("$ZodBase64",(s,t)=>{t.pattern??(t.pattern=qqt),fu.init(s,t),s._zod.bag.contentEncoding="base64",s._zod.check=n=>{sdt(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:s,continue:!t.abort})}});function DVt(s){if(!Zct.test(s))return!1;const t=s.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return sdt(n)}const RVt=fr("$ZodBase64URL",(s,t)=>{t.pattern??(t.pattern=Zct),fu.init(s,t),s._zod.bag.contentEncoding="base64url",s._zod.check=n=>{DVt(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:s,continue:!t.abort})}}),OVt=fr("$ZodE164",(s,t)=>{t.pattern??(t.pattern=Hqt),fu.init(s,t)});function FVt(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 zVt=fr("$ZodJWT",(s,t)=>{fu.init(s,t),s._zod.check=n=>{FVt(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:s,continue:!t.abort})}}),ndt=fr("$ZodNumber",(s,t)=>{xh.init(s,t),s._zod.pattern=s._zod.bag.pattern??Qqt,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}}),BVt=fr("$ZodNumberFormat",(s,t)=>{sVt.init(s,t),ndt.init(s,t)}),$Vt=fr("$ZodBoolean",(s,t)=>{xh.init(s,t),s._zod.pattern=Xqt,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}}),UVt=fr("$ZodUnknown",(s,t)=>{xh.init(s,t),s._zod.parse=n=>n}),qVt=fr("$ZodNever",(s,t)=>{xh.init(s,t),s._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:s}),n)});function jBe(s,t,n){s.issues.length&&t.issues.push(...Gct(n,s.issues)),t.value[n]=s.value}const VVt=fr("$ZodArray",(s,t)=>{xh.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;ljBe(d,n,l))):jBe(c,n,l)}return i.length?Promise.all(i).then(()=>n):n}});function ufe(s,t,n,r,a,i){const l=n in r;if(s.issues.length){if(a&&i&&!l)return;t.issues.push(...Gct(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 rdt(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=iqt(s.shape);return{...s,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function adt(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 p in t){if(p==="__proto__"||o.has(p))continue;if(d==="never"){l.push(p);continue}const f=c.run({value:t[p],issues:[]},r);f instanceof Promise?s.push(f.then(g=>ufe(g,n,p,t,u,h))):ufe(f,n,p,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 HVt=fr("$ZodObject",(s,t)=>{xh.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=uMe(()=>rdt(t));Wc(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=dfe,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 p of l.keys){const f=h[p],g=f._zod.optin==="optional",_=f._zod.optout==="optional",v=f._zod.run({value:d[p],issues:[]},c);v instanceof Promise?u.push(v.then(j=>ufe(j,o,p,d,g,_))):ufe(v,o,p,d,g,_)}return i?adt(u,d,o,c,r.value,s):u.length?Promise.all(u).then(()=>o):o}}),GVt=fr("$ZodObjectJIT",(s,t)=>{HVt.init(s,t);const n=s._zod.parse,r=uMe(()=>rdt(t)),a=p=>{var S,A;const f=new mVt(["shape","payload","ctx"]),g=r.value,_=T=>{const L=_Be(T);return`shape[${L}]._zod.run({ value: input[${L}], issues: [] }, ctx)`};f.write("const input = payload.value;");const v=Object.create(null);let j=0;for(const T of g.keys)v[T]=`key_${j++}`;f.write("const newResult = {};");for(const T of g.keys){const L=v[T],D=_Be(T),M=p[T],F=((S=M==null?void 0:M._zod)==null?void 0:S.optin)==="optional",z=((A=M==null?void 0:M._zod)==null?void 0:A.optout)==="optional";f.write(`const ${L} = ${_(T)};`),F&&z?f.write(` if (${L}.issues.length) { if (${D} in input) { payload.issues = payload.issues.concat(${L}.issues.map(iss => ({ ...iss, path: iss.path ? [${D}, ...iss.path] : [${D}] }))); } } if (${L}.value === undefined) { if (${D} in input) { newResult[${D}] = undefined; } } else { newResult[${D}] = ${L}.value; } `):F?f.write(` if (${L}.issues.length) { payload.issues = payload.issues.concat(${L}.issues.map(iss => ({ ...iss, path: iss.path ? [${D}, ...iss.path] : [${D}] }))); } if (${L}.value === undefined) { if (${D} in input) { newResult[${D}] = undefined; } } else { newResult[${D}] = ${L}.value; } `):f.write(` const ${L}_present = ${D} in input; if (${L}.issues.length) { payload.issues = payload.issues.concat(${L}.issues.map(iss => ({ ...iss, path: iss.path ? [${D}, ...iss.path] : [${D}] }))); } if (!${L}_present && !${L}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${D}] }); } if (${L}_present) { if (${L}.value === undefined) { newResult[${D}] = undefined; } else { newResult[${D}] = ${L}.value; } } `)}f.write("payload.value = newResult;"),f.write("return payload;");const b=f.compile();return(T,L)=>b(p,T,L)};let i;const l=dfe,o=!dMe.jitless,d=o&&rqt.value,u=t.catchall;let h;s._zod.parse=(p,f)=>{h??(h=r.value);const g=p.value;return l(g)?o&&d&&(f==null?void 0:f.async)===!1&&f.jitless!==!0?(i||(i=a(t.shape)),p=i(p,f),u?adt([],g,p,f,h,s):p):n(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:g,inst:s}),p)}});function NBe(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=>!SP(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=>vM(l,r,yM())))}),t)}const WVt=fr("$ZodUnion",(s,t)=>{xh.init(s,t),Wc(s._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Wc(s._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Wc(s._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Wc(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=>mMe(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=>NBe(o,r,s,a)):NBe(l,r,s,a)}}),KVt=fr("$ZodIntersection",(s,t)=>{xh.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])=>kBe(n,c,d)):kBe(n,i,l)}});function z4e(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(dB(s)&&dB(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=z4e(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}),SP(s))return s;const l=z4e(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 YVt=fr("$ZodEnum",(s,t)=>{xh.init(s,t);const n=qct(t.entries),r=new Set(n);s._zod.values=r,s._zod.pattern=new RegExp(`^(${n.filter(a=>aqt.has(typeof a)).map(a=>typeof a=="string"?j8(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}}),ZVt=fr("$ZodLiteral",(s,t)=>{if(xh.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"?j8(r):r?j8(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}}),QVt=fr("$ZodTransform",(s,t)=>{xh.init(s,t),s._zod.optin="optional",s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Uct(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 ML;return n.value=a,n.fallback=!0,n}});function SBe(s,t){return t===void 0&&(s.issues.length||s.fallback)?{issues:[],value:void 0}:s}const idt=fr("$ZodOptional",(s,t)=>{xh.init(s,t),s._zod.optin="optional",s._zod.optout="optional",Wc(s._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Wc(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${mMe(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=>SBe(l,a)):SBe(i,a)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),XVt=fr("$ZodExactOptional",(s,t)=>{idt.init(s,t),Wc(s._zod,"values",()=>t.innerType._zod.values),Wc(s._zod,"pattern",()=>t.innerType._zod.pattern),s._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),JVt=fr("$ZodNullable",(s,t)=>{xh.init(s,t),Wc(s._zod,"optin",()=>t.innerType._zod.optin),Wc(s._zod,"optout",()=>t.innerType._zod.optout),Wc(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${mMe(n.source)}|null)$`):void 0}),Wc(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)}),eHt=fr("$ZodDefault",(s,t)=>{xh.init(s,t),s._zod.optin="optional",Wc(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=>CBe(i,t)):CBe(a,t)}});function CBe(s,t){return s.value===void 0&&(s.value=t.defaultValue),s}const tHt=fr("$ZodPrefault",(s,t)=>{xh.init(s,t),s._zod.optin="optional",Wc(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))}),sHt=fr("$ZodNonOptional",(s,t)=>{xh.init(s,t),Wc(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=>TBe(i,s)):TBe(a,s)}});function TBe(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 nHt=fr("$ZodCatch",(s,t)=>{xh.init(s,t),s._zod.optin="optional",Wc(s._zod,"optout",()=>t.innerType._zod.optout),Wc(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=>vM(l,r,yM()))},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=>vM(i,r,yM()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),rHt=fr("$ZodPipe",(s,t)=>{xh.init(s,t),Wc(s._zod,"values",()=>t.in._zod.values),Wc(s._zod,"optin",()=>t.in._zod.optin),Wc(s._zod,"optout",()=>t.out._zod.optout),Wc(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=>rH(l,t.in,r)):rH(i,t.in,r)}const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(i=>rH(i,t.out,r)):rH(a,t.out,r)}});function rH(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 aHt=fr("$ZodReadonly",(s,t)=>{xh.init(s,t),Wc(s._zod,"propValues",()=>t.innerType._zod.propValues),Wc(s._zod,"values",()=>t.innerType._zod.values),Wc(s._zod,"optin",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),Wc(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(EBe):EBe(a)}});function EBe(s){return s.value=Object.freeze(s.value),s}const iHt=fr("$ZodCustom",(s,t)=>{s0.init(s,t),xh.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=>ABe(i,n,r,s));ABe(a,n,r,s)}});function ABe(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(uB(a))}}var MBe;class oHt{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 lHt(){return new oHt}(MBe=globalThis).__zod_globalRegistry??(MBe.__zod_globalRegistry=lHt());const h7=globalThis.__zod_globalRegistry;function cHt(s,t){return new s({type:"string",...Li(t)})}function dHt(s,t){return new s({type:"string",format:"email",check:"string_format",abort:!1,...Li(t)})}function IBe(s,t){return new s({type:"string",format:"guid",check:"string_format",abort:!1,...Li(t)})}function uHt(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,...Li(t)})}function hHt(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Li(t)})}function mHt(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Li(t)})}function pHt(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Li(t)})}function fHt(s,t){return new s({type:"string",format:"url",check:"string_format",abort:!1,...Li(t)})}function xHt(s,t){return new s({type:"string",format:"emoji",check:"string_format",abort:!1,...Li(t)})}function gHt(s,t){return new s({type:"string",format:"nanoid",check:"string_format",abort:!1,...Li(t)})}function yHt(s,t){return new s({type:"string",format:"cuid",check:"string_format",abort:!1,...Li(t)})}function vHt(s,t){return new s({type:"string",format:"cuid2",check:"string_format",abort:!1,...Li(t)})}function bHt(s,t){return new s({type:"string",format:"ulid",check:"string_format",abort:!1,...Li(t)})}function _Ht(s,t){return new s({type:"string",format:"xid",check:"string_format",abort:!1,...Li(t)})}function wHt(s,t){return new s({type:"string",format:"ksuid",check:"string_format",abort:!1,...Li(t)})}function jHt(s,t){return new s({type:"string",format:"ipv4",check:"string_format",abort:!1,...Li(t)})}function NHt(s,t){return new s({type:"string",format:"ipv6",check:"string_format",abort:!1,...Li(t)})}function kHt(s,t){return new s({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Li(t)})}function SHt(s,t){return new s({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Li(t)})}function CHt(s,t){return new s({type:"string",format:"base64",check:"string_format",abort:!1,...Li(t)})}function THt(s,t){return new s({type:"string",format:"base64url",check:"string_format",abort:!1,...Li(t)})}function EHt(s,t){return new s({type:"string",format:"e164",check:"string_format",abort:!1,...Li(t)})}function AHt(s,t){return new s({type:"string",format:"jwt",check:"string_format",abort:!1,...Li(t)})}function MHt(s,t){return new s({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Li(t)})}function IHt(s,t){return new s({type:"string",format:"date",check:"string_format",...Li(t)})}function PHt(s,t){return new s({type:"string",format:"time",check:"string_format",precision:null,...Li(t)})}function LHt(s,t){return new s({type:"string",format:"duration",check:"string_format",...Li(t)})}function DHt(s,t){return new s({type:"number",checks:[],...Li(t)})}function RHt(s,t){return new s({type:"number",check:"number_format",abort:!1,format:"safeint",...Li(t)})}function OHt(s,t){return new s({type:"boolean",...Li(t)})}function FHt(s){return new s({type:"unknown"})}function zHt(s,t){return new s({type:"never",...Li(t)})}function PBe(s,t){return new edt({check:"less_than",...Li(t),value:s,inclusive:!1})}function uje(s,t){return new edt({check:"less_than",...Li(t),value:s,inclusive:!0})}function LBe(s,t){return new tdt({check:"greater_than",...Li(t),value:s,inclusive:!1})}function hje(s,t){return new tdt({check:"greater_than",...Li(t),value:s,inclusive:!0})}function DBe(s,t){return new tVt({check:"multiple_of",...Li(t),value:s})}function odt(s,t){return new nVt({check:"max_length",...Li(t),maximum:s})}function hfe(s,t){return new rVt({check:"min_length",...Li(t),minimum:s})}function ldt(s,t){return new aVt({check:"length_equals",...Li(t),length:s})}function BHt(s,t){return new iVt({check:"string_format",format:"regex",...Li(t),pattern:s})}function $Ht(s){return new oVt({check:"string_format",format:"lowercase",...Li(s)})}function UHt(s){return new lVt({check:"string_format",format:"uppercase",...Li(s)})}function qHt(s,t){return new cVt({check:"string_format",format:"includes",...Li(t),includes:s})}function VHt(s,t){return new dVt({check:"string_format",format:"starts_with",...Li(t),prefix:s})}function HHt(s,t){return new uVt({check:"string_format",format:"ends_with",...Li(t),suffix:s})}function qD(s){return new hVt({check:"overwrite",tx:s})}function GHt(s){return qD(t=>t.normalize(s))}function WHt(){return qD(s=>s.trim())}function KHt(){return qD(s=>s.toLowerCase())}function YHt(){return qD(s=>s.toUpperCase())}function ZHt(){return qD(s=>nqt(s))}function QHt(s,t,n){return new s({type:"array",element:t,...Li(n)})}function XHt(s,t,n){return new s({type:"custom",check:"custom",fn:t,...Li(n)})}function JHt(s,t){const n=eGt(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(uB(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(uB(i))}},s(r.value,r)),t);return n}function eGt(s,t){const n=new s0({check:"custom",...Li(t)});return n._zod.check=s,n}function cdt(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)??h7,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 Sf(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 p={...n,schemaPath:[...n.schemaPath,s],path:n.path};if(s._zod.processJSONSchema)s._zod.processJSONSchema(t,l.schema,p);else{const g=l.schema,_=t.processors[a.type];if(!_)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);_(s,t,g,p)}const f=s._zod.parent;f&&(l.ref||(l.ref=f),Sf(f,t,p),t.seen.get(f).isParent=!0)}const c=t.metadataRegistry.get(s);return c&&Object.assign(l.schema,c),t.io==="input"&&Rx(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 ddt(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 p=r.get(h);if(p&&p!==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 _;const h=s.target==="draft-2020-12"?"$defs":"definitions";if(s.external){const v=(_=s.external.registry.get(u[0]))==null?void 0:_.id,j=s.external.uri??(S=>S);if(v)return{ref:j(v)};const b=u[1].defId??u[1].schema.id??`schema${s.counter++}`;return u[1].defId=b,{defId:b,ref:`${j("__shared")}#/${h}/${b}`}}if(u[1]===n)return{ref:"#"};const f=`#/${h}/`,g=u[1].schema.id??`__schema${s.counter++}`;return{defId:g,ref:f+g}},i=u=>{if(u[1].schema.$ref)return;const h=u[1],{ref:p,defId:f}=a(u);h.def={...h.schema},f&&(h.defId=f);const g=h.schema;for(const _ in g)delete g[_];g.$ref=p};if(s.cycles==="throw")for(const u of s.seen.entries()){const h=u[1];if(h.cycle)throw new Error(`Cycle detected: #/${(o=h.cycle)==null?void 0:o.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of s.seen.entries()){const h=u[1];if(t===u[0]){i(u);continue}if(s.external){const f=(c=s.external.registry.get(u[0]))==null?void 0:c.id;if(t!==u[0]&&f){i(u);continue}}if((d=s.metadataRegistry.get(u[0]))==null?void 0:d.id){i(u);continue}if(h.cycle){i(u);continue}if(h.count>1&&s.reused==="ref"){i(u);continue}}}function udt(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 p=s.seen.get(h);if(p.ref===null)return;const f=p.def??p.schema,g={...f},_=p.ref;if(p.ref=null,_){r(_);const j=s.seen.get(_),b=j.schema;if(b.$ref&&(s.target==="draft-07"||s.target==="draft-04"||s.target==="openapi-3.0")?(f.allOf=f.allOf??[],f.allOf.push(b)):Object.assign(f,b),Object.assign(f,g),h._zod.parent===_)for(const A in f)A==="$ref"||A==="allOf"||A in g||delete f[A];if(b.$ref&&j.def)for(const A in f)A==="$ref"||A==="allOf"||A in j.def&&JSON.stringify(f[A])===JSON.stringify(j.def[A])&&delete f[A]}const v=h._zod.parent;if(v&&v!==_){r(v);const j=s.seen.get(v);if(j!=null&&j.schema.$ref&&(f.$ref=j.schema.$ref,j.def))for(const b in f)b==="$ref"||b==="allOf"||b in j.def&&JSON.stringify(f[b])===JSON.stringify(j.def[b])&&delete f[b]}s.override({zodSchema:h,jsonSchema:f,path:p.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 p=h[1];p.def&&p.defId&&(p.def.id===p.defId&&delete p.def.id,l[p.defId]=p.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:mfe(t,"input",s.processors),output:mfe(t,"output",s.processors)}},enumerable:!1,writable:!1}),h}catch{throw new Error("Error converting schema to JSON.")}}function Rx(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 Rx(r.element,n);if(r.type==="set")return Rx(r.valueType,n);if(r.type==="lazy")return Rx(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 Rx(r.innerType,n);if(r.type==="intersection")return Rx(r.left,n)||Rx(r.right,n);if(r.type==="record"||r.type==="map")return Rx(r.keyType,n)||Rx(r.valueType,n);if(r.type==="pipe")return s._zod.traits.has("$ZodCodec")?!0:Rx(r.in,n)||Rx(r.out,n);if(r.type==="object"){for(const a in r.shape)if(Rx(r.shape[a],n))return!0;return!1}if(r.type==="union"){for(const a of r.options)if(Rx(a,n))return!0;return!1}if(r.type==="tuple"){for(const a of r.items)if(Rx(a,n))return!0;return!!(r.rest&&Rx(r.rest,n))}return!1}const tGt=(s,t={})=>n=>{const r=cdt({...n,processors:t});return Sf(s,r),ddt(r,s),udt(r,s)},mfe=(s,t,n={})=>r=>{const{libraryOptions:a,target:i}=r??{},l=cdt({...a??{},target:i,io:t,processors:n});return Sf(s,l),ddt(l,s),udt(l,s)},sGt={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},nGt=(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=sGt[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}))])}},rGt=(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),p=typeof d=="number"&&d<=(l??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";h?f?(a.minimum=u,a.exclusiveMinimum=!0):a.exclusiveMinimum=u:typeof i=="number"&&(a.minimum=i),p?f?(a.maximum=d,a.exclusiveMaximum=!0):a.exclusiveMaximum=d:typeof l=="number"&&(a.maximum=l),typeof c=="number"&&(a.multipleOf=c)},aGt=(s,t,n,r)=>{n.type="boolean"},iGt=(s,t,n,r)=>{n.not={}},oGt=(s,t,n,r)=>{},lGt=(s,t,n,r)=>{const a=s._zod.def,i=qct(a.entries);i.every(l=>typeof l=="number")&&(n.type="number"),i.every(l=>typeof l=="string")&&(n.type="string"),n.enum=i},cGt=(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},dGt=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},uGt=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},hGt=(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=Sf(i.element,t,{...r,path:[...r.path,"items"]})},mGt=(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]=Sf(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=Sf(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(a.additionalProperties=!1)},pGt=(s,t,n,r)=>{const a=s._zod.def,i=a.inclusive===!1,l=a.options.map((o,c)=>Sf(o,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=l:n.anyOf=l},fGt=(s,t,n,r)=>{const a=s._zod.def,i=Sf(a.left,t,{...r,path:[...r.path,"allOf",0]}),l=Sf(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},xGt=(s,t,n,r)=>{const a=s._zod.def,i=Sf(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"}]},gGt=(s,t,n,r)=>{const a=s._zod.def;Sf(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},yGt=(s,t,n,r)=>{const a=s._zod.def;Sf(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.default=JSON.parse(JSON.stringify(a.defaultValue))},vGt=(s,t,n,r)=>{const a=s._zod.def;Sf(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)))},bGt=(s,t,n,r)=>{const a=s._zod.def;Sf(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},_Gt=(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;Sf(l,t,r);const o=t.seen.get(s);o.ref=l},wGt=(s,t,n,r)=>{const a=s._zod.def;Sf(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.readOnly=!0},hdt=(s,t,n,r)=>{const a=s._zod.def;Sf(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},jGt=fr("ZodISODateTime",(s,t)=>{SVt.init(s,t),Uu.init(s,t)});function NGt(s){return MHt(jGt,s)}const kGt=fr("ZodISODate",(s,t)=>{CVt.init(s,t),Uu.init(s,t)});function SGt(s){return IHt(kGt,s)}const CGt=fr("ZodISOTime",(s,t)=>{TVt.init(s,t),Uu.init(s,t)});function TGt(s){return PHt(CGt,s)}const EGt=fr("ZodISODuration",(s,t)=>{EVt.init(s,t),Uu.init(s,t)});function AGt(s){return LHt(EGt,s)}const mdt=(s,t)=>{Kct.init(s,t),s.name="ZodError",Object.defineProperties(s,{format:{value:n=>gqt(s,n)},flatten:{value:n=>xqt(s,n)},addIssue:{value:n=>{s.issues.push(n),s.message=JSON.stringify(s.issues,F4e,2)}},addIssues:{value:n=>{s.issues.push(...n),s.message=JSON.stringify(s.issues,F4e,2)}},isEmpty:{get(){return s.issues.length===0}}})},MGt=fr("ZodError",mdt),Qv=fr("ZodError",mdt,{Parent:Error}),IGt=fMe(Qv),PGt=xMe(Qv),LGt=yye(Qv),DGt=vye(Qv),RGt=bqt(Qv),OGt=_qt(Qv),FGt=wqt(Qv),zGt=jqt(Qv),BGt=Nqt(Qv),$Gt=kqt(Qv),UGt=Sqt(Qv),qGt=Cqt(Qv),RBe=new WeakMap;function nU(s,t,n){const r=Object.getPrototypeOf(s);let a=RBe.get(r);if(a||(a=new Set,RBe.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 gh=fr("ZodType",(s,t)=>(xh.init(s,t),Object.assign(s["~standard"],{jsonSchema:{input:mfe(s,"input"),output:mfe(s,"output")}}),s.toJSONSchema=tGt(s,{}),s.def=t,s.type=t.type,Object.defineProperty(s,"_def",{value:t}),s.parse=(n,r)=>IGt(s,n,r,{callee:s.parse}),s.safeParse=(n,r)=>LGt(s,n,r),s.parseAsync=async(n,r)=>PGt(s,n,r,{callee:s.parseAsync}),s.safeParseAsync=async(n,r)=>DGt(s,n,r),s.spa=s.safeParseAsync,s.encode=(n,r)=>RGt(s,n,r),s.decode=(n,r)=>OGt(s,n,r),s.encodeAsync=async(n,r)=>FGt(s,n,r),s.decodeAsync=async(n,r)=>zGt(s,n,r),s.safeEncode=(n,r)=>BGt(s,n,r),s.safeDecode=(n,r)=>$Gt(s,n,r),s.safeEncodeAsync=async(n,r)=>UGt(s,n,r),s.safeDecodeAsync=async(n,r)=>qGt(s,n,r),nU(s,"ZodType",{check(...n){const r=this.def;return this.clone(Q4(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 X4(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(FWt(n,r))},superRefine(n,r){return this.check(zWt(n,r))},overwrite(n){return this.check(qD(n))},optional(){return BBe(this)},exactOptional(){return kWt(this)},nullable(){return $Be(this)},nullish(){return BBe($Be(this))},nonoptional(n){return MWt(this,n)},array(){return fWt(this)},or(n){return yWt([this,n])},and(n){return bWt(this,n)},transform(n){return UBe(this,jWt(n))},default(n){return TWt(this,n)},prefault(n){return AWt(this,n)},catch(n){return PWt(this,n)},pipe(n){return UBe(this,n)},readonly(){return RWt(this)},describe(n){const r=this.clone();return h7.add(r,{description:n}),r},meta(...n){if(n.length===0)return h7.get(this);const r=this.clone();return h7.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=h7.get(s))==null?void 0:n.description},configurable:!0}),s)),pdt=fr("_ZodString",(s,t)=>{gMe.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(r,a,i)=>nGt(s,r,a);const n=s._zod.bag;s.format=n.format??null,s.minLength=n.minimum??null,s.maxLength=n.maximum??null,nU(s,"_ZodString",{regex(...r){return this.check(BHt(...r))},includes(...r){return this.check(qHt(...r))},startsWith(...r){return this.check(VHt(...r))},endsWith(...r){return this.check(HHt(...r))},min(...r){return this.check(hfe(...r))},max(...r){return this.check(odt(...r))},length(...r){return this.check(ldt(...r))},nonempty(...r){return this.check(hfe(1,...r))},lowercase(r){return this.check($Ht(r))},uppercase(r){return this.check(UHt(r))},trim(){return this.check(WHt())},normalize(...r){return this.check(GHt(...r))},toLowerCase(){return this.check(KHt())},toUpperCase(){return this.check(YHt())},slugify(){return this.check(ZHt())}})}),VGt=fr("ZodString",(s,t)=>{gMe.init(s,t),pdt.init(s,t),s.email=n=>s.check(dHt(HGt,n)),s.url=n=>s.check(fHt(GGt,n)),s.jwt=n=>s.check(AHt(oWt,n)),s.emoji=n=>s.check(xHt(WGt,n)),s.guid=n=>s.check(IBe(OBe,n)),s.uuid=n=>s.check(uHt(aH,n)),s.uuidv4=n=>s.check(hHt(aH,n)),s.uuidv6=n=>s.check(mHt(aH,n)),s.uuidv7=n=>s.check(pHt(aH,n)),s.nanoid=n=>s.check(gHt(KGt,n)),s.guid=n=>s.check(IBe(OBe,n)),s.cuid=n=>s.check(yHt(YGt,n)),s.cuid2=n=>s.check(vHt(ZGt,n)),s.ulid=n=>s.check(bHt(QGt,n)),s.base64=n=>s.check(CHt(rWt,n)),s.base64url=n=>s.check(THt(aWt,n)),s.xid=n=>s.check(_Ht(XGt,n)),s.ksuid=n=>s.check(wHt(JGt,n)),s.ipv4=n=>s.check(jHt(eWt,n)),s.ipv6=n=>s.check(NHt(tWt,n)),s.cidrv4=n=>s.check(kHt(sWt,n)),s.cidrv6=n=>s.check(SHt(nWt,n)),s.e164=n=>s.check(EHt(iWt,n)),s.datetime=n=>s.check(NGt(n)),s.date=n=>s.check(SGt(n)),s.time=n=>s.check(TGt(n)),s.duration=n=>s.check(AGt(n))});function go(s){return cHt(VGt,s)}const Uu=fr("ZodStringFormat",(s,t)=>{fu.init(s,t),pdt.init(s,t)}),HGt=fr("ZodEmail",(s,t)=>{gVt.init(s,t),Uu.init(s,t)}),OBe=fr("ZodGUID",(s,t)=>{fVt.init(s,t),Uu.init(s,t)}),aH=fr("ZodUUID",(s,t)=>{xVt.init(s,t),Uu.init(s,t)}),GGt=fr("ZodURL",(s,t)=>{yVt.init(s,t),Uu.init(s,t)}),WGt=fr("ZodEmoji",(s,t)=>{vVt.init(s,t),Uu.init(s,t)}),KGt=fr("ZodNanoID",(s,t)=>{bVt.init(s,t),Uu.init(s,t)}),YGt=fr("ZodCUID",(s,t)=>{_Vt.init(s,t),Uu.init(s,t)}),ZGt=fr("ZodCUID2",(s,t)=>{wVt.init(s,t),Uu.init(s,t)}),QGt=fr("ZodULID",(s,t)=>{jVt.init(s,t),Uu.init(s,t)}),XGt=fr("ZodXID",(s,t)=>{NVt.init(s,t),Uu.init(s,t)}),JGt=fr("ZodKSUID",(s,t)=>{kVt.init(s,t),Uu.init(s,t)}),eWt=fr("ZodIPv4",(s,t)=>{AVt.init(s,t),Uu.init(s,t)}),tWt=fr("ZodIPv6",(s,t)=>{MVt.init(s,t),Uu.init(s,t)}),sWt=fr("ZodCIDRv4",(s,t)=>{IVt.init(s,t),Uu.init(s,t)}),nWt=fr("ZodCIDRv6",(s,t)=>{PVt.init(s,t),Uu.init(s,t)}),rWt=fr("ZodBase64",(s,t)=>{LVt.init(s,t),Uu.init(s,t)}),aWt=fr("ZodBase64URL",(s,t)=>{RVt.init(s,t),Uu.init(s,t)}),iWt=fr("ZodE164",(s,t)=>{OVt.init(s,t),Uu.init(s,t)}),oWt=fr("ZodJWT",(s,t)=>{zVt.init(s,t),Uu.init(s,t)}),fdt=fr("ZodNumber",(s,t)=>{ndt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(r,a,i)=>rGt(s,r,a),nU(s,"ZodNumber",{gt(r,a){return this.check(LBe(r,a))},gte(r,a){return this.check(hje(r,a))},min(r,a){return this.check(hje(r,a))},lt(r,a){return this.check(PBe(r,a))},lte(r,a){return this.check(uje(r,a))},max(r,a){return this.check(uje(r,a))},int(r){return this.check(FBe(r))},safe(r){return this.check(FBe(r))},positive(r){return this.check(LBe(0,r))},nonnegative(r){return this.check(hje(0,r))},negative(r){return this.check(PBe(0,r))},nonpositive(r){return this.check(uje(0,r))},multipleOf(r,a){return this.check(DBe(r,a))},step(r,a){return this.check(DBe(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 Y9(s){return DHt(fdt,s)}const lWt=fr("ZodNumberFormat",(s,t)=>{BVt.init(s,t),fdt.init(s,t)});function FBe(s){return RHt(lWt,s)}const cWt=fr("ZodBoolean",(s,t)=>{$Vt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>aGt(s,n,r)});function dWt(s){return OHt(cWt,s)}const uWt=fr("ZodUnknown",(s,t)=>{UVt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>oGt()});function zBe(){return FHt(uWt)}const hWt=fr("ZodNever",(s,t)=>{qVt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>iGt(s,n,r)});function mWt(s){return zHt(hWt,s)}const pWt=fr("ZodArray",(s,t)=>{VVt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>hGt(s,n,r,a),s.element=t.element,nU(s,"ZodArray",{min(n,r){return this.check(hfe(n,r))},nonempty(n){return this.check(hfe(1,n))},max(n,r){return this.check(odt(n,r))},length(n,r){return this.check(ldt(n,r))},unwrap(){return this.element}})});function fWt(s,t){return QHt(pWt,s,t)}const xWt=fr("ZodObject",(s,t)=>{GVt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>mGt(s,n,r,a),Wc(s,"shape",()=>t.shape),nU(s,"ZodObject",{keyof(){return yMe(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:zBe()})},loose(){return this.clone({...this._zod.def,catchall:zBe()})},strict(){return this.clone({...this._zod.def,catchall:mWt()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return dqt(this,n)},safeExtend(n){return uqt(this,n)},merge(n){return hqt(this,n)},pick(n){return lqt(this,n)},omit(n){return cqt(this,n)},partial(...n){return mqt(xdt,this,n[0])},required(...n){return pqt(gdt,this,n[0])}})});function Yw(s,t){const n={type:"object",shape:s??{},...Li(t)};return new xWt(n)}const gWt=fr("ZodUnion",(s,t)=>{WVt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>pGt(s,n,r,a),s.options=t.options});function yWt(s,t){return new gWt({type:"union",options:s,...Li(t)})}const vWt=fr("ZodIntersection",(s,t)=>{KVt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>fGt(s,n,r,a)});function bWt(s,t){return new vWt({type:"intersection",left:s,right:t})}const B4e=fr("ZodEnum",(s,t)=>{YVt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(r,a,i)=>lGt(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 B4e({...t,checks:[],...Li(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 B4e({...t,checks:[],...Li(a),entries:i})}});function yMe(s,t){const n=Array.isArray(s)?Object.fromEntries(s.map(r=>[r,r])):s;return new B4e({type:"enum",entries:n,...Li(t)})}const _Wt=fr("ZodLiteral",(s,t)=>{ZVt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>cGt(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 jp(s,t){return new _Wt({type:"literal",values:Array.isArray(s)?s:[s],...Li(t)})}const wWt=fr("ZodTransform",(s,t)=>{QVt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>uGt(s,n),s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Uct(s.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(uB(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(uB(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 jWt(s){return new wWt({type:"transform",transform:s})}const xdt=fr("ZodOptional",(s,t)=>{idt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>hdt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function BBe(s){return new xdt({type:"optional",innerType:s})}const NWt=fr("ZodExactOptional",(s,t)=>{XVt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>hdt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function kWt(s){return new NWt({type:"optional",innerType:s})}const SWt=fr("ZodNullable",(s,t)=>{JVt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>xGt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function $Be(s){return new SWt({type:"nullable",innerType:s})}const CWt=fr("ZodDefault",(s,t)=>{eHt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>yGt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeDefault=s.unwrap});function TWt(s,t){return new CWt({type:"default",innerType:s,get defaultValue(){return typeof t=="function"?t():Hct(t)}})}const EWt=fr("ZodPrefault",(s,t)=>{tHt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>vGt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function AWt(s,t){return new EWt({type:"prefault",innerType:s,get defaultValue(){return typeof t=="function"?t():Hct(t)}})}const gdt=fr("ZodNonOptional",(s,t)=>{sHt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>gGt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function MWt(s,t){return new gdt({type:"nonoptional",innerType:s,...Li(t)})}const IWt=fr("ZodCatch",(s,t)=>{nHt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>bGt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeCatch=s.unwrap});function PWt(s,t){return new IWt({type:"catch",innerType:s,catchValue:typeof t=="function"?t:()=>t})}const LWt=fr("ZodPipe",(s,t)=>{rHt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>_Gt(s,n,r,a),s.in=t.in,s.out=t.out});function UBe(s,t){return new LWt({type:"pipe",in:s,out:t})}const DWt=fr("ZodReadonly",(s,t)=>{aHt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>wGt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function RWt(s){return new DWt({type:"readonly",innerType:s})}const OWt=fr("ZodCustom",(s,t)=>{iHt.init(s,t),gh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>dGt(s,n)});function FWt(s,t={}){return XHt(OWt,s,t)}function zWt(s,t){return JHt(s,t)}const BWt=["Excellent","Good","Neutral","Bad","Very Bad"],$Wt=[5,4,3,2,1];function UWt({questions:s,visitorId:t,onComplete:n,onSkip:r}){const a=oBt(),[i,l]=N.useState({}),o=s.filter(p=>p.question_type==="rating"),c=s.filter(p=>p.question_type!=="rating"),d=(p,f)=>{l(g=>({...g,[p]:{rating_value:f}}))},u=(p,f)=>{l(g=>({...g,[p]:{text_value:f}}))},h=async()=>{const p=Object.entries(i).filter(([,f])=>f.rating_value!=null||f.text_value&&f.text_value.trim()).map(([f,g])=>{var _;return{visitor_id:t,question_id:f,rating_value:g.rating_value??null,text_value:((_=g.text_value)==null?void 0:_.trim())||null}});if(p.length>0)try{await a.mutateAsync(p)}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"}),BWt.map(p=>e.jsx("div",{className:"w-12 text-center",children:e.jsx("span",{className:"text-[10px] text-slate-400 leading-tight block",children:p})},p))]}),o.map(p=>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:p.question_text}),$Wt.map(f=>{var g;return e.jsx("div",{className:"w-12 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>d(p.id,f),className:`w-6 h-6 rounded-full border-2 transition-all ${((g=i[p.id])==null?void 0:g.rating_value)===f?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},f)})]},p.id))]}),c.map(p=>{var f;return e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:p.question_text}),e.jsx(Es,{value:((f=i[p.id])==null?void 0:f.text_value)||"",onChange:g=>u(p.id,g.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},p.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(ts,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}var _ye="Checkbox",[qWt,Axn]=pu(_ye),[VWt,vMe]=qWt(_ye);function HWt(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,[p,f]=hm({prop:n,defaultProp:a??!1,onChange:c,caller:_ye}),[g,_]=N.useState(null),[v,j]=N.useState(null),b=N.useRef(!1),S=g?!!l||!!g.closest("form"):!0,A={checked:p,disabled:i,setChecked:f,control:g,setControl:_,name:o,form:l,value:u,hasConsumerStoppedPropagationRef:b,required:d,defaultChecked:f4(a)?!1:a,isFormControl:S,bubbleInput:v,setBubbleInput:j};return e.jsx(VWt,{scope:t,...A,children:GWt(h)?h(A):r})}var ydt="CheckboxTrigger",vdt=N.forwardRef(({__scopeCheckbox:s,onKeyDown:t,onClick:n,...r},a)=>{const{control:i,value:l,disabled:o,checked:c,required:d,setControl:u,setChecked:h,hasConsumerStoppedPropagationRef:p,isFormControl:f,bubbleInput:g}=vMe(ydt,s),_=Si(a,u),v=N.useRef(c);return N.useEffect(()=>{const j=i==null?void 0:i.form;if(j){const b=()=>h(v.current);return j.addEventListener("reset",b),()=>j.removeEventListener("reset",b)}},[i,h]),e.jsx(Jr.button,{type:"button",role:"checkbox","aria-checked":f4(c)?"mixed":c,"aria-required":d,"data-state":Ndt(c),"data-disabled":o?"":void 0,disabled:o,value:l,...r,ref:_,onKeyDown:_r(t,j=>{j.key==="Enter"&&j.preventDefault()}),onClick:_r(n,j=>{h(b=>f4(b)?!0:!b),g&&f&&(p.current=j.isPropagationStopped(),p.current||j.stopPropagation())})})});vdt.displayName=ydt;var bMe=N.forwardRef((s,t)=>{const{__scopeCheckbox:n,name:r,checked:a,defaultChecked:i,required:l,disabled:o,value:c,onCheckedChange:d,form:u,...h}=s;return e.jsx(HWt,{__scopeCheckbox:n,checked:a,defaultChecked:i,disabled:o,required:l,onCheckedChange:d,name:r,form:u,value:c,internal_do_not_use_render:({isFormControl:p})=>e.jsxs(e.Fragment,{children:[e.jsx(vdt,{...h,ref:t,__scopeCheckbox:n}),p&&e.jsx(jdt,{__scopeCheckbox:n})]})})});bMe.displayName=_ye;var bdt="CheckboxIndicator",_dt=N.forwardRef((s,t)=>{const{__scopeCheckbox:n,forceMount:r,...a}=s,i=vMe(bdt,n);return e.jsx(Rh,{present:r||f4(i.checked)||i.checked===!0,children:e.jsx(Jr.span,{"data-state":Ndt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t,style:{pointerEvents:"none",...s.style}})})});_dt.displayName=bdt;var wdt="CheckboxBubbleInput",jdt=N.forwardRef(({__scopeCheckbox:s,...t},n)=>{const{control:r,hasConsumerStoppedPropagationRef:a,checked:i,defaultChecked:l,required:o,disabled:c,name:d,value:u,form:h,bubbleInput:p,setBubbleInput:f}=vMe(wdt,s),g=Si(n,f),_=tU(i),v=B$(r);N.useEffect(()=>{const b=p;if(!b)return;const S=window.HTMLInputElement.prototype,T=Object.getOwnPropertyDescriptor(S,"checked").set,L=!a.current;if(_!==i&&T){const D=new Event("click",{bubbles:L});b.indeterminate=f4(i),T.call(b,f4(i)?!1:i),b.dispatchEvent(D)}},[p,_,i,a]);const j=N.useRef(f4(i)?!1:i);return e.jsx(Jr.input,{type:"checkbox","aria-hidden":!0,defaultChecked:l??j.current,required:o,disabled:c,name:d,value:u,form:h,...t,tabIndex:-1,ref:g,style:{...t.style,...v,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});jdt.displayName=wdt;function GWt(s){return typeof s=="function"}function f4(s){return s==="indeterminate"}function Ndt(s){return f4(s)?"indeterminate":s?"checked":"unchecked"}const ui=N.forwardRef(({className:s,...t},n)=>e.jsx(bMe,{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(_dt,{className:Et("flex items-center justify-center text-current"),children:e.jsx(Ir,{className:"h-4 w-4"})})}));ui.displayName=bMe.displayName;const cg=tye,rU=GAe,WWt=sye,kdt=N.forwardRef(({className:s,...t},n)=>e.jsx(zD,{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}));kdt.displayName=zD.displayName;const KWt=UM("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"}}),ix=N.forwardRef(({side:s="right",className:t,children:n,...r},a)=>e.jsxs(WWt,{children:[e.jsx(kdt,{}),e.jsxs(BD,{ref:a,className:Et(KWt({side:s}),t),...r,children:[n,e.jsxs(J$,{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(Bn,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));ix.displayName=BD.displayName;const n0=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col space-y-2 text-center sm:text-left",s),...t});n0.displayName="SheetHeader";const Sdt=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Sdt.displayName="SheetFooter";const r0=N.forwardRef(({className:s,...t},n)=>e.jsx(Q$,{ref:n,className:Et("text-lg font-semibold text-foreground",s),...t}));r0.displayName=Q$.displayName;const aU=N.forwardRef(({className:s,...t},n)=>e.jsx(X$,{ref:n,className:Et("text-sm text-muted-foreground",s),...t}));aU.displayName=X$.displayName;function $4e(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function YWt({rooms:s}){var h;const[t,n]=N.useState(((h=s[0])==null?void 0:h.id)||""),[r,a]=N.useState(null),i=s.find(p=>p.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(p=>p===null||o===0?p:(p-1+o)%o),u=()=>a(p=>p===null||o===0?p:(p+1)%o);return N.useEffect(()=>{if(r===null)return;const p=f=>{f.key==="Escape"?c():f.key==="ArrowLeft"?d():f.key==="ArrowRight"&&u()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[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(p=>e.jsxs("button",{onClick:()=>n(p.id),className:Et("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",t===p.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[p.name,e.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:p.media.length})]},p.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((p,f)=>e.jsx("button",{onClick:()=>a(f),className:"relative aspect-[4/3] rounded-xl overflow-hidden bg-white/5 group",children:p.kind==="video"?e.jsxs(e.Fragment,{children:[$4e(p.url)?e.jsx("div",{className:"absolute inset-0 bg-slate-900"}):e.jsx("video",{src:p.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(br,{className:"h-5 w-5 text-slate-900"})})})]}):e.jsx("img",{src:p.url,alt:i.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})},p.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:p=>{p.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:p=>{p.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(pl,{className:"h-6 w-6"})}),l.kind==="video"?$4e(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:p=>p.stopPropagation()},l.url):e.jsx("video",{src:l.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded-lg",onClick:p=>p.stopPropagation()},l.url):e.jsx("img",{src:l.url,alt:"",className:"max-w-full max-h-full rounded-lg cursor-default",onClick:p=>p.stopPropagation()}),o>1&&e.jsx("button",{onClick:p=>{p.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(xa,{className:"h-6 w-6"})})]})]}):null}function ZWt({rooms:s}){var o;const t=[];s.forEach(c=>{t.push({type:"cover",roomId:c.id,roomName:c.name,description:c.description,mediaCount:c.media.length}),c.media.forEach((d,u)=>{t.push({type:"media",roomId:c.id,roomName:c.name,url:d.url,kind:d.kind,index:u,total:c.media.length})})});const n=N.useRef(null),[r,a]=N.useState(0);N.useEffect(()=>{const c=n.current;if(!c)return;let d=0;const u=()=>{cancelAnimationFrame(d),d=requestAnimationFrame(()=>{const h=Math.round(c.scrollLeft/c.clientWidth);a(h)})};return c.addEventListener("scroll",u,{passive:!0}),()=>{c.removeEventListener("scroll",u),cancelAnimationFrame(d)}},[]);const i=c=>{const d=n.current;d&&d.scrollTo({left:c*d.clientWidth,behavior:"smooth"})};if(!t.length)return null;const l=(o=t[r])==null?void 0:o.roomId;return e.jsxs("div",{className:"md:hidden -mx-5",children:[e.jsx("div",{className:"px-5 py-3 overflow-x-auto sticky top-0 z-20 bg-slate-950/80 backdrop-blur-md border-b border-white/10",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(c=>{const d=t.findIndex(h=>h.roomId===c.id),u=l===c.id;return e.jsx("button",{onClick:()=>i(d),className: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"?$4e(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(pl,{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(xa,{className:"h-4 w-4"})]})]})]})}const mje={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:Ei},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:yr},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:Nr},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:Zl}},QWt=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function XWt(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 JWt({openHouse:s,visitorId:t,visitorName:n,visitorEmail:r,visitorPhone:a,previewMode:i=!1}){var qe;const l=s.profiles,o=((qe=l==null?void 0:l.name)==null?void 0:qe.split(" ").map(be=>be[0]).join("").slice(0,2))||"?",c=s.brand_color_override||null,[d,u]=N.useState(null),[h,p]=N.useState(""),[f,g]=N.useState(r||""),[_,v]=N.useState(a||""),[j,b]=N.useState(!1),[S,A]=N.useState(null),[T,L]=N.useState(""),[D,M]=N.useState(""),[F,z]=N.useState(""),[V,W]=N.useState([]),[Y,K]=N.useState(""),[J,ne]=N.useState(""),[ie,he]=N.useState(""),[ce,pe]=N.useState(""),le=XWt(s.price),ve=s.tour_mode==="rooms",{data:ge=[]}=gBt(ve?s.id:void 0),Te=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),Me=be=>{u(be),p(""),L(""),M(""),z(""),W([]),K(""),ne(""),he(""),pe("")},Ce=()=>{u(null)},Ae=be=>{W(Ze=>Ze.includes(be)?Ze.filter(Ne=>Ne!==be):[...Ze,be])},De=be=>be==="showing"?{preferred_date:T||null,preferred_time:D||null,alternate_date:F||null}:be==="disclosure"?{requested_documents:V}:be==="offer"?{offer_amount:Y||null,financing:J||null,timeline:ie||null,pre_approved:ce||null}:{},Ie=d?d==="showing"?!!T:d==="question"?h.trim().length>0:!0:!1,Fe=async()=>{if(d){if(i){Pr({title:"Preview mode",description:"Lead not sent — this is just a preview."}),A(d),setTimeout(()=>{u(null),A(null)},1500);return}b(!0);try{const be=De(d),{error:Ze}=await q.from("open_house_leads").insert({open_house_id:s.id,visitor_id:t,action_type:d,payload:{message:h.trim()||null,email:f.trim()||null,phone:_.trim()||null,visitor_name:n,...be}});if(Ze)throw Ze;q.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:s.id,visitor_id:t,action_type:d,message:h.trim()||null,visitor_name:n,visitor_email:f.trim()||null,visitor_phone:_.trim()||null,extras:be}}).catch(()=>{}),A(d),Pr({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{Ce(),A(null)},1400)}catch(be){Pr({title:"Something went wrong",description:be.message,variant:"destructive"})}finally{b(!1)}}};return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs("div",{className:"relative w-full aspect-video bg-slate-900 md:max-h-[70vh]",children:[s.hero_video_url?e.jsx("video",{src:s.hero_video_url,poster:s.hero_video_thumbnail_url||s.photo_url||void 0,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):s.photo_url?e.jsx("img",{src:s.photo_url,alt:s.property_address,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-white/40",children:"No tour video yet"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-32 bg-gradient-to-t from-slate-950 to-transparent pointer-events-none"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto px-5 pb-32 -mt-10 relative z-10",children:[e.jsxs("div",{className:"bg-slate-900/80 backdrop-blur-md border border-white/10 rounded-2xl p-6 shadow-2xl",children:[e.jsx("h1",{className:"text-2xl font-bold leading-tight",children:s.property_address}),s.city&&e.jsxs("p",{className:"text-sm text-white/60 mt-1 flex items-center gap-1",children:[e.jsx(ka,{className:"h-3.5 w-3.5"}),s.city,s.state?`, ${s.state}`:""," ",s.zip]}),le&&e.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:le}),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(sy,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Cp,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ly,{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(ni,{src:l.avatar_url||"",alt:l.name||""}),e.jsx(aa,{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(Ar,{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(Vs,{className:"h-4 w-4"})})]})]}),ve&&ge.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(YWt,{rooms:ge}),e.jsx(ZWt,{rooms:ge})]}),Te.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:Te.map(be=>{const Ze=mje[be],Ne=Ze.icon;return e.jsxs("button",{onClick:()=>Me(be),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(Ne,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-medium text-sm",children:Ze.label})]},be)})}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),e.jsx(cg,{open:!!d,onOpenChange:be=>!be&&Ce(),children:e.jsx(ix,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(n0,{className:"text-left",children:[e.jsx(r0,{children:mje[d].title}),e.jsxs(aU,{children:[(l==null?void 0:l.name)||"The agent"," will be notified by email."]})]}),S===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(xr,{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:f,onChange:be=>g(be.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:_,onChange:be=>v(be.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:be=>L(be.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Preferred time"}),e.jsx(ye,{type:"time",value:D,onChange:be=>M(be.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:F,onChange:be=>z(be.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:QWt.map(be=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(ui,{checked:V.includes(be),onCheckedChange:()=>Ae(be)}),e.jsx("span",{children:be})]},be))})]}),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:Y,onChange:be=>K(be.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Financing"}),e.jsxs(ds,{value:J,onValueChange:ne,children:[e.jsx(ls,{className:"mt-1",children:e.jsx(us,{placeholder:"Select..."})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"Cash",children:"Cash"}),e.jsx(Qe,{value:"Conventional",children:"Conventional"}),e.jsx(Qe,{value:"FHA",children:"FHA"}),e.jsx(Qe,{value:"VA",children:"VA"}),e.jsx(Qe,{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(ds,{value:ie,onValueChange:he,children:[e.jsx(ls,{className:"mt-1",children:e.jsx(us,{placeholder:"Select..."})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"ASAP",children:"ASAP"}),e.jsx(Qe,{value:"30 days",children:"30 days"}),e.jsx(Qe,{value:"60 days",children:"60 days"}),e.jsx(Qe,{value:"90+ days",children:"90+ days"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Pre-approved?"}),e.jsxs(ds,{value:ce,onValueChange:pe,children:[e.jsx(ls,{className:"mt-1",children:e.jsx(us,{placeholder:"Select..."})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"Yes",children:"Yes"}),e.jsx(Qe,{value:"No",children:"No"}),e.jsx(Qe,{value:"In progress",children:"In progress"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs",children:["Message",d==="question"?" *":" (optional)"]}),e.jsx(Es,{value:h,onChange:be=>p(be.target.value),placeholder:mje[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx(B,{onClick:Fe,disabled:j||!Ie,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:j?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const eKt=Yw({first_name:go().trim().min(1,"First name is required").max(50),last_name:go().trim().max(50).optional(),email:go().trim().email("Please enter a valid email").max(255).optional().or(jp("")),phone:go().trim().max(20).optional().or(jp(""))}),tKt=[{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 Cdt({slug:s}={}){var Be;const t=bi(),n=s||t.slug,[r]=gl(),a=r.get("kiosk")==="1"||r.get("mode")==="kiosk",i=8,{data:l,isLoading:o,error:c}=rBt(n),d=mBt(),u=pBt(),h=fBt(),p=N.useRef(!1),[f,g]=N.useState("welcome"),[_,v]=N.useState(null),[j,b]=N.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[S,A]=N.useState(""),[T,L]=N.useState(!1),[D,M]=N.useState(!1),[F,z]=N.useState(""),[V,W]=N.useState(""),[Y,K]=N.useState(i),J=N.useCallback(()=>{v(null),b({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),A(""),L(!1),M(!1),z(""),W(""),K(i),g(a?"info":"welcome")},[a]),ne=N.useCallback((Ye,We)=>{l!=null&&l.id&&q.functions.invoke("guestbook-lead-notify",{body:{open_house_id:l.id,visitor_id:Ye,first_name:We.first_name??j.first_name,last_name:We.last_name??j.last_name,email:We.email??j.email,phone:We.phone??j.phone,visitor_intent:We.visitor_intent??S,message:We.message,wants_market_updates:We.wants_market_updates??T,has_agent:We.has_agent??D,working_with_agent_name:We.working_with_agent_name??F,visitor_address:We.visitor_address??j.visitor_address}}).catch(rt=>console.error("Guest book lead notify failed:",rt))},[l==null?void 0:l.id,j,S,T,D,F]);N.useEffect(()=>{if(!a||f!=="done")return;K(i);const Ye=setInterval(()=>{K(We=>We<=1?(clearInterval(Ye),J(),0):We-1)},1e3);return()=>clearInterval(Ye)},[a,f,J]),N.useEffect(()=>{if(!a)return;g(We=>We==="welcome"?"info":We);let Ye=null;return(async()=>{var We,rt;try{Ye=await((rt=(We=navigator.wakeLock)==null?void 0:We.request)==null?void 0:rt.call(We,"screen"))}catch{}})(),()=>{var We;try{(We=Ye==null?void 0:Ye.release)==null||We.call(Ye)}catch{}}},[a]);const ie=N.useCallback(()=>{var We;const Ye=document.documentElement;document.fullscreenElement||(We=Ye.requestFullscreen||Ye.webkitRequestFullscreen)==null||We.call(Ye).catch(()=>{})},[]),{data:he,isLoading:ce}=iBt(l==null?void 0:l.id),pe=!!(l!=null&&l.enable_survey),le=(l==null?void 0:l.ask_visitor_intent)!==!1,ve=(l==null?void 0:l.ask_visitor_address)===!0;N.useEffect(()=>{if(!n||!(l!=null&&l.id)||p.current)return;const Ye=`oh_scan_${l.id}`;if(sessionStorage.getItem(Ye)){p.current=!0;return}p.current=!0,sessionStorage.setItem(Ye,"1"),h.mutate(n)},[n,l==null?void 0:l.id]),N.useEffect(()=>{f==="pending_survey"&&(ce||g(pe&&((he==null?void 0:he.length)??0)>0?"survey":"done"))},[f,ce,pe,he]);const ge=Ye=>{if(!Ye)return"";const[We,rt]=Ye.split(":"),tt=parseInt(We),at=tt>=12?"PM":"AM";return`${tt>12?tt-12:tt||12}:${rt} ${at}`},Te=async()=>{W("");const Ye=eKt.safeParse(j);if(!Ye.success){W(Ye.error.issues[0].message);return}if(!j.email&&!j.phone){W("Please provide either an email or phone number");return}const We=(l==null?void 0:l.kind)==="virtual";let rt=null;if(!_&&(l!=null&&l.id))try{const tt=await d.mutateAsync({open_house_id:l.id,first_name:j.first_name.trim(),last_name:j.last_name.trim()||void 0,email:j.email.trim()||void 0,phone:j.phone.trim()||void 0,visitor_address:ve&&j.visitor_address.trim()?j.visitor_address.trim():void 0,wants_market_updates:T,has_agent:D,working_with_agent_name:D&&F.trim()?F.trim():void 0,partial_signin:We?!1:le});rt=tt.id,v(tt.id)}catch{if(We){W("We could not start the virtual tour. Please try again.");return}}if(We){le?g("intent"):(rt&&ne(rt,{}),g("done"));return}if(!le){rt&&ne(rt,{}),pe?!ce&&he&&he.length>0?g("survey"):g("pending_survey"):g("done");return}g("intent")},Me=async Ye=>{A(Ye);try{let We=_;if(We?await u.mutateAsync({visitor_id:We,visitor_intent:Ye,wants_market_updates:T,has_agent:D,working_with_agent_name:D&&F.trim()?F.trim():null,partial_signin:!1}):(We=(await d.mutateAsync({open_house_id:l.id,first_name:j.first_name.trim(),last_name:j.last_name.trim()||void 0,email:j.email.trim()||void 0,phone:j.phone.trim()||void 0,visitor_address:ve&&j.visitor_address.trim()?j.visitor_address.trim():void 0,visitor_intent:Ye,wants_market_updates:T,has_agent:D,working_with_agent_name:D&&F.trim()?F.trim():void 0,partial_signin:!1})).id,v(We)),We&&ne(We,{visitor_intent:Ye,wants_market_updates:T,has_agent:D,working_with_agent_name:D&&F.trim()?F.trim():null}),(l==null?void 0:l.kind)==="virtual"){g("done");return}pe?!ce&&he&&he.length>0?g("survey"):g("pending_survey"):g("done")}catch{W("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(Or,{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 Ce=l.profiles,Ae=((Be=Ce==null?void 0:Ce.name)==null?void 0:Be.split(" ").map(Ye=>Ye[0]).join("").slice(0,2))||"?",De=l.event_type==="community",Ie=l.kind==="virtual",Fe=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(Ie&&(Fe||f==="done"))return!Fe&&!_?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(Go,{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"})]}),Fe&&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(JWt,{openHouse:l,visitorId:Fe?"preview":_,visitorName:Fe?"Preview Visitor":`${j.first_name} ${j.last_name}`.trim(),visitorEmail:Fe?"":j.email,visitorPhone:Fe?"":j.phone,previewMode:Fe})]});const be=`${Ie?"Virtual Open House":De?"Community Event":"Open House"} — ${l.property_address}`,Ne=[[l.city,l.state].filter(Boolean).join(", "),l.event_date?Ss(new Date(l.event_date+"T00:00:00"),"EEE, MMM d"):null,Ce!=null&&Ce.name?`Hosted by ${Ce.name}`:null].filter(Boolean).join(" · "),it=l.photo_url||"",je=it&&it.includes("/storage/v1/object/public/")?it.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":it||"https://dashboard.relevelup.com/og-image.png",Ge=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${n}`;return e.jsxs(e.Fragment,{children:[e.jsxs(Go,{children:[e.jsx("title",{children:be}),e.jsx("meta",{name:"description",content:Ne||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:title",content:be}),e.jsx("meta",{property:"og:description",content:Ne||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:image",content:je}),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:Ge}),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:be}),e.jsx("meta",{name:"twitter:description",content:Ne||`Sign in to ${l.property_address}`}),e.jsx("meta",{name:"twitter:image",content:je}),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(ni,{src:(Ce==null?void 0:Ce.avatar_url)||"",alt:(Ce==null?void 0:Ce.name)||""}),e.jsx(aa,{className:"bg-white/10 text-white text-lg",children:Ae})]}),e.jsx("p",{className:"text-white/60 text-sm",children:Ce==null?void 0:Ce.name}),(Ce==null?void 0:Ce.title)&&e.jsx("p",{className:"text-white/40 text-xs",children:Ce.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(ka,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Ie&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(yr,{className:"h-3 w-3"}),Ss(new Date(l.event_date+"T00:00:00"),"MMM d, yyyy")]}),l.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),ge(l.start_time),l.end_time?` – ${ge(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:De?e.jsx(Va,{className:"h-5 w-5 text-white"}):e.jsx(Or,{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(ka,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Ie&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(yr,{className:"h-3 w-3"}),Ss(new Date(l.event_date+"T00:00:00"),"MMM d, yyyy")]}),l.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),ge(l.start_time),l.end_time?` – ${ge(l.end_time)}`:""]})]})]})]})]})}),e.jsxs("div",{className:"p-6",children:[f==="welcome"&&e.jsxs("div",{className:"text-center space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900 mb-2",children:"Welcome!"}),e.jsx("p",{className:"text-slate-500 text-sm",children:l.agent_greeting||"Please sign in below."})]}),e.jsxs(B,{onClick:()=>g("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",e.jsx(Oa,{className:"h-5 w-5 ml-2"})]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),f==="info"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>g("welcome"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(Hr,{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:j.first_name,onChange:Ye=>b(We=>({...We,first_name:Ye.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"Last Name"}),e.jsx(ye,{value:j.last_name,onChange:Ye=>b(We=>({...We,last_name:Ye.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"Email"}),e.jsx(ye,{type:"email",value:j.email,onChange:Ye=>b(We=>({...We,email:Ye.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"Phone"}),e.jsx(ye,{type:"tel",value:j.phone,onChange:Ye=>b(We=>({...We,phone:Ye.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),ve&&e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"Your Home Address"}),e.jsx(ye,{value:j.visitor_address,onChange:Ye=>b(We=>({...We,visitor_address:Ye.target.value})),placeholder:"Street, City, State ZIP",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoComplete:"street-address"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer pt-1",children:[e.jsx("input",{type:"checkbox",checked:T,onChange:Ye=>L(Ye.target.checked),className:"rounded border-slate-300 text-slate-900 focus:ring-slate-500"}),e.jsx("span",{className:"text-sm text-slate-600",children:"Send me market updates for this area"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-slate-600",children:"Already working with an agent?"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-slate-400",children:D?"Yes":"No"}),e.jsx(bn,{checked:D,onCheckedChange:M})]})]}),D&&e.jsx(ye,{value:F,onChange:Ye=>z(Ye.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),V&&e.jsx("p",{className:"text-destructive text-sm",children:V}),e.jsxs(B,{onClick:Te,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(Oa,{className:"h-5 w-5 ml-2"})]})]}),f==="intent"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>g("info"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(Hr,{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:tKt.map(Ye=>e.jsxs("button",{onClick:()=>Me(Ye.value),disabled:d.isPending,className:"flex flex-col items-center gap-2 p-5 rounded-xl border-2 border-slate-200 hover:border-slate-900 hover:bg-slate-50 transition-all text-center group",children:[e.jsx("span",{className:"text-2xl",children:Ye.emoji}),e.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:Ye.label})]},Ye.value))}),V&&e.jsx("p",{className:"text-destructive text-sm text-center",children:V})]}),f==="pending_survey"&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[e.jsx("div",{className:"w-8 h-8 border-[3px] border-slate-200 border-t-slate-900 rounded-full animate-spin"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading survey..."})]}),f==="survey"&&_&&he&&e.jsx(UWt,{questions:he,visitorId:_,onComplete:()=>g("done"),onSkip:()=>g("done")}),f==="done"&&e.jsxs("div",{className:"text-center space-y-4 py-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto",children:e.jsx(xr,{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, ",j.first_name,". ",De?"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(Nr,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),(Ce==null?void 0:Ce.name)&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",e.jsx("strong",{className:"text-slate-600",children:Ce.name})]}),a&&e.jsxs("div",{className:"pt-4 space-y-3",children:[e.jsx(B,{onClick:J,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 ",Y,"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(bL,{className:"h-3 w-3"})," Tablet Mode"]}),e.jsx("button",{onClick:ie,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(u9,{className:"h-3 w-3"})})]})]})})]})}function Mxn(s){const{user:t}=ys();return ct({queryKey:["cohost-tokens",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_cohost_tokens").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(r)throw r;return n},enabled:!!t&&!!s})}function Ixn(){const s=Ht(),{user:t}=ys();return gt({mutationFn:async({openHouseId:n,label:r})=>{const{data:a,error:i}=await q.from("open_house_cohost_tokens").insert({open_house_id:n,label:r||null,created_by:t.id,expires_at:new Date(Date.now()+864e5).toISOString()}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["cohost-tokens",r.openHouseId]})}})}function Pxn(){const s=Ht();return gt({mutationFn:async({id:t,openHouseId:n})=>{const{error:r}=await q.from("open_house_cohost_tokens").update({is_active:!1}).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["cohost-tokens",n.openHouseId]})}})}function sKt(s){return ct({queryKey:["cohost-validate",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_house_cohost_tokens").select("*, open_houses(*)").eq("token",s).eq("is_active",!0).single();if(n)throw n;if(t.expires_at&&new Date(t.expires_at)t[n][r]??n,s)}var _Me="ScrollArea",[Tdt,Lxn]=pu(_Me),[rKt,Xv]=Tdt(_Me),Edt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:a,scrollHideDelay:i=600,...l}=s,[o,c]=N.useState(null),[d,u]=N.useState(null),[h,p]=N.useState(null),[f,g]=N.useState(null),[_,v]=N.useState(null),[j,b]=N.useState(0),[S,A]=N.useState(0),[T,L]=N.useState(!1),[D,M]=N.useState(!1),F=Si(t,V=>c(V)),z=NN(a);return e.jsx(rKt,{scope:n,type:r,dir:z,scrollHideDelay:i,scrollArea:o,viewport:d,onViewportChange:u,content:h,onContentChange:p,scrollbarX:f,onScrollbarXChange:g,scrollbarXEnabled:T,onScrollbarXEnabledChange:L,scrollbarY:_,onScrollbarYChange:v,scrollbarYEnabled:D,onScrollbarYEnabledChange:M,onCornerWidthChange:b,onCornerHeightChange:A,children:e.jsx(Jr.div,{dir:z,...l,ref:F,style:{position:"relative","--radix-scroll-area-corner-width":j+"px","--radix-scroll-area-corner-height":S+"px",...s.style}})})});Edt.displayName=_Me;var Adt="ScrollAreaViewport",Mdt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,children:r,nonce:a,...i}=s,l=Xv(Adt,n),o=N.useRef(null),c=Si(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(Jr.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})})]})});Mdt.displayName=Adt;var Zw="ScrollAreaScrollbar",wMe=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=Xv(Zw,s.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:l}=a,o=s.orientation==="horizontal";return N.useEffect(()=>(o?i(!0):l(!0),()=>{o?i(!1):l(!1)}),[o,i,l]),a.type==="hover"?e.jsx(aKt,{...r,ref:t,forceMount:n}):a.type==="scroll"?e.jsx(iKt,{...r,ref:t,forceMount:n}):a.type==="auto"?e.jsx(Idt,{...r,ref:t,forceMount:n}):a.type==="always"?e.jsx(jMe,{...r,ref:t}):null});wMe.displayName=Zw;var aKt=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=Xv(Zw,s.__scopeScrollArea),[i,l]=N.useState(!1);return N.useEffect(()=>{const o=a.scrollArea;let c=0;if(o){const d=()=>{window.clearTimeout(c),l(!0)},u=()=>{c=window.setTimeout(()=>l(!1),a.scrollHideDelay)};return o.addEventListener("pointerenter",d),o.addEventListener("pointerleave",u),()=>{window.clearTimeout(c),o.removeEventListener("pointerenter",d),o.removeEventListener("pointerleave",u)}}},[a.scrollArea,a.scrollHideDelay]),e.jsx(Rh,{present:n||i,children:e.jsx(Idt,{"data-state":i?"visible":"hidden",...r,ref:t})})}),iKt=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=Xv(Zw,s.__scopeScrollArea),i=s.orientation==="horizontal",l=jye(()=>c("SCROLL_END"),100),[o,c]=nKt("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return N.useEffect(()=>{if(o==="idle"){const d=window.setTimeout(()=>c("HIDE"),a.scrollHideDelay);return()=>window.clearTimeout(d)}},[o,a.scrollHideDelay,c]),N.useEffect(()=>{const d=a.viewport,u=i?"scrollLeft":"scrollTop";if(d){let h=d[u];const p=()=>{const f=d[u];h!==f&&(c("SCROLL"),l()),h=f};return d.addEventListener("scroll",p),()=>d.removeEventListener("scroll",p)}},[a.viewport,i,c,l]),e.jsx(Rh,{present:n||o!=="hidden",children:e.jsx(jMe,{"data-state":o==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:_r(s.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:_r(s.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),Idt=N.forwardRef((s,t)=>{const n=Xv(Zw,s.__scopeScrollArea),{forceMount:r,...a}=s,[i,l]=N.useState(!1),o=s.orientation==="horizontal",c=jye(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=s,a=Xv(Zw,s.__scopeScrollArea),i=N.useRef(null),l=N.useRef(0),[o,c]=N.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=Odt(o.viewport,o.content),u={...r,sizes:o,onSizesChange:c,hasThumb:d>0&&d<1,onThumbChange:p=>i.current=p,onThumbPointerUp:()=>l.current=0,onThumbPointerDown:p=>l.current=p};function h(p,f){return hKt(p,l.current,o,f)}return n==="horizontal"?e.jsx(oKt,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const p=a.viewport.scrollLeft,f=qBe(p,o,a.dir);i.current.style.transform=`translate3d(${f}px, 0, 0)`}},onWheelScroll:p=>{a.viewport&&(a.viewport.scrollLeft=p)},onDragScroll:p=>{a.viewport&&(a.viewport.scrollLeft=h(p,a.dir))}}):n==="vertical"?e.jsx(lKt,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const p=a.viewport.scrollTop,f=qBe(p,o);i.current.style.transform=`translate3d(0, ${f}px, 0)`}},onWheelScroll:p=>{a.viewport&&(a.viewport.scrollTop=p)},onDragScroll:p=>{a.viewport&&(a.viewport.scrollTop=h(p))}}):null}),oKt=N.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=Xv(Zw,s.__scopeScrollArea),[l,o]=N.useState(),c=N.useRef(null),d=Si(t,c,i.onScrollbarXChange);return N.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(Ldt,{"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":wye(n)+"px",...s.style},onThumbPointerDown:u=>s.onThumbPointerDown(u.x),onDragScroll:u=>s.onDragScroll(u.x),onWheelScroll:(u,h)=>{if(i.viewport){const p=i.viewport.scrollLeft+u.deltaX;s.onWheelScroll(p),zdt(p,h)&&u.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:ffe(l.paddingLeft),paddingEnd:ffe(l.paddingRight)}})}})}),lKt=N.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=Xv(Zw,s.__scopeScrollArea),[l,o]=N.useState(),c=N.useRef(null),d=Si(t,c,i.onScrollbarYChange);return N.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(Ldt,{"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":wye(n)+"px",...s.style},onThumbPointerDown:u=>s.onThumbPointerDown(u.y),onDragScroll:u=>s.onDragScroll(u.y),onWheelScroll:(u,h)=>{if(i.viewport){const p=i.viewport.scrollTop+u.deltaY;s.onWheelScroll(p),zdt(p,h)&&u.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:ffe(l.paddingTop),paddingEnd:ffe(l.paddingBottom)}})}})}),[cKt,Pdt]=Tdt(Zw),Ldt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:a,onThumbChange:i,onThumbPointerUp:l,onThumbPointerDown:o,onThumbPositionChange:c,onDragScroll:d,onWheelScroll:u,onResize:h,...p}=s,f=Xv(Zw,n),[g,_]=N.useState(null),v=Si(t,F=>_(F)),j=N.useRef(null),b=N.useRef(""),S=f.viewport,A=r.content-r.viewport,T=lh(u),L=lh(c),D=jye(h,10);function M(F){if(j.current){const z=F.clientX-j.current.left,V=F.clientY-j.current.top;d({x:z,y:V})}}return N.useEffect(()=>{const F=z=>{const V=z.target;(g==null?void 0:g.contains(V))&&T(z,A)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[S,g,A,T]),N.useEffect(L,[r,L]),N8(g,D),N8(f.content,D),e.jsx(cKt,{scope:n,scrollbar:g,hasThumb:a,onThumbChange:lh(i),onThumbPointerUp:lh(l),onThumbPositionChange:L,onThumbPointerDown:lh(o),children:e.jsx(Jr.div,{...p,ref:v,style:{position:"absolute",...p.style},onPointerDown:_r(s.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),j.current=g.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",f.viewport&&(f.viewport.style.scrollBehavior="auto"),M(F))}),onPointerMove:_r(s.onPointerMove,M),onPointerUp:_r(s.onPointerUp,F=>{const z=F.target;z.hasPointerCapture(F.pointerId)&&z.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=b.current,f.viewport&&(f.viewport.style.scrollBehavior=""),j.current=null})})})}),pfe="ScrollAreaThumb",Ddt=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=Pdt(pfe,s.__scopeScrollArea);return e.jsx(Rh,{present:n||a.hasThumb,children:e.jsx(dKt,{ref:t,...r})})}),dKt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,style:r,...a}=s,i=Xv(pfe,n),l=Pdt(pfe,n),{onThumbPositionChange:o}=l,c=Si(t,h=>l.onThumbChange(h)),d=N.useRef(void 0),u=jye(()=>{d.current&&(d.current(),d.current=void 0)},100);return N.useEffect(()=>{const h=i.viewport;if(h){const p=()=>{if(u(),!d.current){const f=mKt(h,o);d.current=f,o()}};return o(),h.addEventListener("scroll",p),()=>h.removeEventListener("scroll",p)}},[i.viewport,u,o]),e.jsx(Jr.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:_r(s.onPointerDownCapture,h=>{const f=h.target.getBoundingClientRect(),g=h.clientX-f.left,_=h.clientY-f.top;l.onThumbPointerDown({x:g,y:_})}),onPointerUp:_r(s.onPointerUp,l.onThumbPointerUp)})});Ddt.displayName=pfe;var NMe="ScrollAreaCorner",Rdt=N.forwardRef((s,t)=>{const n=Xv(NMe,s.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?e.jsx(uKt,{...s,ref:t}):null});Rdt.displayName=NMe;var uKt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,...r}=s,a=Xv(NMe,n),[i,l]=N.useState(0),[o,c]=N.useState(0),d=!!(i&&o);return N8(a.scrollbarX,()=>{var h;const u=((h=a.scrollbarX)==null?void 0:h.offsetHeight)||0;a.onCornerHeightChange(u),c(u)}),N8(a.scrollbarY,()=>{var h;const u=((h=a.scrollbarY)==null?void 0:h.offsetWidth)||0;a.onCornerWidthChange(u),l(u)}),d?e.jsx(Jr.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 ffe(s){return s?parseInt(s,10):0}function Odt(s,t){const n=s/t;return isNaN(n)?0:n}function wye(s){const t=Odt(s.viewport,s.content),n=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,r=(s.scrollbar.size-n)*t;return Math.max(r,18)}function hKt(s,t,n,r="ltr"){const a=wye(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 Fdt([c,d],h)(s)}function qBe(s,t,n="ltr"){const r=wye(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=cB(s,c);return Fdt([0,l],[0,o])(d)}function Fdt(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 zdt(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 jye(s,t){const n=lh(s),r=N.useRef(0);return N.useEffect(()=>()=>window.clearTimeout(r.current),[]),N.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function N8(s,t){const n=lh(t);mh(()=>{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 Bdt=Edt,pKt=Mdt,fKt=Rdt;const hi=N.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(Bdt,{ref:r,className:Et("relative overflow-hidden",s),...n,children:[e.jsx(pKt,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(iU,{}),e.jsx(fKt,{})]}));hi.displayName=Bdt.displayName;const iU=N.forwardRef(({className:s,orientation:t="vertical",...n},r)=>e.jsx(wMe,{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(Ddt,{className:"relative flex-1 rounded-full bg-border"})}));iU.displayName=wMe.displayName;const kMe=N.createContext({});function SMe(s){const t=N.useRef(null);return t.current===null&&(t.current=s()),t.current}const xKt=typeof window<"u",$dt=xKt?N.useLayoutEffect:N.useEffect,Nye=N.createContext(null);function CMe(s,t){s.indexOf(t)===-1&&s.push(t)}function xfe(s,t){const n=s.indexOf(t);n>-1&&s.splice(n,1)}const Iw=(s,t,n)=>n>t?t:n{},k8=()=>{};const P4={},Udt=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s);function qdt(s){return typeof s=="object"&&s!==null}const Vdt=s=>/^0[^.\s]+$/u.test(s);function Hdt(s){let t;return()=>(t===void 0&&(t=s()),t)}const $v=s=>s,gKt=(s,t)=>n=>t(s(n)),oU=(...s)=>s.reduce(gKt),hB=(s,t,n)=>{const r=t-s;return r===0?1:(n-s)/r};class TMe{constructor(){this.subscriptions=[]}add(t){return CMe(this.subscriptions,t),()=>xfe(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,Av=s=>s/1e3;function Gdt(s,t){return t?s*(1e3/t):0}const Wdt=(s,t,n)=>(((1-3*n+3*t)*s+(3*n-6*t))*s+3*t)*s,yKt=1e-7,vKt=12;function bKt(s,t,n,r,a){let i,l,o=0;do l=t+(n-t)/2,i=Wdt(l,r,a)-s,i>0?n=l:t=l;while(Math.abs(i)>yKt&&++obKt(i,0,1,s,n);return i=>i===0||i===1?i:Wdt(a(i),t,r)}const Kdt=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,Ydt=s=>t=>1-s(1-t),Zdt=lU(.33,1.53,.69,.99),EMe=Ydt(Zdt),Qdt=Kdt(EMe),Xdt=s=>s>=1?1:(s*=2)<1?.5*EMe(s):.5*(2-Math.pow(2,-10*(s-1))),AMe=s=>1-Math.sin(Math.acos(s)),Jdt=Ydt(AMe),eut=Kdt(AMe),_Kt=lU(.42,0,1,1),wKt=lU(0,0,.58,1),tut=lU(.42,0,.58,1),jKt=s=>Array.isArray(s)&&typeof s[0]!="number",sut=s=>Array.isArray(s)&&typeof s[0]=="number",VBe={linear:$v,easeIn:_Kt,easeInOut:tut,easeOut:wKt,circIn:AMe,circInOut:eut,circOut:Jdt,backIn:EMe,backInOut:Qdt,backOut:Zdt,anticipate:Xdt},NKt=s=>typeof s=="string",HBe=s=>{if(sut(s)){k8(s.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,r,a]=s;return lU(t,n,r,a)}else if(NKt(s))return k8(VBe[s]!==void 0,`Invalid easing type '${s}'`,"invalid-easing-type"),VBe[s];return s},iH=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],GBe={value:null,addProjectionMetrics:null};function kKt(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,p=!1,f=!1)=>{const _=f&&a?n:r;return p&&l.add(h),_.add(h),h},cancel:h=>{r.delete(h),l.delete(h)},process:h=>{if(o=h,a){i=!0;return}a=!0;const p=n;n=r,r=p,n.forEach(d),t&&GBe.value&&GBe.value.frameloop[t].push(c),c=0,n.clear(),a=!1,i&&(i=!1,u.process(h))}};return u}const SKt=40;function nut(s,t){let n=!1,r=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>n=!0,l=iH.reduce((S,A)=>(S[A]=kKt(i,t?A:void 0),S),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:u,update:h,preRender:p,render:f,postRender:g}=l,_=()=>{const S=P4.useManualTiming,A=S?a.timestamp:performance.now();n=!1,S||(a.delta=r?1e3/60:Math.max(Math.min(A-a.timestamp,SKt),1)),a.timestamp=A,a.isProcessing=!0,o.process(a),c.process(a),d.process(a),u.process(a),h.process(a),p.process(a),f.process(a),g.process(a),a.isProcessing=!1,n&&t&&(r=!1,s(_))},v=()=>{n=!0,r=!0,a.isProcessing||s(_)};return{schedule:iH.reduce((S,A)=>{const T=l[A];return S[A]=(L,D=!1,M=!1)=>(n||v(),T.schedule(L,D,M)),S},{}),cancel:S=>{for(let A=0;A(Pme===void 0&&Wx.set(tf.isProcessing||P4.useManualTiming?tf.timestamp:performance.now()),Pme),set:s=>{Pme=s,queueMicrotask(CKt)}},rut=s=>t=>typeof t=="string"&&t.startsWith(s),aut=rut("--"),TKt=rut("var(--"),MMe=s=>TKt(s)?EKt.test(s.split("/*")[0].trim()):!1,EKt=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function WBe(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const VD={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},mB={...VD,transform:s=>Iw(0,1,s)},oH={...VD,default:1},Z9=s=>Math.round(s*1e5)/1e5,IMe=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function AKt(s){return s==null}const MKt=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,PMe=(s,t)=>n=>!!(typeof n=="string"&&MKt.test(n)&&n.startsWith(s)||t&&!AKt(n)&&Object.prototype.hasOwnProperty.call(n,t)),iut=(s,t,n)=>r=>{if(typeof r!="string")return r;const[a,i,l,o]=r.match(IMe);return{[s]:parseFloat(a),[t]:parseFloat(i),[n]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},IKt=s=>Iw(0,255,s),fje={...VD,transform:s=>Math.round(IKt(s))},WE={test:PMe("rgb","red"),parse:iut("red","green","blue"),transform:({red:s,green:t,blue:n,alpha:r=1})=>"rgba("+fje.transform(s)+", "+fje.transform(t)+", "+fje.transform(n)+", "+Z9(mB.transform(r))+")"};function PKt(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 U4e={test:PMe("#"),parse:PKt,transform:WE.transform},cU=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),Bk=cU("deg"),jw=cU("%"),li=cU("px"),LKt=cU("vh"),DKt=cU("vw"),KBe={...jw,parse:s=>jw.parse(s)/100,transform:s=>jw.transform(s*100)},CP={test:PMe("hsl","hue"),parse:iut("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(s)+", "+jw.transform(Z9(t))+", "+jw.transform(Z9(n))+", "+Z9(mB.transform(r))+")"},Yh={test:s=>WE.test(s)||U4e.test(s)||CP.test(s),parse:s=>WE.test(s)?WE.parse(s):CP.test(s)?CP.parse(s):U4e.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?WE.transform(s):CP.transform(s),getAnimatableNone:s=>{const t=Yh.parse(s);return t.alpha=0,Yh.transform(t)}},RKt=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function OKt(s){var t,n;return isNaN(s)&&typeof s=="string"&&(((t=s.match(IMe))==null?void 0:t.length)||0)+(((n=s.match(RKt))==null?void 0:n.length)||0)>0}const out="number",lut="color",FKt="var",zKt="var(",YBe="${}",BKt=/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 S8(s){const t=s.toString(),n=[],r={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(BKt,c=>(Yh.test(c)?(r.color.push(i),a.push(lut),n.push(Yh.parse(c))):c.startsWith(zKt)?(r.var.push(i),a.push(FKt),n.push(c)):(r.number.push(i),a.push(out),n.push(parseFloat(c))),++i,YBe)).split(YBe);return{values:n,split:o,indexes:r,types:a}}function $Kt(s){return S8(s).values}function cut({split:s,types:t}){const n=s.length;return r=>{let a="";for(let i=0;itypeof s=="number"?0:Yh.test(s)?Yh.getAnimatableNone(s):s,VKt=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:qKt(s);function HKt(s){const t=S8(s);return cut(t)(t.values.map((r,a)=>VKt(r,t.split[a])))}const jb={test:OKt,parse:$Kt,createTransformer:UKt,getAnimatableNone:HKt};function xje(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 GKt({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=xje(c,o,s+1/3),i=xje(c,o,s),l=xje(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function gfe(s,t){return n=>n>0?t:s}const zd=(s,t,n)=>s+(t-s)*n,gje=(s,t,n)=>{const r=s*s,a=n*(t*t-r)+r;return a<0?0:Math.sqrt(a)},WKt=[U4e,WE,CP],KKt=s=>WKt.find(t=>t.test(s));function ZBe(s){const t=KKt(s);if(kye(!!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===CP&&(n=GKt(n)),n}const QBe=(s,t)=>{const n=ZBe(s),r=ZBe(t);if(!n||!r)return gfe(s,t);const a={...n};return i=>(a.red=gje(n.red,r.red,i),a.green=gje(n.green,r.green,i),a.blue=gje(n.blue,r.blue,i),a.alpha=zd(n.alpha,r.alpha,i),WE.transform(a))},q4e=new Set(["none","hidden"]);function YKt(s,t){return q4e.has(s)?n=>n<=0?s:t:n=>n>=1?t:s}function ZKt(s,t){return n=>zd(s,t,n)}function LMe(s){return typeof s=="number"?ZKt:typeof s=="string"?MMe(s)?gfe:Yh.test(s)?QBe:JKt:Array.isArray(s)?dut:typeof s=="object"?Yh.test(s)?QBe:QKt:gfe}function dut(s,t){const n=[...s],r=n.length,a=s.map((i,l)=>LMe(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in r)n[i]=r[i](a);return n}}function XKt(s,t){const n=[],r={color:0,var:0,number:0};for(let a=0;a{const n=jb.createTransformer(t),r=S8(s),a=S8(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?q4e.has(s)&&!a.values.length||q4e.has(t)&&!r.values.length?YKt(s,t):oU(dut(XKt(r,a),a.values),n):(kye(!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"),gfe(s,t))};function uut(s,t,n){return typeof s=="number"&&typeof t=="number"&&typeof n=="number"?zd(s,t,n):LMe(s)(s,t)}const eYt=s=>{const t=({timestamp:n})=>s(n);return{start:(n=!0)=>rd.update(t,n),stop:()=>L4(t),now:()=>tf.isProcessing?tf.timestamp:Wx.now()}},hut=(s,t,n=10)=>{let r="";const a=Math.max(Math.round(t/n),2);for(let i=0;i=yfe?1/0:t}function tYt(s,t=100,n){const r=n({...s,keyframes:[0,t]}),a=Math.min(DMe(r),yfe);return{type:"keyframes",ease:i=>r.next(a*i).value/t,duration:Av(a)}}const Su={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 V4e(s,t){return s*Math.sqrt(1-t*t)}const sYt=12;function nYt(s,t,n){let r=n;for(let a=1;a{const u=d*l,h=u*s,p=u-n,f=V4e(d,l),g=Math.exp(-h);return yje-p/f*g},i=d=>{const h=d*l*s,p=h*n+n,f=Math.pow(l,2)*Math.pow(d,2)*s,g=Math.exp(-h),_=V4e(Math.pow(d,2),l);return(-a(d)+yje>0?-1:1)*((p-f)*g)/_}):(a=d=>{const u=Math.exp(-d*s),h=(d-n)*s+1;return-yje+u*h},i=d=>{const u=Math.exp(-d*s),h=(n-d)*(s*s);return u*h});const o=5/s,c=nYt(a,i,o);if(s=Gg(s),isNaN(c))return{stiffness:Su.stiffness,damping:Su.damping,duration:s};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:s}}}const aYt=["duration","bounce"],iYt=["stiffness","damping","mass"];function XBe(s,t){return t.some(n=>s[n]!==void 0)}function oYt(s){let t={velocity:Su.velocity,stiffness:Su.stiffness,damping:Su.damping,mass:Su.mass,isResolvedFromDuration:!1,...s};if(!XBe(s,iYt)&&XBe(s,aYt))if(t.velocity=0,s.visualDuration){const n=s.visualDuration,r=2*Math.PI/(n*1.2),a=r*r,i=2*Iw(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:Su.mass,stiffness:a,damping:i}}else{const n=rYt({...s,velocity:0});t={...t,...n,mass:Su.mass},t.isResolvedFromDuration=!0}return t}function vfe(s=Su.visualDuration,t=Su.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:p,isResolvedFromDuration:f}=oYt({...n,velocity:-Av(n.velocity||0)}),g=p||0,_=d/(2*Math.sqrt(c*u)),v=l-i,j=Av(Math.sqrt(c/u)),b=Math.abs(v)<5;r||(r=b?Su.restSpeed.granular:Su.restSpeed.default),a||(a=b?Su.restDelta.granular:Su.restDelta.default);let S,A,T,L,D,M;if(_<1)T=V4e(j,_),L=(g+_*j*v)/T,S=z=>{const V=Math.exp(-_*j*z);return l-V*(L*Math.sin(T*z)+v*Math.cos(T*z))},D=_*j*L+v*T,M=_*j*v-L*T,A=z=>Math.exp(-_*j*z)*(D*Math.sin(T*z)+M*Math.cos(T*z));else if(_===1){S=V=>l-Math.exp(-j*V)*(v+(g+j*v)*V);const z=g+j*v;A=V=>Math.exp(-j*V)*(j*z*V-g)}else{const z=j*Math.sqrt(_*_-1);S=K=>{const J=Math.exp(-_*j*K),ne=Math.min(z*K,300);return l-J*((g+_*j*v)*Math.sinh(ne)+z*v*Math.cosh(ne))/z};const V=(g+_*j*v)/z,W=_*j*V-v*z,Y=_*j*v-V*z;A=K=>{const J=Math.exp(-_*j*K),ne=Math.min(z*K,300);return J*(W*Math.sinh(ne)+Y*Math.cosh(ne))}}const F={calculatedDuration:f&&h||null,velocity:z=>Gg(A(z)),next:z=>{if(!f&&_<1){const W=Math.exp(-_*j*z),Y=Math.sin(T*z),K=Math.cos(T*z),J=l-W*(L*Y+v*K),ne=Gg(W*(D*Y+M*K));return o.done=Math.abs(ne)<=r&&Math.abs(l-J)<=a,o.value=o.done?l:J,o}const V=S(z);if(f)o.done=z>=h;else{const W=Gg(A(z));o.done=Math.abs(W)<=r&&Math.abs(l-V)<=a}return o.value=o.done?l:V,o},toString:()=>{const z=Math.min(DMe(F),yfe),V=hut(W=>F.next(z*W).value,z,30);return z+"ms "+V},toTransition:()=>{}};return F}vfe.applyToOptions=s=>{const t=tYt(s,100,vfe);return s.ease=t.ease,s.duration=Gg(t.duration),s.type="keyframes",s};const lYt=5;function mut(s,t,n){const r=Math.max(t-lYt,0);return Gdt(n-s(r),t-r)}function H4e({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],p={done:!1,value:h},f=M=>o!==void 0&&Mc,g=M=>o===void 0?c:c===void 0||Math.abs(o-M)-_*Math.exp(-M/r),S=M=>j+b(M),A=M=>{const F=b(M),z=S(M);p.done=Math.abs(F)<=d,p.value=p.done?j:z};let T,L;const D=M=>{f(p.value)&&(T=M,L=vfe({keyframes:[p.value,g(p.value)],velocity:mut(S,M,p.value),damping:a,stiffness:i,restDelta:d,restSpeed:u}))};return D(0),{calculatedDuration:null,next:M=>{let F=!1;return!L&&T===void 0&&(F=!0,A(M),D(M)),T!==void 0&&M>=T?L.next(M-T):(!F&&A(M),p)}}}function cYt(s,t,n){const r=[],a=n||P4.mix||uut,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=cYt(t,r,a),c=o.length,d=u=>{if(l&&u1)for(;hd(Iw(s[0],s[i-1],u)):d}function uYt(s,t){const n=s[s.length-1];for(let r=1;r<=t;r++){const a=hB(0,t,r);s.push(zd(n,1,a))}}function hYt(s){const t=[0];return uYt(t,s.length-1),t}function mYt(s,t){return s.map(n=>n*t)}function pYt(s,t){return s.map(()=>t||tut).splice(0,s.length-1)}function Q9({duration:s=300,keyframes:t,times:n,ease:r="easeInOut"}){const a=jKt(r)?r.map(HBe):HBe(r),i={done:!1,value:t[0]},l=mYt(n&&n.length===t.length?n:hYt(t),s),o=dYt(l,t,{ease:Array.isArray(a)?a:pYt(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const fYt=s=>s!==null;function Sye(s,{repeat:t,repeatType:n="loop"},r,a=1){const i=s.filter(fYt),o=a<0||t&&n!=="loop"&&t%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const xYt={decay:H4e,inertia:H4e,tween:Q9,keyframes:Q9,spring:vfe};function put(s){typeof s.type=="string"&&(s.type=xYt[s.type])}class RMe{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 gYt=s=>s/100;class bfe extends RMe{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!==Wx.now()&&this.tick(Wx.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;put(t);const{type:n=Q9,repeat:r=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=n||Q9;c!==Q9&&typeof o[0]!="number"&&(this.mixKeyframes=oU(gYt,uut(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=DMe(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:p,repeatDelay:f,type:g,onUpdate:_,finalKeyframe:v}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-a/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const j=this.currentTime-d*(this.playbackSpeed>=0?1:-1),b=this.playbackSpeed>=0?j<0:j>a;this.currentTime=Math.max(j,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=a);let S=this.currentTime,A=r;if(h){const M=Math.min(this.currentTime,a)/o;let F=Math.floor(M),z=M%1;!z&&M>=1&&(z=1),z===1&&F--,F=Math.min(F,h+1),!!(F%2)&&(p==="reverse"?(z=1-z,f&&(z-=f/o)):p==="mirror"&&(A=l)),S=Iw(0,1,z)*o}let T;b?(this.delayState.value=u[0],T=this.delayState):T=A.next(S),i&&!b&&(T.value=i(T.value));let{done:L}=T;!b&&c!==null&&(L=this.playbackSpeed>=0?this.currentTime>=a:this.currentTime<=0);const D=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&L);return D&&g!==H4e&&(T.value=Sye(u,this.options,v,this.speed)),_&&_(T.value),D&&this.finish(),T}then(t,n){return this.finished.then(t,n)}get duration(){return Av(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Av(t)}get time(){return Av(this.currentTime)}set time(t){t=Gg(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 mut(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(Wx.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=Av(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=eYt,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(Wx.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 yYt(s){for(let t=1;ts*180/Math.PI,G4e=s=>{const t=KE(Math.atan2(s[1],s[0]));return W4e(t)},vYt={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:G4e,rotateZ:G4e,skewX:s=>KE(Math.atan(s[1])),skewY:s=>KE(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},W4e=s=>(s=s%360,s<0&&(s+=360),s),JBe=G4e,e$e=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),t$e=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),bYt={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:e$e,scaleY:t$e,scale:s=>(e$e(s)+t$e(s))/2,rotateX:s=>W4e(KE(Math.atan2(s[6],s[5]))),rotateY:s=>W4e(KE(Math.atan2(-s[2],s[0]))),rotateZ:JBe,rotate:JBe,skewX:s=>KE(Math.atan(s[4])),skewY:s=>KE(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function K4e(s){return s.includes("scale")?1:0}function Y4e(s,t){if(!s||s==="none")return K4e(t);const n=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,a;if(n)r=bYt,a=n;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=vYt,a=o}if(!a)return K4e(t);const i=r[t],l=a[1].split(",").map(wYt);return typeof i=="function"?i(l):l[i]}const _Yt=(s,t)=>{const{transform:n="none"}=getComputedStyle(s);return Y4e(n,t)};function wYt(s){return parseFloat(s.trim())}const HD=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],GD=new Set(HD),s$e=s=>s===VD||s===li,jYt=new Set(["x","y","z"]),NYt=HD.filter(s=>!jYt.has(s));function kYt(s){const t=[];return NYt.forEach(n=>{const r=s.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t}const MS={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})=>Y4e(t,"x"),y:(s,{transform:t})=>Y4e(t,"y")};MS.translateX=MS.x;MS.translateY=MS.y;const VA=new Set;let Z4e=!1,Q4e=!1,X4e=!1;function fut(){if(Q4e){const s=Array.from(VA).filter(r=>r.needsMeasurement),t=new Set(s.map(r=>r.element)),n=new Map;t.forEach(r=>{const a=kYt(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)})}Q4e=!1,Z4e=!1,VA.forEach(s=>s.complete(X4e)),VA.clear()}function xut(){VA.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(Q4e=!0)})}function SYt(){X4e=!0,xut(),fut(),X4e=!1}class OMe{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?(VA.add(this),Z4e||(Z4e=!0,rd.read(xut),rd.resolveKeyframes(fut))):(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])}yYt(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),VA.delete(this)}cancel(){this.state==="scheduled"&&(VA.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const CYt=s=>s.startsWith("--");function gut(s,t,n){CYt(t)?s.style.setProperty(t,n):s.style[t]=n}const TYt={};function yut(s,t){const n=Hdt(s);return()=>TYt[t]??n()}const EYt=yut(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),vut=yut(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),m7=([s,t,n,r])=>`cubic-bezier(${s}, ${t}, ${n}, ${r})`,n$e={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:m7([0,.65,.55,1]),circOut:m7([.55,0,1,.45]),backIn:m7([.31,.01,.66,-.59]),backOut:m7([.33,1.53,.69,.99])};function but(s,t){if(s)return typeof s=="function"?vut()?hut(s,t):"ease-out":sut(s)?m7(s):Array.isArray(s)?s.map(n=>but(n,t)||n$e.easeOut):n$e[s]}function AYt(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=but(o,a);Array.isArray(h)&&(u.easing=h);const p={delay:r,duration:a,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return d&&(p.pseudoElement=d),s.animate(u,p)}function _ut(s){return typeof s=="function"&&"applyToOptions"in s}function MYt({type:s,...t}){return _ut(s)&&vut()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class wut extends RMe{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,k8(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const d=MYt(t);this.animation=AYt(n,r,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const u=Sye(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(u),gut(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 Av(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Av(t)}get time(){return Av(Number(this.animation.currentTime)||0)}set time(t){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Gg(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&&EYt()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),r&&(this.animation.rangeEnd=r),$v):a(this)}}const jut={anticipate:Xdt,backInOut:Qdt,circInOut:eut};function IYt(s){return s in jut}function PYt(s){typeof s.ease=="string"&&IYt(s.ease)&&(s.ease=jut[s.ease])}const vje=10;class LYt extends wut{constructor(t){PYt(t),put(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 bfe({...l,autoplay:!1}),c=Math.max(vje,Wx.now()-this.startTime),d=Iw(0,vje,c-vje),u=o.sample(c).value,{name:h}=this.options;i&&h&&gut(i,h,u),n.setWithVelocity(o.sample(Math.max(0,c-d)).value,u,d),o.stop()}}const r$e=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(jb.test(s)||s==="0")&&!s.startsWith("url("));function DYt(s){const t=s[0];if(s.length===1)return!0;for(let n=0;nObject.hasOwnProperty.call(Element.prototype,"animate"));function $Yt(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 BYt()&&n&&(Nut.has(n)||zYt.has(n)&&FYt(o))&&(n!=="transform"||!u)&&!d&&!r&&a!=="mirror"&&i!==0&&l!=="inertia"}const UYt=40;class qYt extends RMe{constructor({autoplay:t=!0,delay:n=0,type:r="keyframes",repeat:a=0,repeatDelay:i=0,repeatType:l="loop",keyframes:o,name:c,motionValue:d,element:u,...h}){var g;super(),this.stop=()=>{var _,v;this._animation&&(this._animation.stop(),(_=this.stopTimeline)==null||_.call(this)),(v=this.keyframeResolver)==null||v.cancel()},this.createdAt=Wx.now();const p={autoplay:t,delay:n,type:r,repeat:a,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:u,...h},f=(u==null?void 0:u.KeyframeResolver)||OMe;this.keyframeResolver=new f(o,(_,v,j)=>this.onKeyframesResolved(_,v,p,!j),c,d,u),(g=this.keyframeResolver)==null||g.scheduleResolve()}onKeyframesResolved(t,n,r,a){var j,b;this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:u}=r;this.resolvedAt=Wx.now();let h=!0;RYt(t,i,l,o)||(h=!1,(P4.instantAnimations||!c)&&(u==null||u(Sye(t,r,n))),t[0]=t[t.length-1],J4e(r),r.repeat=0);const f={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>UYt?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...r,keyframes:t},g=h&&!d&&$Yt(f),_=(b=(j=f.motionValue)==null?void 0:j.owner)==null?void 0:b.current;let v;if(g)try{v=new LYt({...f,element:_})}catch{v=new bfe(f)}else v=new bfe(f);v.finished.then(()=>{this.notifyFinished()}).catch($v),this.pendingTimeline&&(this.stopTimeline=v.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=v}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){var t;return this._animation||((t=this.keyframeResolver)==null||t.resume(),SYt()),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 kut(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 VYt=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function HYt(s){const t=VYt.exec(s);if(!t)return[,];const[,n,r,a]=t;return[`--${n??r}`,a]}const GYt=4;function Sut(s,t,n=1){k8(n<=GYt,`Max CSS variable fallback depth detected in property "${s}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[r,a]=HYt(s);if(!r)return;const i=window.getComputedStyle(t).getPropertyValue(r);if(i){const l=i.trim();return Udt(l)?parseFloat(l):l}return MMe(a)?Sut(a,t,n+1):a}const WYt={type:"spring",stiffness:500,damping:25,restSpeed:10},KYt=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),YYt={type:"keyframes",duration:.8},ZYt={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},QYt=(s,{keyframes:t})=>t.length>2?YYt:GD.has(s)?s.startsWith("scale")?KYt(t[1]):WYt:ZYt;function Cut(s,t){if(s!=null&&s.inherit&&t){const{inherit:n,...r}=s;return{...t,...r}}return s}function FMe(s,t){const n=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return n!==s?Cut(n,s):n}const XYt=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function JYt(s){for(const t in s)if(!XYt.has(t))return!0;return!1}const zMe=(s,t,n,r={},a,i)=>l=>{const o=FMe(r,s)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-Gg(c);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...o,delay:-d,onUpdate:p=>{t.set(p),o.onUpdate&&o.onUpdate(p)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:s,motionValue:t,element:i?void 0:a};JYt(o)||Object.assign(u,QYt(s,u)),u.duration&&(u.duration=Gg(u.duration)),u.repeatDelay&&(u.repeatDelay=Gg(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(J4e(u),u.delay===0&&(h=!0)),(P4.instantAnimations||P4.skipAnimations||a!=null&&a.shouldSkipAnimations)&&(h=!0,J4e(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,h&&!i&&t.get()!==void 0){const p=Sye(u.keyframes,o);if(p!==void 0){rd.update(()=>{u.onUpdate(p),u.onComplete()});return}}return o.isSync?new bfe(u):new qYt(u)};function a$e(s){const t=[{},{}];return s==null||s.values.forEach((n,r)=>{t[0][r]=n.get(),t[1][r]=n.getVelocity()}),t}function BMe(s,t,n,r){if(typeof t=="function"){const[a,i]=a$e(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]=a$e(r);t=t(n!==void 0?n:s.custom,a,i)}return t}function HA(s,t,n){const r=s.getProps();return BMe(r,t,n!==void 0?n:r.custom,s)}const Tut=new Set(["width","height","top","left","right","bottom",...HD]),i$e=30,eZt=s=>!isNaN(parseFloat(s));class tZt{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const a=Wx.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=Wx.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=eZt(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 TMe);const r=this.events[t].add(n);return t==="change"?()=>{r(),rd.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=Wx.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>i$e)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,i$e);return Gdt(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 C8(s,t){return new tZt(s,t)}const eCe=s=>Array.isArray(s);function sZt(s,t,n){s.hasValue(t)?s.getValue(t).set(n):s.addValue(t,C8(n))}function nZt(s){return eCe(s)?s[s.length-1]||0:s}function rZt(s,t){const n=HA(s,t);let{transitionEnd:r={},transition:a={},...i}=n||{};i={...i,...r};for(const l in i){const o=nZt(i[l]);sZt(s,l,o)}}const df=s=>!!(s&&s.getVelocity);function aZt(s){return!!(df(s)&&s.add)}function tCe(s,t){const n=s.getValue("willChange");if(aZt(n))return n.add(t);if(!n&&P4.WillChange){const r=new P4.WillChange("auto");s.addValue("willChange",r),r.add(t)}}function $Me(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const iZt="framerAppearId",Eut="data-"+$Me(iZt);function Aut(s){return s.props[Eut]}function oZt({protectedKeys:s,needsAnimating:t},n){const r=s.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function Mut(s,t,{delay:n=0,transitionOverride:r,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?Cut(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 p in o){const f=s.getValue(p,s.latestValues[p]??null),g=o[p];if(g===void 0||h&&oZt(h,p))continue;const _={delay:n,...FMe(i||{},p)},v=f.get();if(v!==void 0&&!f.isAnimating()&&!Array.isArray(g)&&g===v&&!_.velocity){rd.update(()=>f.set(g));continue}let j=!1;if(window.MotionHandoffAnimation){const A=Aut(s);if(A){const T=window.MotionHandoffAnimation(A,p,rd);T!==null&&(_.startTime=T,j=!0)}}tCe(s,p);const b=d??s.shouldReduceMotion;f.start(zMe(p,f,g,b&&Tut.has(p)?{type:!1}:_,s,j));const S=f.animation;S&&u.push(S)}if(l){const p=()=>rd.update(()=>{l&&rZt(s,l)});u.length?Promise.all(u).then(p):p()}return u}function sCe(s,t,n={}){var c;const r=HA(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(Mut(s,r,n)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:u=0,staggerChildren:h,staggerDirection:p}=a;return lZt(s,t,d,u,h,p,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 lZt(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(sCe(c,t,{...l,delay:n+(typeof r=="function"?0:r)+kut(s.variantChildren,c,r,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function cZt(s,t,n={}){s.notify("AnimationStart",t);let r;if(Array.isArray(t)){const a=t.map(i=>sCe(s,i,n));r=Promise.all(a)}else if(typeof t=="string")r=sCe(s,t,n);else{const a=typeof t=="function"?HA(s,t,n.custom):t;r=Promise.all(Mut(s,a,n))}return r.then(()=>{s.notify("AnimationComplete",t)})}const dZt={test:s=>s==="auto",parse:s=>s},Iut=s=>t=>t.test(s),Put=[VD,li,jw,Bk,DKt,LKt,dZt],o$e=s=>Put.find(Iut(s));function uZt(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||Vdt(s):!0}const hZt=new Set(["brightness","contrast","saturate","opacity"]);function mZt(s){const[t,n]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[r]=n.match(IMe)||[];if(!r)return s;const a=n.replace(r,"");let i=hZt.has(t)?1:0;return r!==n&&(i*=100),t+"("+i+a+")"}const pZt=/\b([a-z-]*)\(.*?\)/gu,nCe={...jb,getAnimatableNone:s=>{const t=s.match(pZt);return t?t.map(mZt).join(" "):s}},rCe={...jb,getAnimatableNone:s=>{const t=jb.parse(s);return jb.createTransformer(s)(t.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},l$e={...VD,transform:Math.round},fZt={rotate:Bk,rotateX:Bk,rotateY:Bk,rotateZ:Bk,scale:oH,scaleX:oH,scaleY:oH,scaleZ:oH,skew:Bk,skewX:Bk,skewY:Bk,distance:li,translateX:li,translateY:li,translateZ:li,x:li,y:li,z:li,perspective:li,transformPerspective:li,opacity:mB,originX:KBe,originY:KBe,originZ:li},UMe={borderWidth:li,borderTopWidth:li,borderRightWidth:li,borderBottomWidth:li,borderLeftWidth:li,borderRadius:li,borderTopLeftRadius:li,borderTopRightRadius:li,borderBottomRightRadius:li,borderBottomLeftRadius:li,width:li,maxWidth:li,height:li,maxHeight:li,top:li,right:li,bottom:li,left:li,inset:li,insetBlock:li,insetBlockStart:li,insetBlockEnd:li,insetInline:li,insetInlineStart:li,insetInlineEnd:li,padding:li,paddingTop:li,paddingRight:li,paddingBottom:li,paddingLeft:li,paddingBlock:li,paddingBlockStart:li,paddingBlockEnd:li,paddingInline:li,paddingInlineStart:li,paddingInlineEnd:li,margin:li,marginTop:li,marginRight:li,marginBottom:li,marginLeft:li,marginBlock:li,marginBlockStart:li,marginBlockEnd:li,marginInline:li,marginInlineStart:li,marginInlineEnd:li,fontSize:li,backgroundPositionX:li,backgroundPositionY:li,...fZt,zIndex:l$e,fillOpacity:mB,strokeOpacity:mB,numOctaves:l$e},xZt={...UMe,color:Yh,backgroundColor:Yh,outlineColor:Yh,fill:Yh,stroke:Yh,borderColor:Yh,borderTopColor:Yh,borderRightColor:Yh,borderBottomColor:Yh,borderLeftColor:Yh,filter:nCe,WebkitFilter:nCe,mask:rCe,WebkitMask:rCe},Lut=s=>xZt[s],gZt=new Set([nCe,rCe]);function Dut(s,t){let n=Lut(s);return gZt.has(n)||(n=jb),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const yZt=new Set(["auto","none","0"]);function vZt(s,t,n){let r=0,a;for(;r{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function qMe(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 Rut=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function Lme(s){return qdt(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:VMe,cancel:Dxn}=nut(queueMicrotask,!1),q1={x:!1,y:!1};function Out(){return q1.x||q1.y}function _Zt(s){return s==="x"||s==="y"?q1[s]?null:(q1[s]=!0,()=>{q1[s]=!1}):q1.x||q1.y?null:(q1.x=q1.y=!0,()=>{q1.x=q1.y=!1})}function Fut(s,t){const n=qMe(s),r=new AbortController,a={passive:!0,...t,signal:r.signal};return[n,a,()=>r.abort()]}function wZt(s){return!(s.pointerType==="touch"||Out())}function jZt(s,t,n={}){const[r,a,i]=Fut(s,n);return r.forEach(l=>{let o=!1,c=!1,d;const u=()=>{l.removeEventListener("pointerleave",g)},h=v=>{d&&(d(v),d=void 0),u()},p=v=>{o=!1,window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",p),c&&(c=!1,h(v))},f=()=>{o=!0,window.addEventListener("pointerup",p,a),window.addEventListener("pointercancel",p,a)},g=v=>{if(v.pointerType!=="touch"){if(o){c=!0;return}h(v)}},_=v=>{if(!wZt(v))return;c=!1;const j=t(l,v);typeof j=="function"&&(d=j,l.addEventListener("pointerleave",g,a))};l.addEventListener("pointerenter",_,a),l.addEventListener("pointerdown",f,a)}),i}const zut=(s,t)=>t?s===t?!0:zut(s,t.parentElement):!1,HMe=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,NZt=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function kZt(s){return NZt.has(s.tagName)||s.isContentEditable===!0}const SZt=new Set(["INPUT","SELECT","TEXTAREA"]);function CZt(s){return SZt.has(s.tagName)||s.isContentEditable===!0}const Dme=new WeakSet;function c$e(s){return t=>{t.key==="Enter"&&s(t)}}function bje(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const TZt=(s,t)=>{const n=s.currentTarget;if(!n)return;const r=c$e(()=>{if(Dme.has(n))return;bje(n,"down");const a=c$e(()=>{bje(n,"up")}),i=()=>bje(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 d$e(s){return HMe(s)&&!Out()}const u$e=new WeakSet;function EZt(s,t,n={}){const[r,a,i]=Fut(s,n),l=o=>{const c=o.currentTarget;if(!d$e(o)||u$e.has(o))return;Dme.add(c),n.stopPropagation&&u$e.add(o);const d=t(c,o),u=(f,g)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",p),Dme.has(c)&&Dme.delete(c),d$e(f)&&typeof d=="function"&&d(f,{success:g})},h=f=>{u(f,c===window||c===document||n.useGlobalTarget||zut(c,f.target))},p=f=>{u(f,!1)};window.addEventListener("pointerup",h,a),window.addEventListener("pointercancel",p,a)};return r.forEach(o=>{(n.useGlobalTarget?window:o).addEventListener("pointerdown",l,a),Lme(o)&&(o.addEventListener("focus",d=>TZt(d,a)),!kZt(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function GMe(s){return qdt(s)&&"ownerSVGElement"in s}const Rme=new WeakMap;let $k;const But=(s,t,n)=>(r,a)=>a&&a[0]?a[0][s+"Size"]:GMe(r)&&"getBBox"in r?r.getBBox()[t]:r[n],AZt=But("inline","width","offsetWidth"),MZt=But("block","height","offsetHeight");function IZt({target:s,borderBoxSize:t}){var n;(n=Rme.get(s))==null||n.forEach(r=>{r(s,{get width(){return AZt(s,t)},get height(){return MZt(s,t)}})})}function PZt(s){s.forEach(IZt)}function LZt(){typeof ResizeObserver>"u"||($k=new ResizeObserver(PZt))}function DZt(s,t){$k||LZt();const n=qMe(s);return n.forEach(r=>{let a=Rme.get(r);a||(a=new Set,Rme.set(r,a)),a.add(t),$k==null||$k.observe(r)}),()=>{n.forEach(r=>{const a=Rme.get(r);a==null||a.delete(t),a!=null&&a.size||$k==null||$k.unobserve(r)})}}const Ome=new Set;let TP;function RZt(){TP=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};Ome.forEach(t=>t(s))},window.addEventListener("resize",TP)}function OZt(s){return Ome.add(s),TP||RZt(),()=>{Ome.delete(s),!Ome.size&&typeof TP=="function"&&(window.removeEventListener("resize",TP),TP=void 0)}}function h$e(s,t){return typeof s=="function"?OZt(s):DZt(s,t)}function FZt(s){return GMe(s)&&s.tagName==="svg"}const zZt=[...Put,Yh,jb],BZt=s=>zZt.find(Iut(s)),m$e=()=>({translate:0,scale:1,origin:0,originPoint:0}),EP=()=>({x:m$e(),y:m$e()}),p$e=()=>({min:0,max:0}),Em=()=>({x:p$e(),y:p$e()}),$Zt=new WeakMap;function Cye(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function pB(s){return typeof s=="string"||Array.isArray(s)}const WMe=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],KMe=["initial",...WMe];function Tye(s){return Cye(s.animate)||KMe.some(t=>pB(s[t]))}function $ut(s){return!!(Tye(s)||s.variants)}function UZt(s,t,n){for(const r in t){const a=t[r],i=n[r];if(df(a))s.addValue(r,a);else if(df(i))s.addValue(r,C8(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,C8(l!==void 0?l:a,{owner:s}))}}for(const r in n)t[r]===void 0&&s.removeValue(r);return t}const aCe={current:null},Uut={current:!1},qZt=typeof window<"u";function VZt(){if(Uut.current=!0,!!qZt)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>aCe.current=s.matches;s.addEventListener("change",t),t()}else aCe.current=!1}const f$e=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let _fe={};function qut(s){_fe=s}function HZt(){return _fe}class GZt{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=OMe,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const f=Wx.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(Uut.current||VZt(),this.shouldReduceMotion=aCe.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(),L4(this.notifyUpdate),L4(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&&Nut.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:u}=n.accelerate,h=new wut({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:Gg(u)}),p=l(h);this.valueSubscriptions.set(t,()=>{p(),h.cancel()});return}const r=GD.has(t);r&&this.onBindTransform&&this.onBindTransform();const a=n.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&rd.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 _fe){const n=_fe[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):Em()}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=C8(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"&&(Udt(r)||Vdt(r))?r=parseFloat(r):!BZt(r)&&jb.test(n)&&(r=Dut(t,n)),this.setBaseTarget(t,df(r)?r.get():r)),df(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=BMe(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&&!df(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 TMe),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){VMe.render(this.render)}}class Vut extends GZt{constructor(){super(...arguments),this.KeyframeResolver=bZt}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;df(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class J4{constructor(t){this.isMounted=!1,this.node=t}update(){}}function Hut({top:s,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:s,max:r}}}function WZt({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function KZt(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 _je(s){return s===void 0||s===1}function iCe({scale:s,scaleX:t,scaleY:n}){return!_je(s)||!_je(t)||!_je(n)}function ME(s){return iCe(s)||Gut(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function Gut(s){return x$e(s.x)||x$e(s.y)}function x$e(s){return s&&s!=="0%"}function wfe(s,t,n){const r=s-n,a=t*r;return n+a}function g$e(s,t,n,r,a){return a!==void 0&&(s=wfe(s,a,r)),wfe(s,n,r)+t}function oCe(s,t=0,n=1,r,a){s.min=g$e(s.min,t,n,r,a),s.max=g$e(s.max,t,n,r,a)}function Wut(s,{x:t,y:n}){oCe(s.x,t.translate,t.scale,t.originPoint),oCe(s.y,n.translate,n.scale,n.originPoint)}const y$e=.999999999999,v$e=1.0000000000001;function YZt(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;cy$e&&(t.x=1),t.yy$e&&(t.y=1)}function Z_(s,t){s.min+=t,s.max+=t}function b$e(s,t,n,r,a=.5){const i=zd(s.min,s.max,a);oCe(s,t,n,i,r)}function _$e(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function Fme(s,t,n){const r=n??s;b$e(s.x,_$e(t.x,r.x),t.scaleX,t.scale,t.originX),b$e(s.y,_$e(t.y,r.y),t.scaleY,t.scale,t.originY)}function Kut(s,t){return Hut(KZt(s.getBoundingClientRect(),t))}function ZZt(s,t,n){const r=Kut(s,n),{scroll:a}=t;return a&&(Z_(r.x,a.offset.x),Z_(r.y,a.offset.y)),r}const QZt={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},XZt=HD.length;function JZt(s,t,n){let r="",a=!0;for(let i=0;i{if(!t.target)return s;if(typeof s=="string")if(li.test(s))s=parseFloat(s);else return s;const n=w$e(s,t.target.x),r=w$e(s,t.target.y);return`${n}% ${r}%`}},eQt={correct:(s,{treeScale:t,projectionDelta:n})=>{const r=s,a=jb.parse(s);if(a.length>5)return r;const i=jb.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=zd(o,c,.5);return typeof a[2+l]=="number"&&(a[2+l]/=d),typeof a[3+l]=="number"&&(a[3+l]/=d),i(a)}},lCe={borderRadius:{...lF,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:lF,borderTopRightRadius:lF,borderBottomLeftRadius:lF,borderBottomRightRadius:lF,boxShadow:eQt};function Zut(s,{layout:t,layoutId:n}){return GD.has(s)||s.startsWith("origin")||(t||n!==void 0)&&(!!lCe[s]||s==="opacity")}function ZMe(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)(df(r[o])||a&&df(a[o])||Zut(o,s)||((l=n==null?void 0:n.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=r[o]);return i}function tQt(s){return window.getComputedStyle(s)}class sQt extends Vut{constructor(){super(...arguments),this.type="html",this.renderInstance=Yut}readValueFromInstance(t,n){var r;if(GD.has(n))return(r=this.projection)!=null&&r.isProjecting?K4e(n):_Yt(t,n);{const a=tQt(t),i=(aut(n)?a.getPropertyValue(n):a[n])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:n}){return Kut(t,n)}build(t,n,r){YMe(t,n,r.transformTemplate)}scrapeMotionValuesFromProps(t,n,r){return ZMe(t,n,r)}}const nQt={offset:"stroke-dashoffset",array:"stroke-dasharray"},rQt={offset:"strokeDashoffset",array:"strokeDasharray"};function aQt(s,t,n=1,r=0,a=!0){s.pathLength=1;const i=a?nQt:rQt;s[i.offset]=`${-r}`,s[i.array]=`${t} ${n}`}const iQt=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function Qut(s,{attrX:t,attrY:n,attrScale:r,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,u){if(YMe(s,o,d),c){s.style.viewBox&&(s.attrs.viewBox=s.style.viewBox);return}s.attrs=s.style,s.style={};const{attrs:h,style:p}=s;h.transform&&(p.transform=h.transform,delete h.transform),(p.transform||h.transformOrigin)&&(p.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),p.transform&&(p.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete h.transformBox);for(const f of iQt)h[f]!==void 0&&(p[f]=h[f],delete h[f]);t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),r!==void 0&&(h.scale=r),a!==void 0&&aQt(h,a,i,l,!1)}const Xut=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"]),Jut=s=>typeof s=="string"&&s.toLowerCase()==="svg";function oQt(s,t,n,r){Yut(s,t,void 0,r);for(const a in t.attrs)s.setAttribute(Xut.has(a)?a:$Me(a),t.attrs[a])}function eht(s,t,n){const r=ZMe(s,t,n);for(const a in s)if(df(s[a])||df(t[a])){const i=HD.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;r[i]=s[a]}return r}class lQt extends Vut{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Em}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(GD.has(n)){const r=Lut(n);return r&&r.default||0}return n=Xut.has(n)?n:$Me(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,r){return eht(t,n,r)}build(t,n,r){Qut(t,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(t,n,r,a){oQt(t,n,r,a)}mount(t){this.isSVGTag=Jut(t.tagName),super.mount(t)}}const cQt=KMe.length;function tht(s){if(!s)return;if(!s.isControllingVariants){const n=s.parent?tht(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})=>cZt(s,n,r)))}function mQt(s){let t=hQt(s),n=j$e(),r=!0,a=!1;const i=d=>(u,h)=>{var f;const p=HA(s,h,d==="exit"?(f=s.presenceContext)==null?void 0:f.custom:void 0);if(p){const{transition:g,transitionEnd:_,...v}=p;u={...u,...v,..._}}return u};function l(d){t=d(s)}function o(d){const{props:u}=s,h=tht(s.parent)||{},p=[],f=new Set;let g={},_=1/0;for(let j=0;j_&&T,z=!1;const V=Array.isArray(A)?A:[A];let W=V.reduce(i(b),{});L===!1&&(W={});const{prevResolvedValues:Y={}}=S,K={...Y,...W},J=he=>{F=!0,f.has(he)&&(z=!0,f.delete(he)),S.needsAnimating[he]=!0;const ce=s.getValue(he);ce&&(ce.liveStyle=!1)};for(const he in K){const ce=W[he],pe=Y[he];if(g.hasOwnProperty(he))continue;let le=!1;eCe(ce)&&eCe(pe)?le=!sht(ce,pe):le=ce!==pe,le?ce!=null?J(he):f.add(he):ce!==void 0&&f.has(he)?J(he):S.protectedKeys[he]=!0}S.prevProp=A,S.prevResolvedValues=W,S.isActive&&(g={...g,...W}),(r||a)&&s.blockInitialAnimation&&(F=!1);const ne=D&&M;F&&(!ne||z)&&p.push(...V.map(he=>{const ce={type:b};if(typeof he=="string"&&(r||a)&&!ne&&s.manuallyAnimateOnMount&&s.parent){const{parent:pe}=s,le=HA(pe,he);if(pe.enteringChildren&&le){const{delayChildren:ve}=le.transition||{};ce.delay=kut(pe.enteringChildren,s,ve)}}return{animation:he,options:ce}}))}if(f.size){const j={};if(typeof u.initial!="boolean"){const b=HA(s,Array.isArray(u.initial)?u.initial[0]:u.initial);b&&b.transition&&(j.transition=b.transition)}f.forEach(b=>{const S=s.getBaseTarget(b),A=s.getValue(b);A&&(A.liveStyle=!0),j[b]=S??null}),p.push({animation:j})}let v=!!p.length;return r&&(u.initial===!1||u.initial===u.animate)&&!s.manuallyAnimateOnMount&&(v=!1),r=!1,a=!1,v?t(p):Promise.resolve()}function c(d,u){var p;if(n[d].isActive===u)return Promise.resolve();(p=s.variantChildren)==null||p.forEach(f=>{var g;return(g=f.animationState)==null?void 0:g.setActive(d,u)}),n[d].isActive=u;const h=o(d);for(const f in n)n[f].protectedKeys={};return h}return{animateChanges:o,setActive:c,setAnimateFunction:l,getState:()=>n,reset:()=>{n=j$e(),a=!0}}}function pQt(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!sht(t,s):!1}function d3(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function j$e(){return{animate:d3(!0),whileInView:d3(),whileHover:d3(),whileTap:d3(),whileDrag:d3(),whileFocus:d3(),exit:d3()}}function cCe(s,t){s.min=t.min,s.max=t.max}function F1(s,t){cCe(s.x,t.x),cCe(s.y,t.y)}function N$e(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const nht=1e-4,fQt=1-nht,xQt=1+nht,rht=.01,gQt=0-rht,yQt=0+rht;function Kx(s){return s.max-s.min}function vQt(s,t,n){return Math.abs(s-t)<=n}function k$e(s,t,n,r=.5){s.origin=r,s.originPoint=zd(t.min,t.max,s.origin),s.scale=Kx(n)/Kx(t),s.translate=zd(n.min,n.max,s.origin)-s.originPoint,(s.scale>=fQt&&s.scale<=xQt||isNaN(s.scale))&&(s.scale=1),(s.translate>=gQt&&s.translate<=yQt||isNaN(s.translate))&&(s.translate=0)}function X9(s,t,n,r){k$e(s.x,t.x,n.x,r?r.originX:void 0),k$e(s.y,t.y,n.y,r?r.originY:void 0)}function S$e(s,t,n,r=0){const a=r?zd(n.min,n.max,r):n.min;s.min=a+t.min,s.max=s.min+Kx(t)}function bQt(s,t,n,r){S$e(s.x,t.x,n.x,r==null?void 0:r.x),S$e(s.y,t.y,n.y,r==null?void 0:r.y)}function C$e(s,t,n,r=0){const a=r?zd(n.min,n.max,r):n.min;s.min=t.min-a,s.max=s.min+Kx(t)}function jfe(s,t,n,r){C$e(s.x,t.x,n.x,r==null?void 0:r.x),C$e(s.y,t.y,n.y,r==null?void 0:r.y)}function T$e(s,t,n,r,a){return s-=t,s=wfe(s,1/n,r),a!==void 0&&(s=wfe(s,1/a,r)),s}function _Qt(s,t=0,n=1,r=.5,a,i=s,l=s){if(jw.test(t)&&(t=parseFloat(t),t=zd(l.min,l.max,t/100)-l.min),typeof t!="number")return;let o=zd(i.min,i.max,r);s===i&&(o-=t),s.min=T$e(s.min,t,n,o,a),s.max=T$e(s.max,t,n,o,a)}function E$e(s,t,[n,r,a],i,l){_Qt(s,t[n],t[r],t[a],t.scale,i,l)}const wQt=["x","scaleX","originX"],jQt=["y","scaleY","originY"];function A$e(s,t,n,r){E$e(s.x,t,wQt,n?n.x:void 0,r?r.x:void 0),E$e(s.y,t,jQt,n?n.y:void 0,r?r.y:void 0)}function M$e(s){return s.translate===0&&s.scale===1}function aht(s){return M$e(s.x)&&M$e(s.y)}function I$e(s,t){return s.min===t.min&&s.max===t.max}function NQt(s,t){return I$e(s.x,t.x)&&I$e(s.y,t.y)}function P$e(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function iht(s,t){return P$e(s.x,t.x)&&P$e(s.y,t.y)}function L$e(s){return Kx(s.x)/Kx(s.y)}function D$e(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function z_(s){return[s("x"),s("y")]}function kQt(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:p,skewX:f,skewY:g}=n;d&&(r=`perspective(${d}px) ${r}`),u&&(r+=`rotate(${u}deg) `),h&&(r+=`rotateX(${h}deg) `),p&&(r+=`rotateY(${p}deg) `),f&&(r+=`skewX(${f}deg) `),g&&(r+=`skewY(${g}deg) `)}const o=s.x.scale*t.x,c=s.y.scale*t.y;return(o!==1||c!==1)&&(r+=`scale(${o}, ${c})`),r||"none"}const oht=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],SQt=oht.length,R$e=s=>typeof s=="string"?parseFloat(s):s,O$e=s=>typeof s=="number"||li.test(s);function CQt(s,t,n,r,a,i){a?(s.opacity=zd(0,n.opacity??1,TQt(r)),s.opacityExit=zd(t.opacity??1,0,EQt(r))):i&&(s.opacity=zd(t.opacity??1,n.opacity??1,r));for(let l=0;lrt?1:n(hB(s,t,r))}function AQt(s,t,n){const r=df(s)?s:C8(s);return r.start(zMe("",r,t,n)),r.animation}function fB(s,t,n,r={passive:!0}){return s.addEventListener(t,n,r),()=>s.removeEventListener(t,n)}const MQt=(s,t)=>s.depth-t.depth;class IQt{constructor(){this.children=[],this.isDirty=!1}add(t){CMe(this.children,t),this.isDirty=!0}remove(t){xfe(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(MQt),this.isDirty=!1,this.children.forEach(t)}}function PQt(s,t){const n=Wx.now(),r=({timestamp:a})=>{const i=a-n;i>=t&&(L4(r),s(i-t))};return rd.setup(r,!0),()=>L4(r)}function zme(s){return df(s)?s.get():s}class LQt{constructor(){this.members=[]}add(t){CMe(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&&(xfe(this.members,r),r.unmount())}t.scheduleRender()}remove(t){if(xfe(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 Bme={hasAnimatedSinceResize:!0,hasEverUpdated:!1},wje=["","X","Y","Z"],DQt=1e3;let RQt=0;function jje(s,t,n,r){const{latestValues:a}=t;a[s]&&(n[s]=a[s],t.setStaticValue(s,0),r&&(r[s]=0))}function cht(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const n=Aut(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:a,layoutId:i}=s.options;window.MotionCancelOptimisedAnimation(n,"transform",rd,!(a||i))}const{parent:r}=s;r&&!r.hasCheckedOptimisedAppear&&cht(r)}function dht({attachResizeListener:s,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=RQt++,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(zQt),this.nodes.forEach(HQt),this.nodes.forEach(GQt),this.nodes.forEach(BQt)},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;rd.read(()=>{h=window.innerWidth}),s(l,()=>{const f=window.innerWidth;f!==h&&(h=f,this.root.updateBlockedByResize=!0,u&&u(),u=PQt(p,250),Bme.hasAnimatedSinceResize&&(Bme.hasAnimatedSinceResize=!1,this.nodes.forEach($$e)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:h,hasRelativeLayoutChanged:p,layout:f})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||QQt,{onLayoutAnimationStart:_,onLayoutAnimationComplete:v}=d.getProps(),j=!this.targetLayout||!iht(this.targetLayout,f),b=!h&&p;if(this.options.layoutRoot||this.resumeFrom||b||h&&(j||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const S={...FMe(g,"layout"),onPlay:_,onComplete:v};(d.shouldReduceMotion||this.options.layoutRoot)&&(S.delay=0,S.type=!1),this.startAnimation(S),this.setAnimationOrigin(u,b)}else h||$$e(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=f})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const l=this.getStack();l&&l.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),L4(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(WQt),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&&cht(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&&!Kx(this.snapshot.measuredBox.x)&&!Kx(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c{const T=A/1e3;U$e(h.x,l.x,T),U$e(h.y,l.y,T),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(jfe(p,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),YQt(this.relativeTarget,this.relativeTargetOrigin,p,T),S&&NQt(this.relativeTarget,S)&&(this.isProjectionDirty=!1),S||(S=Em()),F1(S,this.relativeTarget)),_&&(this.animationValues=u,CQt(u,d,this.latestValues,T,b,j)),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&&(L4(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=rd.update(()=>{Bme.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=C8(0)),this.motionValue.jump(0,!1),this.currentAnimation=AQt(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(DQt),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&&uht(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Em();const h=Kx(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const p=Kx(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+p}F1(o,c),Fme(o,u),X9(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new LQt),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&&jje("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(z$e),this.root.sharedNodes.clear()}}}function OQt(s){s.updateLayout()}function FQt(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")z_(h=>{const p=l?t.measuredBox[h]:t.layoutBox[h],f=Kx(p);p.min=r[h].min,p.max=p.min+f});else if(i==="x"||i==="y"){const h=i==="x"?"y":"x";cCe(l?t.measuredBox[h]:t.layoutBox[h],r[h])}else uht(i,t.layoutBox,r)&&z_(h=>{const p=l?t.measuredBox[h]:t.layoutBox[h],f=Kx(r[h]);p.max=p.min+f,s.relativeTarget&&!s.currentAnimation&&(s.isProjectionDirty=!0,s.relativeTarget[h].max=s.relativeTarget[h].min+f)});const o=EP();X9(o,r,t.layoutBox);const c=EP();l?X9(c,s.applyTransform(a,!0),t.measuredBox):X9(c,r,t.layoutBox);const d=!aht(o);let u=!1;if(!s.resumeFrom){const h=s.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:p,layout:f}=h;if(p&&f){const g=s.options.layoutAnchor||void 0,_=Em();jfe(_,t.layoutBox,p.layoutBox,g);const v=Em();jfe(v,r,f.layoutBox,g),iht(_,v)||(u=!0),h.options.layoutRoot&&(s.relativeTarget=v,s.relativeTargetOrigin=_,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 zQt(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 BQt(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function $Qt(s){s.clearSnapshot()}function z$e(s){s.clearMeasurements()}function UQt(s){s.isLayoutDirty=!0,s.updateLayout()}function B$e(s){s.isLayoutDirty=!1}function qQt(s){s.isAnimationBlocked&&s.layout&&!s.isLayoutDirty&&(s.snapshot=s.layout,s.isLayoutDirty=!0)}function VQt(s){const{visualElement:t}=s.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),s.resetTransform()}function $$e(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function HQt(s){s.resolveTargetDelta()}function GQt(s){s.calcProjection()}function WQt(s){s.resetSkewAndRotation()}function KQt(s){s.removeLeadSnapshot()}function U$e(s,t,n){s.translate=zd(t.translate,0,n),s.scale=zd(t.scale,1,n),s.origin=t.origin,s.originPoint=t.originPoint}function q$e(s,t,n,r){s.min=zd(t.min,n.min,r),s.max=zd(t.max,n.max,r)}function YQt(s,t,n,r){q$e(s.x,t.x,n.x,r),q$e(s.y,t.y,n.y,r)}function ZQt(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const QQt={duration:.45,ease:[.4,0,.1,1]},V$e=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),H$e=V$e("applewebkit/")&&!V$e("chrome/")?Math.round:$v;function G$e(s){s.min=H$e(s.min),s.max=H$e(s.max)}function XQt(s){G$e(s.x),G$e(s.y)}function uht(s,t,n){return s==="position"||s==="preserve-aspect"&&!vQt(L$e(t),L$e(n),.2)}function JQt(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const eXt=dht({attachResizeListener:(s,t)=>fB(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}),Nje={current:void 0},hht=dht({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!Nje.current){const s=new eXt({});s.mount(window),s.setOptions({layoutScroll:!0}),Nje.current=s}return Nje.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),QMe=N.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function W$e(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function tXt(...s){return t=>{let n=!1;const r=s.map(a=>{const i=W$e(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{width:f,height:g,top:_,left:v,right:j,bottom:b}=c.current;if(t||i===!1||!o.current||!f||!g)return;const S=n==="left"?`left: ${v}`:`right: ${j}`,A=r==="bottom"?`bottom: ${b}`:`top: ${_}`;o.current.dataset.motionPopId=l;const T=document.createElement("style");d&&(T.nonce=d);const L=a??document.head;return L.appendChild(T),T.sheet&&T.sheet.insertRule(` [data-motion-pop-id="${l}"] { position: absolute !important; width: ${f}px !important; height: ${g}px !important; ${S}px !important; ${A}px !important; } `),()=>{var D;(D=o.current)==null||D.removeAttribute("data-motion-pop-id"),L.contains(T)&&L.removeChild(T)}},[t]),e.jsx(nXt,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:N.cloneElement(s,{ref:h})})}const aXt=({children:s,initial:t,isPresent:n,onExitComplete:r,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const u=SMe(iXt),h=N.useId();let p=!0,f=N.useMemo(()=>(p=!1,{id:h,initial:t,isPresent:n,custom:a,onExitComplete:g=>{u.set(g,!0);for(const _ of u.values())if(!_)return;r&&r()},register:g=>(u.set(g,!1),()=>u.delete(g))}),[n,u,r]);return i&&p&&(f={...f}),N.useMemo(()=>{u.forEach((g,_)=>u.set(_,!1))},[n]),N.useEffect(()=>{!n&&!u.size&&r&&r()},[n]),s=e.jsx(rXt,{pop:l==="popLayout",isPresent:n,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(Nye.Provider,{value:f,children:s})};function iXt(){return new Map}function mht(s=!0){const t=N.useContext(Nye);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:r,register:a}=t,i=N.useId();N.useEffect(()=>{if(s)return a(i)},[s]);const l=N.useCallback(()=>s&&r&&r(i),[i,r,s]);return!n&&r?[!1,l]:[!0]}const lH=s=>s.key||"";function K$e(s){const t=[];return N.Children.forEach(s,n=>{N.isValidElement(n)&&t.push(n)}),t}const Eye=({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]=mht(l),p=N.useMemo(()=>K$e(s),[s]),f=l&&!u?[]:p.map(lH),g=N.useRef(!0),_=N.useRef(p),v=SMe(()=>new Map),j=N.useRef(new Set),[b,S]=N.useState(p),[A,T]=N.useState(p);$dt(()=>{g.current=!1,_.current=p;for(let M=0;M{const F=lH(M),z=l&&!u?!1:p===A||f.includes(F),V=()=>{if(j.current.has(F))return;if(v.has(F))j.current.add(F),v.set(F,!0);else return;let W=!0;v.forEach(Y=>{Y||(W=!1)}),W&&(D==null||D(),T(_.current),l&&(h==null||h()),r&&r())};return e.jsx(aXt,{isPresent:z,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:a,mode:i,root:d,onExitComplete:z?void 0:V,anchorX:o,anchorY:c,children:M},F)})})},pht=N.createContext({strict:!1}),Y$e={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 Z$e=!1;function oXt(){if(Z$e)return;const s={};for(const t in Y$e)s[t]={isEnabled:n=>Y$e[t].some(r=>!!n[r])};qut(s),Z$e=!0}function fht(){return oXt(),HZt()}function lXt(s){const t=fht();for(const n in s)t[n]={...t[n],...s[n]};qut(t)}const cXt=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 Nfe(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||cXt.has(s)}let xht=s=>!Nfe(s);function dXt(s){typeof s=="function"&&(xht=t=>t.startsWith("on")?!Nfe(t):s(t))}try{dXt(require("@emotion/is-prop-valid").default)}catch{}function uXt(s,t,n){const r={};for(const a in s)a==="values"&&typeof s.values=="object"||df(s[a])||(xht(a)||n===!0&&Nfe(a)||!t&&!Nfe(a)||s.draggable&&a.startsWith("onDrag"))&&(r[a]=s[a]);return r}const Aye=N.createContext({});function hXt(s,t){if(Tye(s)){const{initial:n,animate:r}=s;return{initial:n===!1||pB(n)?n:void 0,animate:pB(r)?r:void 0}}return s.inherit!==!1?t:{}}function mXt(s){const{initial:t,animate:n}=hXt(s,N.useContext(Aye));return N.useMemo(()=>({initial:t,animate:n}),[Q$e(t),Q$e(n)])}function Q$e(s){return Array.isArray(s)?s.join(" "):s}const XMe=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function ght(s,t,n){for(const r in t)!df(t[r])&&!Zut(r,n)&&(s[r]=t[r])}function pXt({transformTemplate:s},t){return N.useMemo(()=>{const n=XMe();return YMe(n,t,s),Object.assign({},n.vars,n.style)},[t])}function fXt(s,t){const n=s.style||{},r={};return ght(r,n,s),Object.assign(r,pXt(s,t)),r}function xXt(s,t){const n={},r=fXt(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 yht=()=>({...XMe(),attrs:{}});function gXt(s,t,n,r){const a=N.useMemo(()=>{const i=yht();return Qut(i,t,Jut(r),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};ght(i,s.style,s),a.style={...i,...a.style}}return a}const yXt=["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 JMe(s){return typeof s!="string"||s.includes("-")?!1:!!(yXt.indexOf(s)>-1||/[A-Z]/u.test(s))}function vXt(s,t,n,{latestValues:r},a,i=!1,l){const c=(l??JMe(s)?gXt:xXt)(t,r,a,s),d=uXt(t,typeof s=="string",i),u=s!==N.Fragment?{...d,...c,ref:n}:{},{children:h}=t,p=N.useMemo(()=>df(h)?h.get():h,[h]);return N.createElement(s,{...u,children:p})}function bXt({scrapeMotionValuesFromProps:s,createRenderState:t},n,r,a){return{latestValues:_Xt(n,r,a,s),renderState:t()}}function _Xt(s,t,n,r){const a={},i=r(s,{});for(const p in i)a[p]=zme(i[p]);let{initial:l,animate:o}=s;const c=Tye(s),d=$ut(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"&&!Cye(h)){const p=Array.isArray(h)?h:[h];for(let f=0;f(t,n)=>{const r=N.useContext(Aye),a=N.useContext(Nye),i=()=>bXt(s,t,r,a);return n?i():SMe(i)},wXt=vht({scrapeMotionValuesFromProps:ZMe,createRenderState:XMe}),jXt=vht({scrapeMotionValuesFromProps:eht,createRenderState:yht}),NXt=Symbol.for("motionComponentSymbol");function kXt(s,t,n){const r=N.useRef(n);N.useInsertionEffect(()=>{r.current=n});const a=N.useRef(null);return N.useCallback(i=>{var o;i&&((o=s.onMount)==null||o.call(s,i));const l=r.current;if(typeof l=="function")if(i){const c=l(i);typeof c=="function"&&(a.current=c)}else a.current?(a.current(),a.current=null):l(i);else l&&(l.current=i);t&&(i?t.mount(i):t.unmount())},[t])}const bht=N.createContext({});function rP(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function SXt(s,t,n,r,a,i){var S,A;const{visualElement:l}=N.useContext(Aye),o=N.useContext(pht),c=N.useContext(Nye),d=N.useContext(QMe),u=d.reducedMotion,h=d.skipAnimations,p=N.useRef(null),f=N.useRef(!1);r=r||o.renderer,!p.current&&r&&(p.current=r(s,{visualState:t,parent:l,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:h,isSVG:i}),f.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));const g=p.current,_=N.useContext(bht);g&&!g.projection&&a&&(g.type==="html"||g.type==="svg")&&CXt(p.current,n,a,_);const v=N.useRef(!1);N.useInsertionEffect(()=>{g&&v.current&&g.update(n,c)});const j=n[Eut],b=N.useRef(!!j&&typeof window<"u"&&!((S=window.MotionHandoffIsComplete)!=null&&S.call(window,j))&&((A=window.MotionHasOptimisedAnimation)==null?void 0:A.call(window,j)));return $dt(()=>{f.current=!0,g&&(v.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),b.current&&g.animationState&&g.animationState.animateChanges())}),N.useEffect(()=>{g&&(!b.current&&g.animationState&&g.animationState.animateChanges(),b.current&&(queueMicrotask(()=>{var T;(T=window.MotionHandoffMarkAsComplete)==null||T.call(window,j)}),b.current=!1),g.enteringChildren=void 0)}),g}function CXt(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:_ht(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&rP(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:h,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function _ht(s){if(s)return s.options.allowProjection!==!1?s.projection:_ht(s.parent)}function kje(s,{forwardMotionProps:t=!1,type:n}={},r,a){r&&lXt(r);const i=n?n==="svg":JMe(s),l=i?jXt:wXt;function o(d,u){let h;const p={...N.useContext(QMe),...d,layoutId:TXt(d)},{isStatic:f}=p,g=mXt(d),_=l(d,f);if(!f&&typeof window<"u"){EXt();const v=AXt(p);h=v.MeasureLayout,g.visualElement=SXt(s,_,p,a,v.ProjectionNode,i)}return e.jsxs(Aye.Provider,{value:g,children:[h&&g.visualElement?e.jsx(h,{visualElement:g.visualElement,...p}):null,vXt(s,d,kXt(_,g.visualElement,u),_,f,t,i)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const c=N.forwardRef(o);return c[NXt]=s,c}function TXt({layoutId:s}){const t=N.useContext(kMe).id;return t&&s!==void 0?t+"-"+s:s}function EXt(s,t){N.useContext(pht).strict}function AXt(s){const t=fht(),{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 MXt(s,t){if(typeof Proxy>"u")return kje;const n=new Map,r=(i,l)=>kje(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,kje(l,void 0,s,t)),n.get(l))})}const IXt=(s,t)=>t.isSVG??JMe(s)?new lQt(t):new sQt(t,{allowProjection:s!==N.Fragment});class PXt extends J4{constructor(t){super(t),t.animationState||(t.animationState=mQt(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Cye(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 LXt=0;class DXt extends J4{constructor(){super(...arguments),this.id=LXt++,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=HA(this.node,l,o);if(c){const{transition:d,transitionEnd:u,...h}=c;for(const p in h)(i=this.node.getValue(p))==null||i.jump(h[p])}}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 RXt={animation:{Feature:PXt},exit:{Feature:DXt}};function dU(s){return{point:{x:s.pageX,y:s.pageY}}}const OXt=s=>t=>HMe(t)&&s(t,dU(t));function J9(s,t,n,r){return fB(s,t,OXt(n),r)}const wht=({current:s})=>s?s.ownerDocument.defaultView:null,X$e=(s,t)=>Math.abs(s-t);function FXt(s,t){const n=X$e(s.x,t.x),r=X$e(s.y,t.y);return Math.sqrt(n**2+r**2)}const J$e=new Set(["auto","scroll"]);class jht{constructor(t,n,{transformPagePoint:r,contextWindow:a=window,dragSnapToOrigin:i=!1,distanceThreshold:l=3,element:o}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=f=>{this.handleScroll(f.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=cH(this.lastRawMoveEventInfo,this.transformPagePoint));const f=Sje(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,_=FXt(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!_)return;const{point:v}=f,{timestamp:j}=tf;this.history.push({...v,timestamp:j});const{onStart:b,onMove:S}=this.handlers;g||(b&&b(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),S&&S(this.lastMoveEvent,f)},this.handlePointerMove=(f,g)=>{this.lastMoveEvent=f,this.lastRawMoveEventInfo=g,this.lastMoveEventInfo=cH(g,this.transformPagePoint),rd.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:_,onSessionEnd:v,resumeAnimation:j}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&j&&j(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=Sje(f.type==="pointercancel"?this.lastMoveEventInfo:cH(g,this.transformPagePoint),this.history);this.startEvent&&_&&_(f,b),v&&v(f,b)},!HMe(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=a||window;const c=dU(t),d=cH(c,this.transformPagePoint),{point:u}=d,{timestamp:h}=tf;this.history=[{...u,timestamp:h}];const{onSessionStart:p}=n;p&&p(t,Sje(d,this.history)),this.removeListeners=oU(J9(this.contextWindow,"pointermove",this.handlePointerMove),J9(this.contextWindow,"pointerup",this.handlePointerUp),J9(this.contextWindow,"pointercancel",this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(t){let n=t.parentElement;for(;n;){const r=getComputedStyle(n);(J$e.has(r.overflowX)||J$e.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),rd.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),L4(this.updatePoint)}}function cH(s,t){return t?{point:t(s.point)}:s}function eUe(s,t){return{x:s.x-t.x,y:s.y-t.y}}function Sje({point:s},t){return{point:s,delta:eUe(s,Nht(t)),offset:eUe(s,zXt(t)),velocity:BXt(t,.1)}}function zXt(s){return s[0]}function Nht(s){return s[s.length-1]}function BXt(s,t){if(s.length<2)return{x:0,y:0};let n=s.length-1,r=null;const a=Nht(s);for(;n>=0&&(r=s[n],!(a.timestamp-r.timestamp>Gg(t)));)n--;if(!r)return{x:0,y:0};r===s[0]&&s.length>2&&a.timestamp-r.timestamp>Gg(t)*2&&(r=s[1]);const i=Av(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 $Xt(s,{min:t,max:n},r){return t!==void 0&&sn&&(s=r?zd(n,s,r.max):Math.min(s,n)),s}function tUe(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 UXt(s,{top:t,left:n,bottom:r,right:a}){return{x:tUe(s.x,n,a),y:tUe(s.y,t,r)}}function sUe(s,t){let n=t.min-s.min,r=t.max-s.max;return t.max-t.minr?n=hB(t.min,t.max-r,s.min):r>a&&(n=hB(s.min,s.max-a,t.min)),Iw(0,1,n)}function HXt(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 dCe=.35;function GXt(s=dCe){return s===!1?s=0:s===!0&&(s=dCe),{x:nUe(s,"left","right"),y:nUe(s,"top","bottom")}}function nUe(s,t,n){return{min:rUe(s,t),max:rUe(s,n)}}function rUe(s,t){return typeof s=="number"?s:s[t]||0}const WXt=new WeakMap;class KXt{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=Em(),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(dU(h).point),this.stopAnimation()},l=(h,p)=>{const{drag:f,dragPropagation:g,onDragStart:_}=this.getProps();if(f&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=_Zt(f),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=p,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),z_(j=>{let b=this.getAxisMotionValue(j).get()||0;if(jw.test(b)){const{projection:S}=this.visualElement;if(S&&S.layout){const A=S.layout.layoutBox[j];A&&(b=Kx(A)*(parseFloat(b)/100))}}this.originPoint[j]=b}),_&&rd.update(()=>_(h,p),!1,!0),tCe(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},o=(h,p)=>{this.latestPointerEvent=h,this.latestPanInfo=p;const{dragPropagation:f,dragDirectionLock:g,onDirectionLock:_,onDrag:v}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:j}=p;if(g&&this.currentDirection===null){this.currentDirection=ZXt(j),this.currentDirection!==null&&_&&_(this.currentDirection);return}this.updateAxis("x",p.point,j),this.updateAxis("y",p.point,j),this.visualElement.render(),v&&rd.update(()=>v(h,p),!1,!0)},c=(h,p)=>{this.latestPointerEvent=h,this.latestPanInfo=p,this.stop(h,p),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 jht(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:wht(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&&rd.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||!dH(t,a,this.currentDirection))return;const i=this.getAxisMotionValue(t);let l=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(l=$Xt(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&&rP(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&r?this.constraints=UXt(r.layoutBox,t):this.constraints=!1,this.elastic=GXt(n),a!==this.constraints&&!rP(t)&&r&&this.constraints&&!this.hasMutatedConstraints&&z_(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=HXt(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!rP(t))return!1;const r=t.current;k8(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=ZZt(r,a.root,this.visualElement.getTransformPagePoint());let l=qXt(a.layout.layoutBox,i);if(n){const o=n(WZt(l));this.hasMutatedConstraints=!!o,o&&(l=Hut(o))}return l}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=z_(u=>{if(!dH(u,n,this.currentDirection))return;let h=c&&c[u]||{};(l===!0||l===u)&&(h={min:0,max:0});const p=a?200:1e6,f=a?40:1e7,g={type:"inertia",velocity:r?t[u]:0,bounceStiffness:p,bounceDamping:f,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(u,g)});return Promise.all(d).then(o)}startAxisValueAnimation(t,n){const r=this.getAxisMotionValue(t);return tCe(this.visualElement,t),r.start(zMe(t,r,0,n,this.visualElement,!1))}stopAnimation(){z_(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){z_(n=>{const{drag:r}=this.getProps();if(!dH(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]-zd(l,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!rP(n)||!r||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};z_(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();a[l]=VXt({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(),z_(l=>{if(!dH(l,t,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(zd(c,d,a[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;WXt.set(this.visualElement,this);const t=this.visualElement.current,n=J9(t,"pointerdown",d=>{const{drag:u,dragListener:h=!0}=this.getProps(),p=d.target,f=p!==t&&CZt(p);u&&h&&!f&&this.start(d)});let r;const a=()=>{const{dragConstraints:d}=this.getProps();rP(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),r||(r=YXt(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,l=i.addEventListener("measure",a);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),rd.read(a);const o=fB(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(z_(h=>{const p=this.getAxisMotionValue(h);p&&(this.originPoint[h]+=d[h].translate,p.set(p.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=dCe,dragMomentum:o=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function aUe(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function YXt(s,t,n){const r=h$e(s,aUe(n)),a=h$e(t,aUe(n));return()=>{r(),a()}}function dH(s,t,n){return(t===!0||t===s)&&(n===null||n===s)}function ZXt(s,t=10){let n=null;return Math.abs(s.y)>t?n="y":Math.abs(s.x)>t&&(n="x"),n}class QXt extends J4{constructor(t){super(t),this.removeGroupControls=$v,this.removeListeners=$v,this.controls=new KXt(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||$v}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 Cje=s=>(t,n)=>{s&&rd.update(()=>s(t,n),!1,!0)};class XXt extends J4{constructor(){super(...arguments),this.removePointerDownListener=$v}onPointerDown(t){this.session=new jht(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:wht(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:a}=this.node.getProps();return{onSessionStart:Cje(t),onStart:Cje(n),onMove:Cje(r),onEnd:(i,l)=>{delete this.session,a&&rd.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=J9(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 Tje=!1;class JXt extends N.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r,layoutId:a}=this.props,{projection:i}=t;i&&(n.group&&n.group.add(i),r&&r.register&&a&&r.register(i),Tje&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Bme.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}),Tje=!0,a||t.layoutDependency!==n||n===void 0||t.isPresent!==i?l.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?l.promote():l.relegate()||rd.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(),VMe.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:a}=t;Tje=!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 kht(s){const[t,n]=mht(),r=N.useContext(kMe);return e.jsx(JXt,{...s,layoutGroup:r,switchLayoutGroup:N.useContext(bht),isPresent:t,safeToRemove:n})}const eJt={pan:{Feature:XXt},drag:{Feature:QXt,ProjectionNode:hht,MeasureLayout:kht}};function iUe(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&&rd.postRender(()=>i(t,dU(t)))}class tJt extends J4{mount(){const{current:t}=this.node;t&&(this.unmount=jZt(t,(n,r)=>(iUe(this.node,r,"Start"),a=>iUe(this.node,a,"End"))))}unmount(){}}class sJt extends J4{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=oU(fB(this.node.current,"focus",()=>this.onFocus()),fB(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function oUe(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&&rd.postRender(()=>i(t,dU(t)))}class nJt extends J4{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:r}=this.node.props;this.unmount=EZt(t,(a,i)=>(oUe(this.node,i,"Start"),(l,{success:o})=>oUe(this.node,l,o?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:(r==null?void 0:r.tap)===!1})}unmount(){}}const uCe=new WeakMap,Eje=new WeakMap,rJt=s=>{const t=uCe.get(s.target);t&&t(s)},aJt=s=>{s.forEach(rJt)};function iJt({root:s,...t}){const n=s||document;Eje.has(n)||Eje.set(n,{});const r=Eje.get(n),a=JSON.stringify(t);return r[a]||(r[a]=new IntersectionObserver(aJt,{root:s,...t})),r[a]}function oJt(s,t,n){const r=iJt(t);return uCe.set(s,n),r.observe(s),()=>{uCe.delete(s),r.unobserve(s)}}const lJt={some:0,all:1};class cJt extends J4{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:lJt[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:p}=this.node.getProps(),f=u?h:p;f&&f(d)};this.stopObserver=oJt(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(dJt(t,n))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function dJt({viewport:s={}},{viewport:t={}}={}){return n=>s[n]!==t[n]}const uJt={inView:{Feature:cJt},tap:{Feature:nJt},focus:{Feature:sJt},hover:{Feature:tJt}},hJt={layout:{ProjectionNode:hht,MeasureLayout:kht}},mJt={...RXt,...uJt,...eJt,...hJt},Yn=MXt(mJt,IXt),pJt={some:0,all:1};function fJt(s,t,{root:n,margin:r,amount:a="some"}={}){const i=qMe(s),l=new WeakMap,o=d=>{d.forEach(u=>{const h=l.get(u.target);if(u.isIntersecting!==!!h)if(u.isIntersecting){const p=t(u.target,u);typeof p=="function"?l.set(u.target,p):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:pJt[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function xJt(s,{root:t,margin:n,amount:r,once:a=!1,initial:i=!1}={}){const[l,o]=N.useState(i);return N.useEffect(()=>{if(!s.current||a&&l)return;const c=()=>(o(!0),a?void 0:()=>o(!1)),d={root:t&&t.current||void 0,margin:n,amount:r};return fJt(s.current,c,d)},[t,s,n,a,r]),l}function gJt(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 lUe(s){return s.visitor_intent==="buying"&&!s.has_agent}function yJt({token:s}={}){var g;const t=bi(),n=s||t.token,{data:r,isLoading:a,isError:i}=sKt(n),l=Ht(),o=(g=r==null?void 0:r.open_houses)==null?void 0:g.id,{data:c}=ct({queryKey:["cohost-visitors",o],queryFn:async()=>{const{data:_,error:v}=await q.from("open_house_visitors").select("*").eq("open_house_id",o).order("created_at",{ascending:!1});if(v)throw v;return _},enabled:!!o});if(N.useEffect(()=>{if(!o)return;const _=q.channel(`cohost-visitors-${o}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${o}`},()=>{l.invalidateQueries({queryKey:["cohost-visitors",o]})}).subscribe();return()=>{q.removeChannel(_)}},[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(_=>_.visitor_intent==="buying").length)||0,p=(c==null?void 0:c.filter(lUe).length)||0,f=_=>{if(!_)return"";const[v,j]=_.split(":"),b=parseInt(v);return`${b>12?b-12:b||12}:${j} ${b>=12?"PM":"AM"}`};return e.jsxs("div",{className:"fixed inset-0 bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex flex-col",children:[e.jsxs("div",{className:"border-b border-white/10 px-4 sm:px-6 py-3 flex items-center justify-between bg-black/30 backdrop-blur-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{className:"text-xs font-medium text-emerald-400 uppercase tracking-wider",children:"Live · Co-Host View"})]}),e.jsx("h1",{className:"text-white font-bold text-sm sm:text-base truncate",children:d.property_address})]}),e.jsxs("div",{className:"flex items-center gap-4 sm:gap-6 text-white/70",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Nn,{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(Dc,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:p})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Or,{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:Ss(new Date(d.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),d.start_time&&e.jsxs("span",{children:[f(d.start_time),d.end_time?` – ${f(d.end_time)}`:""]})]}),e.jsx(hi,{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(Eye,{children:c.map((_,v)=>{var S;const j=gJt(_.visitor_intent),b=lUe(_);return e.jsxs(Yn.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:v*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${b?"bg-orange-500/10 border-orange-500/30":"bg-white/5 border-white/10"}`,children:[e.jsx("div",{className:`w-11 h-11 rounded-full flex items-center justify-center text-lg font-bold shrink-0 ${b?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(S=_.first_name[0])==null?void 0:S.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:[_.first_name," ",_.last_name||""]}),b&&e.jsx(ze,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),_.has_agent&&e.jsx(ze,{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(ze,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${j.color}`,children:[j.emoji," ",j.label]}),e.jsx("span",{className:"text-white/30 text-xs",children:Ss(new Date(_.created_at),"h:mm a")})]})]})]},_.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(_f,{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 vJt(){const t=Jl().pathname.slice(1);if(N.useEffect(()=>(document.body.classList.add("guestbook-page"),()=>{document.body.classList.remove("guestbook-page")}),[]),t.startsWith("live/")){const n=t.slice(5);if(n)return e.jsx(yJt,{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(Cdt,{slug:t})}function bJt({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:"grayscale(0.4) brightness(0.45)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:o?"linear-gradient(180deg, hsl(0 0% 3% / 0.85) 0%, hsl(0 0% 5% / 0.75) 50%, hsl(0 0% 5%) 100%)":"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(Yn.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(Yn.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:"hsl(var(--portal-gold))"},children:((d=t.name)==null?void 0:d.charAt(0))||"?"}),e.jsx("p",{className:"portal-serif text-lg",style:{color:"hsl(var(--portal-ink))"},children:t.name}),e.jsx("p",{className:"text-[10px] mt-1 tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:c})]}),e.jsxs(Yn.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:"hsl(var(--portal-gold))"},children:[e.jsx(Or,{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:"hsl(var(--portal-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:"hsl(var(--portal-ink-muted))"},children:[e.jsx(ka,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}),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:"hsl(var(--portal-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:"hsl(var(--portal-gold))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Ar,{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:"hsl(var(--portal-gold))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Vs,{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:"hsl(var(--portal-gold))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Ql,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function Sht({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=Wv(a,new Date);if(ww(a)&&!cf(a))return null;const o=cf(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(Yn.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(Yn.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 Cht({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(Yn.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 Cl(s){const t=s.split(/[-/T]/);if(t.length>=3){const n=Number(t[0]);return n>99?new Date(n,Number(t[1])-1,Number(t[2])):new Date(Number(t[2]),Number(t[0])-1,Number(t[1]))}return new Date(`${s}T12:00:00`)}function _Jt(s,t){const n=Ss(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 wJt(s,t){const n=Ss(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 Eht({targetCloseDate:s,contractDate:t,inspectionDate:n,appraisalDate:r,actualCloseDate:a}){const i=[{label:"Contract",date:t,icon:G2},{label:"Inspection",date:n,icon:vr},{label:"Appraisal",date:r,icon:Or},{label:a?"Closed":"Target Close",date:a||s,icon:yr}].filter(o=>o.date);if(i.length===0)return null;const l=(o,c,d)=>{const u=Cl(c);if(d==="google")window.open(_Jt(o,u),"_blank");else{const h=wJt(o,u),p=document.createElement("a");p.href=h,p.download=`${o.replace(/\s+/g,"-").toLowerCase()}.ics`,p.click()}};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Milestones"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Key dates"}),e.jsxs("div",{className:"space-y-4 relative",children:[e.jsx("div",{className:"absolute left-[7px] top-2 bottom-2 w-[1px]",style:{background:"hsl(var(--portal-gold) / 0.15)"}}),i.map(({label:o,date:c,icon:d})=>{const u=Cl(c),h=ww(u)&&!cf(u),p=cf(u),f=!h&&!p;return e.jsxs("div",{className:"flex items-start gap-3 relative",children:[e.jsx("div",{className:"w-[15px] h-[15px] rounded-full mt-1 flex-shrink-0 relative z-10",style:{background:h?"hsl(var(--portal-gold) / 0.4)":p?"hsl(var(--portal-gold))":"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold))",boxShadow:p?"0 0 12px hsl(var(--portal-gold) / 0.6)":"none"}}),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:o}),e.jsxs("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.15rem",color:h?"hsl(var(--portal-ink-muted))":"hsl(var(--portal-ink))"},children:[Ss(u,"MMM d, yyyy"),p&&e.jsx("span",{className:"ml-2 text-[10px] tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-gold))"},children:"Today"})]})]}),f&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("button",{onClick:()=>l(o,c,"google"),className:"p-1.5 rounded transition-colors",style:{color:"hsl(var(--portal-ink-dim))"},onMouseEnter:g=>{g.currentTarget.style.color="hsl(var(--portal-gold))"},onMouseLeave:g=>{g.currentTarget.style.color="hsl(var(--portal-ink-dim))"},title:"Add to Google Calendar",children:e.jsx(Rg,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>l(o,c,"apple"),className:"text-[9px] tracking-widest px-1.5 py-1 rounded",style:{color:"hsl(var(--portal-ink-dim))"},title:"Download .ics",children:".ICS"})]})]},o)})]})]})}function Aht({documents:s}){const t=r=>r<1024?`${r} B`:r<1048576?`${(r/1024).toFixed(0)} KB`:`${(r/1048576).toFixed(1)} MB`,n=async r=>{const{data:a}=await q.storage.from("deal-files").createSignedUrl(r.storage_path,300);a!=null&&a.signedUrl&&window.open(a.signedUrl,"_blank")};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Paperwork"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents"}),e.jsx("div",{className:"space-y-2",children:s.map(r=>e.jsxs("button",{onClick:()=>n(r),className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left group",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.08)"},onMouseEnter:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.35)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.08)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx(Nr,{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(Pa,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},r.id))})]})}function Mht({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(em,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(im,{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:Ss(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 fe=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Et("rounded-lg border bg-card text-card-foreground shadow-sm",s),...t}));fe.displayName="Card";const Mt=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Et("flex flex-col space-y-1.5 p-6",s),...t}));Mt.displayName="CardHeader";const It=N.forwardRef(({className:s,...t},n)=>e.jsx("h3",{ref:n,className:Et("text-2xl font-semibold leading-none tracking-tight",s),...t}));It.displayName="CardTitle";const Vn=N.forwardRef(({className:s,...t},n)=>e.jsx("p",{ref:n,className:Et("text-sm text-muted-foreground",s),...t}));Vn.displayName="CardDescription";const Ee=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Et("p-6 pt-0",s),...t}));Ee.displayName="CardContent";const ez=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Et("flex items-center p-6 pt-0",s),...t}));ez.displayName="CardFooter";const WD=[{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"}],jJt=[{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 NJt(s){return ct({queryKey:["vendors","brokerage",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("vendors").select("*").eq("owner_type","brokerage").eq("owner_brokerage_id",s).order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function kJt(){const s=ma(),{brokerageId:t}=ys();return ct({queryKey:["vendors","library",s,t],queryFn:async()=>{if(!s)return{vendors:[],selections:[]};let n=q.from("vendors").select("*");t?n=n.or(`and(owner_type.eq.agent,owner_user_id.eq.${s}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${t})`):n=n.eq("owner_type","agent").eq("owner_user_id",s);const[{data:r,error:a},{data:i,error:l}]=await Promise.all([n.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),q.from("agent_vendor_selections").select("*").eq("agent_user_id",s)]);if(a)throw a;if(l)throw l;return{vendors:r||[],selections:i||[]}},enabled:!!s})}function SJt(){const s=Ht();return gt({mutationFn:async t=>{if(t.id){const{id:n,created_at:r,...a}=t,{data:i,error:l}=await q.from("vendors").update(a).eq("id",n).select().single();if(l)throw l;return i}else{const{data:n,error:r}=await q.from("vendors").insert(t).select().single();if(r)throw r;return n}},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function Iht(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("vendors").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function CJt(){const s=ma(),t=Ht();return gt({mutationFn:async({vendorId:n,isVisible:r})=>{if(!s)throw new Error("No user");const{data:a}=await q.from("agent_vendor_selections").select("id").eq("agent_user_id",s).eq("vendor_id",n).maybeSingle();if(a){const{error:i}=await q.from("agent_vendor_selections").update({is_visible:r}).eq("id",a.id);if(i)throw i}else{const{error:i}=await q.from("agent_vendor_selections").insert({agent_user_id:s,vendor_id:n,is_visible:r});if(i)throw i}},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function Pht(s){return ct({queryKey:["portal-vendors",s==null?void 0:s.id,s==null?void 0:s.owner_user_id],queryFn:async()=>{if(!(s!=null&&s.id)||!(s!=null&&s.owner_user_id))return[];const t=s.owner_user_id,{data:n}=await q.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),r=n==null?void 0:n.brokerage_id,a=q.from("vendors").select("*").eq("is_active",!0),i=r?a.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${r})`):a.eq("owner_type","agent").eq("owner_user_id",t),[{data:l,error:o},{data:c},{data:d}]=await Promise.all([i.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),q.from("agent_vendor_selections").select("vendor_id, display_order, is_visible").eq("agent_user_id",t),q.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s.id)]);if(o)throw o;const u=new Map;(c||[]).forEach(f=>u.set(f.vendor_id,{display_order:f.display_order,is_visible:f.is_visible}));const h=new Map;return(d||[]).forEach(f=>h.set(f.vendor_id,f.is_visible)),(l||[]).filter(f=>{if(h.get(f.id)===!1)return!1;const g=u.get(f.id);return!(g&&g.is_visible===!1&&!f.is_required)}).map(f=>{var g;return{...f,display_order:((g=u.get(f.id))==null?void 0:g.display_order)??f.sort_order??0}}).sort((f,g)=>(f.display_order||0)-(g.display_order||0))},enabled:!!(s!=null&&s.id)&&!!(s!=null&&s.owner_user_id)})}async function cUe(s){try{await q.from("vendor_clicks").insert({vendor_id:s.vendorId,portal_id:s.portalId||null,agent_user_id:s.agentUserId||null,action_taken:s.actionTaken||null,user_agent:typeof navigator<"u"?navigator.userAgent.slice(0,500):null})}catch(t){console.warn("vendor click track failed",t)}}function Lht(s,t){return ct({queryKey:["vendor-clicks",s,t],queryFn:async()=>{if(!t)return{};const{data:n}=await q.from("vendors").select("id").eq(s==="agent"?"owner_user_id":"owner_brokerage_id",t).eq("owner_type",s),r=(n||[]).map(l=>l.id);if(r.length===0)return{};const{data:a}=await q.from("vendor_clicks").select("vendor_id").in("vendor_id",r),i={};return(a||[]).forEach(l=>{i[l.vendor_id]=(i[l.vendor_id]||0)+1}),i},enabled:!!t})}function Dht({portalId:s,ownerUserId:t,currentStage:n,brandingColor:r,layout:a="list"}){const{data:i=[],isLoading:l}=Pht({id:s,owner_user_id:t});if(l||i.length===0)return null;const o=i.filter(b=>!b.stage_filter||b.stage_filter.length===0||!n?!0:b.stage_filter.includes(n));if(o.length===0)return null;const c=r||"#406E71",d=(b,S)=>{switch(S){case"book":return b.booking_url;case"website":return b.website;case"call":return b.phone?`tel:${b.phone.replace(/[^\d+]/g,"")}`:null;case"email":case"quote":return b.email?`mailto:${b.email}`:null}},u=b=>{const S=d(b,b.action_type);cUe({vendorId:b.id,portalId:s,agentUserId:t,actionTaken:b.action_type}),S&&window.open(S,b.action_type==="call"||b.action_type==="email"||b.action_type==="quote"?"_self":"_blank")},h=b=>{const S=d(b,b.action_type);return[{action:"website",label:"Website",icon:e.jsx(lc,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:e.jsx(Vs,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:e.jsx(Ar,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:e.jsx(yr,{className:"w-3.5 h-3.5"})}].filter(T=>T.action!==b.action_type).map(T=>{const L=d(b,T.action);return!L||L===S?null:e.jsxs("button",{onClick:()=>{cUe({vendorId:b.id,portalId:s,agentUserId:t,actionTaken:T.action}),window.open(L,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)},p=b=>{switch(b.action_type){case"book":return"Book Now";case"quote":return"Request Quote";case"call":return"Call";case"email":return"Email";case"website":return"Visit Site"}},f=b=>{switch(b.action_type){case"book":return e.jsx(yr,{className:"w-3.5 h-3.5"});case"call":return e.jsx(Ar,{className:"w-3.5 h-3.5"});case"email":case"quote":return e.jsx(Vs,{className:"w-3.5 h-3.5"});case"website":return e.jsx(lc,{className:"w-3.5 h-3.5"})}},g=b=>{var S;return((S=WD.find(A=>A.value===b))==null?void 0:S.label)||b},_=e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center",style:{backgroundColor:`${c}15`,color:c},children:e.jsx(un,{className:"w-4 h-4"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"font-semibold text-slate-800",children:"Trusted Partners"}),e.jsx("p",{className:"text-xs text-slate-500",children:"My personally-vetted recommendations for you"})]})]}),v=o.some(b=>b.disclosure_text)&&e.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:o.filter(b=>b.disclosure_text).map(b=>e.jsxs("p",{className:"text-[10px] text-slate-400",children:[e.jsxs("span",{className:"font-medium",children:[b.company||b.name,":"]})," ",b.disclosure_text]},b.id))});if(a==="grid")return e.jsxs(fe,{className:"p-5 sm:p-6 rounded-2xl border-slate-200/80 shadow-sm bg-white/70 backdrop-blur",children:[_,e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:o.map(b=>e.jsxs("div",{className:"group flex flex-col p-4 rounded-xl border border-slate-200/70 bg-white hover:shadow-md hover:-translate-y-0.5 transition-all",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg bg-slate-50 border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:b.logo_url?e.jsx("img",{src:b.logo_url,alt:b.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-base font-semibold text-slate-500",children:(b.company||b.name).charAt(0)})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-semibold text-sm text-slate-800 truncate",children:b.company||b.name}),b.company&&b.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:b.name}),e.jsx("span",{className:"inline-block mt-1 text-[10px] font-medium px-1.5 py-0.5 rounded",style:{backgroundColor:`${c}12`,color:c},children:g(b.category)})]})]}),b.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-3 line-clamp-2",children:b.description}),e.jsxs("div",{className:"mt-auto pt-4 flex flex-col gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>u(b),style:{backgroundColor:c},className:"text-white hover:opacity-90 w-full",children:[f(b),e.jsx("span",{className:"ml-1.5 text-xs",children:p(b)})]}),h(b).length>0&&e.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3",children:h(b)})]})]},b.id))}),v]});const j=o.reduce((b,S)=>((b[S.category]=b[S.category]||[]).push(S),b),{});return e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[_,e.jsx("div",{className:"space-y-4",children:Object.entries(j).map(([b,S])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:g(b)}),e.jsx("div",{className:"space-y-2",children:S.map(A=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-slate-50 hover:bg-slate-100 transition-colors",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-white border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:A.logo_url?e.jsx("img",{src:A.logo_url,alt:A.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-slate-500",children:A.name.charAt(0)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm text-slate-800 truncate",children:A.company||A.name}),A.company&&A.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:A.name}),A.description&&e.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:A.description})]}),e.jsxs(B,{size:"sm",onClick:()=>u(A),style:{backgroundColor:c},className:"text-white hover:opacity-90 shrink-0",children:[f(A),e.jsx("span",{className:"ml-1.5 text-xs",children:p(A)})]})]},A.id))})]},b))}),v]})}function TJt(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 EJt(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 Rht({portalId:s,portalSlug:t,ownerUserId:n,rewardText:r,ctaHeadline:a,agentName:i,clientName:l,reviewUrl:o,hubVideoUrl:c}){const[d,u]=N.useState(!1),h=N.useRef(!1),p=TJt(t);N.useEffect(()=>{h.current||(h.current=!0,q.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:"card_view",user_agent:navigator.userAgent.slice(0,500)}).then(()=>{}))},[s,n]);const f=async L=>{await q.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:L,user_agent:navigator.userAgent.slice(0,500)})},g=()=>`${l?`Hey, it's ${l}!`:"Hey!"} I just had an amazing experience working with ${i||"my real estate agent"} on my home. If you or someone you know is thinking about buying or selling, here's their referral link: ${p}`,_=async()=>{await navigator.clipboard.writeText(p),u(!0),f("copy_link"),setTimeout(()=>u(!1),2e3)},v=()=>{f("share_sms");const L=encodeURIComponent(g());window.location.href=`sms:?&body=${L}`},j=()=>{f("share_email");const L=encodeURIComponent("A referral you'll thank me for"),D=encodeURIComponent(g());window.location.href=`mailto:?subject=${L}&body=${D}`},b=()=>{f("open_form"),window.open(p,"_blank")},S=a||"Know someone buying or selling?",A=c?EJt(c):null,T=A==null?void 0:A.match(/\.(mp4|webm|mov)(\?|$)/i);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-gradient-to-br from-emerald-50 via-teal-50 to-cyan-50 rounded-2xl p-6 border border-emerald-100 text-center",children:[e.jsx("div",{className:"text-5xl mb-2",children:"🎉"}),e.jsxs("h3",{className:"text-xl font-bold text-emerald-900 mb-1 font-serif",children:["Welcome Home",l?`, ${l.split(" ")[0]}`:"","!"]}),e.jsx("p",{className:"text-sm text-emerald-700/80",children:"Your transaction is complete. We're so proud to have been part of your journey."})]}),A&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden",children:[e.jsx("div",{className:"px-4 pt-4 pb-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"w-4 h-4 text-[#406E71]"}),e.jsxs("p",{className:"text-sm font-medium text-slate-700",children:["A message from ",i||"your agent"]})]})}),e.jsx("div",{className:"aspect-video bg-slate-900",children:T?e.jsx("video",{src:A,controls:!0,className:"w-full h-full",playsInline:!0}):e.jsx("iframe",{src:A,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}),e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] via-[#345e7a] to-[#406E71] text-white shadow-xl",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.07]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"20px 20px"}}),e.jsxs("div",{className:"relative p-6",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/15 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium mb-3",children:[e.jsx(Oi,{className:"w-3 h-3"}),"Referral Program"]}),e.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:S}),r&&e.jsxs("p",{className:"text-sm text-white/85 mb-1",children:[e.jsx("span",{className:"font-semibold text-white",children:"Your reward:"})," ",r]}),e.jsxs("p",{className:"text-sm text-white/70 mb-5 leading-relaxed",children:["The biggest compliment you can give ",i||"us"," is sending a friend or family member."]}),e.jsxs("button",{onClick:b,className:"w-full bg-white text-[#2a4c64] font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 shadow-md hover:bg-white/95 active:scale-[0.99] transition-all",children:["Refer a Friend",e.jsx(Oa,{className:"w-4 h-4"})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[e.jsxs("button",{onClick:v,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(Ql,{className:"w-3.5 h-3.5"}),"Text"]}),e.jsxs("button",{onClick:j,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(Vs,{className:"w-3.5 h-3.5"}),"Email"]}),e.jsxs("button",{onClick:_,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[d?e.jsx(Ir,{className:"w-3.5 h-3.5"}):e.jsx(Xr,{className:"w-3.5 h-3.5"}),d?"Copied":"Copy"]})]})]})]}),o&&e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:()=>f("review_click"),className:"block bg-white border border-slate-200 hover:border-amber-300 hover:bg-amber-50/30 rounded-2xl p-4 transition-colors",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"text-2xl",children:"⭐"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-800",children:"Loved working together?"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Leave a quick review — it means the world."})]}),e.jsx(Oa,{className:"w-4 h-4 text-slate-400"})]})})]})}function AJt(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function MJt(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 IJt={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. 🎉"}},Oht=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function Mye(s){return Oht.map(t=>{if(t==="Active")return{key:"Active",label:AJt(s),description:MJt(s)};const n=IJt[t];return{key:t,label:n.label,description:n.description}})}function kfe(s){if(!s)return 0;const t=Oht.indexOf(s);return t>=0?t:0}function PJt({portal:s,linkedPortal:t,activePortal:n,activeTab:r,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var J,ne,ie;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",p=n==null?void 0:n.deal_pipeline,f=p==null?void 0:p.deal_pipeline_stages,g=f==null?void 0:f.is_won_stage,_=p==null?void 0:p.deal_type,v=n==null?void 0:n.stage_mapping;let j=Mye(_);v&&v.length>0&&(j=v.map((he,ce)=>{var pe,le;return{key:`custom-${ce}`,label:he.label||((pe=j[ce])==null?void 0:pe.label)||`Stage ${ce+1}`,description:he.description||((le=j[ce])==null?void 0:le.description)||"",video_url:he.video_url||void 0}}));const b=v&&v.length>0?Math.min(kfe(f==null?void 0:f.name),j.length-1):kfe(f==null?void 0:f.name),S=j[b],A=S==null?void 0:S.video_url,T=g&&n.show_post_close_tips!==!1&&n.referral_enabled!==!1,L=p!=null&&p.property_address?`${p.property_address}, ${p.city||""}, ${p.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,D=!!t,M=(J=s==null?void 0:s.deal_pipeline)==null?void 0:J.deal_type,F=(ne=t==null?void 0:t.deal_pipeline)==null?void 0:ne.deal_type,z=he=>he==="listing"?"Your Sale":he==="buy-side"?"Your Purchase":"Transaction",V=j.length>1?Math.round((b+1)/j.length*100):0,{data:W=[]}=Pht({id:n==null?void 0:n.id,owner_user_id:n==null?void 0:n.owner_user_id}),Y=W.some(he=>!he.stage_filter||he.stage_filter.length===0||!(f!=null&&f.name)?!0:he.stage_filter.includes(f.name)),K=()=>{var he;(he=document.getElementById("trusted-vendors"))==null||he.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(Yn.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(dh,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}}),"Secure & Encrypted"]})]}),e.jsxs(Yn.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:"grayscale(0.3) brightness(0.55)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, hsl(0 0% 3% / 0.4) 0%, hsl(0 0% 3% / 0.7) 55%, hsl(0 0% 5%) 100%)"}})]}):e.jsx("div",{className:"absolute inset-0",style:{background:"radial-gradient(ellipse 80% 60% at 20% 20%, hsl(var(--portal-gold) / 0.15), transparent 60%), radial-gradient(ellipse 80% 60% at 80% 80%, hsl(var(--portal-gold) / 0.08), transparent 60%), hsl(var(--portal-surface))"}}),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(var(--portal-gold) / 0.1)",border:"1px solid hsl(var(--portal-gold) / 0.3)",color:"hsl(var(--portal-gold))"},children:[e.jsx(Or,{className:"w-3 h-3"}),_==="listing"?"Sale":_==="buy-side"?"Purchase":"Transaction",g&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50 mx-1",children:"·"}),"Complete"]})]}),e.jsx("h1",{className:"portal-serif leading-[0.95] mb-4",style:{fontSize:"4.5rem",color:"hsl(var(--portal-ink))"},children:(p==null?void 0:p.deal_name)||"Your Transaction"}),e.jsx("div",{className:"portal-hairline w-32 mb-5"}),L&&e.jsxs("div",{className:"flex items-center gap-2",style:{color:"hsl(var(--portal-ink-muted))"},children:[e.jsx(ka,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}}),e.jsx("span",{className:"text-base",children:L})]}),(n==null?void 0:n.welcome_message)&&e.jsxs("p",{className:"mt-6 portal-serif italic leading-relaxed max-w-2xl",style:{color:"hsl(var(--portal-ink-muted))",fontSize:"1.15rem"},children:["“",n.welcome_message,"”"]})]}),e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx(LJt,{pct:V}),e.jsx("p",{className:"portal-eyebrow mt-4",children:"Journey Progress"}),e.jsxs("p",{className:"portal-serif mt-1",style:{fontSize:"1.1rem",color:"hsl(var(--portal-ink))"},children:["Stage ",b+1," of ",j.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)"}})]}),D&&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(he=>{const ce=he==="primary"?M:F,pe=r===he;return e.jsx("button",{onClick:()=>a(he),className:"portal-serif px-5 py-2 rounded-lg transition-all",style:{fontSize:"1rem",background:pe?"hsl(var(--portal-surface-3))":"transparent",color:pe?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",borderBottom:pe?"1px solid hsl(var(--portal-gold))":"1px solid transparent"},children:z(ce)},he)})}),e.jsxs(Yn.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(Sk,{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:((ie=i==null?void 0:i.name)==null?void 0:ie.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(Aje,{href:`tel:${i.phone}`,icon:Ar,label:"Call",sub:i.phone}),(i==null?void 0:i.phone)&&e.jsx(Aje,{href:`sms:${i.phone}`,icon:Ql,label:"Text message"}),(i==null?void 0:i.email)&&e.jsx(Aje,{href:`mailto:${i.email}`,icon:Vs,label:"Email",sub:i.email})]})]}),e.jsxs(Sk,{children:[e.jsx("p",{className:"portal-eyebrow mb-4",children:"At a Glance"}),e.jsxs("div",{className:"space-y-4",children:[(p==null?void 0:p.target_close_date)&&e.jsx(Mje,{icon:yr,label:"Target close",value:dUe(p.target_close_date)}),(p==null?void 0:p.contract_date)&&e.jsx(Mje,{icon:gr,label:"Under contract",value:dUe(p.contract_date)}),e.jsx(Mje,{icon:io,label:"Progress",value:`${V}%`})]})]})]})}),e.jsxs("main",{className:"col-span-6 space-y-5",children:[T&&e.jsx(Rht,{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(Sht,{targetCloseDate:p==null?void 0:p.target_close_date,actualCloseDate:p==null?void 0:p.actual_close_date,clientName:n.client_name}),S&&e.jsx(Sk,{children:e.jsx(Tht,{currentStage:S,nextStepText:n.next_step_text,nextStepVideoUrl:A||n.next_step_video_url})}),e.jsx(Sk,{children:e.jsx(Cht,{journeyStages:j,currentIndex:b})}),o&&o.length>0&&e.jsx(Sk,{children:e.jsx(Mht,{updates:o})})]}),e.jsxs("aside",{className:"col-span-3 space-y-5",children:[e.jsx(Sk,{children:e.jsx(Eht,{targetCloseDate:p==null?void 0:p.target_close_date,contractDate:p==null?void 0:p.contract_date,inspectionDate:n.inspection_date,appraisalDate:n.appraisal_date,actualCloseDate:p==null?void 0:p.actual_close_date})}),c&&c.length>0&&e.jsx(Sk,{children:e.jsx(Aht,{documents:c})}),Y&&e.jsx(Sk,{children:e.jsxs("button",{onClick:K,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:he=>{he.currentTarget.style.background="hsl(var(--portal-gold) / 0.12)"},onMouseLeave:he=>{he.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(A9,{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(io,{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(Dht,{portalId:n.id,ownerUserId:n.owner_user_id,currentStage:f==null?void 0:f.name,brandingColor:"#c9a84c",layout:"grid"})})]})]})}function Sk({children:s}){return e.jsx(Yn.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 Aje({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 Mje({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 LJt({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:"hsl(44, 51%, 54%)"}),e.jsx("stop",{offset:"100%",stopColor:"hsl(44, 74%, 74%)"})]})}),e.jsx("circle",{cx:170/2,cy:170/2,r:78,stroke:"hsl(44, 40%, 55%, 0.15)",strokeWidth:2,fill:"none"}),e.jsx(Yn.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(44, 74%, 74%, 0.6))"}})]}),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:"hsl(var(--portal-gold))"},children:s}),e.jsx("span",{className:"text-[10px] tracking-[0.25em] uppercase mt-1",style:{color:"hsl(var(--portal-ink-dim))"},children:"percent"})]})]})}function dUe(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 DJt({portal:s,dealData:t,agentProfile:n,customQuestions:r,deviceFingerprint:a,onComplete:i}){var v,j;const[l,o]=N.useState({first_name:((v=s.client_name)==null?void 0:v.split(" ")[0])||"",last_name:((j=s.client_name)==null?void 0:j.split(" ").slice(1).join(" "))||"",email:s.client_email||"",phone:s.client_phone||"",preferred_contact_method:"email",client_role:"buyer",notes:"",spouse_first_name:"",spouse_last_name:"",spouse_email:"",spouse_phone:""}),[c,d]=N.useState({}),[u,h]=N.useState(!1),p=gt({mutationFn:async()=>{const{error:b}=await q.from("portal_onboarding_submissions").insert({portal_id:s.id,first_name:l.first_name,last_name:l.last_name||null,email:l.email||null,phone:l.phone||null,preferred_contact_method:l.preferred_contact_method,client_role:l.client_role,notes:l.notes||null,device_fingerprint:a,custom_answers:Object.keys(c).length>0?c:null,spouse_first_name:u&&l.spouse_first_name||null,spouse_last_name:u&&l.spouse_last_name||null,spouse_email:u&&l.spouse_email||null,spouse_phone:u&&l.spouse_phone||null});if(b)throw b},onSuccess:i,onError:b=>{console.error("[PortalOnboarding] Submit failed:",b),ae.error("Something went wrong. Please try again.")}}),f=t!=null&&t.property_address?`${t.property_address}, ${t.city||""}, ${t.state||""}`:null,g="mt-1 rounded-xl bg-white text-slate-900 placeholder:text-slate-400 border-slate-200 focus-visible:ring-slate-400",_="mt-1 w-full rounded-xl border border-slate-200 bg-white text-slate-900 placeholder:text-slate-400 px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400";return e.jsx("div",{className:"max-w-md mx-auto px-4 py-10",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl ring-1 ring-slate-200 p-6 sm:p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[(n==null?void 0:n.avatar_url)&&e.jsx("img",{src:n.avatar_url,alt:n.name,className:"w-16 h-16 rounded-full border-2 border-slate-200 mx-auto mb-3 object-cover"}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"Welcome to Your Portal"}),f&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[e.jsx(ka,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:f.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Please fill in your details to access your transaction portal."})]}),e.jsxs("form",{onSubmit:b=>{b.preventDefault(),p.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:b=>o(S=>({...S,first_name:b.target.value})),className:g,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:b=>o(S=>({...S,last_name:b.target.value})),className:g,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:b=>o(S=>({...S,email:b.target.value})),className:g,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:b=>o(S=>({...S,phone:b.target.value})),className:g,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(b=>e.jsx("button",{type:"button",onClick:()=>o(S=>({...S,preferred_contact_method:b.value})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.preferred_contact_method===b.value?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:b.label},b.value))})]}),e.jsxs("div",{children:[e.jsx(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(b=>e.jsx("button",{type:"button",onClick:()=>o(S=>({...S,client_role:b})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.client_role===b?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:b.charAt(0).toUpperCase()+b.slice(1)},b))})]}),r.map(b=>e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs font-medium text-slate-700",children:[b.question_text," ",b.is_required&&"*"]}),b.field_type==="text"&&e.jsx(ye,{required:b.is_required,value:c[b.id]||"",onChange:S=>d(A=>({...A,[b.id]:S.target.value})),className:g}),b.field_type==="textarea"&&e.jsx("textarea",{required:b.is_required,value:c[b.id]||"",onChange:S=>d(A=>({...A,[b.id]:S.target.value})),className:`${_} min-h-[80px]`}),b.field_type==="dropdown"&&e.jsxs("select",{required:b.is_required,value:c[b.id]||"",onChange:S=>d(A=>({...A,[b.id]:S.target.value})),className:`${_} h-10`,children:[e.jsx("option",{value:"",children:"Select..."}),(b.options||[]).map(S=>e.jsx("option",{value:S,children:S},S))]}),b.field_type==="toggle"&&e.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(S=>e.jsx("button",{type:"button",onClick:()=>d(A=>({...A,[b.id]:S})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c[b.id]===S?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:S},S))})]},b.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:b=>o(S=>({...S,notes:b.target.value})),className:`${_} 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:b=>o(S=>({...S,spouse_first_name:b.target.value})),className:g})]}),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:b=>o(S=>({...S,spouse_last_name:b.target.value})),className:g})]})]}),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:b=>o(S=>({...S,spouse_email:b.target.value})),className:g})]}),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:b=>o(S=>({...S,spouse_phone:b.target.value})),className:g})]})]})]}),e.jsx(B,{type:"submit",disabled:p.isPending||!l.first_name,className:"w-full h-12 rounded-full text-sm font-semibold bg-slate-900 hover:bg-slate-800",children:p.isPending?"Submitting...":"Access My Portal"})]})]})})}function RJt(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)}}function Fht(){const s=ma();return ct({queryKey:["agent-portal-branding",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_portal_branding").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function OJt(s){return ct({queryKey:["agent-portal-branding-public",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_portal_branding").select("logo_url, cover_photo_url, brand_color, accent_color, tagline, welcome_message").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function FJt(){const s=ma(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("agent_portal_branding").upsert({user_id:s,...n},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-portal-branding",s]}),t.invalidateQueries({queryKey:["agent-portal-branding-public",s]})}})}async function zht(s,t,n){var o;const r=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${n}-${Date.now()}.${r}`,{error:i}=await q.storage.from("portal-branding").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=q.storage.from("portal-branding").getPublicUrl(a);return l.publicUrl}function zJt(s,t){return ct({queryKey:["client-portal-public",s],queryFn:async()=>{if(!s)return null;const{data:n,error:r}=await q.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, 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 BJt(s){return ct({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, 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 Bht({slug:s}){var ie,he,ce,pe,le,ve;const[t,n]=N.useState(!1),[r,a]=N.useState("primary"),[i]=N.useState(()=>{const ge=`portal_fp_${s}`;let Te=localStorage.getItem(ge);return Te||(Te=localStorage.getItem("portal_fp"),Te?localStorage.setItem(ge,Te):(Te=crypto.randomUUID(),localStorage.setItem(ge,Te),localStorage.setItem("portal_fp",Te))),Te});N.useEffect(()=>(document.body.classList.add("client-portal-page","portal-theme-noir"),()=>document.body.classList.remove("client-portal-page","portal-theme-noir")),[]);const{data:l,isLoading:o,error:c}=zJt(s,!0),d=l==null?void 0:l.linked_portal_id,{data:u}=BJt(d),h=(ie=l==null?void 0:l.deal_pipeline)==null?void 0:ie.owner_user_id;ct({queryKey:["portal-stages",h],queryFn:async()=>{const{data:ge,error:Te}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",h).order("sort_order",{ascending:!0});if(Te)throw Te;return ge},enabled:!!h});const{data:p}=ct({queryKey:["portal-agent",h],queryFn:async()=>{const{data:ge,error:Te}=await q.from("profiles").select("id, name, avatar_url, phone, email").eq("id",h).single();if(Te)throw Te;return ge},enabled:!!h}),{data:f}=OJt(h),g=r==="linked"&&u?u:l,_=g==null?void 0:g.id,v=RJt(f,g==null?void 0:g.branding_override),{data:j}=ct({queryKey:["portal-updates-public",_],queryFn:async()=>{const{data:ge,error:Te}=await q.from("portal_updates").select("*").eq("portal_id",_).order("created_at",{ascending:!1});if(Te)throw Te;return ge},enabled:!!_}),b=(he=g==null?void 0:g.deal_pipeline)==null?void 0:he.id,{data:S}=ct({queryKey:["portal-documents",b],queryFn:async()=>{const{data:ge,error:Te}=await q.from("deal_files").select("*").eq("deal_id",b).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(Te)throw Te;return ge},enabled:!!b}),A=l==null?void 0:l.id,T=A?`portal_onboarded_${A}_${i}`:null,L=T?localStorage.getItem(T)==="1":!1,{data:D,isLoading:M}=ct({queryKey:["portal-onboarding-check",A,i],queryFn:async()=>{const{data:ge,error:Te}=await q.from("portal_onboarding_submissions").select("id").eq("portal_id",A).eq("device_fingerprint",i).maybeSingle();if(Te)throw Te;return ge&&T&&localStorage.setItem(T,"1"),ge},enabled:!!A&&!!(l!=null&&l.require_onboarding)&&!L,staleTime:5*60*1e3}),F=!!(l!=null&&l.require_onboarding)&&!L&&!D&&!t,{data:z}=ct({queryKey:["portal-custom-questions-public",h],queryFn:async()=>{const{data:ge,error:Te}=await q.from("portal_custom_questions").select("*").eq("owner_user_id",h).eq("is_active",!0).order("sort_order",{ascending:!0});if(Te)throw Te;return ge},enabled:!!h&&F}),V=L||!!D||t||!(l!=null&&l.require_onboarding);if(o||l!=null&&l.require_onboarding&&!L&&M)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:"hsl(var(--portal-bg))"},children:e.jsx(ts,{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(dh,{className:"w-6 h-6",style:{color:"hsl(var(--portal-gold))"}})}),e.jsx("h1",{className:"portal-serif text-4xl mb-3",style:{color:"hsl(var(--portal-ink))"},children:"Portal Not Available"}),e.jsx("div",{className:"portal-hairline mx-auto w-24 mb-4"}),e.jsx("p",{className:"text-sm",style:{color:"hsl(var(--portal-ink-muted))"},children:"This portal is no longer active or doesn't exist."})]})});if(!V){const ge=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(DJt,{portal:l,dealData:ge,agentProfile:p,customQuestions:z||[],deviceFingerprint:i,onComplete:()=>{T&&localStorage.setItem(T,"1"),n(!0)}})})}const W=(ce=l==null?void 0:l.deal_pipeline)==null?void 0:ce.deal_type,Y=(pe=u==null?void 0:u.deal_pipeline)==null?void 0:pe.deal_type,K=!!u,J=ge=>ge==="listing"?"Your Sale":ge==="buy-side"?"Your Purchase":"Transaction",ne=ge=>ge==="listing"?e.jsx(Or,{className:"w-3.5 h-3.5"}):e.jsx(Vg,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx(PJt,{portal:l,linkedPortal:u,activePortal:g,activeTab:r,onTabChange:a,agentProfile:p,branding:v,updates:j,documents:S})}),e.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx(bJt,{dealData:g==null?void 0:g.deal_pipeline,agentProfile:p,welcomeMessage:(g==null?void 0:g.welcome_message)||v.welcome_message,isWon:(ve=(le=g==null?void 0:g.deal_pipeline)==null?void 0:le.deal_pipeline_stages)==null?void 0:ve.is_won_stage,branding:v}),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(ge=>{const Te=r===ge,Me=ge==="primary"?W:Y;return e.jsxs("button",{onClick:()=>a(ge),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:Te?"hsl(var(--portal-surface-3))":"transparent",color:Te?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",boxShadow:Te?"0 1px 0 hsl(var(--portal-gold) / 0.3) inset":"none"},children:[ne(Me),e.jsx("span",{style:{fontSize:"1rem"},children:J(Me)})]},ge)})}),e.jsx($Jt,{portal:g,updates:j,documents:S,agentProfile:p}),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(dh,{className:"w-3 h-3"}),e.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase",children:"Secure Client Portal"})]}),p&&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:p.name})]})]})]})]})]})}function $Jt({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=Mye(c);d&&d.length>0&&(u=d.map((_,v)=>{var j,b;return{key:`custom-${v}`,label:_.label||((j=u[v])==null?void 0:j.label)||`Stage ${v+1}`,description:_.description||((b=u[v])==null?void 0:b.description)||"",video_url:_.video_url||void 0}}));const h=d&&d.length>0?Math.min(kfe(l==null?void 0:l.name),u.length-1):kfe(l==null?void 0:l.name),p=u[h],f=p==null?void 0:p.video_url,g=o&&s.show_post_close_tips!==!1&&s.referral_enabled!==!1;return e.jsxs(e.Fragment,{children:[g&&e.jsx(Rht,{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(Sht,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(Cht,{journeyStages:u,currentIndex:h}),p&&e.jsx(Tht,{currentStage:p,nextStepText:s.next_step_text,nextStepVideoUrl:f||s.next_step_video_url}),e.jsx(Eht,{targetCloseDate:i==null?void 0:i.target_close_date,contractDate:i==null?void 0:i.contract_date,inspectionDate:s.inspection_date,appraisalDate:s.appraisal_date,actualCloseDate:i==null?void 0:i.actual_close_date}),n&&n.length>0&&e.jsx(Aht,{documents:n}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx(Dht,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(Mht,{updates:t})]})}function $ht({slug:s}){const t=bi(),n=s||t.slug,[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(""),[_,v]=N.useState(""),[j,b]=N.useState("buying"),[S,A]=N.useState("");N.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:T,isLoading:L,error:D}=ct({queryKey:["portal-referral-target",n],queryFn:async()=>{if(!n)return null;const{data:z,error:V}=await q.from("client_portals").select(` id, slug, owner_user_id, client_name, referral_enabled, referral_reward_text, referral_cta_headline, is_enabled `).eq("slug",n).eq("is_enabled",!0).maybeSingle();if(V)throw V;return z},enabled:!!n}),{data:M}=ct({queryKey:["portal-referral-agent",T==null?void 0:T.owner_user_id],queryFn:async()=>{const{data:z}=await q.from("profiles").select("id, name, avatar_url").eq("id",T.owner_user_id).single();return z},enabled:!!(T!=null&&T.owner_user_id)}),F=async z=>{if(z.preventDefault(),!T||!h.trim()){ae.error("Please enter your friend's name");return}if(!f.trim()&&!_.trim()){ae.error("Please add at least an email or phone for your friend");return}a(!0);try{const{error:V}=await q.from("portal_referrals").insert({portal_id:T.id,owner_user_id:T.owner_user_id,referrer_name:o.trim()||T.client_name||null,referrer_email:d.trim()||null,friend_name:h.trim(),friend_email:f.trim()||null,friend_phone:_.trim()||null,friend_interest:j,friend_message:S.trim()||null});if(V)throw V;l(!0)}catch(V){ae.error(V.message||"Could not submit referral")}finally{a(!1)}};return L?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsx(Ws,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):D||!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(Ir,{className:"w-8 h-8 text-emerald-600"})}),e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2 font-serif",children:"Thank you! 🙏"}),e.jsxs("p",{className:"text-sm text-slate-600 leading-relaxed mb-6",children:["Your referral has been sent to ",(M==null?void 0:M.name)||"your agent",". They'll reach out to"," ",e.jsx("span",{className:"font-semibold text-slate-800",children:h})," personally and treat them like family."]}),e.jsxs("button",{onClick:()=>window.history.back(),className:"inline-flex items-center gap-2 text-sm text-[#406E71] hover:text-[#2a4c64] font-medium",children:[e.jsx(Hr,{className:"w-4 h-4"}),"Back to your portal"]})]})}):e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white pb-12",children:[e.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] via-[#345e7a] to-[#406E71] text-white px-4 pt-10 pb-12 overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.05]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"24px 24px"}}),e.jsxs("div",{className:"relative max-w-lg mx-auto text-center",children:[M!=null&&M.avatar_url?e.jsx("img",{src:M.avatar_url,alt:M.name||"Agent",className:"w-16 h-16 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 object-cover"}):e.jsx("div",{className:"w-16 h-16 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 bg-white/10 flex items-center justify-center",children:e.jsx(Oi,{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(Oi,{className:"w-3 h-3"})," Referral"]}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children:T.referral_cta_headline||"Refer a Friend"}),e.jsxs("p",{className:"text-sm text-white/70",children:["Send ",(M==null?void 0:M.name)||"your agent"," someone you trust."]}),T.referral_reward_text&&e.jsxs("p",{className:"text-xs text-white/60 mt-2",children:["You'll get: ",e.jsx("span",{className:"text-white font-medium",children:T.referral_reward_text})," when they close."]})]})]}),e.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-6 relative z-10",children:e.jsxs("form",{onSubmit:F,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:z=>p(z.target.value),placeholder:"Jane Smith",required:!0,className:"mt-1"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),e.jsx(ye,{id:"friend_email",type:"email",value:f,onChange:z=>g(z.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),e.jsx(ye,{id:"friend_phone",type:"tel",value:_,onChange:z=>v(z.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),e.jsx("p",{className:"text-[11px] text-slate-400",children:"Add at least an email or phone so we can reach them."}),e.jsxs("div",{children:[e.jsx(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(z=>e.jsx("button",{type:"button",onClick:()=>b(z.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${j===z.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:z.l},z.v))})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),e.jsx("textarea",{id:"friend_message",value:S,onChange:z=>A(z.target.value),placeholder:"They're moving from Boston in the spring...",rows:3,className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Your info"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),e.jsx(ye,{id:"referrer_name",value:o,onChange:z=>c(z.target.value),placeholder:T.client_name||"Your name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),e.jsx(ye,{id:"referrer_email",type:"email",value:d,onChange:z=>u(z.target.value),placeholder:"So we can thank you!",className:"mt-1"})]})]})]}),e.jsxs("button",{type:"submit",disabled:r,className:"w-full bg-[#406E71] hover:bg-[#345e7a] disabled:opacity-60 text-white font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 transition-colors",children:[r?e.jsx(ts,{className:"w-4 h-4 animate-spin"}):e.jsx(Oi,{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 UJt(){const t=Jl().pathname.slice(1).replace(/\/$/,"");if(N.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>{document.body.classList.remove("client-portal-page")}),[]),!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Client Portal"}),e.jsx("p",{className:"text-slate-500",children:"Visit your personalized portal link to view your transaction details."})]})});const n=t.match(/^([^/]+)\/refer$/);return n?e.jsx($ht,{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(Bht,{slug:t})}function qJt(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 Sfe({photos:s,alt:t="",className:n="w-full h-full",imgClassName:r="w-full h-full object-cover",iconClassName:a="w-8 h-8"}){const i=N.useMemo(()=>qJt(Array.isArray(s)?s:[]),[s]),[l,o]=N.useState(0);return N.useEffect(()=>{o(0)},[i.join("|")]),!i.length||l>=i.length?e.jsx("div",{className:`${n} bg-muted flex items-center justify-center text-muted-foreground`,children:e.jsx(Or,{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 Uht({comp:s,open:t,onClose:n}){var d;const[r,a]=N.useState(0);if(!s)return null;const i=Array.isArray(s.photos)?s.photos.filter(Boolean):[],l=s.soldPrice||s.price,o=s.sqft&&l?Math.round(l/s.sqft):null,c=u=>{if(!u)return null;const[h,p,f]=u.split(/[-/T]/);return h?`${p}/${f}/${h}`:null};return e.jsx(bs,{open:t,onOpenChange:u=>{u||n()},children:e.jsxs(vs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(ws,{className:"px-6 pt-6 pb-2",children:[e.jsx(_s,{className:"text-xl",children:s.address}),e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ka,{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(Sfe,{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(Sfe,{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(Or,{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(Zl,{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(ze,{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(Ije,{label:"Active",date:c(s.listDate),active:!0}),e.jsx(Ije,{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(Ije,{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(uH,{icon:e.jsx(sy,{className:"w-4 h-4"}),label:"Beds",value:s.bedrooms??"—"}),e.jsx(uH,{icon:e.jsx(Cp,{className:"w-4 h-4"}),label:"Baths",value:s.bathrooms??"—"}),e.jsx(uH,{icon:e.jsx(J2,{className:"w-4 h-4"}),label:"SqFt",value:((d=s.sqft)==null?void 0:d.toLocaleString())??"—"}),e.jsx(uH,{icon:e.jsx(yr,{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(Dx,{label:"MLS #",value:s.mlsNumber}),e.jsx(Dx,{label:"Property Type",value:s.propertySubType||s.propertyType}),e.jsx(Dx,{label:"Lot Size",value:s.lotSize}),e.jsx(Dx,{label:"Garage",value:s.garageSpaces}),e.jsx(Dx,{label:"Stories",value:s.stories}),e.jsx(Dx,{label:"HOA",value:s.hoaFee?`$${s.hoaFee}/${(s.hoaFrequency||"mo").toLowerCase()}`:null}),e.jsx(Dx,{label:"Tax (annual)",value:s.taxAmount?`$${s.taxAmount.toLocaleString()}`:null}),e.jsx(Dx,{label:"Heating",value:s.heating}),e.jsx(Dx,{label:"Cooling",value:s.cooling}),e.jsx(Dx,{label:"Parking",value:s.parking}),e.jsx(Dx,{label:"Elementary",value:s.elementarySchool}),e.jsx(Dx,{label:"Middle",value:s.middleSchool}),e.jsx(Dx,{label:"High",value:s.highSchool}),e.jsx(Dx,{label:"Listed By",value:s.listAgentFullName}),e.jsx(Dx,{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 uH({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 Dx({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 Ije({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 hH({to:s,durationMs:t=1400,prefix:n="",suffix:r="",className:a,delayMs:i=0}){const[l,o]=N.useState(0),c=N.useRef(null);return N.useEffect(()=>{if(!Number.isFinite(s))return;let d=0;const u=0,h=f=>1-Math.pow(1-f,3),p=setTimeout(()=>{const f=g=>{d||(d=g);const _=g-d,v=Math.min(1,_/t);o(Math.round(u+(s-u)*h(v))),v<1&&(c.current=requestAnimationFrame(f))};c.current=requestAnimationFrame(f)},i);return()=>{clearTimeout(p),c.current&&cancelAnimationFrame(c.current)}},[s,t,i]),e.jsxs("span",{className:a,children:[n,l.toLocaleString(),r]})}function VJt({low:s,likely:t,high:n,defaultMortgage:r=0,defaultCommissionPct:a=6,defaultClosingPct:i=1}){const[l,o]=N.useState(t),[c,d]=N.useState(r),[u,h]=N.useState(a),[p,f]=N.useState(i),{commission:g,closing:_,net:v}=N.useMemo(()=>{const S=Math.round(l*u/100),A=Math.round(l*p/100);return{commission:S,closing:A,net:Math.max(0,l-S-A-(c||0))}},[l,u,p,c]),j=S=>`$${S.toLocaleString()}`,b=n>s?(l-s)/(n-s)*100:50;return e.jsxs(fe,{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(mo,{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(Ee,{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:j(l)})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Bm,{value:[l],min:s,max:n,step:1e3,onValueChange:([S])=>o(S)}),e.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-2",children:[e.jsx("span",{children:j(s)}),e.jsxs("span",{children:["Suggested ",j(t)]}),e.jsx("span",{children:j(n)})]})]}),e.jsx("div",{className:"mt-2 h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-emerald-500 via-primary to-amber-500 transition-all",style:{width:`${Math.min(100,Math.max(0,b))}%`}})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Mortgage payoff"}),e.jsx(ye,{type:"number",inputMode:"numeric",value:c||"",placeholder:"$0",onChange:S=>d(Number(S.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:S=>h(Number(S.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:p,onChange:S=>f(Number(S.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:j(l)}),e.jsxs("span",{className:"text-muted-foreground",children:["Commission (",u,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",j(g)]}),e.jsxs("span",{className:"text-muted-foreground",children:["Closing (",p,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",j(_)]}),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:["−",j(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(jL,{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:j(v)})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:"This is a rough estimate to help you think through pricing. Actual proceeds depend on title fees, prorations, repairs, and other items your agent will walk through in detail."})]})]})}function qht({tokenOverride:s}={}){var Fe,qe,be,Ze,Ne,it,je,Ge,Be,Ye,We,rt;const t=bi(),n=s??t.token,[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState([]),[d,u]=N.useState(!0),[h,p]=N.useState(""),[f,g]=N.useState(""),[_,v]=N.useState(""),[j,b]=N.useState(!1),[S,A]=N.useState(!1),[T,L]=N.useState(null),[D,M]=N.useState(null),[F,z]=N.useState(!1),{toast:V}=Ba();N.useEffect(()=>{n&&(async()=>{const{data:tt}=await q.from("cmas").select("*").eq("share_token",n).eq("status","shared").maybeSingle();if(!tt){u(!1);return}a(tt);const[{data:at},{data:He}]=await Promise.all([q.from("cma_comps").select("*").eq("cma_id",tt.id).order("position"),q.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",tt.agent_id).maybeSingle()]);c((at||[]).filter(bt=>bt.selected)),l(He);const dt=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",dt),await q.from("cma_views").insert({cma_id:tt.id,visitor_token:dt,user_agent:navigator.userAgent}),u(!1)})()},[n]);const W=async tt=>{if(!r)return;const at=localStorage.getItem("cma_visitor_token")||"";await q.from("cma_views").insert({cma_id:r.id,visitor_token:at,reactions:{[tt]:!0}}),q.functions.invoke("cma-reply-notify",{body:{shareToken:n,reaction:tt,visitorToken:at}}).catch(()=>{}),V({title:"Thanks — your agent just got notified ✨"})},Y=!(r!=null&&r.contact_id),K=async()=>{if(!r||!h.trim())return;if(Y&&(!f.trim()||!_.trim())){V({title:"Please add your name and email",variant:"destructive"});return}b(!0);const tt=localStorage.getItem("cma_visitor_token")||"",{data:at,error:He}=await q.functions.invoke("cma-reply-notify",{body:{shareToken:n,message:h,visitorToken:tt,viewerName:f.trim()||void 0,viewerEmail:_.trim()||void 0}});if(b(!1),He||!(at!=null&&at.success)){V({title:"Could not send",description:(He==null?void 0:He.message)||(at==null?void 0:at.error),variant:"destructive"});return}p(""),A(!0),V({title:"Message sent to your agent"})},J=N.useMemo(()=>{const tt=o.map(at=>{const He=at.snapshot,dt=(He==null?void 0:He.soldPrice)||(He==null?void 0:He.price);return dt&&(He!=null&&He.sqft)?dt/He.sqft:null}).filter(at=>!!at).sort((at,He)=>at-He);return tt.length?Math.round(tt[Math.floor(tt.length/2)]):null},[o]);if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(ts,{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(Or,{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 ne=r.subject||{},ie=(Fe=r.settings)==null?void 0:Fe.personalVideo,he=(qe=ne.photos)==null?void 0:qe[0],ce=r.contact_first_name?r.contact_first_name:null,pe=((i==null?void 0:i.name)||"A").split(" ").map(tt=>tt[0]).slice(0,2).join("").toUpperCase(),le=i!=null&&i.phone?`tel:${String(i.phone).replace(/[^\d+]/g,"")}`:null,ve=i!=null&&i.email?`mailto:${i.email}`:null,ge=i!=null&&i.phone?`sms:${String(i.phone).replace(/[^\d+]/g,"")}`:null,Te=r.price_low??null,Me=r.price_likely??null,Ce=r.price_high??null,Ae=Te&&Me&&Ce,De=Me&&ne.sqft?Math.round(Me/ne.sqft):null,Ie=De&&J?Math.round((De-J)/J*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:pe}),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(Va,{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:[le&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:le,children:[e.jsx(Ar,{className:"w-4 h-4 mr-1"}),"Call"]})}),ve&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:ve,children:[e.jsx(Vs,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),e.jsxs("div",{className:"relative overflow-hidden",children:[he?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("img",{src:he,alt:ne.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:`${ie!=null&&ie.url?"md:col-span-3":"md:col-span-5"} text-white animate-fade-in`,children:[e.jsxs(ze,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[e.jsx(un,{className:"w-3 h-3 mr-1"}),ce?`Prepared for ${ce}`:r.buyer_mode?"Your Buyer Analysis":"Your Market Analysis"]}),e.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold leading-[1.05] tracking-tight",children:ne.address}),e.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[e.jsx(ka,{className:"w-4 h-4"}),ne.city,", ",ne.state," ",ne.zip]}),Ae&&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(hH,{to:Me,prefix:"$",durationMs:1600,delayMs:250})})}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 md:gap-6 text-sm text-white/80",children:[e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Low"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(hH,{to:Te,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(hH,{to:Me,prefix:"$",delayMs:650})})]}),e.jsx("div",{className:"h-8 w-px bg-white/20"}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"High"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(hH,{to:Ce,prefix:"$",delayMs:800})})]})]})]})]}),(ie==null?void 0:ie.url)&&e.jsx("div",{className:"md:col-span-2 animate-scale-in",children:e.jsxs("button",{onClick:()=>z(!0),className:"group relative w-full aspect-[4/5] md:aspect-[4/5] rounded-2xl overflow-hidden shadow-2xl ring-1 ring-white/20 bg-black",children:[ie.thumb?e.jsx("img",{src:ie.thumb,alt:"",className:"w-full h-full object-cover"}):e.jsx("video",{src:ie.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(Al,{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 ",((be=i==null?void 0:i.name)==null?void 0:be.split(" ")[0])||"your agent"]})]})]})})]})})]}),F&&(ie==null?void 0:ie.url)&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 animate-fade-in",onClick:()=>z(!1),children:e.jsxs("div",{className:"relative w-full max-w-4xl",onClick:tt=>tt.stopPropagation(),children:[e.jsx("video",{src:ie.url,controls:!0,autoPlay:!0,className:"w-full rounded-xl"}),e.jsx(B,{variant:"ghost",className:"absolute -top-12 right-0 text-white hover:bg-white/10",onClick:()=>z(!1),children:"Close"})]})}),e.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-8 py-10 md:py-16 space-y-10 md:space-y-14",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 -mt-20 md:-mt-24 relative z-10",children:[{label:"Beds",value:ne.bedrooms??"—"},{label:"Baths",value:ne.bathrooms??"—"},{label:"Sq Ft",value:((Ze=ne.sqft)==null?void 0:Ze.toLocaleString())??"—"},{label:"Year Built",value:ne.yearBuilt??"—"}].map((tt,at)=>e.jsx(fe,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${at*80}ms`},children:e.jsxs(Ee,{className:"p-4 md:p-6 text-center",children:[e.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:tt.value}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:tt.label})]})},at))}),((it=(Ne=r.settings)==null?void 0:Ne.priceOverride)==null?void 0:it.enabled)&&((Ge=(je=r.settings)==null?void 0:je.priceOverride)==null?void 0:Ge.note)&&e.jsx(fe,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:e.jsxs(Ee,{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})]})}),Ae&&e.jsx(VJt,{low:Te,likely:Me,high:Ce}),J&&De&&e.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[e.jsx(fe,{className:"md:col-span-2",children:e.jsxs(Ee,{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 ",ne.city,", the median sale rate is ",e.jsxs("strong",{className:"text-foreground",children:["$",J,"/sqft"]}),". Applied to your home's ",(Be=ne.sqft)==null?void 0:Be.toLocaleString()," sqft, the comps support a value near ",e.jsxs("strong",{className:"text-foreground",children:["$",(J*(ne.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),e.jsx(fe,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:e.jsxs(Ee,{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:["$",De,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:["$",J,"/sqft"]})]}),Ie!==null&&Ie!==0&&e.jsxs("p",{className:`text-sm font-medium mt-1 ${Ie>0?"text-emerald-600":"text-rose-600"}`,children:[Ie>0?"▲":"▼"," ",Math.abs(Ie),"% ",Ie>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(ze,{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((tt,at)=>{var bt;const He=tt.snapshot,dt=He.soldPrice||He.price;return e.jsxs(fe,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${D===at?"ring-2 ring-primary":""}`,style:{animationDelay:`${at*60}ms`},onClick:()=>L(at),onMouseEnter:()=>M(at),onMouseLeave:()=>M(null),children:[e.jsxs("div",{className:"relative",children:[e.jsx(Sfe,{photos:He.photos,className:"w-full h-44"}),e.jsxs(ze,{className:"absolute top-2 left-2 bg-black/70 text-white border-0 backdrop-blur-sm",children:["#",at+1]}),e.jsx(ze,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:He.status})]}),e.jsxs(Ee,{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight truncate",children:He.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[He.city,", ",He.state]}),e.jsx("div",{className:"flex justify-between items-center mt-3 text-sm",children:e.jsxs("span",{className:"text-muted-foreground",children:[He.bedrooms??"?","bd · ",He.bathrooms??"?","ba · ",((bt=He.sqft)==null?void 0:bt.toLocaleString())??"?"," sqft"]})}),e.jsxs("div",{className:"flex justify-between items-center mt-3 pt-3 border-t",children:[e.jsxs("span",{className:"text-xl font-bold tabular-nums",children:["$",dt==null?void 0:dt.toLocaleString()]}),He.sqft&&dt?e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(dt/He.sqft),"/sqft"]}):null]})]})]},at)})})]}),e.jsx(Uht,{comp:T!==null?(Ye=o[T])==null?void 0:Ye.snapshot:null,open:T!==null,onClose:()=>L(null)}),e.jsx(fe,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:e.jsxs(Ee,{className:"p-6 md:p-8 space-y-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-1",children:"Your turn"}),e.jsxs("h2",{className:"text-2xl md:text-3xl font-bold",children:["What do you think",ce?`, ${ce}`:"","?"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["One tap. ",((We=i==null?void 0:i.name)==null?void 0:We.split(" ")[0])||"Your agent"," hears you instantly."]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{kind:"love",icon:gi,label:"I love this price"},{kind:"fair",icon:Vm,label:"Seems fair"},{kind:"lower",icon:vb,label:"I'd price lower"},{kind:"higher",icon:mo,label:"I'd price higher"},{kind:"ready_to_list",icon:pb,label:"Ready to list"},{kind:"want_walkthrough",icon:Er,label:"Want a walkthrough"},{kind:"need_time",icon:yr,label:"Need more time"},{kind:"have_questions",icon:K_,label:"I have questions"}].map(({kind:tt,icon:at,label:He})=>e.jsxs(B,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>W(tt),children:[e.jsx(at,{className:"w-4 h-4 mr-2"}),He]},tt))}),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(Ql,{className:"w-4 h-4"}),"Ask your agent a question"]}),S?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! ",((rt=i==null?void 0:i.name)==null?void 0:rt.split(" ")[0])||"Your agent"," was notified and will get back to you shortly."]}):e.jsxs(e.Fragment,{children:[Y&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2",children:[e.jsx("input",{className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your name",value:f,onChange:tt=>g(tt.target.value)}),e.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:_,onChange:tt=>v(tt.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:tt=>p(tt.target.value)}),e.jsx(B,{onClick:K,disabled:!h.trim()||j,className:"mt-2",children:j?"Sending…":"Send to agent"})]})]})]})}),i&&e.jsx(fe,{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:pe}),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:[le&&e.jsx(B,{asChild:!0,children:e.jsxs("a",{href:le,children:[e.jsx(Ar,{className:"w-4 h-4 mr-2"}),i.phone]})}),ve&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:ve,children:[e.jsx(Vs,{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(lc,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),i&&(le||ge||ve)&&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:[le&&e.jsx(B,{className:"flex-1",asChild:!0,children:e.jsxs("a",{href:le,children:[e.jsx(Ar,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),ge&&e.jsx(B,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:ge,children:[e.jsx(Ql,{className:"w-4 h-4 mr-1.5"}),"Text"]})}),ve&&e.jsx(B,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:ve,children:[e.jsx(Vs,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}function HJt(){const t=Jl().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(qht,{tokenOverride:t})}const hCe="levelup_affiliate_ref",GJt=30,WJt=()=>{const[s]=gl();N.useEffect(()=>{const t=s.get("ref");if(t){const n={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem(hCe,JSON.stringify(n)),console.log("[Affiliate] Stored referral code:",t)}},[s])},KJt=()=>{try{const s=localStorage.getItem(hCe);if(!s)return null;const t=JSON.parse(s),n=GJt*24*60*60*1e3;return Date.now()-t.timestamp>n?(localStorage.removeItem(hCe),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},Cfe="/assets/levelup-logo-header-_ZX7DvlA.png",YJt="/assets/scale-your-team-ku4MPatU.png";function ZJt({open:s,onOpenChange:t}){return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(ws,{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(Va,{className:"h-5 w-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(_s,{children:"Schedule a Brokerage Interest Meeting"}),e.jsx(Qn,{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 pp={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}},QJt=[{icon:Au,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:fl,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:yr,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Ql,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Nr,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Oi,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],XJt=[{icon:Nn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:un,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Ar,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:cu,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ka,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:yo,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:gi,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:hh,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],JJt=[{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."}],ees=()=>{const{user:s,loading:t}=ys(),n=Mn(),[r]=gl();N.useEffect(()=>{const D=window.location.host==="listings.relevelup.com",M=window.location.pathname==="/";if(D&&M){n("/public/listings",{replace:!0});return}},[n]);const[a,i]=N.useState(null),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState(""),[g,_]=N.useState(""),[v,j]=N.useState(!1),[b,S]=N.useState(!1),A=(D,M=!1)=>{o({tier:D,skipTrial:M}),d(!0)};WJt(),N.useEffect(()=>{const D=window.location.host==="listings.relevelup.com",M=location.pathname.startsWith("/public/");!t&&s&&!D&&!M&&n("/dashboard")},[s,t,n,location.pathname]),N.useEffect(()=>{r.get("canceled")==="true"&&ae.error("Checkout was canceled. Feel free to try again when you're ready!")},[r]);const T=async(D,M=!1)=>{if(!u){ae.error("Please enter your email address");return}if(!p.trim()){ae.error("Please enter your full name");return}j(!0),i(D+(M?"_direct":""));const F=KJt();try{const{data:z,error:V}=await q.functions.invoke("create-checkout",{body:{tier:D,email:u,name:p.trim(),couponCode:g.trim()||void 0,skipTrial:M,referralCode:F}});if(V)throw V;if(z!=null&&z.url)window.open(z.url,"_blank","noopener,noreferrer"),ae.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(z){console.error("Checkout error:",z),ae.error(z.message||"Failed to start checkout. Please try again.")}finally{j(!1),i(null),d(!1),o(null)}},L=()=>{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:Cfe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(B,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var D;return(D=document.getElementById("features"))==null?void 0:D.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx(B,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var D;return(D=document.getElementById("pricing"))==null?void 0:D.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 D;return(D=document.getElementById("free-trial"))==null?void 0:D.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(Oa,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),e.jsx(B,{size:"lg",variant:"outline",onClick:()=>{var D;return(D=document.getElementById("features"))==null?void 0:D.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 D;return(D=document.getElementById("brokerage"))==null?void 0:D.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[e.jsx(Va,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),e.jsxs(B,{size:"lg",onClick:()=>{var D;return(D=document.getElementById("pricing"))==null?void 0:D.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[e.jsx(Xi,{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:QJt.map((D,M)=>e.jsxs(fe,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Mt,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(D.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(It,{className:"text-xl font-sans",children:D.title})]}),e.jsx(Ee,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:D.description})})]},M))})]})}),e.jsxs("section",{id:"agent-os",className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[e.jsx(un,{className:"w-4 h-4"}),"Included with Membership"]}),e.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",e.jsx("span",{className:"italic",children:"Agent OS"})]}),e.jsx("p",{className:"text-lg text-white/80",children:"Your relationship-first operating system. Never forget a follow-up, track every touchpoint, and turn your sphere into a referral machine."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:XJt.map((D,M)=>e.jsxs(fe,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Mt,{className:"pb-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:e.jsx(D.icon,{className:"w-6 h-6 text-white"})}),e.jsx(It,{className:"text-lg font-semibold text-white",children:D.title})]}),e.jsx(Ee,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:D.description})})]},M))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs(B,{size:"lg",onClick:()=>{var D;return(D=document.getElementById("pricing"))==null?void 0:D.scrollIntoView({behavior:"smooth"})},className:"bg-white text-[#4a6b6d] hover:bg-white/90 shadow-xl transition-all hover:scale-105",children:["Get Agent OS with Your Membership",e.jsx(Oa,{className:"ml-2 w-5 h-5"})]})})]})]}),e.jsx("section",{id:"brokerage",className:"py-20 bg-[#4a6b6d]/5",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsx("div",{className:"max-w-6xl mx-auto",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-12 items-center",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-medium",children:[e.jsx(Va,{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((D,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center flex-shrink-0",children:e.jsx(Ir,{className:"w-4 h-4 text-[#4a6b6d]"})}),e.jsx("span",{className:"text-foreground",children:D})]},M))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[e.jsxs(B,{size:"lg",onClick:()=>{var D;return(D=document.getElementById("pricing"))==null?void 0:D.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",e.jsx(xa,{className:"ml-2 w-5 h-5"})]}),e.jsxs(B,{size:"lg",variant:"outline",onClick:()=>S(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[e.jsx(yr,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:YJt,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:JJt.map((D,M)=>e.jsx(fe,{className:"bg-muted/30 border-0",children:e.jsxs(Ee,{className:"pt-8",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(F=>e.jsx(ca,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},F))}),e.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',D.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:D.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:D.role})]})]})},M))})]})}),e.jsxs("section",{id:"free-trial",className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-3xl mx-auto text-center space-y-8",children:[e.jsxs("h2",{className:"text-3xl md:text-5xl font-bold text-white",children:["Start Your Free Trial ",e.jsx("span",{className:"italic",children:"Today"})]}),e.jsx("p",{className:"text-lg md:text-xl text-white/80 leading-relaxed",children:"Get instant access to 7 days of trainings, templates, and tools — designed to give you quick wins now and resources you'll keep forever."}),e.jsx("div",{className:"pt-4",children:e.jsxs(B,{size:"lg",className:"px-12 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 group rounded-full",onClick:()=>A("individual_agent"),children:["Start Free Trial",e.jsx(Oa,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]})})]}),e.jsx("section",{id:"pricing",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-16",children:[e.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Simple, Transparent ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Pricing"})]}),e.jsx("p",{className:"text-lg text-muted-foreground max-w-2xl mx-auto",children:"Choose the plan that fits your needs. All plans include everything you need to succeed."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:[e.jsxs(fe,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Mt,{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(Xi,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx(It,{className:"text-xl font-sans",children:pp.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:pp.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:pp.individual_agent.period})]}),e.jsx(Vn,{className:"text-base mt-2",children:pp.individual_agent.description}),e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-green-500/10 text-green-600 text-sm font-medium mt-4",children:[e.jsx(gr,{className:"w-4 h-4"}),pp.individual_agent.trial]})]}),e.jsx(Ee,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:pp.individual_agent.features.map((D,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Ir,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:D})]},M))})}),e.jsxs(ez,{className:"flex flex-col gap-3 pt-4",children:[e.jsx(B,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("individual_agent"),children:"Start Free Trial"}),e.jsx(B,{variant:"outline",className:"w-full rounded-full border-2 border-[#4a6b6d] text-[#4a6b6d] bg-white hover:bg-[#4a6b6d]/5 uppercase text-sm font-medium tracking-wide",onClick:()=>A("individual_agent",!0),children:"Skip Trial, Subscribe Now"})]})]}),e.jsxs(fe,{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(Mt,{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(Va,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-xl font-sans",children:pp.brokerage_under_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:pp.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:pp.brokerage_under_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:pp.brokerage_under_25.period})]}),e.jsx(Vn,{className:"text-base mt-2",children:pp.brokerage_under_25.description})]}),e.jsx(Ee,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:pp.brokerage_under_25.features.map((D,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Ir,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:D})]},M))})}),e.jsx(ez,{className:"pt-4",children:e.jsx(B,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("brokerage_under_25"),children:"Get Started"})})]}),e.jsxs(fe,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Mt,{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(Va,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-xl font-sans",children:pp.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:pp.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:pp.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:pp.brokerage_over_25.period})]}),e.jsx(Vn,{className:"text-base mt-2",children:pp.brokerage_over_25.description})]}),e.jsx(Ee,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:pp.brokerage_over_25.features.map((D,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Ir,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:D})]},M))})}),e.jsx(ez,{className:"pt-4",children:e.jsx(B,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("brokerage_over_25"),children:"Get Started"})})]})]})]})}),e.jsx("section",{id:"neutrality",className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-medium mb-4",children:[e.jsx(dh,{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(fe,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ee,{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(Va,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),e.jsx(fe,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ee,{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(Kc,{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(fe,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ee,{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(bb,{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(fe,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ee,{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(Nr,{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 D;return(D=document.getElementById("pricing"))==null?void 0:D.scrollIntoView({behavior:"smooth"})},className:"px-10 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105",children:["Start Your Free Trial",e.jsx(Oa,{className:"ml-2 w-5 h-5"})]}),e.jsx(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:Cfe,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(ZJt,{open:b,onOpenChange:S}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),e.jsx(Qn,{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:p,onChange:D=>f(D.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:D=>h(D.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:g,onChange:D=>_(D.target.value),className:"mt-1"})]})]}),e.jsx(B,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:L,disabled:v,children:v?"Loading...":"Continue to Checkout"})]})})]})},uUe=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Go,{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"})]})]})]})]})})]}),hUe=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Go,{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"})]})]})]})]})})]}),tes=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Go,{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"})]})]})]})]})})]}),mUe="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.",ses=Yw({name:go().trim().min(1,"Name is required").max(200),phone:go().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:go().trim().email("Enter a valid email").max(320).optional().or(jp(""))});function nes(){const[s,t]=N.useState(""),[n,r]=N.useState(""),[a,i]=N.useState(""),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState(!1),p=async f=>{var v;if(f.preventDefault(),!l){ae.error("Please check the consent box to opt in.");return}const g=ses.safeParse({name:s,phone:n,email:a});if(!g.success){ae.error(((v=g.error.issues[0])==null?void 0:v.message)??"Please check your inputs.");return}d(!0);const{error:_}=await q.from("sms_opt_in_consents").insert({name:g.data.name,phone:g.data.phone,email:g.data.email||null,consent_text:mUe,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),_){ae.error("Something went wrong. Please try again.");return}h(!0)};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-background via-background to-muted/30 py-10 px-4",children:[e.jsxs(Go,{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(Ei,{className:"w-7 h-7"})}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"LevelUp — SMS Opt-In"}),e.jsx("p",{className:"text-muted-foreground mt-3 max-w-xl mx-auto",children:"Sign up to receive SMS account notifications and real-time lead alerts from LevelUp. These messages help subscribed real estate agents review and respond to new consumer inquiries submitted through their websites."})]}),u?e.jsxs(fe,{className:"p-8 text-center",children:[e.jsx(xr,{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(fe,{className:"p-6 md:p-8",children:e.jsxs("form",{onSubmit:p,className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"name",children:"Full Name *"}),e.jsx(ye,{id:"name",value:s,onChange:f=>t(f.target.value),required:!0,maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"phone",children:"Mobile Number *"}),e.jsx(ye,{id:"phone",type:"tel",value:n,onChange:f=>r(f.target.value),required:!0,maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email (optional)"}),e.jsx(ye,{id:"email",type:"email",value:a,onChange:f=>i(f.target.value),maxLength:320,autoComplete:"email",className:"mt-1.5"})]}),e.jsx("div",{className:"rounded-lg border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ui,{id:"consent",checked:l,onCheckedChange:f=>o(f===!0),className:"mt-0.5"}),e.jsx(se,{htmlFor:"consent",className:"text-sm leading-relaxed font-normal cursor-pointer",children:mUe})]})}),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(Ln,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(Ln,{to:"/privacy-policy",className:"text-primary underline underline-offset-2",children:"Privacy Policy"}),"."]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Message types:"})," account notifications, real-time lead alerts, service updates, customer support."," ",e.jsx("strong",{children:"Frequency:"})," varies."," ",e.jsx("strong",{children:"Msg & data rates may apply."})," ","Reply ",e.jsx("strong",{children:"STOP"})," to opt out, ",e.jsx("strong",{children:"HELP"})," for help."]}),e.jsx("p",{children:"No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties."})]}),e.jsx(B,{type:"submit",disabled:!l||c,className:"w-full",size:"lg",children:c?"Submitting…":"Opt in to SMS"}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-muted-foreground pt-2",children:[e.jsx(sg,{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 Vht="/assets/levelup-logo-horizontal-DEFNc0ms.png",res=Yw({email:go().email("Invalid email address"),password:go().min(6,"Password must be at least 6 characters")}),aes="https://dashboard.relevelup.com",mH="/oauth-connect",$me="levelupOAuthRouteHistory";function pUe(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function ies(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem($me)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem($me,JSON.stringify([{route:s,at:t}])),!1}}function oes(){sessionStorage.removeItem($me)}const les=()=>{const{signIn:s,user:t,loading:n}=ys(),r=(t==null?void 0:t.id)??null,a=Mn(),[i]=gl(),l=i.get("authorization_id")??"",o=i.get("next")??"",[c,d]=N.useState(!1),[u,h]=N.useState({}),[p,f]=N.useState(""),[g,_]=N.useState(!1),[v,j]=N.useState(!1),[b,S]=N.useState(null),A=N.useRef(!1);N.useEffect(()=>{if(l&&window.location.hostname==="tile-portal.lovable.app"){const D=new URL("/auth",aes);D.searchParams.set("next",`${mH}?authorization_id=${encodeURIComponent(l)}`),window.location.replace(D.toString());return}if(l){const D=`${mH}?authorization_id=${encodeURIComponent(l)}`;sessionStorage.setItem("redirectAfterLogin",D);return}o&&pUe(o)&&sessionStorage.setItem("redirectAfterLogin",o)},[l,o]),N.useEffect(()=>{if(n||!r||A.current)return;const D=l?`${mH}?authorization_id=${encodeURIComponent(l)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!pUe(D)){sessionStorage.removeItem("redirectAfterLogin"),A.current=!0,a("/dashboard",{replace:!0});return}const M=D.startsWith(mH)||D.startsWith("/oauth/consent")||D.startsWith("/.lovable/oauth/consent");if(M&&ies("auth")){S("We couldn't complete the OAuth sign-in handoff because the browser kept bouncing between sign-in and consent. Please refresh this page and try Connect again.");return}A.current=!0,M||(oes(),sessionStorage.removeItem("redirectAfterLogin")),a(D,{replace:!0})},[l,n,a,r]);const T=async D=>{D.preventDefault(),h({}),d(!0);const M=new FormData(D.currentTarget),F=M.get("email"),z=M.get("password");try{res.parse({email:F,password:z}),await s(F,z)}catch(V){if(V instanceof MGt){const W={};V.issues.forEach(Y=>{Y.path[0]&&(W[Y.path[0]]=Y.message)}),h(W)}}finally{d(!1)}},L=async()=>{if(!p){ae.error("Please enter your email address");return}_(!0);try{const{error:D}=await q.functions.invoke("send-password-reset",{body:{email:p,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(D)throw D;ae.success("Password reset email sent! Check your inbox."),j(!1),f("")}catch(D){ae.error(D instanceof Error?D.message:"Failed to send reset email")}finally{_(!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(Ln,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[e.jsx(Hr,{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:Vht,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(fe,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Mt,{className:"space-y-1 text-center pb-4",children:[e.jsx(It,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),e.jsx(Vn,{className:"text-gray-600",children:b||"Sign in to access your dashboard"})]}),e.jsx(Ee,{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(bs,{open:v,onOpenChange:j,children:[e.jsx(Ai,{asChild:!0,children:e.jsx(B,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),e.jsxs(vs,{className:"bg-white",children:[e.jsxs(ws,{children:[e.jsx(_s,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),e.jsx(Qn,{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:p,onChange:D=>f(D.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),e.jsx(B,{onClick:L,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:g,children:g?"Sending...":"Send Reset Link"})]})]})]})]})})]}),e.jsxs("p",{className:"text-center text-white/70 text-sm mt-6",children:["Don't have an account?"," ",e.jsx(Ln,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},fUe=()=>q.auth.oauth,ces="https://dashboard.relevelup.com",des="/oauth-connect",Ume="levelupOAuthRouteHistory",ues="https://relzejiswnotikjgvjhz.supabase.co/auth/v1",hes="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";function mes(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function pes(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(Ume)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(Ume,JSON.stringify([{route:s,at:t}])),!1}}function fes(){sessionStorage.removeItem(Ume)}async function xUe(s,t,n){const r=await fetch(`${ues}${s}`,{...n,headers:{Authorization:`Bearer ${t}`,apikey:hes,"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 Pje(){var _;const{user:s,session:t,loading:n}=ys(),r=(s==null?void 0:s.id)??null,a=(t==null?void 0:t.access_token)??null,[i]=gl(),l=i.get("authorization_id")??"",[o,c]=N.useState(null),[d,u]=N.useState(null),[h,p]=N.useState(!1);N.useEffect(()=>{let v=!0;return(async()=>{if(!l){u("Missing authorization_id");return}const j=`${des}?authorization_id=${encodeURIComponent(l)}`;if(window.location.hostname==="tile-portal.lovable.app"){window.location.href=`${ces}${j}`;return}if(n)return;if(!r){if(pes("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}mes(j)&&sessionStorage.setItem("redirectAfterLogin",j),window.location.replace(`/auth?next=${encodeURIComponent(j)}`);return}if(!a)return;fes(),sessionStorage.removeItem("redirectAfterLogin");const b=fUe(),{data:S,error:A}=b?await b.getAuthorizationDetails(l):await xUe(`/oauth/authorizations/${encodeURIComponent(l)}`,a);if(!v)return;if(A){u(A.message);return}const T=(S==null?void 0:S.redirect_url)??(S==null?void 0:S.redirect_to);if(T&&!(S!=null&&S.client)){window.location.href=T;return}c(S)})(),()=>{v=!1}},[a,l,n,r]);async function f(v){if(!(t!=null&&t.access_token)){u("Your sign-in session is not ready yet. Please refresh and try again.");return}p(!0);const j=fUe(),{data:b,error:S}=j?v?await j.approveAuthorization(l,{skipBrowserRedirect:!0}):await j.denyAuthorization(l,{skipBrowserRedirect:!0}):await xUe(`/oauth/authorizations/${encodeURIComponent(l)}/consent`,t.access_token,{method:"POST",body:JSON.stringify({action:v?"approve":"deny"})});if(S){p(!1),u(S.message);return}const A=(b==null?void 0:b.redirect_url)??(b==null?void 0:b.redirect_to);if(!A){p(!1),u("No redirect returned by the authorization server.");return}window.location.href=A}if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsx(fe,{className:"w-full max-w-md",children:e.jsxs(Mt,{children:[e.jsx(It,{children:"Authorization error"}),e.jsx(Vn,{children:d})]})})});if(!o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(ts,{className:"h-8 w-8 animate-spin text-primary"})});const g=((_=o.client)==null?void 0:_.name)??"An app";return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{children:[e.jsxs(It,{children:["Connect ",g," to LevelUp"]}),e.jsxs(Vn,{children:[g," is requesting access to use LevelUp tools on your behalf. You can revoke access at any time."]})]}),e.jsxs(Ee,{className:"flex gap-3 justify-end",children:[e.jsx(B,{variant:"outline",disabled:h,onClick:()=>f(!1),children:"Deny"}),e.jsx(B,{disabled:h,onClick:()=>f(!0),children:h?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):"Approve"})]})]})})}const Hht=s=>{const[t,n]=N.useState(null),[r,a]=N.useState(!0);return N.useEffect(()=>{if(!s){a(!1);return}(async()=>{try{const{data:o}=await q.storage.from("avatars").list(`${s}`);if(o&&o.length>0){const{data:c}=q.storage.from("avatars").getPublicUrl(`${s}/${o[0].name}`);n(`${c.publicUrl}?t=${Date.now()}`)}else n(null)}catch(o){console.error("Error fetching avatar:",o),n(null)}finally{a(!1)}})()},[s]),{avatarUrl:t,loading:r,refreshAvatar:async()=>{if(s)try{const{data:l}=await q.storage.from("avatars").list(`${s}`);if(l&&l.length>0){const{data:o}=q.storage.from("avatars").getPublicUrl(`${s}/${l[0].name}`);n(`${o.publicUrl}?t=${Date.now()}`)}}catch(l){console.error("Error refreshing avatar:",l)}}}},Ght=async s=>{const t=new Map;return await Promise.all(s.map(async n=>{try{const{data:r}=await q.storage.from("avatars").list(`${n}`);if(r&&r.length>0){const{data:a}=q.storage.from("avatars").getPublicUrl(`${n}/${r[0].name}`);t.set(n,a.publicUrl)}}catch{}})),t},xes=s=>{const[t,n]=N.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return N.useEffect(()=>{if(!s){n(a=>({...a,loading:!1}));return}(async()=>{try{const{data:a,error:i}=await q.from("profiles").select("is_trial, trial_expires_at, subscription_status, subscription_end_date").eq("id",s).single();if(i){console.error("Error fetching trial status:",i),n(h=>({...h,loading:!1}));return}const l=(a==null?void 0:a.subscription_status)==="trialing",o=!!(a!=null&&a.is_trial),c=!!(a!=null&&a.trial_expires_at)&&new Date(a.trial_expires_at).getTime()>Date.now()&&(a==null?void 0:a.subscription_status)!=="active",d=l&&(a==null?void 0:a.subscription_end_date)||(a==null?void 0:a.trial_expires_at)||(a==null?void 0:a.subscription_end_date)||null;if((l||o||c)&&!!d&&d){const h=new Date().getTime(),p=new Date(d).getTime(),f=Math.ceil((p-h)/(1e3*60*60*24)),g=f<=0;n({isTrial:!0,isExpired:g,expiresAt:d,daysLeft:g?0:f,loading:!1})}else n({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!1})}catch(a){console.error("Error in useTrialStatus:",a),n(i=>({...i,loading:!1}))}})()},[s]),t},Wht=()=>{const{data:s,isLoading:t}=ct({queryKey:["feature-flags"],queryFn:async()=>{const{data:r,error:a}=await q.from("feature_flags").select("*");if(a)throw a;return r}}),n=r=>{if(!s)return!1;const a=s.find(i=>i.key===r);return(a==null?void 0:a.enabled)??!1};return{flags:s,isLoading:t,isFeatureEnabled:n,isAgentOSEnabled:n("agent_os_enabled"),isInnerCircleEnabled:n("innercircle_enabled"),isMarketplaceEnabled:n("marketplace")}},gUe="community_last_seen_post_at";function ges(){const{user:s}=ys(),t=Jl(),[n,r]=N.useState(0),[a,i]=N.useState(null);N.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${gUe}_${s.id}`);i(o)},[s]),N.useEffect(()=>{if(!s)return;const o=`community_unread_count_${s.id}`,c=2*60*1e3;(async()=>{try{const f=sessionStorage.getItem(o);if(f){const g=JSON.parse(f);if(g.ts&&Date.now()-g.ts{if(!s)return;const o=q.channel("community-new-posts").on("postgres_changes",{event:"INSERT",schema:"public",table:"community_posts"},async c=>{const d=c.new;if(d.user_id===s.id)return;const u=t.pathname==="/community";u||r(_=>_+1);const{data:h}=await q.from("profiles").select("name").eq("id",d.user_id).single(),p=(h==null?void 0:h.name)||"Someone",f=d.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),g=f.length>50?f.substring(0,50)+"...":f;u||ae("New Community Post",{description:`${p}: ${g}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{q.removeChannel(o)}},[s,t.pathname]);const l=N.useCallback(()=>{if(!s)return;const o=new Date().toISOString();localStorage.setItem(`${gUe}_${s.id}`,o),i(o),r(0)},[s]);return N.useEffect(()=>{t.pathname==="/community"&&n>0&&l()},[t.pathname,n,l]),{unreadCount:n,markAsRead:l}}function yes(){const{isAdmin:s}=ys(),{data:t=0}=ct({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:n,error:r}=await q.from("wishlist_items").select("*",{count:"exact",head:!0}).eq("status","open");if(r)throw r;return n||0},enabled:s,staleTime:6e4});return{openCount:s?t:0}}var Iye="Collapsible",[ves,Kht]=pu(Iye),[bes,e6e]=ves(Iye),Yht=N.forwardRef((s,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:a,disabled:i,onOpenChange:l,...o}=s,[c,d]=hm({prop:r,defaultProp:a??!1,onChange:l,caller:Iye});return e.jsx(bes,{scope:n,disabled:i,contentId:dm(),open:c,onOpenToggle:N.useCallback(()=>d(u=>!u),[d]),children:e.jsx(Jr.div,{"data-state":r6e(c),"data-disabled":i?"":void 0,...o,ref:t})})});Yht.displayName=Iye;var Zht="CollapsibleTrigger",t6e=N.forwardRef((s,t)=>{const{__scopeCollapsible:n,...r}=s,a=e6e(Zht,n);return e.jsx(Jr.button,{type:"button","aria-controls":a.contentId,"aria-expanded":a.open||!1,"data-state":r6e(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...r,ref:t,onClick:_r(s.onClick,a.onOpenToggle)})});t6e.displayName=Zht;var s6e="CollapsibleContent",n6e=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=e6e(s6e,s.__scopeCollapsible);return e.jsx(Rh,{present:n||a.open,children:({present:i})=>e.jsx(_es,{...r,ref:t,present:i})})});n6e.displayName=s6e;var _es=N.forwardRef((s,t)=>{const{__scopeCollapsible:n,present:r,children:a,...i}=s,l=e6e(s6e,n),[o,c]=N.useState(r),d=N.useRef(null),u=Si(t,d),h=N.useRef(0),p=h.current,f=N.useRef(0),g=f.current,_=l.open||o,v=N.useRef(_),j=N.useRef(void 0);return N.useEffect(()=>{const b=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(b)},[]),mh(()=>{const b=d.current;if(b){j.current=j.current||{transitionDuration:b.style.transitionDuration,animationName:b.style.animationName},b.style.transitionDuration="0s",b.style.animationName="none";const S=b.getBoundingClientRect();h.current=S.height,f.current=S.width,v.current||(b.style.transitionDuration=j.current.transitionDuration,b.style.animationName=j.current.animationName),c(r)}},[l.open,r]),e.jsx(Jr.div,{"data-state":r6e(l.open),"data-disabled":l.disabled?"":void 0,id:l.contentId,hidden:!_,...i,ref:u,style:{"--radix-collapsible-content-height":p?`${p}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...s.style},children:_&&a})});function r6e(s){return s?"open":"closed"}var Qht=Yht,wes=t6e,jes=n6e;const dy=Qht,uy=t6e,hy=n6e,Nes="/assets/levelup-logo-Eif24dqY.png",kes="/assets/levelup-logo-icon-C-7iromj.png",Ses="/assets/levelup-logo-mobile-B9skSjUG.png";var uU=s=>s.type==="checkbox",YE=s=>s instanceof Date,Vx=s=>s==null;const Xht=s=>typeof s=="object";var Dh=s=>!Vx(s)&&!Array.isArray(s)&&Xht(s)&&!YE(s),Jht=s=>Dh(s)&&s.target?uU(s.target)?s.target.checked:s.target.value:s,Ces=s=>s.substring(0,s.search(/\.\d+(\.|$)/))||s,emt=(s,t)=>s.has(Ces(t)),Tes=s=>{const t=s.constructor&&s.constructor.prototype;return Dh(t)&&t.hasOwnProperty("isPrototypeOf")},a6e=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Tm(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(!(a6e&&(s instanceof Blob||r))&&(n||Dh(s)))if(t=n?[]:{},!n&&!Tes(s))t=s;else for(const a in s)s.hasOwnProperty(a)&&(t[a]=Tm(s[a]));else return s;return t}var Pye=s=>/^\w*$/.test(s),kh=s=>s===void 0,i6e=s=>Array.isArray(s)?s.filter(Boolean):[],o6e=s=>i6e(s.replace(/["|']|\]/g,"").split(/\.|\[/)),Ia=(s,t,n)=>{if(!t||!Dh(s))return n;const r=(Pye(t)?[t]:o6e(t)).reduce((a,i)=>Vx(a)?a:a[i],s);return kh(r)||r===s?kh(s[t])?n:s[t]:r},H0=s=>typeof s=="boolean",Sc=(s,t,n)=>{let r=-1;const a=Pye(t)?[t]:o6e(t),i=a.length,l=i-1;for(;++rSt.useContext(l6e),Ees=s=>{const{children:t,...n}=s;return St.createElement(l6e.Provider,{value:n},t)};var tmt=(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]!==nb.all&&(t._proxyFormState[l]=!r||nb.all),n&&(n[l]=!0),s[l]}});return a};const c6e=typeof window<"u"?St.useLayoutEffect:St.useEffect;function Aes(s){const t=Lye(),{control:n=t.control,disabled:r,name:a,exact:i}=s||{},[l,o]=St.useState(n._formState),c=St.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return c6e(()=>n._subscribe({name:a,formState:c.current,exact:i,callback:d=>{!r&&o({...n._formState,...d})}}),[a,r,i]),St.useEffect(()=>{c.current.isValid&&n._setValid(!0)},[n]),St.useMemo(()=>tmt(l,n,c.current,!1),[l,n])}var rw=s=>typeof s=="string",smt=(s,t,n,r,a)=>rw(s)?(r&&t.watch.add(s),Ia(n,s,a)):Array.isArray(s)?s.map(i=>(r&&t.watch.add(i),Ia(n,i))):(r&&(t.watchAll=!0),n),mCe=s=>Vx(s)||!Xht(s);function I2(s,t,n=new WeakSet){if(mCe(s)||mCe(t))return s===t;if(YE(s)&&YE(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(YE(l)&&YE(o)||Dh(l)&&Dh(o)||Array.isArray(l)&&Array.isArray(o)?!I2(l,o,n):l!==o)return!1}}return!0}function Mes(s){const t=Lye(),{control:n=t.control,name:r,defaultValue:a,disabled:i,exact:l,compute:o}=s||{},c=St.useRef(a),d=St.useRef(o),u=St.useRef(void 0);d.current=o;const h=St.useMemo(()=>n._getWatch(r,c.current),[n,r]),[p,f]=St.useState(d.current?d.current(h):h);return c6e(()=>n._subscribe({name:r,formState:{values:!0},exact:l,callback:g=>{if(!i){const _=smt(r,n._names,g.values||n._formValues,!1,c.current);if(d.current){const v=d.current(_);I2(v,u.current)||(f(v),u.current=v)}else f(_)}}}),[n,i,r,l]),St.useEffect(()=>n._removeUnmounted()),p}function Ies(s){const t=Lye(),{name:n,disabled:r,control:a=t.control,shouldUnregister:i,defaultValue:l}=s,o=emt(a._names.array,n),c=St.useMemo(()=>Ia(a._formValues,n,Ia(a._defaultValues,n,l)),[a,n,l]),d=Mes({control:a,name:n,defaultValue:c,exact:!0}),u=Aes({control:a,name:n,exact:!0}),h=St.useRef(s),p=St.useRef(a.register(n,{...s.rules,value:d,...H0(s.disabled)?{disabled:s.disabled}:{}}));h.current=s;const f=St.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!Ia(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!Ia(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!Ia(u.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!Ia(u.validatingFields,n)},error:{enumerable:!0,get:()=>Ia(u.errors,n)}}),[u,n]),g=St.useCallback(b=>p.current.onChange({target:{value:Jht(b),name:n},type:Tfe.CHANGE}),[n]),_=St.useCallback(()=>p.current.onBlur({target:{value:Ia(a._formValues,n),name:n},type:Tfe.BLUR}),[n,a._formValues]),v=St.useCallback(b=>{const S=Ia(a._fields,n);S&&b&&(S._f.ref={focus:()=>b.focus&&b.focus(),select:()=>b.select&&b.select(),setCustomValidity:A=>b.setCustomValidity(A),reportValidity:()=>b.reportValidity()})},[a._fields,n]),j=St.useMemo(()=>({name:n,value:d,...H0(r)||u.disabled?{disabled:u.disabled||r}:{},onChange:g,onBlur:_,ref:v}),[n,r,u.disabled,g,_,v,d]);return St.useEffect(()=>{const b=a._options.shouldUnregister||i;a.register(n,{...h.current.rules,...H0(h.current.disabled)?{disabled:h.current.disabled}:{}});const S=(A,T)=>{const L=Ia(a._fields,A);L&&L._f&&(L._f.mount=T)};if(S(n,!0),b){const A=Tm(Ia(a._options.defaultValues,n));Sc(a._defaultValues,n,A),kh(Ia(a._formValues,n))&&Sc(a._formValues,n,A)}return!o&&a.register(n),()=>{(o?b&&!a._state.action:b)?a.unregister(n):S(n,!1)}},[n,a,o,i]),St.useEffect(()=>{a._setDisabledField({disabled:r,name:n})},[r,n,a]),St.useMemo(()=>({field:j,formState:u,fieldState:f}),[j,u,f])}const Pes=s=>s.render(Ies(s));var nmt=(s,t,n,r,a)=>t?{...n[s],types:{...n[s]&&n[s].types?n[s].types:{},[r]:a||!0}}:{},tz=s=>Array.isArray(s)?s:[s],yUe=()=>{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=[]}}},Eg=s=>Dh(s)&&!Object.keys(s).length,d6e=s=>s.type==="file",rb=s=>typeof s=="function",Efe=s=>{if(!a6e)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},rmt=s=>s.type==="select-multiple",u6e=s=>s.type==="radio",Les=s=>u6e(s)||uU(s),Lje=s=>Efe(s)&&s.isConnected;function Des(s,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const t in s)if(rb(s[t]))return!0;return!1};function Afe(s,t={}){const n=Array.isArray(s);if(Dh(s)||n)for(const r in s)Array.isArray(s[r])||Dh(s[r])&&!amt(s[r])?(t[r]=Array.isArray(s[r])?[]:{},Afe(s[r],t[r])):Vx(s[r])||(t[r]=!0);return t}function imt(s,t,n){const r=Array.isArray(s);if(Dh(s)||r)for(const a in s)Array.isArray(s[a])||Dh(s[a])&&!amt(s[a])?kh(t)||mCe(n[a])?n[a]=Array.isArray(s[a])?Afe(s[a],[]):{...Afe(s[a])}:imt(s[a],Vx(t)?{}:t[a],n[a]):n[a]=!I2(s[a],t[a]);return n}var cF=(s,t)=>imt(s,t,Afe(t));const vUe={value:!1,isValid:!1},bUe={value:!0,isValid:!0};var omt=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&&!kh(s[0].attributes.value)?kh(s[0].value)||s[0].value===""?bUe:{value:s[0].value,isValid:!0}:bUe:vUe}return vUe},lmt=(s,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>kh(s)?s:t?s===""?NaN:s&&+s:n&&rw(s)?new Date(s):r?r(s):s;const _Ue={isValid:!1,value:null};var cmt=s=>Array.isArray(s)?s.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,_Ue):_Ue;function wUe(s){const t=s.ref;return d6e(t)?t.files:u6e(t)?cmt(s.refs).value:rmt(t)?[...t.selectedOptions].map(({value:n})=>n):uU(t)?omt(s.refs).value:lmt(kh(t.value)?s.ref.value:t.value,s)}var Oes=(s,t,n,r)=>{const a={};for(const i of s){const l=Ia(t,i);l&&Sc(a,i,l._f)}return{criteriaMode:n,names:[...s],fields:a,shouldUseNativeValidation:r}},Mfe=s=>s instanceof RegExp,dF=s=>kh(s)?s:Mfe(s)?s.source:Dh(s)?Mfe(s.value)?s.value.source:s.value:s,jUe=s=>({isOnSubmit:!s||s===nb.onSubmit,isOnBlur:s===nb.onBlur,isOnChange:s===nb.onChange,isOnAll:s===nb.all,isOnTouch:s===nb.onTouched});const NUe="AsyncFunction";var Fes=s=>!!s&&!!s.validate&&!!(rb(s.validate)&&s.validate.constructor.name===NUe||Dh(s.validate)&&Object.values(s.validate).find(t=>t.constructor.name===NUe)),zes=s=>s.mount&&(s.required||s.min||s.max||s.maxLength||s.minLength||s.pattern||s.validate),kUe=(s,t,n)=>!n&&(t.watchAll||t.watch.has(s)||[...t.watch].some(r=>s.startsWith(r)&&/^\.\w+/.test(s.slice(r.length))));const sz=(s,t,n,r)=>{for(const a of n||Object.keys(s)){const i=Ia(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(sz(o,t))break}else if(Dh(o)&&sz(o,t))break}}};function SUe(s,t,n){const r=Ia(s,n);if(r||Pye(n))return{error:r,name:n};const a=n.split(".");for(;a.length;){const i=a.join("."),l=Ia(t,i),o=Ia(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 Bes=(s,t,n,r)=>{n(s);const{name:a,...i}=s;return Eg(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(l=>t[l]===(!r||nb.all))},$es=(s,t,n)=>!s||!t||s===t||tz(s).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r))),Ues=(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,qes=(s,t)=>!i6e(Ia(s,t)).length&&Wh(s,t),Ves=(s,t,n)=>{const r=tz(Ia(s,n));return Sc(r,"root",t[n]),Sc(s,n,r),s},qme=s=>rw(s);function CUe(s,t,n="validate"){if(qme(s)||Array.isArray(s)&&s.every(qme)||H0(s)&&!s)return{type:n,message:qme(s)?s:"",ref:t}}var _I=s=>Dh(s)&&!Mfe(s)?s:{value:s,message:""},TUe=async(s,t,n,r,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:u,min:h,max:p,pattern:f,validate:g,name:_,valueAsNumber:v,mount:j}=s._f,b=Ia(n,_);if(!j||t.has(_))return{};const S=o?o[0]:l,A=W=>{a&&S.reportValidity&&(S.setCustomValidity(H0(W)?"":W||""),S.reportValidity())},T={},L=u6e(l),D=uU(l),M=L||D,F=(v||d6e(l))&&kh(l.value)&&kh(b)||Efe(l)&&l.value===""||b===""||Array.isArray(b)&&!b.length,z=nmt.bind(null,_,r,T),V=(W,Y,K,J=n2.maxLength,ne=n2.minLength)=>{const ie=W?Y:K;T[_]={type:W?J:ne,message:ie,ref:l,...z(W?J:ne,ie)}};if(i?!Array.isArray(b)||!b.length:c&&(!M&&(F||Vx(b))||H0(b)&&!b||D&&!omt(o).isValid||L&&!cmt(o).isValid)){const{value:W,message:Y}=qme(c)?{value:!!c,message:c}:_I(c);if(W&&(T[_]={type:n2.required,message:Y,ref:S,...z(n2.required,Y)},!r))return A(Y),T}if(!F&&(!Vx(h)||!Vx(p))){let W,Y;const K=_I(p),J=_I(h);if(!Vx(b)&&!isNaN(b)){const ne=l.valueAsNumber||b&&+b;Vx(K.value)||(W=ne>K.value),Vx(J.value)||(Y=nenew Date(new Date().toDateString()+" "+pe),he=l.type=="time",ce=l.type=="week";rw(K.value)&&b&&(W=he?ie(b)>ie(K.value):ce?b>K.value:ne>new Date(K.value)),rw(J.value)&&b&&(Y=he?ie(b)+W.value,J=!Vx(Y.value)&&b.length<+Y.value;if((K||J)&&(V(K,W.message,Y.message),!r))return A(T[_].message),T}if(f&&!F&&rw(b)){const{value:W,message:Y}=_I(f);if(Mfe(W)&&!b.match(W)&&(T[_]={type:n2.pattern,message:Y,ref:l,...z(n2.pattern,Y)},!r))return A(Y),T}if(g){if(rb(g)){const W=await g(b,n),Y=CUe(W,S);if(Y&&(T[_]={...Y,...z(n2.validate,Y.message)},!r))return A(Y.message),T}else if(Dh(g)){let W={};for(const Y in g){if(!Eg(W)&&!r)break;const K=CUe(await g[Y](b,n),S,Y);K&&(W={...K,...z(Y,K.message)},A(K.message),r&&(T[_]=W))}if(!Eg(W)&&(T[_]={ref:S,...W},!r))return T}}return A(!0),T};const Hes={mode:nb.onSubmit,reValidateMode:nb.onChange,shouldFocusError:!0};function Ges(s={}){let t={...Hes,...s},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:rb(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},a=Dh(t.defaultValues)||Dh(t.values)?Tm(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:Tm(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 p={array:yUe(),state:yUe()},f=t.criteriaMode===nb.all,g=We=>rt=>{clearTimeout(d),d=setTimeout(We,rt)},_=async We=>{if(!t.disabled&&(u.isValid||h.isValid||We)){const rt=t.resolver?Eg((await D()).errors):await F(r,!0);rt!==n.isValid&&p.state.next({isValid:rt})}},v=(We,rt)=>{!t.disabled&&(u.isValidating||u.validatingFields||h.isValidating||h.validatingFields)&&((We||Array.from(o.mount)).forEach(tt=>{tt&&(rt?Sc(n.validatingFields,tt,rt):Wh(n.validatingFields,tt))}),p.state.next({validatingFields:n.validatingFields,isValidating:!Eg(n.validatingFields)}))},j=(We,rt=[],tt,at,He=!0,dt=!0)=>{if(at&&tt&&!t.disabled){if(l.action=!0,dt&&Array.isArray(Ia(r,We))){const bt=tt(Ia(r,We),at.argA,at.argB);He&&Sc(r,We,bt)}if(dt&&Array.isArray(Ia(n.errors,We))){const bt=tt(Ia(n.errors,We),at.argA,at.argB);He&&Sc(n.errors,We,bt),qes(n.errors,We)}if((u.touchedFields||h.touchedFields)&&dt&&Array.isArray(Ia(n.touchedFields,We))){const bt=tt(Ia(n.touchedFields,We),at.argA,at.argB);He&&Sc(n.touchedFields,We,bt)}(u.dirtyFields||h.dirtyFields)&&(n.dirtyFields=cF(a,i)),p.state.next({name:We,isDirty:V(We,rt),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Sc(i,We,rt)},b=(We,rt)=>{Sc(n.errors,We,rt),p.state.next({errors:n.errors})},S=We=>{n.errors=We,p.state.next({errors:n.errors,isValid:!1})},A=(We,rt,tt,at)=>{const He=Ia(r,We);if(He){const dt=Ia(i,We,kh(tt)?Ia(a,We):tt);kh(dt)||at&&at.defaultChecked||rt?Sc(i,We,rt?dt:wUe(He._f)):K(We,dt),l.mount&&_()}},T=(We,rt,tt,at,He)=>{let dt=!1,bt=!1;const vt={name:We};if(!t.disabled){if(!tt||at){(u.isDirty||h.isDirty)&&(bt=n.isDirty,n.isDirty=vt.isDirty=V(),dt=bt!==vt.isDirty);const Bt=I2(Ia(a,We),rt);bt=!!Ia(n.dirtyFields,We),Bt?Wh(n.dirtyFields,We):Sc(n.dirtyFields,We,!0),vt.dirtyFields=n.dirtyFields,dt=dt||(u.dirtyFields||h.dirtyFields)&&bt!==!Bt}if(tt){const Bt=Ia(n.touchedFields,We);Bt||(Sc(n.touchedFields,We,tt),vt.touchedFields=n.touchedFields,dt=dt||(u.touchedFields||h.touchedFields)&&Bt!==tt)}dt&&He&&p.state.next(vt)}return dt?vt:{}},L=(We,rt,tt,at)=>{const He=Ia(n.errors,We),dt=(u.isValid||h.isValid)&&H0(rt)&&n.isValid!==rt;if(t.delayError&&tt?(c=g(()=>b(We,tt)),c(t.delayError)):(clearTimeout(d),c=null,tt?Sc(n.errors,We,tt):Wh(n.errors,We)),(tt?!I2(He,tt):He)||!Eg(at)||dt){const bt={...at,...dt&&H0(rt)?{isValid:rt}:{},errors:n.errors,name:We};n={...n,...bt},p.state.next(bt)}},D=async We=>{v(We,!0);const rt=await t.resolver(i,t.context,Oes(We||o.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return v(We),rt},M=async We=>{const{errors:rt}=await D(We);if(We)for(const tt of We){const at=Ia(rt,tt);at?Sc(n.errors,tt,at):Wh(n.errors,tt)}else n.errors=rt;return rt},F=async(We,rt,tt={valid:!0})=>{for(const at in We){const He=We[at];if(He){const{_f:dt,...bt}=He;if(dt){const vt=o.array.has(dt.name),Bt=He._f&&Fes(He._f);Bt&&u.validatingFields&&v([at],!0);const Zt=await TUe(He,o.disabled,i,f,t.shouldUseNativeValidation&&!rt,vt);if(Bt&&u.validatingFields&&v([at]),Zt[dt.name]&&(tt.valid=!1,rt))break;!rt&&(Ia(Zt,dt.name)?vt?Ves(n.errors,Zt,dt.name):Sc(n.errors,dt.name,Zt[dt.name]):Wh(n.errors,dt.name))}!Eg(bt)&&await F(bt,rt,tt)}}return tt.valid},z=()=>{for(const We of o.unMount){const rt=Ia(r,We);rt&&(rt._f.refs?rt._f.refs.every(tt=>!Lje(tt)):!Lje(rt._f.ref))&&Ae(We)}o.unMount=new Set},V=(We,rt)=>!t.disabled&&(We&&rt&&Sc(i,We,rt),!I2(pe(),a)),W=(We,rt,tt)=>smt(We,o,{...l.mount?i:kh(rt)?a:rw(We)?{[We]:rt}:rt},tt,rt),Y=We=>i6e(Ia(l.mount?i:a,We,t.shouldUnregister?Ia(a,We,[]):[])),K=(We,rt,tt={})=>{const at=Ia(r,We);let He=rt;if(at){const dt=at._f;dt&&(!dt.disabled&&Sc(i,We,lmt(rt,dt)),He=Efe(dt.ref)&&Vx(rt)?"":rt,rmt(dt.ref)?[...dt.ref.options].forEach(bt=>bt.selected=He.includes(bt.value)):dt.refs?uU(dt.ref)?dt.refs.forEach(bt=>{(!bt.defaultChecked||!bt.disabled)&&(Array.isArray(He)?bt.checked=!!He.find(vt=>vt===bt.value):bt.checked=He===bt.value||!!He)}):dt.refs.forEach(bt=>bt.checked=bt.value===He):d6e(dt.ref)?dt.ref.value="":(dt.ref.value=He,dt.ref.type||p.state.next({name:We,values:Tm(i)})))}(tt.shouldDirty||tt.shouldTouch)&&T(We,He,tt.shouldTouch,tt.shouldDirty,!0),tt.shouldValidate&&ce(We)},J=(We,rt,tt)=>{for(const at in rt){if(!rt.hasOwnProperty(at))return;const He=rt[at],dt=We+"."+at,bt=Ia(r,dt);(o.array.has(We)||Dh(He)||bt&&!bt._f)&&!YE(He)?J(dt,He,tt):K(dt,He,tt)}},ne=(We,rt,tt={})=>{const at=Ia(r,We),He=o.array.has(We),dt=Tm(rt);Sc(i,We,dt),He?(p.array.next({name:We,values:Tm(i)}),(u.isDirty||u.dirtyFields||h.isDirty||h.dirtyFields)&&tt.shouldDirty&&p.state.next({name:We,dirtyFields:cF(a,i),isDirty:V(We,dt)})):at&&!at._f&&!Vx(dt)?J(We,dt,tt):K(We,dt,tt),kUe(We,o)&&p.state.next({...n,name:We}),p.state.next({name:l.mount?We:void 0,values:Tm(i)})},ie=async We=>{l.mount=!0;const rt=We.target;let tt=rt.name,at=!0;const He=Ia(r,tt),dt=Bt=>{at=Number.isNaN(Bt)||YE(Bt)&&isNaN(Bt.getTime())||I2(Bt,Ia(i,tt,Bt))},bt=jUe(t.mode),vt=jUe(t.reValidateMode);if(He){let Bt,Zt;const Fs=rt.type?wUe(He._f):Jht(We),Rs=We.type===Tfe.BLUR||We.type===Tfe.FOCUS_OUT,ms=!zes(He._f)&&!t.resolver&&!Ia(n.errors,tt)&&!He._f.deps||Ues(Rs,Ia(n.touchedFields,tt),n.isSubmitted,vt,bt),Pt=kUe(tt,o,Rs);Sc(i,tt,Fs),Rs?(He._f.onBlur&&He._f.onBlur(We),c&&c(0)):He._f.onChange&&He._f.onChange(We);const Jt=T(tt,Fs,Rs),ft=!Eg(Jt)||Pt;if(!Rs&&p.state.next({name:tt,type:We.type,values:Tm(i)}),ms)return(u.isValid||h.isValid)&&(t.mode==="onBlur"?Rs&&_():Rs||_()),ft&&p.state.next({name:tt,...Pt?{}:Jt});if(!Rs&&Pt&&p.state.next({...n}),t.resolver){const{errors:Vt}=await D([tt]);if(dt(Fs),at){const Ms=SUe(n.errors,r,tt),Xt=SUe(Vt,r,Ms.name||tt);Bt=Xt.error,tt=Xt.name,Zt=Eg(Vt)}}else v([tt],!0),Bt=(await TUe(He,o.disabled,i,f,t.shouldUseNativeValidation))[tt],v([tt]),dt(Fs),at&&(Bt?Zt=!1:(u.isValid||h.isValid)&&(Zt=await F(r,!0)));at&&(He._f.deps&&ce(He._f.deps),L(tt,Zt,Bt,Jt))}},he=(We,rt)=>{if(Ia(n.errors,rt)&&We.focus)return We.focus(),1},ce=async(We,rt={})=>{let tt,at;const He=tz(We);if(t.resolver){const dt=await M(kh(We)?We:He);tt=Eg(dt),at=We?!He.some(bt=>Ia(dt,bt)):tt}else We?(at=(await Promise.all(He.map(async dt=>{const bt=Ia(r,dt);return await F(bt&&bt._f?{[dt]:bt}:bt)}))).every(Boolean),!(!at&&!n.isValid)&&_()):at=tt=await F(r);return p.state.next({...!rw(We)||(u.isValid||h.isValid)&&tt!==n.isValid?{}:{name:We},...t.resolver||!We?{isValid:tt}:{},errors:n.errors}),rt.shouldFocus&&!at&&sz(r,he,We?He:o.mount),at},pe=We=>{const rt={...l.mount?i:a};return kh(We)?rt:rw(We)?Ia(rt,We):We.map(tt=>Ia(rt,tt))},le=(We,rt)=>({invalid:!!Ia((rt||n).errors,We),isDirty:!!Ia((rt||n).dirtyFields,We),error:Ia((rt||n).errors,We),isValidating:!!Ia(n.validatingFields,We),isTouched:!!Ia((rt||n).touchedFields,We)}),ve=We=>{We&&tz(We).forEach(rt=>Wh(n.errors,rt)),p.state.next({errors:We?n.errors:{}})},ge=(We,rt,tt)=>{const at=(Ia(r,We,{_f:{}})._f||{}).ref,He=Ia(n.errors,We)||{},{ref:dt,message:bt,type:vt,...Bt}=He;Sc(n.errors,We,{...Bt,...rt,ref:at}),p.state.next({name:We,errors:n.errors,isValid:!1}),tt&&tt.shouldFocus&&at&&at.focus&&at.focus()},Te=(We,rt)=>rb(We)?p.state.subscribe({next:tt=>"values"in tt&&We(W(void 0,rt),tt)}):W(We,rt,!0),Me=We=>p.state.subscribe({next:rt=>{$es(We.name,rt.name,We.exact)&&Bes(rt,We.formState||u,Ge,We.reRenderRoot)&&We.callback({values:{...i},...n,...rt,defaultValues:a})}}).unsubscribe,Ce=We=>(l.mount=!0,h={...h,...We.formState},Me({...We,formState:h})),Ae=(We,rt={})=>{for(const tt of We?tz(We):o.mount)o.mount.delete(tt),o.array.delete(tt),rt.keepValue||(Wh(r,tt),Wh(i,tt)),!rt.keepError&&Wh(n.errors,tt),!rt.keepDirty&&Wh(n.dirtyFields,tt),!rt.keepTouched&&Wh(n.touchedFields,tt),!rt.keepIsValidating&&Wh(n.validatingFields,tt),!t.shouldUnregister&&!rt.keepDefaultValue&&Wh(a,tt);p.state.next({values:Tm(i)}),p.state.next({...n,...rt.keepDirty?{isDirty:V()}:{}}),!rt.keepIsValid&&_()},De=({disabled:We,name:rt})=>{(H0(We)&&l.mount||We||o.disabled.has(rt))&&(We?o.disabled.add(rt):o.disabled.delete(rt))},Ie=(We,rt={})=>{let tt=Ia(r,We);const at=H0(rt.disabled)||H0(t.disabled);return Sc(r,We,{...tt||{},_f:{...tt&&tt._f?tt._f:{ref:{name:We}},name:We,mount:!0,...rt}}),o.mount.add(We),tt?De({disabled:H0(rt.disabled)?rt.disabled:t.disabled,name:We}):A(We,!0,rt.value),{...at?{disabled:rt.disabled||t.disabled}:{},...t.progressive?{required:!!rt.required,min:dF(rt.min),max:dF(rt.max),minLength:dF(rt.minLength),maxLength:dF(rt.maxLength),pattern:dF(rt.pattern)}:{},name:We,onChange:ie,onBlur:ie,ref:He=>{if(He){Ie(We,rt),tt=Ia(r,We);const dt=kh(He.value)&&He.querySelectorAll&&He.querySelectorAll("input,select,textarea")[0]||He,bt=Les(dt),vt=tt._f.refs||[];if(bt?vt.find(Bt=>Bt===dt):dt===tt._f.ref)return;Sc(r,We,{_f:{...tt._f,...bt?{refs:[...vt.filter(Lje),dt,...Array.isArray(Ia(a,We))?[{}]:[]],ref:{type:dt.type,name:We}}:{ref:dt}}}),A(We,!1,void 0,dt)}else tt=Ia(r,We,{}),tt._f&&(tt._f.mount=!1),(t.shouldUnregister||rt.shouldUnregister)&&!(emt(o.array,We)&&l.action)&&o.unMount.add(We)}}},Fe=()=>t.shouldFocusError&&sz(r,he,o.mount),qe=We=>{H0(We)&&(p.state.next({disabled:We}),sz(r,(rt,tt)=>{const at=Ia(r,tt);at&&(rt.disabled=at._f.disabled||We,Array.isArray(at._f.refs)&&at._f.refs.forEach(He=>{He.disabled=at._f.disabled||We}))},0,!1))},be=(We,rt)=>async tt=>{let at;tt&&(tt.preventDefault&&tt.preventDefault(),tt.persist&&tt.persist());let He=Tm(i);if(p.state.next({isSubmitting:!0}),t.resolver){const{errors:dt,values:bt}=await D();n.errors=dt,He=Tm(bt)}else await F(r);if(o.disabled.size)for(const dt of o.disabled)Wh(He,dt);if(Wh(n.errors,"root"),Eg(n.errors)){p.state.next({errors:{}});try{await We(He,tt)}catch(dt){at=dt}}else rt&&await rt({...n.errors},tt),Fe(),setTimeout(Fe);if(p.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Eg(n.errors)&&!at,submitCount:n.submitCount+1,errors:n.errors}),at)throw at},Ze=(We,rt={})=>{Ia(r,We)&&(kh(rt.defaultValue)?ne(We,Tm(Ia(a,We))):(ne(We,rt.defaultValue),Sc(a,We,Tm(rt.defaultValue))),rt.keepTouched||Wh(n.touchedFields,We),rt.keepDirty||(Wh(n.dirtyFields,We),n.isDirty=rt.defaultValue?V(We,Tm(Ia(a,We))):V()),rt.keepError||(Wh(n.errors,We),u.isValid&&_()),p.state.next({...n}))},Ne=(We,rt={})=>{const tt=We?Tm(We):a,at=Tm(tt),He=Eg(We),dt=He?a:at;if(rt.keepDefaultValues||(a=tt),!rt.keepValues){if(rt.keepDirtyValues){const bt=new Set([...o.mount,...Object.keys(cF(a,i))]);for(const vt of Array.from(bt))Ia(n.dirtyFields,vt)?Sc(dt,vt,Ia(i,vt)):ne(vt,Ia(dt,vt))}else{if(a6e&&kh(We))for(const bt of o.mount){const vt=Ia(r,bt);if(vt&&vt._f){const Bt=Array.isArray(vt._f.refs)?vt._f.refs[0]:vt._f.ref;if(Efe(Bt)){const Zt=Bt.closest("form");if(Zt){Zt.reset();break}}}}if(rt.keepFieldsRef)for(const bt of o.mount)ne(bt,Ia(dt,bt));else r={}}i=t.shouldUnregister?rt.keepDefaultValues?Tm(a):{}:Tm(dt),p.array.next({values:{...dt}}),p.state.next({values:{...dt}})}o={mount:rt.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!u.isValid||!!rt.keepIsValid||!!rt.keepDirtyValues,l.watch=!!t.shouldUnregister,p.state.next({submitCount:rt.keepSubmitCount?n.submitCount:0,isDirty:He?!1:rt.keepDirty?n.isDirty:!!(rt.keepDefaultValues&&!I2(We,a)),isSubmitted:rt.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:He?{}:rt.keepDirtyValues?rt.keepDefaultValues&&i?cF(a,i):n.dirtyFields:rt.keepDefaultValues&&We?cF(a,We):rt.keepDirty?n.dirtyFields:{},touchedFields:rt.keepTouched?n.touchedFields:{},errors:rt.keepErrors?n.errors:{},isSubmitSuccessful:rt.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},it=(We,rt)=>Ne(rb(We)?We(i):We,rt),je=(We,rt={})=>{const tt=Ia(r,We),at=tt&&tt._f;if(at){const He=at.refs?at.refs[0]:at.ref;He.focus&&(He.focus(),rt.shouldSelect&&rb(He.select)&&He.select())}},Ge=We=>{n={...n,...We}},Ye={control:{register:Ie,unregister:Ae,getFieldState:le,handleSubmit:be,setError:ge,_subscribe:Me,_runSchema:D,_focusError:Fe,_getWatch:W,_getDirty:V,_setValid:_,_setFieldArray:j,_setDisabledField:De,_setErrors:S,_getFieldArray:Y,_reset:Ne,_resetDefaultValues:()=>rb(t.defaultValues)&&t.defaultValues().then(We=>{it(We,t.resetOptions),p.state.next({isLoading:!1})}),_removeUnmounted:z,_disableForm:qe,_subjects:p,_proxyFormState:u,get _fields(){return r},get _formValues(){return i},get _state(){return l},set _state(We){l=We},get _defaultValues(){return a},get _names(){return o},set _names(We){o=We},get _formState(){return n},get _options(){return t},set _options(We){t={...t,...We}}},subscribe:Ce,trigger:ce,register:Ie,handleSubmit:be,watch:Te,setValue:ne,getValues:pe,reset:it,resetField:Ze,clearErrors:ve,unregister:Ae,setError:ge,setFocus:je,getFieldState:le};return{...Ye,formControl:Ye}}function Dye(s={}){const t=St.useRef(void 0),n=St.useRef(void 0),[r,a]=St.useState({isDirty:!1,isValidating:!1,isLoading:rb(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:rb(s.defaultValues)?void 0:s.defaultValues});if(!t.current)if(s.formControl)t.current={...s.formControl,formState:r},s.defaultValues&&!rb(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:l,...o}=Ges(s);t.current={...o,formState:r}}const i=t.current.control;return i._options=s,c6e(()=>{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]),St.useEffect(()=>i._disableForm(s.disabled),[i,s.disabled]),St.useEffect(()=>{s.mode&&(i._options.mode=s.mode),s.reValidateMode&&(i._options.reValidateMode=s.reValidateMode)},[i,s.mode,s.reValidateMode]),St.useEffect(()=>{s.errors&&(i._setErrors(s.errors),i._focusError())},[i,s.errors]),St.useEffect(()=>{s.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,s.shouldUnregister]),St.useEffect(()=>{if(i._proxyFormState.isDirty){const l=i._getDirty();l!==r.isDirty&&i._subjects.state.next({isDirty:l})}},[i,r.isDirty]),St.useEffect(()=>{s.values&&!I2(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]),St.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=tmt(r,i),t.current}const EUe=(s,t,n)=>{if(s&&"reportValidity"in s){const r=Ia(n,t);s.setCustomValidity(r&&r.message||""),s.reportValidity()}},dmt=(s,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?EUe(r.ref,n,s):r.refs&&r.refs.forEach(a=>EUe(a,n,s))}},Wes=(s,t)=>{t.shouldUseNativeValidation&&dmt(s,t);const n={};for(const r in s){const a=Ia(t.fields,r),i=Object.assign(s[r]||{},{ref:a&&a.ref});if(Kes(t.names||Object.keys(s),r)){const l=Object.assign({},Ia(n,r));Sc(l,"root",i),Sc(n,r,l)}else Sc(n,r,i)}return n},Kes=(s,t)=>s.some(n=>n.startsWith(t+"."));var Yes=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]=nmt(l,t,n,a,d?[].concat(d,r.message):r.message)}s.shift()}return n},Rye=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&&dmt({},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:Wes(Yes(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}};const Oye=Ees,umt=N.createContext({}),Nu=({...s})=>e.jsx(umt.Provider,{value:{name:s.name},children:e.jsx(Pes,{...s})}),Fye=()=>{const s=N.useContext(umt),t=N.useContext(hmt),{getFieldState:n,formState:r}=Lye(),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}},hmt=N.createContext({}),nu=N.forwardRef(({className:s,...t},n)=>{const r=N.useId();return e.jsx(hmt.Provider,{value:{id:r},children:e.jsx("div",{ref:n,className:Et("space-y-2",s),...t})})});nu.displayName="FormItem";const ru=N.forwardRef(({className:s,...t},n)=>{const{error:r,formItemId:a}=Fye();return e.jsx(se,{ref:n,className:Et(r&&"text-destructive",s),htmlFor:a,...t})});ru.displayName="FormLabel";const au=N.forwardRef(({...s},t)=>{const{error:n,formItemId:r,formDescriptionId:a,formMessageId:i}=Fye();return e.jsx(iAe,{ref:t,id:r,"aria-describedby":n?`${a} ${i}`:`${a}`,"aria-invalid":!!n,...s})});au.displayName="FormControl";const Vme=N.forwardRef(({className:s,...t},n)=>{const{formDescriptionId:r}=Fye();return e.jsx("p",{ref:n,id:r,className:Et("text-sm text-muted-foreground",s),...t})});Vme.displayName="FormDescription";const Yx=N.forwardRef(({className:s,children:t,...n},r)=>{const{error:a,formMessageId:i}=Fye(),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});Yx.displayName="FormMessage";const Zes=Yw({category:yMe(["general","technology","crm","marketing"]),subject:go().min(5,"Subject must be at least 5 characters").max(200),description:go().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),Qes={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function pCe({trigger:s}){const[t,n]=N.useState(!1),[r,a]=N.useState(!1),{user:i}=ys(),l=Dye({resolver:Rye(Zes),defaultValues:{category:"general",subject:"",description:""}}),o=async c=>{if(!i){ae.error("You must be logged in to submit a ticket");return}a(!0);try{const{error:d}=await q.from("support_tickets").insert({user_id:i.id,category:c.category,subject:c.subject,description:c.description});if(d)throw d;try{await q.functions.invoke("support-ticket-notify",{body:{category:Qes[c.category],subject:c.subject}})}catch(u){console.log("Notification send attempted:",u)}ae.success("Support ticket submitted successfully!"),l.reset(),n(!1)}catch(d){console.error("Error submitting ticket:",d),ae.error("Failed to submit ticket. Please try again.")}finally{a(!1)}};return e.jsxs(bs,{open:t,onOpenChange:n,children:[e.jsx(Ai,{asChild:!0,children:s||e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(h9,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(vs,{className:"sm:max-w-[500px]",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Need Help?"}),e.jsx(Qn,{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(Ar,{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(Oye,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(Nu,{control:l.control,name:"category",render:({field:c})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Category"}),e.jsxs(ds,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx(au,{children:e.jsx(ls,{children:e.jsx(us,{placeholder:"Select a category"})})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"general",children:"General Support"}),e.jsx(Qe,{value:"technology",children:"Technology Support"}),e.jsx(Qe,{value:"crm",children:"CRM Support"}),e.jsx(Qe,{value:"marketing",children:"Marketing Support"})]})]}),e.jsx(Yx,{})]})}),e.jsx(Nu,{control:l.control,name:"subject",render:({field:c})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Subject"}),e.jsx(au,{children:e.jsx(ye,{placeholder:"Brief description of your issue",...c})}),e.jsx(Yx,{})]})}),e.jsx(Nu,{control:l.control,name:"description",render:({field:c})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Description"}),e.jsx(au,{children:e.jsx(Es,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...c})}),e.jsx(Yx,{})]})}),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 Xes=()=>{const{user:s}=ys(),t=Mn(),[n,r]=N.useState([]),[a,i]=N.useState(0),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=N.useRef(null);N.useEffect(()=>{u.current=c},[c]),N.useEffect(()=>{if(!s)return;const _=`notification_last_read_${s.id}`,v=localStorage.getItem(_);v&&!u.current&&(u.current=v,d(v));const j=`nb_cache_${s.id}`,b=60*1e3,S=async()=>{try{const M=sessionStorage.getItem(j);if(M){const F=JSON.parse(M);if(F.ts&&Date.now()-F.ts{r(L);const D=u.current?new Date(u.current):null,M=L.filter(F=>D?new Date(F.created_at)>D:!0);i(M.length)};S();const T=q.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},L=>{const D=L.new;r(F=>{const z=[D,...F].slice(0,20);try{sessionStorage.setItem(j,JSON.stringify({ts:Date.now(),data:z}))}catch{}return z});const M=u.current?new Date(u.current):null;(!M||new Date(D.created_at)>M)&&i(F=>F+1),Notification.permission==="granted"&&new Notification(D.title,{body:D.body,icon:"/favicon.ico"})}).subscribe();return()=>{q.removeChannel(T)}},[s]);const h=_=>{const v=_.toLowerCase();return v.includes("community")||v.includes("post")?Ei:v.includes("academy")||v.includes("video")?br:v.includes("template")?fl:v.includes("event")?yr:v.includes("newsletter")?ay:v.includes("brokerage")?qm:v.includes("swag")||v.includes("social")?Oi:v.includes("toolbox")||v.includes("tool")?_b:v.includes("brief")?un:Ei},p=_=>{o(!1),_.url&&_.url!=="/"&&t(_.url)},f=()=>{if(!s)return;const _=new Date().toISOString(),v=`notification_last_read_${s.id}`;localStorage.setItem(v,_),d(_),i(0)},g=_=>{o(_),_&&a>0&&f()};return e.jsxs(wc,{open:l,onOpenChange:g,children:[e.jsx(jc,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(im,{className:"h-5 w-5"}),a>0&&e.jsx(ze,{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(cc,{align:"end",className:"w-80",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[e.jsx("span",{className:"font-semibold",children:"Notifications"}),n.length>0&&e.jsx(B,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:f,children:"Mark all read"})]}),e.jsx(hi,{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(_=>{const v=h(_.title);return e.jsxs(Qr,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>p(_),children:[e.jsx("div",{className:"flex-shrink-0 mt-0.5",children:e.jsx(v,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[e.jsx("span",{className:"font-medium text-sm",children:_.title}),e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:_.body}),e.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:Vo(new Date(_.created_at),{addSuffix:!0})})]})]},_.id)})})]})]})};var AUe=1,Jes=.9,ets=.8,tts=.17,Dje=.1,Rje=.999,sts=.9999,nts=.99,rts=/[\\\/_+.#"@\[\(\{&]/,ats=/[\\\/_+.#"@\[\(\{&]/g,its=/[\s-]/,mmt=/[\s-]/g;function fCe(s,t,n,r,a,i,l){if(i===t.length)return a===s.length?AUe:nts;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,p,f,g;d>=0;)h=fCe(s,t,n,r,d+1,i+1,l),h>u&&(d===a?h*=AUe:rts.test(s.charAt(d-1))?(h*=ets,f=s.slice(a,d-1).match(ats),f&&a>0&&(h*=Math.pow(Rje,f.length))):its.test(s.charAt(d-1))?(h*=Jes,g=s.slice(a,d-1).match(mmt),g&&a>0&&(h*=Math.pow(Rje,g.length))):(h*=tts,a>0&&(h*=Math.pow(Rje,d-a))),s.charAt(d)!==t.charAt(i)&&(h*=sts)),(hh&&(h=p*Dje)),h>u&&(u=h),d=n.indexOf(c,d+1);return l[o]=u,u}function MUe(s){return s.toLowerCase().replace(mmt," ")}function ots(s,t,n){return s=n&&n.length>0?`${s+" "+n.join(" ")}`:s,fCe(s,t,MUe(s),MUe(t),0,0,{})}var uF='[cmdk-group=""]',Oje='[cmdk-group-items=""]',lts='[cmdk-group-heading=""]',pmt='[cmdk-item=""]',IUe=`${pmt}:not([aria-disabled="true"])`,xCe="cmdk-item-select",aP="data-value",cts=(s,t,n)=>ots(s,t,n),fmt=N.createContext(void 0),hU=()=>N.useContext(fmt),xmt=N.createContext(void 0),h6e=()=>N.useContext(xmt),gmt=N.createContext(void 0),ymt=N.forwardRef((s,t)=>{let n=iP(()=>{var ve,ge;return{search:"",value:(ge=(ve=s.value)!=null?ve:s.defaultValue)!=null?ge:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=iP(()=>new Set),a=iP(()=>new Map),i=iP(()=>new Map),l=iP(()=>new Set),o=vmt(s),{label:c,children:d,value:u,onValueChange:h,filter:p,shouldFilter:f,loop:g,disablePointerSelection:_=!1,vimBindings:v=!0,...j}=s,b=dm(),S=dm(),A=dm(),T=N.useRef(null),L=bts();bM(()=>{if(u!==void 0){let ve=u.trim();n.current.value=ve,D.emit()}},[u]),bM(()=>{L(6,Y)},[]);let D=N.useMemo(()=>({subscribe:ve=>(l.current.add(ve),()=>l.current.delete(ve)),snapshot:()=>n.current,setState:(ve,ge,Te)=>{var Me,Ce,Ae,De;if(!Object.is(n.current[ve],ge)){if(n.current[ve]=ge,ve==="search")W(),z(),L(1,V);else if(ve==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Ie=document.getElementById(A);Ie?Ie.focus():(Me=document.getElementById(b))==null||Me.focus()}if(L(7,()=>{var Ie;n.current.selectedItemId=(Ie=K())==null?void 0:Ie.id,D.emit()}),Te||L(5,Y),((Ce=o.current)==null?void 0:Ce.value)!==void 0){let Ie=ge??"";(De=(Ae=o.current).onValueChange)==null||De.call(Ae,Ie);return}}D.emit()}},emit:()=>{l.current.forEach(ve=>ve())}}),[]),M=N.useMemo(()=>({value:(ve,ge,Te)=>{var Me;ge!==((Me=i.current.get(ve))==null?void 0:Me.value)&&(i.current.set(ve,{value:ge,keywords:Te}),n.current.filtered.items.set(ve,F(ge,Te)),L(2,()=>{z(),D.emit()}))},item:(ve,ge)=>(r.current.add(ve),ge&&(a.current.has(ge)?a.current.get(ge).add(ve):a.current.set(ge,new Set([ve]))),L(3,()=>{W(),z(),n.current.value||V(),D.emit()}),()=>{i.current.delete(ve),r.current.delete(ve),n.current.filtered.items.delete(ve);let Te=K();L(4,()=>{W(),(Te==null?void 0:Te.getAttribute("id"))===ve&&V(),D.emit()})}),group:ve=>(a.current.has(ve)||a.current.set(ve,new Set),()=>{i.current.delete(ve),a.current.delete(ve)}),filter:()=>o.current.shouldFilter,label:c||s["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:b,inputId:A,labelId:S,listInnerRef:T}),[]);function F(ve,ge){var Te,Me;let Ce=(Me=(Te=o.current)==null?void 0:Te.filter)!=null?Me:cts;return ve?Ce(ve,n.current.search,ge):0}function z(){if(!n.current.search||o.current.shouldFilter===!1)return;let ve=n.current.filtered.items,ge=[];n.current.filtered.groups.forEach(Me=>{let Ce=a.current.get(Me),Ae=0;Ce.forEach(De=>{let Ie=ve.get(De);Ae=Math.max(Ie,Ae)}),ge.push([Me,Ae])});let Te=T.current;J().sort((Me,Ce)=>{var Ae,De;let Ie=Me.getAttribute("id"),Fe=Ce.getAttribute("id");return((Ae=ve.get(Fe))!=null?Ae:0)-((De=ve.get(Ie))!=null?De:0)}).forEach(Me=>{let Ce=Me.closest(Oje);Ce?Ce.appendChild(Me.parentElement===Ce?Me:Me.closest(`${Oje} > *`)):Te.appendChild(Me.parentElement===Te?Me:Me.closest(`${Oje} > *`))}),ge.sort((Me,Ce)=>Ce[1]-Me[1]).forEach(Me=>{var Ce;let Ae=(Ce=T.current)==null?void 0:Ce.querySelector(`${uF}[${aP}="${encodeURIComponent(Me[0])}"]`);Ae==null||Ae.parentElement.appendChild(Ae)})}function V(){let ve=J().find(Te=>Te.getAttribute("aria-disabled")!=="true"),ge=ve==null?void 0:ve.getAttribute(aP);D.setState("value",ge||void 0)}function W(){var ve,ge,Te,Me;if(!n.current.search||o.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let Ce=0;for(let Ae of r.current){let De=(ge=(ve=i.current.get(Ae))==null?void 0:ve.value)!=null?ge:"",Ie=(Me=(Te=i.current.get(Ae))==null?void 0:Te.keywords)!=null?Me:[],Fe=F(De,Ie);n.current.filtered.items.set(Ae,Fe),Fe>0&&Ce++}for(let[Ae,De]of a.current)for(let Ie of De)if(n.current.filtered.items.get(Ie)>0){n.current.filtered.groups.add(Ae);break}n.current.filtered.count=Ce}function Y(){var ve,ge,Te;let Me=K();Me&&(((ve=Me.parentElement)==null?void 0:ve.firstChild)===Me&&((Te=(ge=Me.closest(uF))==null?void 0:ge.querySelector(lts))==null||Te.scrollIntoView({block:"nearest"})),Me.scrollIntoView({block:"nearest"}))}function K(){var ve;return(ve=T.current)==null?void 0:ve.querySelector(`${pmt}[aria-selected="true"]`)}function J(){var ve;return Array.from(((ve=T.current)==null?void 0:ve.querySelectorAll(IUe))||[])}function ne(ve){let ge=J()[ve];ge&&D.setState("value",ge.getAttribute(aP))}function ie(ve){var ge;let Te=K(),Me=J(),Ce=Me.findIndex(De=>De===Te),Ae=Me[Ce+ve];(ge=o.current)!=null&&ge.loop&&(Ae=Ce+ve<0?Me[Me.length-1]:Ce+ve===Me.length?Me[0]:Me[Ce+ve]),Ae&&D.setState("value",Ae.getAttribute(aP))}function he(ve){let ge=K(),Te=ge==null?void 0:ge.closest(uF),Me;for(;Te&&!Me;)Te=ve>0?yts(Te,uF):vts(Te,uF),Me=Te==null?void 0:Te.querySelector(IUe);Me?D.setState("value",Me.getAttribute(aP)):ie(ve)}let ce=()=>ne(J().length-1),pe=ve=>{ve.preventDefault(),ve.metaKey?ce():ve.altKey?he(1):ie(1)},le=ve=>{ve.preventDefault(),ve.metaKey?ne(0):ve.altKey?he(-1):ie(-1)};return N.createElement(Jr.div,{ref:t,tabIndex:-1,...j,"cmdk-root":"",onKeyDown:ve=>{var ge;(ge=j.onKeyDown)==null||ge.call(j,ve);let Te=ve.nativeEvent.isComposing||ve.keyCode===229;if(!(ve.defaultPrevented||Te))switch(ve.key){case"n":case"j":{v&&ve.ctrlKey&&pe(ve);break}case"ArrowDown":{pe(ve);break}case"p":case"k":{v&&ve.ctrlKey&&le(ve);break}case"ArrowUp":{le(ve);break}case"Home":{ve.preventDefault(),ne(0);break}case"End":{ve.preventDefault(),ce();break}case"Enter":{ve.preventDefault();let Me=K();if(Me){let Ce=new Event(xCe);Me.dispatchEvent(Ce)}}}}},N.createElement("label",{"cmdk-label":"",htmlFor:M.inputId,id:M.labelId,style:wts},c),zye(s,ve=>N.createElement(xmt.Provider,{value:D},N.createElement(fmt.Provider,{value:M},ve))))}),dts=N.forwardRef((s,t)=>{var n,r;let a=dm(),i=N.useRef(null),l=N.useContext(gmt),o=hU(),c=vmt(s),d=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:l==null?void 0:l.forceMount;bM(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let u=bmt(a,i,[s.value,s.children,i],s.keywords),h=h6e(),p=D4(L=>L.value&&L.value===u.current),f=D4(L=>d||o.filter()===!1?!0:L.search?L.filtered.items.get(a)>0:!0);N.useEffect(()=>{let L=i.current;if(!(!L||s.disabled))return L.addEventListener(xCe,g),()=>L.removeEventListener(xCe,g)},[f,s.onSelect,s.disabled]);function g(){var L,D;_(),(D=(L=c.current).onSelect)==null||D.call(L,u.current)}function _(){h.setState("value",u.current,!0)}if(!f)return null;let{disabled:v,value:j,onSelect:b,forceMount:S,keywords:A,...T}=s;return N.createElement(Jr.div,{ref:uN(i,t),...T,id:a,"cmdk-item":"",role:"option","aria-disabled":!!v,"aria-selected":!!p,"data-disabled":!!v,"data-selected":!!p,onPointerMove:v||o.getDisablePointerSelection()?void 0:_,onClick:v?void 0:g},s.children)}),uts=N.forwardRef((s,t)=>{let{heading:n,children:r,forceMount:a,...i}=s,l=dm(),o=N.useRef(null),c=N.useRef(null),d=dm(),u=hU(),h=D4(f=>a||u.filter()===!1?!0:f.search?f.filtered.groups.has(l):!0);bM(()=>u.group(l),[]),bmt(l,o,[s.value,s.heading,c]);let p=N.useMemo(()=>({id:l,forceMount:a}),[a]);return N.createElement(Jr.div,{ref:uN(o,t),...i,"cmdk-group":"",role:"presentation",hidden:h?void 0:!0},n&&N.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},n),zye(s,f=>N.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?d:void 0},N.createElement(gmt.Provider,{value:p},f))))}),hts=N.forwardRef((s,t)=>{let{alwaysRender:n,...r}=s,a=N.useRef(null),i=D4(l=>!l.search);return!n&&!i?null:N.createElement(Jr.div,{ref:uN(a,t),...r,"cmdk-separator":"",role:"separator"})}),mts=N.forwardRef((s,t)=>{let{onValueChange:n,...r}=s,a=s.value!=null,i=h6e(),l=D4(d=>d.search),o=D4(d=>d.selectedItemId),c=hU();return N.useEffect(()=>{s.value!=null&&i.setState("search",s.value)},[s.value]),N.createElement(Jr.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)}})}),pts=N.forwardRef((s,t)=>{let{children:n,label:r="Suggestions",...a}=s,i=N.useRef(null),l=N.useRef(null),o=D4(d=>d.selectedItemId),c=hU();return N.useEffect(()=>{if(l.current&&i.current){let d=l.current,u=i.current,h,p=new ResizeObserver(()=>{h=requestAnimationFrame(()=>{let f=d.offsetHeight;u.style.setProperty("--cmdk-list-height",f.toFixed(1)+"px")})});return p.observe(d),()=>{cancelAnimationFrame(h),p.unobserve(d)}}},[]),N.createElement(Jr.div,{ref:uN(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},zye(s,d=>N.createElement("div",{ref:uN(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),fts=N.forwardRef((s,t)=>{let{open:n,onOpenChange:r,overlayClassName:a,contentClassName:i,container:l,...o}=s;return N.createElement(tye,{open:n,onOpenChange:r},N.createElement(sye,{container:l},N.createElement(zD,{"cmdk-overlay":"",className:a}),N.createElement(BD,{"aria-label":s.label,"cmdk-dialog":"",className:i},N.createElement(ymt,{ref:t,...o}))))}),xts=N.forwardRef((s,t)=>D4(n=>n.filtered.count===0)?N.createElement(Jr.div,{ref:t,...s,"cmdk-empty":"",role:"presentation"}):null),gts=N.forwardRef((s,t)=>{let{progress:n,children:r,label:a="Loading...",...i}=s;return N.createElement(Jr.div,{ref:t,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},zye(s,l=>N.createElement("div",{"aria-hidden":!0},l)))}),a0=Object.assign(ymt,{List:pts,Item:dts,Input:mts,Group:uts,Separator:hts,Dialog:fts,Empty:xts,Loading:gts});function yts(s,t){let n=s.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function vts(s,t){let n=s.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function vmt(s){let t=N.useRef(s);return bM(()=>{t.current=s}),t}var bM=typeof window>"u"?N.useEffect:N.useLayoutEffect;function iP(s){let t=N.useRef();return t.current===void 0&&(t.current=s()),t}function D4(s){let t=h6e(),n=()=>s(t.snapshot());return N.useSyncExternalStore(t.subscribe,n,n)}function bmt(s,t,n,r=[]){let a=N.useRef(),i=hU();return bM(()=>{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(aP,o),a.current=o}),a}var bts=()=>{let[s,t]=N.useState(),n=iP(()=>new Map);return bM(()=>{n.current.forEach(r=>r()),n.current=new Map},[s]),(r,a)=>{n.current.set(r,a),t({})}};function _ts(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function zye({asChild:s,children:t},n){return s&&N.isValidElement(t)?N.cloneElement(_ts(t),{ref:t.ref},n(t.props.children)):n(t)}var wts={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const Qg=N.forwardRef(({className:s,...t},n)=>e.jsx(a0,{ref:n,className:Et("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));Qg.displayName=a0.displayName;const jts=({children:s,...t})=>e.jsx(bs,{...t,children:e.jsx(vs,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(Qg,{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})})}),Xg=N.forwardRef(({className:s,...t},n)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(vr,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(a0.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})]}));Xg.displayName=a0.Input.displayName;const Jg=N.forwardRef(({className:s,...t},n)=>e.jsx(a0.List,{ref:n,className:Et("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));Jg.displayName=a0.List.displayName;const e0=N.forwardRef((s,t)=>e.jsx(a0.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));e0.displayName=a0.Empty.displayName;const t0=N.forwardRef(({className:s,...t},n)=>e.jsx(a0.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}));t0.displayName=a0.Group.displayName;const Nts=N.forwardRef(({className:s,...t},n)=>e.jsx(a0.Separator,{ref:n,className:Et("-mx-1 h-px bg-border",s),...t}));Nts.displayName=a0.Separator.displayName;const Jf=N.forwardRef(({className:s,...t},n)=>e.jsx(a0.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}));Jf.displayName=a0.Item.displayName;const kts={event:{label:"Events",icon:Tl,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:fl,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:_d,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:_b,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:un,color:"bg-fuchsia-500/10 text-fuchsia-600"}},PUe=()=>{const[s,t]=N.useState(!1),[n,r]=N.useState(""),[a,i]=N.useState([]),[l,o]=N.useState(!1),c=Mn();N.useEffect(()=>{const p=f=>{f.key==="k"&&(f.metaKey||f.ctrlKey)&&(f.preventDefault(),t(g=>!g))};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[]);const d=N.useCallback(async p=>{if(!p.trim()){i([]);return}o(!0);const f=`%${p}%`;try{const[g,_,v,j,b]=await Promise.all([q.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${f},description.ilike.${f}`).limit(5),q.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${f},description.ilike.${f}`).limit(5),q.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${f},description.ilike.${f}`).limit(5),q.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${f},description.ilike.${f}`).limit(5),q.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${f},description.ilike.${f}`).limit(5)]),S=[];g.data&&g.data.forEach(A=>{S.push({id:A.id,title:A.title,description:A.description,type:"event",date:A.event_date,path:`/event/${A.id}`})}),_.data&&_.data.forEach(A=>{S.push({id:A.id,title:A.name,description:A.description,type:"template",date:A.publish_date,path:`/templates/${A.id}`})}),v.data&&v.data.forEach(A=>{S.push({id:A.id,title:A.title,description:A.description,type:"academy",date:A.publish_date,path:`/academy/${A.id}`})}),j.data&&j.data.forEach(A=>{S.push({id:A.id,title:A.name,description:A.description,type:"toolbox",date:A.publish_date,path:`/toolbox/${A.id}`})}),b.data&&b.data.forEach(A=>{S.push({id:A.id,title:A.title,description:A.description,type:"social-swag",date:A.publish_date,path:`/social-swag/${A.id}`})}),i(S)}catch(g){console.error("Search error:",g)}finally{o(!1)}},[]);N.useEffect(()=>{const p=setTimeout(()=>{d(n)},300);return()=>clearTimeout(p)},[n,d]);const u=p=>{t(!1),r(""),c(p)},h=a.reduce((p,f)=>(p[f.type]||(p[f.type]=[]),p[f.type].push(f),p),{});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(vr,{className:"h-4 w-4 xl:mr-2"}),e.jsx("span",{className:"hidden xl:inline-flex text-muted-foreground text-sm",children:"Search..."}),e.jsxs("kbd",{className:"pointer-events-none absolute right-1.5 top-1.5 hidden h-6 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium opacity-100 xl:flex",children:[e.jsx("span",{className:"text-xs",children:"⌘"}),"K"]})]}),e.jsxs(jts,{open:s,onOpenChange:t,children:[e.jsx(Xg,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:n,onValueChange:r}),e.jsxs(Jg,{children:[l&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!l&&n&&a.length===0&&e.jsxs(e0,{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(([p,f])=>{const g=kts[p],_=g.icon;return e.jsx(t0,{heading:g.label,children:f.map(v=>e.jsxs(Jf,{value:`${v.type}-${v.id}-${v.title}`,onSelect:()=>u(v.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:`p-2 rounded-md ${g.color}`,children:e.jsx(_,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:v.title}),v.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:v.description})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[e.jsx(ze,{variant:"secondary",className:"text-xs",children:g.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Vo(new Date(v.date),{addSuffix:!0})})]})]},`${v.type}-${v.id}`))},p)})]})]})]})},Sts=({expiresAt:s,className:t,showUpgradeButton:n=!0})=>{const[r,a]=N.useState(null),i=Mn();if(N.useEffect(()=>{const d=()=>{const h=new Date().getTime(),f=new Date(s).getTime()-h;if(f<=0){a({days:0,hours:0,minutes:0});return}const g=Math.floor(f/(1e3*60*60*24)),_=Math.floor(f%(1e3*60*60*24)/(1e3*60*60)),v=Math.floor(f%(1e3*60*60)/(1e3*60));a({days:g,hours:_,minutes:v})};d();const u=setInterval(d,6e4);return()=>clearInterval(u)},[s]),!r)return null;const l=r.days===0&&r.hours===0&&r.minutes===0,o=r.days<=1,c=r.days<=3&&!o;return l?e.jsxs("div",{className: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($l,{className:"h-4 w-4 text-destructive"}),e.jsx("span",{className:"text-sm font-medium text-destructive",children:"Your free trial has expired"})]}),n&&e.jsxs(B,{size:"sm",onClick:()=>i("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):e.jsxs("div",{className: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(gr,{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(un,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},Cts=()=>{const s=Mn();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(fe,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[e.jsxs(Mt,{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($l,{className:"h-8 w-8 text-destructive"})}),e.jsx(It,{className:"text-2xl",children:"Your Free Trial Has Ended"}),e.jsx(Vn,{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(Ee,{className:"space-y-6",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(fe,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Ee,{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(Nn,{className:"h-6 w-6 text-primary"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Individual Agent"}),e.jsxs("p",{className:"text-2xl font-bold text-primary mb-2",children:["$39",e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Perfect for solo agents ready to level up"}),e.jsxs(B,{className:"w-full",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),e.jsx(fe,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Ee,{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(Va,{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(Va,{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(Ar,{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(Vs,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},Tts=({hasUnseenBrief:s,onClick:t,className:n})=>e.jsxs(Ec,{children:[e.jsx(Ac,{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($d,{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(vc,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var m6e="Radio",[Ets,_mt]=pu(m6e),[Ats,Mts]=Ets(m6e),wmt=N.forwardRef((s,t)=>{const{__scopeRadio:n,name:r,checked:a=!1,required:i,disabled:l,value:o="on",onCheck:c,form:d,...u}=s,[h,p]=N.useState(null),f=Si(t,v=>p(v)),g=N.useRef(!1),_=h?d||!!h.closest("form"):!0;return e.jsxs(Ats,{scope:n,checked:a,disabled:l,children:[e.jsx(Jr.button,{type:"button",role:"radio","aria-checked":a,"data-state":Smt(a),"data-disabled":l?"":void 0,disabled:l,value:o,...u,ref:f,onClick:_r(s.onClick,v=>{a||c==null||c(),_&&(g.current=v.isPropagationStopped(),g.current||v.stopPropagation())})}),_&&e.jsx(kmt,{control:h,bubbles:!g.current,name:r,value:o,checked:a,required:i,disabled:l,form:d,style:{transform:"translateX(-100%)"}})]})});wmt.displayName=m6e;var jmt="RadioIndicator",Nmt=N.forwardRef((s,t)=>{const{__scopeRadio:n,forceMount:r,...a}=s,i=Mts(jmt,n);return e.jsx(Rh,{present:r||i.checked,children:e.jsx(Jr.span,{"data-state":Smt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t})})});Nmt.displayName=jmt;var Its="RadioBubbleInput",kmt=N.forwardRef(({__scopeRadio:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=N.useRef(null),o=Si(l,i),c=tU(n),d=B$(t);return N.useEffect(()=>{const u=l.current;if(!u)return;const h=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(h,"checked").set;if(c!==n&&f){const g=new Event("click",{bubbles:r});f.call(u,n),u.dispatchEvent(g)}},[c,n,r]),e.jsx(Jr.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}})});kmt.displayName=Its;function Smt(s){return s?"checked":"unchecked"}var Pts=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Bye="RadioGroup",[Lts,Oxn]=pu(Bye,[W4,_mt]),Cmt=W4(),Tmt=_mt(),[Dts,Rts]=Lts(Bye),Emt=N.forwardRef((s,t)=>{const{__scopeRadioGroup:n,name:r,defaultValue:a,value:i,required:l=!1,disabled:o=!1,orientation:c,dir:d,loop:u=!0,onValueChange:h,...p}=s,f=Cmt(n),g=NN(d),[_,v]=hm({prop:i,defaultProp:a??null,onChange:h,caller:Bye});return e.jsx(Dts,{scope:n,name:r,required:l,disabled:o,value:_,onValueChange:v,children:e.jsx(W0e,{asChild:!0,...f,orientation:c,dir:g,loop:u,children:e.jsx(Jr.div,{role:"radiogroup","aria-required":l,"aria-orientation":c,"data-disabled":o?"":void 0,dir:g,...p,ref:t})})})});Emt.displayName=Bye;var Amt="RadioGroupItem",Mmt=N.forwardRef((s,t)=>{const{__scopeRadioGroup:n,disabled:r,...a}=s,i=Rts(Amt,n),l=i.disabled||r,o=Cmt(n),c=Tmt(n),d=N.useRef(null),u=Si(t,d),h=i.value===a.value,p=N.useRef(!1);return N.useEffect(()=>{const f=_=>{Pts.includes(_.key)&&(p.current=!0)},g=()=>p.current=!1;return document.addEventListener("keydown",f),document.addEventListener("keyup",g),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",g)}},[]),e.jsx(K0e,{asChild:!0,...o,focusable:!l,active:h,children:e.jsx(wmt,{disabled:l,required:i.required,checked:h,...c,...a,name:i.name,ref:u,onCheck:()=>i.onValueChange(a.value),onKeyDown:_r(f=>{f.key==="Enter"&&f.preventDefault()}),onFocus:_r(a.onFocus,()=>{var f;p.current&&((f=d.current)==null||f.click())})})})});Mmt.displayName=Amt;var Ots="RadioGroupIndicator",Imt=N.forwardRef((s,t)=>{const{__scopeRadioGroup:n,...r}=s,a=Tmt(n);return e.jsx(Nmt,{...a,...r,ref:t})});Imt.displayName=Ots;var Pmt=Emt,Lmt=Mmt,Fts=Imt;const cb=N.forwardRef(({className:s,...t},n)=>e.jsx(Pmt,{className:Et("grid gap-2",s),...t,ref:n}));cb.displayName=Pmt.displayName;const Rd=N.forwardRef(({className:s,...t},n)=>e.jsx(Lmt,{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(Fts,{className:"flex items-center justify-center",children:e.jsx(lm,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Rd.displayName=Lmt.displayName;const zts=({brief:s,open:t,onClose:n,onDismiss:r})=>{const{user:a}=ys(),[i,l]=N.useState({}),[o,c]=N.useState({}),[d,u]=N.useState([]);N.useEffect(()=>{t&&a&&s.polls.length>0&&h()},[t,a,s.polls]);const h=async()=>{if(!a)return;const v=s.polls.map(b=>b.id),{data:j}=await q.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",v);if(j){const b={};j.forEach(S=>{b[S.poll_id]||(b[S.poll_id]=[]),b[S.poll_id].push(S.option_id)}),c(b)}},p=(v,j)=>{l(b=>({...b,[v]:j}))},f=(v,j,b)=>{l(S=>{const A=S[v]||[];return b?{...S,[v]:[...A,j]}:{...S,[v]:A.filter(T=>T!==j)}})},g=async v=>{if(!a)return;const j=i[v];if(!j||Array.isArray(j)&&j.length===0){ae.error("Please select an option");return}u(b=>[...b,v]);try{await q.from("levelup_brief_poll_responses").delete().eq("poll_id",v).eq("user_id",a.id);const b=Array.isArray(j)?j:[j],S=b.map(T=>({poll_id:v,option_id:T,user_id:a.id})),{error:A}=await q.from("levelup_brief_poll_responses").insert(S);if(A)throw A;c(T=>({...T,[v]:b})),ae.success("Response submitted!")}catch(b){console.error("Error submitting poll response:",b),ae.error("Failed to submit response")}finally{u(b=>b.filter(S=>S!==v))}},_=v=>(v.includes("mediadelivery.net")||v.includes("bunny"),v);return e.jsx(bs,{open:t,onOpenChange:v=>!v&&n(),children:e.jsxs(vs,{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(Bn,{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($d,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsx(ze,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),e.jsx(_s,{className:"text-xl font-bold text-white",children:s.brief.title})]})]})]}),e.jsx(hi,{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:_(s.brief.video_url),className:"absolute inset-0 w-full h-full",allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0})}),s.brief.graphic_url&&!s.brief.video_url&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted",children:s.brief.graphic_link_url?e.jsx("a",{href:s.brief.graphic_link_url,target:"_blank",rel:"noopener noreferrer",className:"block",children:e.jsx("img",{src:s.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain cursor-pointer hover:opacity-90 transition-opacity"})}):e.jsx("img",{src:s.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain"})}),s.links.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:"Quick Links"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:s.links.map(v=>e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(v.url,"_blank"),className:"gap-2",children:[e.jsx(tr,{className:"h-4 w-4"}),v.title]},v.id))})]}),s.polls.map(v=>{var S,A;const j=((S=o[v.id])==null?void 0:S.length)>0,b=d.includes(v.id);return e.jsxs("div",{className:"space-y-3 p-4 bg-muted/50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:v.question}),j&&e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(xr,{className:"h-3 w-3"}),"Responded"]})]}),v.poll_type==="single"?e.jsx(cb,{value:i[v.id]||((A=o[v.id])==null?void 0:A[0])||"",onValueChange:T=>p(v.id,T),className:"space-y-2",children:v.options.map(T=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Rd,{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:v.options.map(T=>{const D=(i[v.id]||o[v.id]||[]).includes(T.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ui,{id:T.id,checked:D,onCheckedChange:M=>f(v.id,T.id,M)}),e.jsx(se,{htmlFor:T.id,className:"cursor-pointer",children:T.option_text})]},T.id)})}),e.jsx(B,{size:"sm",onClick:()=>g(v.id),disabled:b,children:b?"Submitting...":j?"Update Response":"Submit"})]},v.id)})]})}),e.jsxs("div",{className:"p-4 pb-[calc(1rem+env(safe-area-inset-bottom))] border-t bg-muted/30 flex flex-col items-center gap-2 sticky bottom-0 z-10",children:[e.jsx(B,{onClick:n,className:"w-full max-w-xs",children:"Got it!"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:r,children:"Don't show again"})]})]})})},Bts=()=>{const{user:s}=ys(),[t,n]=N.useState(null),[r,a]=N.useState(!1),[i,l]=N.useState(!0),[o,c]=N.useState(!1),d=N.useCallback(async()=>{if(!s){l(!1);return}try{const{data:g,error:_}=await q.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(_||!g){l(!1);return}const{data:v}=await q.from("levelup_brief_views").select("*").eq("brief_id",g.id).eq("user_id",s.id).maybeSingle(),[j,b]=await Promise.all([q.from("levelup_brief_links").select("*").eq("brief_id",g.id).order("sort_order"),q.from("levelup_brief_polls").select("*").eq("brief_id",g.id).order("sort_order")]),S=[];if(b.data)for(const M of b.data){const{data:F}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",M.id).order("sort_order");S.push({...M,options:F||[]})}const A={brief:g,links:j.data||[],polls:S};n(A);const T=!!v,L=(v==null?void 0:v.dismissed_at)!=null,D=localStorage.getItem(`brief-dismissed-${g.id}`)==="true";if(L||D)c(!1),a(!1);else if(!T)a(!0),c(!0);else if(g.show_frequency==="every_login")a(!0),c(!0);else if(g.show_frequency==="daily"){const M=new Date(v.viewed_at);(new Date().getTime()-M.getTime())/(1e3*60*60)>=24&&(a(!0),c(!0))}else c(!1)}catch(g){console.error("Error fetching brief:",g)}finally{l(!1)}},[s]);N.useEffect(()=>{d()},[d]);const u=async()=>{if(!(!s||!t))try{const{data:g}=await q.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();g?await q.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",g.id):await q.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id})}catch(g){console.error("Error marking brief as viewed:",g)}};return{currentBrief:t,shouldShowPopup:r,hasUnseenBrief:o,loading:i,openBrief:()=>{a(!0)},closeBrief:()=>{a(!1),u()},dismissBrief:async()=>{if(!(!s||!t)){a(!1),c(!1);try{const{data:g,error:_}=await q.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();if(_&&console.error("Error checking existing brief view:",_),g){const{error:v}=await q.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",g.id).eq("user_id",s.id);v&&console.error("Error updating brief dismiss:",v)}else{const{error:v}=await q.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id,dismissed_at:new Date().toISOString()});v&&console.error("Error inserting brief dismiss:",v)}localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}catch(g){console.error("Error dismissing brief:",g),t&&localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}}},refetch:d}};function $ts(){const[s,t]=N.useState(!1),[n,r]=N.useState(!1),[a,i]=N.useState(null);N.useEffect(()=>{if(localStorage.getItem("install-banner-dismissed")||window.matchMedia("(display-mode: standalone)").matches||!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent))return;const h=/iPhone|iPad|iPod/i.test(navigator.userAgent);r(h),t(!0);const p=f=>{f.preventDefault(),i(f)};return window.addEventListener("beforeinstallprompt",p),()=>{window.removeEventListener("beforeinstallprompt",p)}},[]);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(Pa,{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(T9,{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(Bn,{className:"h-4 w-4"})})]})]})}):null}const Uts=({children:s,onRefresh:t})=>{const[n,r]=N.useState(!1),[a,i]=N.useState(0),[l,o]=N.useState(!1),c=N.useRef(null),d=N.useRef(0),u=Ht(),h=80,p=120,f=N.useCallback(b=>{const S=c.current;S&&S.scrollTop<=0&&(d.current=b.touches[0].clientY,r(!0))},[]),g=N.useCallback(b=>{if(!n||l)return;const S=c.current;if(!S||S.scrollTop>0){r(!1),i(0);return}const T=b.touches[0].clientY-d.current;if(T>0){const D=Math.min(T*.5,p);i(D),D>10&&b.preventDefault()}},[n,l]),_=N.useCallback(async()=>{if(n)if(r(!1),a>=h&&!l){o(!0),i(h);try{t?await t():await u.invalidateQueries()}catch(b){console.error("Refresh failed:",b)}finally{o(!1),i(0)}}else i(0)},[n,a,l,t,u]),v=Math.min(a/h,1),j=v*180;return e.jsxs("div",{ref:c,className:"h-full overflow-auto",onTouchStart:f,onTouchMove:g,onTouchEnd:_,children:[e.jsx("div",{className:"flex justify-center items-center overflow-hidden transition-all duration-200 ease-out",style:{height:a>0?a:0,opacity:v},children:e.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${l?"animate-spin":""}`,style:{transform:l?void 0:`rotate(${j}deg)`,transition:l?void 0:"transform 0.1s ease-out"},children:e.jsx(Ti,{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})]})},Dmt=()=>{const{user:s}=ys(),[t,n]=N.useState(!1),[r,a]=N.useState(!1),[i,l]=N.useState(0),[o,c]=N.useState(!0);N.useEffect(()=>{(async()=>{if(!s){c(!1);return}try{const{data:f}=await q.from("membership_reviews").select("id").eq("user_id",s.id).maybeSingle();if(f){a(!0),n(!1),c(!1);return}const{data:g}=await q.from("profiles").select("login_count").eq("id",s.id).single(),_=(g==null?void 0:g.login_count)||0;l(_);const v=sessionStorage.getItem("review-prompt-dismissed");n(_>=4&&!v)}catch(f){console.error("Error checking review eligibility:",f)}finally{c(!1)}})()},[s]);const d=N.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),n(!1)},[]),u=N.useCallback(async(p,f)=>{if(!s)return{success:!1,error:"Not authenticated"};try{const{error:g}=await q.from("membership_reviews").insert({user_id:s.id,rating:p,review_text:f});if(g)throw g;return a(!0),n(!1),{success:!0,pointsAwarded:25}}catch(g){return console.error("Error submitting review:",g),{success:!1,error:g.message}}},[s]),h=N.useCallback(async()=>{if(s)try{await q.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",s.id)}catch(p){console.error("Error updating Google review status:",p)}},[s]);return{shouldShowPrompt:t,hasSubmittedReview:r,loginCount:i,isLoading:o,dismissPrompt:d,submitReview:u,markPostedToGoogle:h}},qts="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",Vts=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:n,submitReview:r,markPostedToGoogle:a}=Dmt(),[i,l]=N.useState(!1),[o,c]=N.useState("review"),[d,u]=N.useState(0),[h,p]=N.useState(0),[f,g]=N.useState(""),[_,v]=N.useState(!1),[j,b]=N.useState(!1);if(t||!s&&!j)return null;const S=async()=>{if(d===0){Pr({title:"Please select a rating",variant:"destructive"});return}v(!0);const L=await r(d,f);v(!1),L.success?(b(!0),Pr({title:"Thank you for your feedback!",description:"Your review helps us improve."}),c("google")):Pr({title:"Error submitting review",description:L.error,variant:"destructive"})},A=async L=>{L&&(await navigator.clipboard.writeText(f||`${d} star rating for LevelUp!`),Pr({title:"Review copied!",description:"Paste it on Google Reviews."}),await a(),window.open(qts,"_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(ca,{className:"h-3.5 w-3.5 fill-current"}),e.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),e.jsx(bs,{open:i,onOpenChange:T,children:e.jsx(vs,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs(ws,{children:[e.jsx(_s,{className:"text-center",children:"How are you enjoying LevelUp?"}),e.jsx(Qn,{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(L=>e.jsx("button",{type:"button",onClick:()=>u(L),onMouseEnter:()=>p(L),onMouseLeave:()=>p(0),className:"p-1 transition-transform hover:scale-110",children:e.jsx(ca,{className:Et("h-8 w-8 transition-colors",(h||d)>=L?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},L))}),e.jsx(Es,{placeholder:"Tell us about your experience (optional)",value:f,onChange:L=>g(L.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:S,disabled:_||d===0,className:"flex-1",children:_?"Submitting...":"Submit Review"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ws,{children:[e.jsx(_s,{className:"text-center",children:"🎉 Thank you!"}),e.jsx(Qn,{className:"text-center",children:"Would you mind sharing your review on Google? It really helps other agents discover LevelUp!"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("p",{className:"text-center text-sm text-muted-foreground",children:"We'll copy your review so you can easily paste it."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>A(!1),className:"flex-1",children:"No Thanks"}),e.jsx(B,{onClick:()=>A(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function Hts(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 _="vapid_public_key";let v=localStorage.getItem(_);if(!v){const{data:S,error:A}=await q.functions.invoke("get-vapid-public-key",{body:{}});if(A)throw A;if(v=(S==null?void 0:S.vapidPublicKey)??null,!v)throw new Error("Missing VAPID public key");localStorage.setItem(_,v)}u(v);const j=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});c(j),n(Notification.permission);const b=await j.pushManager.getSubscription();a(!!b)}catch(_){console.error("Error initializing push notifications:",_)}finally{l(!1)}})()},[h]);const p=N.useCallback(async()=>{if(!h||!o||!s)return console.error("Push notifications not supported or user not logged in"),!1;if(!d)return ae.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{l(!0);const g=await o.pushManager.getSubscription();if(g){try{await g.unsubscribe()}catch(A){console.warn("Failed to unsubscribe existing push subscription:",A)}const{error:S}=await q.from("push_subscriptions").delete().eq("user_id",s.id);S&&console.warn("Failed to cleanup push_subscriptions rows:",S)}if(Notification.permission!=="granted"){const S=await Notification.requestPermission();if(n(S),S!=="granted")return S==="denied"?ae.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):ae.error("Notification permission was dismissed. Please try again."),!1}const _=Hts(d);let v;try{v=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:_})}catch(S){console.error("PushManager.subscribe() failed:",S);const A=(S==null?void 0:S.message)||String(S);return A.includes("permission")?ae.error("Push permission denied. Check your browser notification settings."):A.includes("key")||A.includes("VAPID")?ae.error("Push configuration error. Please contact support."):A.includes("AbortError")?ae.error("Push subscription was cancelled. Please try again."):ae.error(`Failed to subscribe: ${A}`),!1}const j=v.toJSON(),{error:b}=await q.from("push_subscriptions").upsert({user_id:s.id,endpoint:j.endpoint,p256dh_key:j.keys.p256dh,auth_key:j.keys.auth},{onConflict:"user_id,endpoint"});if(b)throw console.error("Error saving subscription:",b),ae.error("Failed to save notification preferences. Please try again."),b;return a(!0),ae.success("Push notifications enabled!"),!0}catch(g){if(console.error("Error subscribing to push notifications:",g),!(g instanceof Error&&g.message.includes("toast"))){const _=g instanceof Error?g.message:"Unknown error";ae.error("Failed to enable push notifications: "+_)}return!1}finally{l(!1)}},[h,o,s,d]),f=N.useCallback(async()=>{if(!o||!s)return!1;try{l(!0);const g=await o.pushManager.getSubscription();return g&&await g.unsubscribe(),await q.from("push_subscriptions").delete().eq("user_id",s.id),a(!1),ae.success("Push notifications disabled"),!0}catch(g){console.error("Error unsubscribing:",g);const _=g instanceof Error?g.message:"Unknown error";return ae.error("Failed to disable push notifications: "+_),!1}finally{l(!1)}},[o,s]);return{isSupported:h,permission:t,isSubscribed:r,isLoading:i,vapidPublicKey:d,subscribe:p,unsubscribe:f}}const Fje="push_notification_prompt_dismissed",Gts=["/dashboard","/admin"],Wts=()=>{const{user:s}=ys(),{isSupported:t,isSubscribed:n,isLoading:r,subscribe:a}=Rmt(),i=Jl(),[l,o]=N.useState(!1),[c,d]=N.useState(!1),u=Gts.some(f=>i.pathname===f||i.pathname.startsWith(`${f}/`));N.useEffect(()=>{if(u){o(!1);return}if(!s||!t||n||r||localStorage.getItem(`${Fje}_${s.id}`))return;const g=setTimeout(()=>{o(!0)},2e3);return()=>clearTimeout(g)},[s,t,n,r,u]);const h=async()=>{d(!0);const f=await a();d(!1),f&&(s&&localStorage.setItem(`${Fje}_${s.id}`,"true"),o(!1))},p=()=>{s&&localStorage.setItem(`${Fje}_${s.id}`,"true"),o(!1)};return!t||n||u?null:e.jsx(bs,{open:l,onOpenChange:f=>!f&&p(),children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{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(im,{className:"h-6 w-6 text-primary"})}),e.jsx(_s,{className:"text-center",children:"Stay in the Loop!"}),e.jsx(Qn,{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:p,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."})]})})},LUe=s=>{let t;const n=new Set,r=(d,u)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const p=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(f=>f(t,p))}},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},Kts=s=>s?LUe(s):LUe,Yts=s=>s;function Zts(s,t=Yts){const n=St.useSyncExternalStore(s.subscribe,St.useCallback(()=>t(s.getState()),[s,t]),St.useCallback(()=>t(s.getInitialState()),[s,t]));return St.useDebugValue(n),n}const DUe=s=>{const t=Kts(s),n=r=>Zts(t,r);return Object.assign(n,t),n},Qts=s=>s?DUe(s):DUe;function Xts(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 gCe=s=>t=>{try{const n=s(t);return n instanceof Promise?n:{then(r){return gCe(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return gCe(r)(n)}}}},Jts=(s,t)=>(n,r,a)=>{let i={storage:Xts(()=>window.localStorage),partialize:v=>v,version:0,merge:(v,j)=>({...j,...v}),...t},l=!1,o=0;const c=new Set,d=new Set;let u=i.storage;if(!u)return s((...v)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...v)},r,a);const h=()=>{const v=i.partialize({...r()});return u.setItem(i.name,{state:v,version:i.version})},p=a.setState;a.setState=(v,j)=>(p(v,j),h());const f=s((...v)=>(n(...v),h()),r,a);a.getInitialState=()=>f;let g;const _=()=>{var v,j;if(!u)return;const b=++o;l=!1,c.forEach(A=>{var T;return A((T=r())!=null?T:f)});const S=((j=i.onRehydrateStorage)==null?void 0:j.call(i,(v=r())!=null?v:f))||void 0;return gCe(u.getItem.bind(u))(i.name).then(A=>{if(A)if(typeof A.version=="number"&&A.version!==i.version){if(i.migrate){const T=i.migrate(A.state,A.version);return T instanceof Promise?T.then(L=>[!0,L]):[!0,T]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,A.state];return[!1,void 0]}).then(A=>{var T;if(b!==o)return;const[L,D]=A;if(g=i.merge(D,(T=r())!=null?T:f),n(g,!0),L)return h()}).then(()=>{b===o&&(S==null||S(r(),void 0),g=r(),l=!0,d.forEach(A=>A(g)))}).catch(A=>{b===o&&(S==null||S(void 0,A))})};return a.persist={setOptions:v=>{i={...i,...v},v.storage&&(u=v.storage)},clearStorage:()=>{u==null||u.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>l,onHydrate:v=>(c.add(v),()=>{c.delete(v)}),onFinishHydration:v=>(d.add(v),()=>{d.delete(v)})},i.skipHydration||_(),g||f},ess=Jts,$ye=Qts()(ess((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 tss(s){return s!=null&&s.length?s.find(t=>t.is_active&&t.mls_provider_id&&!t.no_mls_mode)||s[0]:null}function Ip(){const{user:s}=ys(),{data:t,isLoading:n}=ct({queryKey:["agent-lead-site",s==null?void 0:s.id],queryFn:async()=>{const{data:r,error:a}=await q.from("lead_sites").select("id, subdomain_slug, 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 tss(r)},enabled:!!s,staleTime:5*60*1e3});return{leadSite:t??null,hasLeadSite:!!t,isLoading:n,siteUrl:t?`https://${t.subdomain_slug}.thelocalmove.com`:null}}const RUe="dashboard-sidebar-collapsed",Ts=({children:s,title:t})=>{var it;const{user:n,signOut:r,isAdmin:a,isBrokerageManager:i,isCoach:l,brokerageId:o}=ys(),{isAssistant:c,actingAsAgent:d,hasPermission:u}=PAe(),{isImpersonating:h}=H0e(),f=(c&&!!d?40:0)+(h?40:0),{avatarUrl:g}=Hht(n==null?void 0:n.id),{isTrial:_,isExpired:v,expiresAt:j}=xes(n==null?void 0:n.id),{isInnerCircleEnabled:b,isMarketplaceEnabled:S}=Wht(),{currentBrief:A,shouldShowPopup:T,hasUnseenBrief:L,openBrief:D,closeBrief:M,dismissBrief:F}=Bts(),{unreadCount:z}=ges(),{openCount:V}=yes(),{data:W}=Zv(),Y=!!W,J=$ye(je=>je.cartItems).reduce((je,Ge)=>je+Ge.quantity,0),{leadSite:ne,hasLeadSite:ie,siteUrl:he}=Ip(),ce=Mn(),pe=Jl(),[le,ve]=N.useState(null);N.useEffect(()=>{n!=null&&n.id&&q.from("profiles").select("name").eq("id",n.id).single().then(({data:je})=>{je!=null&&je.name&&ve(je.name)})},[n==null?void 0:n.id]);const ge=le||((it=n==null?void 0:n.user_metadata)==null?void 0:it.name)||(n==null?void 0:n.email)||"User",[Te,Me]=N.useState(()=>typeof window<"u"?localStorage.getItem(RUe)==="true":!1);N.useEffect(()=>{localStorage.setItem(RUe,String(Te))},[Te]);const[Ce,Ae]=N.useState({agentos:!0,tools:!0,marketing:!0,learning:!0,community:!0,contacts:!0,website:!0,help:!1}),De=je=>{Ae(Ge=>({...Ge,[je]:!Ge[je]}))},Ie=je=>je.split(" ").map(Ge=>Ge[0]).join("").toUpperCase().slice(0,2),Fe=je=>pe.pathname===je,qe=je=>je.some(Ge=>pe.pathname===Ge),be=({path:je,icon:Ge,label:Be,badgeCount:Ye})=>{const We=e.jsxs(B,{variant:"ghost",size:"sm",className:Et("text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",Fe(je)&&"bg-sidebar-accent text-sidebar-accent-foreground",Te?"w-10 h-10 p-0 justify-center":"w-full justify-start gap-2"),onClick:()=>ce(je),children:[e.jsxs("div",{className:"relative",children:[e.jsx(Ge,{className:"h-4 w-4 shrink-0"}),Te&&Ye!=null&&Ye>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-muted-foreground/40 border border-background"})]}),!Te&&Be,!Te&&Ye!=null&&Ye>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:Ye>9?"9+":Ye})]});return Te?e.jsxs(Ec,{delayDuration:0,children:[e.jsx(Ac,{asChild:!0,children:We}),e.jsxs(vc,{side:"right",className:"flex items-center gap-2",children:[Be,Ye!=null&&Ye>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:Ye>9?"9+":Ye})]})]}):We},Ze=({id:je,label:Ge,icon:Be,children:Ye,activePaths:We,showBetaBadge:rt,defaultPath:tt,badgeCount:at})=>{if(Te){const He=tt||We[0];return e.jsxs(Ec,{delayDuration:0,children:[e.jsx(Ac,{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",qe(We)&&"text-primary"),onClick:()=>ce(He),children:e.jsxs("div",{className:"relative",children:[e.jsx(Be,{className:"h-4 w-4"}),at!=null&&at>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(vc,{side:"right",className:"flex items-center gap-2",children:[Ge,rt&&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"}),at!=null&&at>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:at>9?"9+":at})]})]})}return e.jsxs(dy,{open:Ce[je],onOpenChange:()=>De(je),children:[e.jsx(uy,{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",qe(We)&&"text-primary"),children:[e.jsxs("span",{className:"flex items-center gap-2 font-semibold text-[15px]",children:[e.jsx(Be,{className:"h-4 w-4"}),Ge,rt&&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:[at!=null&&at>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:at>9?"9+":at}),e.jsx(io,{className:Et("h-4 w-4 transition-transform duration-200",Ce[je]&&"rotate-180")})]})]})}),e.jsx(hy,{className:"pl-4 space-y-1 mt-1",children:Ye})]})},Ne=({isMobile:je=!1})=>{const Ge=je?!1:Te;return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:Et("p-3 border-b border-sidebar-border",Ge?"flex flex-col items-center gap-2":"flex items-center justify-between"),children:[Ge?e.jsx("img",{src:kes,alt:"LevelUp",className:"h-8 w-auto"}):e.jsx("img",{src:Nes,alt:"LevelUp",className:"h-8 w-auto"}),!je&&e.jsxs(Ec,{delayDuration:0,children:[e.jsx(Ac,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>Me(!Ge),children:e.jsx(pl,{className:Et("h-4 w-4 transition-transform duration-300",Ge&&"rotate-180")})})}),e.jsx(vc,{side:"right",children:Ge?"Expand sidebar":"Collapse sidebar"})]})]}),e.jsx(hi,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:e.jsxs("nav",{className:Et("p-3 space-y-1",Ge&&"flex flex-col items-center"),children:[je&&_&&!v&&e.jsx("button",{type:"button",onClick:()=>ce("/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(un,{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?"}),j&&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(j).getTime()-Date.now())/864e5)),"d left"]})]})}),e.jsx(be,{path:"/dashboard",icon:e4,label:"Dashboard"}),e.jsx(be,{path:"/apps",icon:pv,label:"Apps & Tools"}),Te?e.jsxs(Ec,{delayDuration:0,children:[e.jsx(Ac,{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",Fe("/programs")&&"bg-primary/25"),onClick:()=>ce("/programs"),children:e.jsx(sx,{className:"h-4 w-4 shrink-0"})})}),e.jsx(vc,{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",Fe("/programs")&&"bg-primary/25"),onClick:()=>ce("/programs"),children:[e.jsx(sx,{className:"h-4 w-4 shrink-0"}),"Programs"]}),Te?e.jsxs(Ec,{delayDuration:0,children:[e.jsx(Ac,{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",Fe("/levelup-u")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/levelup-u"),children:[e.jsx(_d,{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(vc,{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",Fe("/levelup-u")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/levelup-u"),children:[e.jsx(_d,{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(be,{path:"/events",icon:Tl,label:"Events"}),e.jsxs(Ze,{id:"agentos",label:"Agent OS",icon:YS,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(be,{path:"/mission-control",icon:gi,label:"Mission Control"}),u("contacts")&&!Ge&&e.jsxs(dy,{open:Ce.contacts,onOpenChange:()=>De("contacts"),children:[e.jsx(uy,{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",qe(["/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(Nn,{className:"h-4 w-4"}),"Contacts"]}),e.jsx(io,{className:Et("h-3.5 w-3.5 transition-transform duration-200",Ce.contacts&&"rotate-180")})]})}),e.jsxs(hy,{className:"pl-4 pr-1 space-y-0.5 mt-0.5",children:[e.jsx(be,{path:"/mission-control/contacts",icon:Nn,label:"All Contacts"}),e.jsx(be,{path:"/mission-control/relationship-scorecard",icon:nm,label:"Relationship Report"}),e.jsx(be,{path:"/mission-control/sphere-gaps",icon:S9,label:"Sphere Gaps"}),e.jsx(be,{path:"/mission-control/sent-emails",icon:cr,label:"Sent Emails"}),e.jsx(be,{path:"/mission-control/connect-page",icon:El,label:"Connect Page"})]})]}),u("contacts")&&Ge&&e.jsx(be,{path:"/mission-control/contacts",icon:Nn,label:"Contacts"}),u("contacts")&&e.jsx(be,{path:"/mission-control/plans",icon:Tl,label:"TouchPlans"}),u("pipeline")&&e.jsx(be,{path:"/mission-control/pipeline",icon:Z2,label:"Deal Pipeline"}),u("pipeline")&&e.jsx(be,{path:"/mission-control/transactions",icon:G2,label:"Transactions"}),u("pipeline")&&e.jsx(be,{path:"/mission-control/tasks",icon:E2,label:"Tasks"}),u("popbys")&&e.jsx(be,{path:"/mission-control/popbys",icon:Oi,label:"Popbys"}),u("videos")&&e.jsx(be,{path:"/mission-control/video-library",icon:br,label:"Video Library"}),u("scorecard")&&e.jsx(be,{path:"/mission-control/scorecard",icon:yo,label:"Scorecard"}),u("listings")&&e.jsx(be,{path:"/mission-control/listings",icon:Va,label:"Listing Exchange"}),e.jsx(be,{path:"/mission-control/client-portals",icon:un,label:"Client Portals"}),e.jsx(be,{path:"/mission-control/signals",icon:FA,label:"Signals"}),!Ge&&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",Fe("/mission-control/smart-drips")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/mission-control/smart-drips"),children:[e.jsx(hh,{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"})]}),Ge&&e.jsx(be,{path:"/mission-control/smart-drips",icon:hh,label:"Smart Drips"}),e.jsx(be,{path:"/email-campaigns/templates",icon:Vs,label:"Email Templates"})]}),ie&&ne&&e.jsxs(Ze,{id:"website",label:"My Website",icon:lc,activePaths:[`/admin/lead-sites/${ne.id}/edit`],defaultPath:`/admin/lead-sites/${ne.id}/edit`,children:[Ge?e.jsxs(Ec,{delayDuration:0,children:[e.jsx(Ac,{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(he||"#","_blank"),children:e.jsx(Er,{className:"h-4 w-4"})})}),e.jsx(vc,{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(he||"#","_blank"),children:[e.jsx(Er,{className:"h-4 w-4"}),"View Site",e.jsx(tr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsx(be,{path:`/my-website/${ne.id}/edit`,icon:_a,label:"Edit Website"}),e.jsx(be,{path:"/my-website/mls-listings",icon:Or,label:"MLS Listings"}),e.jsx(be,{path:"/my-website/market-report",icon:yo,label:"Market Reports"}),(ne==null?void 0:ne.mls_provider_id)&&e.jsx(be,{path:"/mission-control/cma",icon:fw,label:"CMA Reports"}),e.jsx(be,{path:"/mission-control/website-activity",icon:nm,label:"Website Activity"}),e.jsx(be,{path:"/m",icon:ng,label:"Mobile Command"})]}),e.jsxs(Ze,{id:"marketing",label:"Marketing",icon:$d,activePaths:["/templates","/social-swag-2","/newsletters","/website-apps","/marketing-studio"],defaultPath:"/templates",children:[e.jsx(be,{path:"/templates",icon:fl,label:"Templates"}),e.jsx(be,{path:"/marketing-studio",icon:nl,label:"Marketing Studio"}),e.jsx(be,{path:"/social-swag-2",icon:ng,label:"Social Swag"}),Te?e.jsxs(Ec,{delayDuration:0,children:[e.jsx(Ac,{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",Fe("/newsletters")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/newsletters"),children:[e.jsx(ay,{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(vc,{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",Fe("/newsletters")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/newsletters"),children:[e.jsx(ay,{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(be,{path:"/website-apps",icon:un,label:"Website Apps"})]}),e.jsxs(Ze,{id:"learning",label:"Learning",icon:Ou,activePaths:["/academy","/toolbox","/programs"],defaultPath:"/academy",children:[e.jsx(be,{path:"/academy",icon:_d,label:"Academy"}),e.jsx(be,{path:"/toolbox",icon:_b,label:"Toolbox"})]}),e.jsxs(Ze,{id:"community",label:"Community",icon:Ei,activePaths:["/community","/wishlist"],defaultPath:"/community",badgeCount:z,children:[e.jsx(be,{path:"/community",icon:Nn,label:"Community",badgeCount:z}),e.jsx(be,{path:"/wishlist",icon:vw,label:"Wishlist",badgeCount:V}),!Ge&&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(Ze,{id:"goods",label:"The Goods",icon:Og,activePaths:["/marketplace","/reward-store"],defaultPath:"/reward-store",children:[S&&!Ge&&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",pe.pathname.startsWith("/marketplace")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/marketplace"),children:[e.jsx(Og,{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"})]}),S&&Ge&&e.jsx(be,{path:"/marketplace",icon:Og,label:"Marketplace"}),e.jsx(be,{path:"/reward-store",icon:vo,label:"Reward Store"}),e.jsx(be,{path:"/refer-friends",icon:Oi,label:"Refer & Earn"})]}),e.jsxs(Ze,{id:"help",label:"Help & Services",icon:K_,activePaths:["/support","/additional-services"],defaultPath:"/support",children:[e.jsx(be,{path:"/support",icon:aL,label:"Support"}),e.jsx(be,{path:"/additional-services",icon:un,label:"Additional Services"})]}),l&&e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(be,{path:"/coaching",icon:_d,label:"Coaching"})}),e.jsx(sss,{}),(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",pe.pathname.startsWith("/attract")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/attract"),children:[e.jsx(un,{className:"h-4 w-4 text-violet-600"}),!Ge&&e.jsx("span",{children:"LevelUp Attract"}),!Ge&&e.jsx("span",{className:"ml-auto text-[9px] font-semibold text-violet-600 uppercase tracking-wider",children:"Beta"})]}),a&&e.jsxs(e.Fragment,{children:[!Ge&&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"})}),Ge?e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(be,{path:"/admin",icon:Kc,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",pe.pathname==="/admin"&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/admin"),children:[e.jsx(Kc,{className:"h-4 w-4"}),"Admin Dashboard"]})]}),(o||i)&&!a&&e.jsxs(e.Fragment,{children:[!Ge&&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"})}),Ge?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(be,{path:"/my-brokerage",icon:Va,label:"My Brokerage"}),e.jsx(be,{path:"/brokerage/help-board",icon:tb,label:"Help Board"}),e.jsx(be,{path:"/brokerage-content",icon:Ou,label:"Brokerage Content"})]}),Y&&!i&&e.jsx(be,{path:"/my-team",icon:Nn,label:"My Team"}),i&&e.jsxs(e.Fragment,{children:[e.jsx(be,{path:"/brokerage/dashboard",icon:Xo,label:"Manage Brokerages"}),e.jsx(be,{path:"/brokerage/teams",icon:Nn,label:"Teams"}),e.jsx(be,{path:"/brokerage/recruiting",icon:$d,label:"Recruiting"}),e.jsx(be,{path:"/brokerage/vendors",icon:pb,label:"Vendors"}),e.jsx(be,{path:"/brokerage-resources",icon:qm,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",Fe("/my-brokerage")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/my-brokerage"),children:[e.jsx(Va,{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",Fe("/brokerage/help-board")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/help-board"),children:[e.jsx(tb,{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",Fe("/brokerage-content")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage-content"),children:[e.jsx(Ou,{className:"h-4 w-4"}),"Brokerage Content"]})]}),Y&&!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",Fe("/my-team")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/my-team"),children:[e.jsx(Nn,{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",Fe("/brokerage/dashboard")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/dashboard"),children:[e.jsx(Xo,{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",Fe("/brokerage/teams")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/teams"),children:[e.jsx(Nn,{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",Fe("/brokerage/recruiting")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/recruiting"),children:[e.jsx($d,{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",Fe("/brokerage/vendors")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/vendors"),children:[e.jsx(pb,{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",Fe("/brokerage-resources")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage-resources"),children:[e.jsx(qm,{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",Fe("/profile")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/profile"),children:[e.jsx(Xi,{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(LA,{className:"h-4 w-4"}),"Sign Out"]})]})]})};return e.jsx(Ww,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[_&&v&&pe.pathname!=="/subscription"&&e.jsx(Cts,{}),typeof document<"u"&&Hx.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",Te?"w-16":"w-56"),style:{top:`${f}px`,height:`calc(100vh - ${f}px)`},children:e.jsx(Ne,{})}),document.body),e.jsxs("div",{className:Et("flex-1 flex flex-col overflow-hidden transition-all duration-300",Te?"md:ml-16":"md:ml-56"),style:{height:`calc(100vh - ${f}px)`,marginTop:`${f}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(cg,{children:[e.jsx(rU,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(s4,{className:"h-5 w-5"})})}),e.jsx(ix,{side:"left",className:"w-56 p-0 bg-card",children:e.jsx(Ne,{isMobile:!0})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:Ses,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(PUe,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[_&&!v&&j&&e.jsx(Sts,{expiresAt:j,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(PUe,{})}),A&&e.jsx(Tts,{hasUnseenBrief:L,onClick:D}),S&&e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",onClick:()=>ce("/marketplace/cart"),children:[e.jsx(Og,{className:"h-5 w-5"}),J>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:J>99?"99+":J})]}),e.jsx(Xes,{}),e.jsx(pCe,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",ge.split(" ")[0],"!"]}),e.jsxs(wc,{children:[e.jsx(jc,{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(ni,{src:g||void 0}),e.jsx(aa,{className:"bg-primary text-primary-foreground font-medium text-sm",children:Ie(ge)})]})})}),e.jsxs(cc,{align:"end",className:"w-48",children:[e.jsxs(Qr,{onClick:()=>ce("/profile"),className:"cursor-pointer",children:[e.jsx(Xi,{className:"h-4 w-4 mr-2"}),"Profile"]}),e.jsxs(Qr,{onClick:()=>ce("/mission-control/integrations"),className:"cursor-pointer",children:[e.jsx(X2,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(Qr,{onClick:()=>ce("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(X2,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(Zg,{}),e.jsxs(Qr,{onClick:r,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(LA,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(Uts,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),A&&e.jsx(zts,{brief:A,open:T,onClose:M,onDismiss:F}),e.jsx($ts,{}),e.jsx(Vts,{}),e.jsx(Wts,{})]})]})})};function sss(){const{user:s}=ys(),t=Jl(),n=Mn(),{data:r}=ct({queryKey:["my-coach-nav",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i}=await q.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(_d,{className:"h-4 w-4"}),"My Coach"]})})}const OUe="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/mcp",nss="https://tile-portal.lovable.app/mcp-oauth-bridge.html",rss=[{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 ass(){const[s,t]=N.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(OUe),t(!0),ae.success("MCP URL copied to clipboard"),setTimeout(()=>t(!1),2e3)}catch{ae.error("Could not copy URL")}};return e.jsx(Ts,{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(YS,{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(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Use this exact MCP server URL"}),e.jsx(Vn,{children:"Paste only this URL into ChatGPT's Server URL field."})]}),e.jsx(Ee,{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:OUe}),e.jsx(B,{variant:"outline",size:"icon",onClick:n,"aria-label":"Copy MCP URL",children:s?e.jsx(Ri,{className:"h-4 w-4 text-green-600"}):e.jsx(Xr,{className:"h-4 w-4"})})]})})]}),e.jsx(fe,{className:"border-destructive/30 bg-destructive/5",children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx($l,{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:nss}),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(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Quick steps"}),e.jsx(Vn,{children:"ChatGPT adds MCP servers as a new plugin / custom tool. Share these steps with any agent who wants to connect."})]}),e.jsx(Ee,{children:e.jsx("ol",{className:"space-y-4",children:rss.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 iss=()=>{const[s]=gl(),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(fe,{className:"max-w-lg w-full",children:[e.jsxs(Mt,{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(Ri,{className:"w-10 h-10 text-green-500"})}),e.jsx(It,{className:"text-2xl",children:"Welcome to LevelUp!"}),e.jsx(Vn,{className:"text-lg",children:"Your subscription has been activated successfully."})]}),e.jsxs(Ee,{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(Vs,{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."})})]})]})})},oss=()=>{const{user:s}=ys(),[t,n]=N.useState(!1),[r,a]=N.useState(null),[i,l]=N.useState(""),o=async h=>{var p;if(!(s!=null&&s.email)){ae.error("Please sign in to upgrade");return}n(!0),a(h);try{const{data:f,error:g}=await q.functions.invoke("create-checkout",{body:{tier:h,email:s.email,name:((p=s.user_metadata)==null?void 0:p.full_name)||s.email,couponCode:i.trim()||void 0,skipTrial:!0}});if(g)throw g;if(f!=null&&f.url)window.open(f.url,"_blank","noopener,noreferrer"),ae.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(f){console.error("Checkout error:",f),ae.error(f.message||"Failed to start checkout. Please try again.")}finally{n(!1),a(null)}},c=["Unlimited access to all marketing templates","Complete Academy training library","AI-powered tools and resources","Community forums and support","Exclusive member events and workshops","Deal pipeline & scorecard tracking","Listing exchange access","Social media content library"],d=["Everything in Individual plan","Up to 25 agent seats","Brokerage admin dashboard","Team performance analytics","Custom branding options","Priority support","Agent onboarding tools","Brokerage-wide announcements"],u=["Everything in Brokerage plan","Unlimited agent seats","Dedicated account manager","Advanced analytics & reporting","White-label options","API access","Custom integrations","Enterprise-level support"];return e.jsx(Ts,{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(fe,{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(Mt,{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(Nn,{className:"h-7 w-7 text-primary"})}),e.jsx(It,{className:"text-xl",children:"Individual Agent"}),e.jsx(Vn,{children:"Perfect for solo agents ready to level up"})]}),e.jsxs(Ee,{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,p)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Ir,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},p))}),e.jsxs(B,{className:"w-full",size:"lg",onClick:()=>o("individual_agent"),disabled:t,children:[t&&r==="individual_agent"?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(fe,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors",children:[e.jsxs(Mt,{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(Va,{className:"h-7 w-7 text-amber-600"})}),e.jsx(It,{className:"text-xl",children:"Brokerage"}),e.jsx(Vn,{children:"For teams and brokerages up to 25 agents"})]}),e.jsxs(Ee,{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,p)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Ir,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},p))}),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(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Va,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(fe,{className:"border-2 border-purple-500/20 hover:border-purple-500/50 transition-colors",children:[e.jsxs(Mt,{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(Va,{className:"h-7 w-7 text-purple-600"})}),e.jsx(It,{className:"text-xl",children:"Brokerage 25+"}),e.jsx(Vn,{children:"For larger brokerages with 25+ agents"})]}),e.jsxs(Ee,{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,p)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Ir,{className:"h-4 w-4 text-purple-600 mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},p))}),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(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Va,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(fe,{className:"bg-muted/50",children:e.jsxs(Ee,{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(Ar,{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(Vs,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})})]})})},lss=()=>{const{user:s,loading:t,isBrokerageManager:n,brokerageId:r}=ys(),a=Mn(),[i,l]=N.useState(""),[o,c]=N.useState(!1),[d,u]=N.useState(!1);N.useEffect(()=>{!t&&!s&&a("/auth")},[s,t,a]),N.useEffect(()=>{!t&&s&&r&&a("/profile?setup=true")},[s,t,r,a]);const h=async()=>{if(!i.trim()){ae.error("Please enter a brokerage name");return}const{data:p}=await q.auth.getSession(),f=p.session;if(!s||!f){ae.error("Please sign in again to create your brokerage."),a("/auth");return}c(!0);try{console.log("[SetupBrokerage] Creating brokerage…",{hasUser:!!s,hasSession:!!f,userId:s==null?void 0:s.id});const{data:g,error:_}=await q.functions.invoke("create-brokerage",{body:{name:i.trim()}});if(console.log("[SetupBrokerage] create-brokerage response",{data:g,error:_}),_)throw _;if(!(g!=null&&g.ok))throw new Error((g==null?void 0:g.error)||"Failed to create brokerage");c(!1),u(!0),ae.success("Brokerage created! Setting up your account..."),setTimeout(()=>{a("/profile?setup=true")},2e3)}catch(g){console.error("Error creating brokerage:",g),ae.error(g.message||"Failed to create brokerage"),c(!1)}};return t?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(fe,{className:"max-w-lg w-full",children:[e.jsxs(Mt,{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(ts,{className:"w-10 h-10 text-primary animate-spin"})}),e.jsx(It,{className:"text-2xl",children:"Setting Up Your Brokerage"}),e.jsx(Vn,{className:"text-lg",children:"We're assigning you as the brokerage manager and preparing your dashboard..."})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(Ri,{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(ts,{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(fe,{className:"max-w-lg w-full",children:[e.jsxs(Mt,{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(Va,{className:"w-10 h-10 text-primary"})}),e.jsx(It,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(Vn,{className:"text-lg",children:"Create your brokerage to start managing your team"})]}),e.jsxs(Ee,{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:p=>l(p.target.value),onKeyDown:p=>p.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(Nn,{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(Ri,{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(Ri,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(Ri,{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(Ri,{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(Oa,{className:"w-4 h-4 ml-2"})]})]})]})})},FUe=()=>{const s=Mn(),[t,n]=N.useState("verifying"),[r,a]=N.useState("");N.useEffect(()=>{(async()=>{try{const{data:{session:o},error:c}=await q.auth.getSession();if(c)throw c;if(o!=null&&o.user){const{data:d}=await q.from("profiles").select("login_count").eq("id",o.user.id).single();if(((d==null?void 0:d.login_count)||0)>1){console.log("Account already claimed, redirecting to dashboard"),n("already_claimed");return}console.log("User logged in successfully:",o.user.email),n("success");try{await q.functions.invoke("trial-claim-hook",{body:{userId:o.user.id}})}catch(u){console.log("Trial claim hook (non-critical):",u)}setTimeout(()=>{s("/profile?setup=true")},1500)}else setTimeout(()=>{n("already_claimed")},2e3)}catch(o){console.error("Claim error:",o),n("already_claimed")}})()},[s]);const i=()=>{window.location.href="https://dashboard.relevelup.com/auth"};return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"space-y-1 text-center",children:[e.jsxs("div",{className:"mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-primary/10",children:[t==="verifying"&&e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"}),t==="success"&&e.jsx("svg",{className:"h-8 w-8 text-primary",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),t==="already_claimed"&&e.jsx("svg",{className:"h-8 w-8 text-primary",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})}),t==="error"&&e.jsx("svg",{className:"h-8 w-8 text-destructive",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})]}),e.jsxs(It,{className:"text-2xl",children:[t==="verifying"&&"Claiming Your Account...",t==="success"&&"Account Claimed!",t==="already_claimed"&&"Account Already Claimed",t==="error"&&"Claim Failed"]}),e.jsxs(Vn,{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(Ee,{children:e.jsx(B,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},css=()=>{const[s,t]=N.useState(!1),n=N.useMemo(()=>new URLSearchParams(window.location.search).get("link"),[]),r=N.useMemo(()=>{if(!n)return!1;try{const i=new URL(n);return i.hostname.endsWith(".supabase.co")&&i.pathname.startsWith("/auth/v1/verify")}catch{return!1}},[n]);N.useEffect(()=>{document.title="Reset Your Password"},[]);const a=()=>{!r||!n||(t(!0),window.location.href=n)};return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]"}),e.jsx("div",{className:"relative z-10 flex flex-col min-h-screen items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:e.jsx("img",{src:Vht,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(fe,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Mt,{className:"text-center",children:[e.jsx(It,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Your Password"}),e.jsx(Vn,{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(Ee,{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."})]})]})]})})]})},dss=()=>{const s=Mn(),[t]=gl(),[n,r]=N.useState(t.get("code")||""),[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[g,_]=N.useState(!1),[v,j]=N.useState(!1),[b,S]=N.useState(null),[A,T]=N.useState(null),[L,D]=N.useState(null),[M,F]=N.useState(null);N.useEffect(()=>{const Y=t.get("code");Y&&(r(Y),z(Y))},[t]);const z=async Y=>{_(!0);const{data:K,error:J}=await q.from("invite_codes").select("id, code, max_uses, uses_count, expires_at, is_active, brokerage_id, trial_days").eq("code",Y.toUpperCase().trim()).single();if(J||!K){ae.error("Invalid invite code"),_(!1);return}if(!K.is_active){ae.error("This invite code is no longer active"),_(!1);return}if(K.max_uses&&K.uses_count>=K.max_uses){ae.error("This invite code has reached its maximum uses"),_(!1);return}if(K.expires_at&&new Date(K.expires_at){Y.preventDefault(),z(n)},W=async Y=>{var K;if(Y.preventDefault(),!c.trim()){ae.error("Please enter your name");return}if(l.length<6){ae.error("Password must be at least 6 characters");return}f(!0);try{const J=`${window.location.origin}/`,{data:ne,error:ie}=await q.auth.signUp({email:a.trim(),password:l,options:{emailRedirectTo:J,data:{name:c.trim()}}});if(ie){ie.message.includes("already registered")?ae.error("This email is already registered. Please sign in instead."):ae.error(ie.message);return}if(ne.user){await q.rpc("add_default_signup_tag",{user_id:ne.user.id});const he=n.toUpperCase().trim();A?await q.functions.invoke("assign-brokerage",{body:{userId:ne.user.id,brokerageId:A,inviteCode:he}}):M?await q.functions.invoke("assign-brokerage",{body:{userId:ne.user.id,trialDays:M,inviteCode:he}}):await q.functions.invoke("assign-brokerage",{body:{userId:ne.user.id,grandfathered:!0,inviteCode:he}}),b&&await q.from("invite_codes").update({uses_count:((K=(await q.from("invite_codes").select("uses_count").eq("id",b).single()).data)==null?void 0:K.uses_count)+1}).eq("id",b),ae.success("Account created! You can now access the dashboard."),s("/dashboard")}}catch(J){console.error("Signup error:",J),ae.error("An unexpected error occurred")}finally{f(!1)}};return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[e.jsx(It,{className:"text-2xl font-bold text-primary",children:L?`Join ${L}`:"Join LevelUp"}),e.jsx(Vn,{children:v?L?`Create your account to join ${L}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(Ee,{children:v?e.jsxs("form",{onSubmit:W,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:Y=>d(Y.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:Y=>i(Y.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:Y=>o(Y.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(xf,{className:"h-4 w-4"}):e.jsx(Er,{className:"h-4 w-4"})})]})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:p,children:p?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating Account..."]}):"Create Account"})]}):e.jsxs("form",{onSubmit:V,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:Y=>r(Y.target.value),required:!0,autoFocus:!0})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})},mU=()=>{const{user:s,isCoach:t}=ys();return ct({queryKey:["my-coach-profile",s==null?void 0:s.id],enabled:!!s&&t,queryFn:async()=>{const{data:n,error:r}=await q.from("coaches").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return n}})},uss=()=>{const{data:s}=mU();return ct({queryKey:["coach-roster",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_assignments").select("*").eq("coach_id",s.id).order("started_at",{ascending:!1});if(n)throw n;const r=t||[];if(r.length===0)return[];const a=r.map(o=>o.agent_id),{data:i}=await q.from("profiles").select("id, name, email, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return r.map(o=>({...o,agent:l.get(o.agent_id)||null}))}})},hss=()=>{const{user:s}=ys();return ct({queryKey:["my-coaching-assignment",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_assignments").select("*").eq("agent_id",s.id).eq("status","active").order("started_at",{ascending:!1}).limit(1);if(n)throw n;const r=(t||[])[0];if(!r)return null;const{data:a}=await q.from("coaches").select("*").eq("id",r.coach_id).maybeSingle();let i=null;if(a!=null&&a.user_id){const{data:l}=await q.from("profiles").select("id, name, email, avatar_url").eq("id",a.user_id).maybeSingle();i=l}return{...r,coach:a,coachProfile:i}}})},mss=s=>ct({queryKey:["coaching-assignment",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_assignments").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return null;const{data:r}=await q.from("profiles").select("id, name, email, avatar_url").eq("id",t.agent_id).maybeSingle();return{...t,agent:r}}}),Omt=s=>ct({queryKey:["coaching-sessions",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_sessions").select("*").eq("assignment_id",s).order("scheduled_at",{ascending:!1});if(n)throw n;return t||[]}}),Fmt=s=>ct({queryKey:["coaching-action-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_action_items").select("*").eq("assignment_id",s).order("due_date",{ascending:!0,nullsFirst:!1});if(n)throw n;return t||[]}}),pss=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function fss(){const s=Mn(),{data:t,isLoading:n}=mU(),{data:r=[],isLoading:a}=uss();if(n)return e.jsx(Ts,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Ts,{title:"Coaching",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(_d,{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."})]})});pss.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(Ts,{title:"Coaching",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white p-8",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-white/80",children:[e.jsx(un,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider font-medium",children:"Coaching Command Center"})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-2",children:"Welcome back, Coach"}),e.jsx("p",{className:"text-white/80 mb-6",children:"Lead your agents. Track momentum. Build champions."}),e.jsxs("div",{className:"flex flex-wrap gap-6",children:[e.jsx(zje,{icon:_d,label:"Active agents",value:i}),e.jsx(zje,{icon:Tl,label:"This month",value:"—"}),e.jsx(zje,{icon:Dc,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(fe,{children:e.jsx(Ee,{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(fe,{className:"cursor-pointer hover:shadow-lg transition-all hover:-translate-y-0.5",onClick:()=>s(`/coaching/agent/${l.id}`),children:e.jsx(Ee,{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(ni,{src:((o=l.agent)==null?void 0:o.avatar_url)||void 0}),e.jsx(aa,{children:(((c=l.agent)==null?void 0:c.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("h3",{className:"font-semibold truncate",children:((d=l.agent)==null?void 0:d.name)||"Unknown"}),e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:(u=l.agent)==null?void 0:u.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[e.jsx(ze,{variant:"secondary",className:"capitalize",children:(l.pipeline_stage||"active").replace("_"," ")}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Started ",Vo(new Date(l.started_at),{addSuffix:!0})]})]})]})]})})},l.id)})})]})]})})}function zje({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 zmt({assignmentId:s}){const{user:t}=ys(),n=Ht(),[r,a]=N.useState(""),[i,l]=N.useState(!1),o=N.useRef(null),{data:c=[]}=ct({queryKey:["coaching-messages",s],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await q.from("coaching_messages").select("*").eq("assignment_id",s).order("created_at",{ascending:!0});if(h)throw h;return u||[]}});N.useEffect(()=>{if(!s)return;const u=q.channel(`coaching-messages-${s}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"coaching_messages",filter:`assignment_id=eq.${s}`},()=>n.invalidateQueries({queryKey:["coaching-messages",s]})).subscribe();return()=>{q.removeChannel(u)}},[s,n]),N.useEffect(()=>{var u;(u=o.current)==null||u.scrollTo({top:o.current.scrollHeight,behavior:"smooth"})},[c]);const d=async()=>{const u=r.trim();if(!u||!t)return;l(!0);const{error:h}=await q.from("coaching_messages").insert({assignment_id:s,sender_id:t.id,body:u});l(!1),h||a("")};return e.jsxs(fe,{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(aa,{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:Vo(new Date(u.created_at),{addSuffix:!0})})]})]},u.id)})}),e.jsx(Ee,{className:"border-t p-3",children:e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(Es,{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(cr,{className:"h-4 w-4"})})]})})]})}var p6e="Progress",f6e=100,[xss,Fxn]=pu(p6e),[gss,yss]=xss(p6e),Bmt=N.forwardRef((s,t)=>{const{__scopeProgress:n,value:r=null,max:a,getValueLabel:i=vss,...l}=s;(a||a===0)&&!zUe(a)&&console.error(bss(`${a}`,"Progress"));const o=zUe(a)?a:f6e;r!==null&&!BUe(r,o)&&console.error(_ss(`${r}`,"Progress"));const c=BUe(r,o)?r:null,d=Ife(c)?i(c,o):void 0;return e.jsx(gss,{scope:n,value:c,max:o,children:e.jsx(Jr.div,{"aria-valuemax":o,"aria-valuemin":0,"aria-valuenow":Ife(c)?c:void 0,"aria-valuetext":d,role:"progressbar","data-state":qmt(c,o),"data-value":c??void 0,"data-max":o,...l,ref:t})})});Bmt.displayName=p6e;var $mt="ProgressIndicator",Umt=N.forwardRef((s,t)=>{const{__scopeProgress:n,...r}=s,a=yss($mt,n);return e.jsx(Jr.div,{"data-state":qmt(a.value,a.max),"data-value":a.value??void 0,"data-max":a.max,...r,ref:t})});Umt.displayName=$mt;function vss(s,t){return`${Math.round(s/t*100)}%`}function qmt(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}function Ife(s){return typeof s=="number"}function zUe(s){return Ife(s)&&!isNaN(s)&&s>0}function BUe(s,t){return Ife(s)&&!isNaN(s)&&s<=t&&s>=0}function bss(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${f6e}\`.`}function _ss(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 ${f6e} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var Vmt=Bmt,wss=Umt;const pi=N.forwardRef(({className:s,value:t,...n},r)=>e.jsx(Vmt,{ref:r,className:Et("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...n,children:e.jsx(wss,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));pi.displayName=Vmt.displayName;function Hmt({agentUserId:s}){const t=new Date().getFullYear(),n=`${t}-01-01`,r=`${t}-12-31`,{data:a=[]}=ct({queryKey:["coaching-kpi-txns",s,t],enabled:!!s,queryFn:async()=>{const{data:_,error:v}=await q.from("scorecard_transactions").select("id, sale_price, commission_amount, close_date, is_win").eq("owner_user_id",s).gte("close_date",n).lte("close_date",r);if(v)throw v;return _||[]}}),{data:i}=ct({queryKey:["coaching-kpi-goal",s,t],enabled:!!s,queryFn:async()=>{const{data:_}=await q.from("scorecard_goals").select("*").eq("owner_user_id",s).eq("year",t).maybeSingle();return _}}),l=a.filter(_=>_.is_win),o=l.length,c=l.reduce((_,v)=>_+(Number(v.sale_price)||0),0),d=l.reduce((_,v)=>_+(Number(v.commission_amount)||0),0),u=i,h=(u==null?void 0:u.transactions_goal)||0,p=(u==null?void 0:u.volume_goal)||0,f=(u==null?void 0:u.gci_goal)||0,g=_=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(_);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(mo,{className:"h-5 w-5"})," ",t," KPIs"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(Bje,{icon:bc,label:"Transactions",value:o.toString(),goal:h,current:o,suffix:h?`/ ${h}`:""}),e.jsx(Bje,{icon:mo,label:"Volume",value:g(c),goal:p,current:c,suffix:p?`of ${g(p)}`:""}),e.jsx(Bje,{icon:Zl,label:"GCI",value:g(d),goal:f,current:d,suffix:f?`of ${g(f)}`:""})]}),o===0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function Bje({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(fe,{children:e.jsxs(Ee,{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(pi,{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 Gmt({assignmentId:s,canEdit:t}){const n=Ht(),[r,a]=N.useState(!1),[i,l]=N.useState(null),{data:o=[]}=ct({queryKey:["coaching-goals",s],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("coaching_goals").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(u)throw u;return d||[]}}),c=()=>n.invalidateQueries({queryKey:["coaching-goals",s]});return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(Oc,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs(B,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(fe,{children:e.jsx(Ee,{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),p=u>0?Math.min(100,h/u*100):0;return e.jsx(fe,{children:e.jsxs(Ee,{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(ze,{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(_a,{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:[p.toFixed(0),"%"]})]}),e.jsx(pi,{value:p})]}),d.due_date&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Due ",Ss(new Date(d.due_date),"PP")]})]})},d.id)}),t&&e.jsx(jss,{open:r,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function jss({open:s,onOpenChange:t,assignmentId:n,goal:r,onSaved:a}){var A,T;const[i,l]=N.useState((r==null?void 0:r.title)||""),[o,c]=N.useState((r==null?void 0:r.description)||""),[d,u]=N.useState((r==null?void 0:r.target_metric)||""),[h,p]=N.useState(((A=r==null?void 0:r.target_value)==null?void 0:A.toString())||""),[f,g]=N.useState(((T=r==null?void 0:r.current_value)==null?void 0:T.toString())||"0"),[_,v]=N.useState((r==null?void 0:r.due_date)||""),[j,b]=N.useState(!1);N.useState(()=>{var L,D;l((r==null?void 0:r.title)||""),c((r==null?void 0:r.description)||""),u((r==null?void 0:r.target_metric)||""),p(((L=r==null?void 0:r.target_value)==null?void 0:L.toString())||""),g(((D=r==null?void 0:r.current_value)==null?void 0:D.toString())||"0"),v((r==null?void 0:r.due_date)||"")});const S=async()=>{if(!i.trim())return;b(!0);const L={assignment_id:n,title:i,description:o||null,target_metric:d||null,target_value:h?Number(h):null,current_value:f?Number(f):0,due_date:_||null},{error:D}=r!=null&&r.id?await q.from("coaching_goals").update(L).eq("id",r.id):await q.from("coaching_goals").insert(L);if(b(!1),D)return ae.error(D.message);ae.success(r!=null&&r.id?"Goal updated":"Goal created"),a==null||a(),t(!1)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{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:L=>l(L.target.value)}),e.jsx(Es,{placeholder:"Description (optional)",rows:2,value:o,onChange:L=>c(L.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:L=>u(L.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:L=>p(L.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Current"}),e.jsx(ye,{type:"number",value:f,onChange:L=>g(L.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Due date"}),e.jsx(ye,{type:"date",value:_,onChange:L=>v(L.target.value)})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:S,disabled:j,children:r!=null&&r.id?"Save":"Create"})]})]})})}function Wmt({assignmentId:s}){const t=Ht(),{user:n}=ys(),r=N.useRef(null),[a,i]=N.useState(!1),{data:l=[]}=ct({queryKey:["coaching-files",s],enabled:!!s,queryFn:async()=>{const{data:h,error:p}=await q.from("coaching_shared_files").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(p)throw p;return h||[]}}),o=()=>t.invalidateQueries({queryKey:["coaching-files",s]}),c=async h=>{var f;const p=(f=h.target.files)==null?void 0:f[0];if(!(!p||!n)){i(!0);try{const g=`${s}/${Date.now()}-${p.name}`,{error:_}=await q.storage.from("coaching-files").upload(g,p);if(_)throw _;const{error:v}=await q.from("coaching_shared_files").insert({assignment_id:s,uploaded_by:n.id,file_url:g,file_name:p.name,file_size_bytes:p.size,mime_type:p.type});if(v)throw v;ae.success("File uploaded"),o()}catch(g){ae.error(g.message||"Upload failed")}finally{i(!1),r.current&&(r.current.value="")}}},d=async h=>{const{data:p,error:f}=await q.storage.from("coaching-files").createSignedUrl(h.file_url,60);if(f||!p)return ae.error("Could not get download link");window.open(p.signedUrl,"_blank")},u=async h=>{confirm("Delete this file?")&&(await q.storage.from("coaching-files").remove([h.file_url]),await q.from("coaching_shared_files").delete().eq("id",h.id),o())};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Shared Files"}),e.jsxs(B,{size:"sm",onClick:()=>{var h;return(h=r.current)==null?void 0:h.click()},disabled:a,children:[e.jsx(Na,{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(fe,{children:e.jsx(Ee,{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(fe,{children:e.jsxs(Ee,{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(Nr,{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 · `:"",Ss(new Date(h.created_at),"PP")]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>d(h),children:e.jsx(Pa,{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(_n,{className:"h-4 w-4"})})]})},h.id))})]})}function Nss(){var p,f,g,_;const{id:s}=bi(),t=Mn(),n=Ht(),{data:r,isLoading:a}=mss(s),{data:i=[]}=Omt(s),{data:l=[]}=Fmt(s),[o,c]=N.useState(!1),[d,u]=N.useState(!1);if(a)return e.jsx(Ts,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!r)return e.jsx(Ts,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Assignment not found."})});const h=r;return e.jsxs(Ts,{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(Hr,{className:"h-4 w-4 mr-2"})," Back to roster"]}),e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-24 bg-gradient-to-br from-[#2a4c64] to-[#406E71]"}),e.jsx(Ee,{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(ni,{src:((p=h.agent)==null?void 0:p.avatar_url)||void 0}),e.jsx(aa,{className:"text-2xl",children:(((f=h.agent)==null?void 0:f.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-2xl font-bold",children:((g=h.agent)==null?void 0:g.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(_=h.agent)==null?void 0:_.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(ze,{variant:"secondary",className:"capitalize",children:(h.pipeline_stage||"active").replace("_"," ")}),e.jsx(ze,{variant:"outline",className:"capitalize",children:h.status})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(kss,{value:h.pipeline_stage||"active",onChange:async v=>{await q.from("coaching_assignments").update({pipeline_stage:v}).eq("id",h.id),n.invalidateQueries({queryKey:["coaching-assignment",h.id]}),n.invalidateQueries({queryKey:["coach-roster"]})}})})]})})]}),e.jsxs(Br,{defaultValue:"sessions",children:[e.jsxs(Fr,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(Kt,{value:"sessions",children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(Kt,{value:"actions",children:[e.jsx(uu,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(Kt,{value:"goals",children:[e.jsx(Oc,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(Kt,{value:"kpis",children:[e.jsx(mo,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(Kt,{value:"messages",children:[e.jsx(Ei,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(Kt,{value:"files",children:[e.jsx(gf,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(Kt,{value:"notes",children:[e.jsx(Nr,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(is,{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(Is,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 text-muted-foreground text-center",children:"No sessions yet."})}):e.jsx("div",{className:"space-y-3",children:i.map(v=>e.jsx(fe,{children:e.jsx(Ee,{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:Ss(new Date(v.scheduled_at),"PPp")}),e.jsx(ze,{variant:"outline",className:"capitalize",children:v.status}),v.template&&e.jsx(ze,{variant:"secondary",children:v.template})]}),v.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:v.summary}),v.private_notes&&e.jsxs("div",{className:"mt-2 p-2 rounded bg-muted/50 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground mb-1",children:[e.jsx(Kc,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:v.private_notes})]})]})})})},v.id))})]}),e.jsxs(is,{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(Is,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 text-muted-foreground text-center",children:"No action items yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(v=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-3 flex items-center gap-3",children:[e.jsx(ui,{checked:v.status==="done",onCheckedChange:async j=>{await q.from("coaching_action_items").update({status:j?"done":"open",completed_at:j?new Date().toISOString():null}).eq("id",v.id),n.invalidateQueries({queryKey:["coaching-action-items",h.id]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:v.status==="done"?"line-through text-muted-foreground":"font-medium",children:v.title}),v.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:v.description})]}),v.due_date&&e.jsx(ze,{variant:"outline",children:Ss(new Date(v.due_date),"MMM d")}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:v.priority})]})},v.id))})]}),e.jsx(is,{value:"goals",children:e.jsx(Gmt,{assignmentId:h.id,canEdit:!0})}),e.jsx(is,{value:"kpis",children:h.agent_id&&e.jsx(Hmt,{agentUserId:h.agent_id})}),e.jsx(is,{value:"messages",children:e.jsx(zmt,{assignmentId:h.id})}),e.jsx(is,{value:"files",children:e.jsx(Wmt,{assignmentId:h.id})}),e.jsx(is,{value:"notes",className:"space-y-4",children:e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 text-muted-foreground",children:"Private notes per session live under the Sessions tab. General-relationship notes coming soon."})})})]})]}),e.jsx(Sss,{open:o,onOpenChange:c,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-sessions",h.id]})}),e.jsx(Css,{open:d,onOpenChange:u,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-action-items",h.id]})})]})}function kss({value:s,onChange:t}){return e.jsxs(ds,{value:s,onValueChange:t,children:[e.jsx(ls,{className:"w-40",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"onboarding",children:"Onboarding"}),e.jsx(Qe,{value:"active",children:"Active"}),e.jsx(Qe,{value:"thriving",children:"Thriving"}),e.jsx(Qe,{value:"at_risk",children:"At Risk"}),e.jsx(Qe,{value:"graduated",children:"Graduated"})]})]})}function Sss({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=N.useState(()=>new Date().toISOString().slice(0,16)),[l,o]=N.useState(60),[c,d]=N.useState("weekly_1on1"),[u,h]=N.useState(""),[p,f]=N.useState(""),[g,_]=N.useState(!1),[v,j]=N.useState(!0),[b,S]=N.useState(null),[A,T]=N.useState(!1),L=async()=>{T(!0);const{data:M,error:F}=await q.functions.invoke("coaching-prep-brief",{body:{assignmentId:n}});if(T(!1),F||M!=null&&M.error)return ae.error((M==null?void 0:M.error)||(F==null?void 0:F.message)||"Failed to generate brief");S(M.brief||"No brief returned.")},D=async()=>{_(!0);const{data:M,error:F}=await q.from("coaching_sessions").insert({assignment_id:n,scheduled_at:new Date(a).toISOString(),duration_minutes:l,template:c,summary:u,private_notes:p,status:"completed"}).select("id").maybeSingle();if(F)return _(!1),ae.error(F.message);if(ae.success("Session saved"),v&&u.trim()&&(M!=null&&M.id)){const{error:z}=await q.functions.invoke("coaching-send-recap",{body:{sessionId:M.id}});z?ae.error("Saved, but recap email failed: "+z.message):ae.success("Recap emailed to agent")}_(!1),r==null||r(),t(!1),h(""),f(""),S(null)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(_s,{children:"New Session"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:L,disabled:A,children:[A?e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-1"}),"Pre-session brief"]})]})}),e.jsxs("div",{className:"space-y-3",children:[b&&e.jsxs("div",{className:"rounded-lg border bg-gradient-to-br from-[#406E71]/5 to-[#2a4c64]/5 p-3 text-sm whitespace-pre-wrap max-h-60 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-[#406E71] mb-2",children:[e.jsx(un,{className:"h-3 w-3"})," AI Brief"]}),b]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"When"}),e.jsx(ye,{type:"datetime-local",value:a,onChange:M=>i(M.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Duration (min)"}),e.jsx(ye,{type:"number",value:l,onChange:M=>o(Number(M.target.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Template"}),e.jsxs(ds,{value:c,onValueChange:d,children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"weekly_1on1",children:"Weekly 1:1"}),e.jsx(Qe,{value:"grow",children:"GROW Model"}),e.jsx(Qe,{value:"goal_review",children:"Goal Review"}),e.jsx(Qe,{value:"breakthrough",children:"Breakthrough Session"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Summary (agent sees this)"}),e.jsx(Es,{rows:4,value:u,onChange:M=>h(M.target.value),placeholder:"Key takeaways, wins, focus areas…"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-sm font-medium flex items-center gap-1",children:[e.jsx(Kc,{className:"h-3 w-3"})," Private notes (only you)"]}),e.jsx(Es,{rows:3,value:p,onChange:M=>f(M.target.value),placeholder:"Your private observations…"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm pt-1",children:[e.jsx(ui,{checked:v,onCheckedChange:M=>j(!!M)}),e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:D,disabled:g,children:[e.jsx(qo,{className:"h-4 w-4 mr-1"})," Save Session"]})]})]})})}function Css({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState("medium"),[p,f]=N.useState(!1),g=async()=>{if(!a.trim())return;f(!0);const{error:_}=await q.from("coaching_action_items").insert({assignment_id:n,title:a,description:l||null,due_date:c||null,priority:u});if(f(!1),_)return ae.error(_.message);ae.success("Action item added"),r==null||r(),t(!1),i(""),o(""),d("")};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"New Action Item"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ye,{placeholder:"Title",value:a,onChange:_=>i(_.target.value)}),e.jsx(Es,{rows:3,placeholder:"Description (optional)",value:l,onChange:_=>o(_.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:_=>d(_.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Priority"}),e.jsxs(ds,{value:u,onValueChange:h,children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"low",children:"Low"}),e.jsx(Qe,{value:"medium",children:"Medium"}),e.jsx(Qe,{value:"high",children:"High"})]})]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:g,disabled:p,children:"Add"})]})]})})}function yCe({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(ca,{style:{width:t,height:t},className:r<=s?"fill-yellow-400 text-yellow-400":"text-muted-foreground/40"})},r))})}function Tss({coachId:s}){const[t,n]=N.useState([]),[r,a]=N.useState(!0);N.useEffect(()=>{(async()=>{const{data:l}=await q.from("coaching_reviews").select("*").eq("coach_id",s).eq("is_published",!0).order("created_at",{ascending:!1}),o=l||[];if(o.length){const c=o.map(h=>h.agent_id),{data:d}=await q.from("profiles").select("id, name, avatar_url").in("id",c),u=new Map((d||[]).map(h=>[h.id,h]));o.forEach(h=>h.profile=u.get(h.agent_id))}n(o),a(!1)})()},[s]);const i=t.length?t.reduce((l,o)=>l+o.rating,0)/t.length:0;return r||!t.length?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Reviews"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(yCe,{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(fe,{children:e.jsx(Ee,{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(ni,{src:((o=l.profile)==null?void 0:o.avatar_url)||void 0}),e.jsx(aa,{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(yCe,{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 Ess({coachId:s,assignmentId:t}){const{user:n}=ys(),[r,a]=N.useState(null),[i,l]=N.useState(0),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(!1);N.useEffect(()=>{n&&(async()=>{const{data:g}=await q.from("coaching_reviews").select("*").eq("coach_id",s).eq("agent_id",n.id).maybeSingle();g&&(a(g),l(g.rating),c(g.title||""),u(g.body||""))})()},[n,s]);const f=async()=>{if(!n)return;if(!i)return ae.error("Pick a rating");p(!0);const g={coach_id:s,agent_id:n.id,assignment_id:t||null,rating:i,title:o||null,body:d||null},{error:_}=r?await q.from("coaching_reviews").update(g).eq("id",r.id):await q.from("coaching_reviews").insert(g);if(p(!1),_)return ae.error(_.message);ae.success("Thanks for your review!"),a({...g,id:r==null?void 0:r.id})};return e.jsx(fe,{children:e.jsxs(Ee,{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(yCe,{value:i,size:28,onChange:l}),e.jsx(ye,{placeholder:"Title (optional)",value:o,onChange:g=>c(g.target.value)}),e.jsx(Es,{rows:4,placeholder:"What was your experience like?",value:d,onChange:g=>u(g.target.value)}),e.jsx(B,{onClick:f,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":r?"Update review":"Submit review"})]})})}function Ass(){var h,p,f,g,_,v;const{user:s}=ys(),{data:t,isLoading:n,refetch:r}=hss(),a=Ht(),i=t==null?void 0:t.id,{data:l=[]}=Omt(i),{data:o=[]}=Fmt(i);if(N.useEffect(()=>{new URLSearchParams(window.location.search).get("subscribed")==="1"&&q.functions.invoke("coaching-verify-checkout").then(()=>{r(),a.invalidateQueries({queryKey:["my-coaching-assignment"]})})},[r,a]),n)return e.jsx(Ts,{title:"My Coach",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Ts,{title:"My Coach",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(_d,{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(j=>j.status!=="done"),u=o.length-d.length;return e.jsx(Ts,{title:"My Coach",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-5xl mx-auto space-y-6",children:[e.jsx(fe,{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(ni,{src:((h=c.coachProfile)==null?void 0:h.avatar_url)||void 0}),e.jsx(aa,{className:"text-2xl bg-white/20 text-white",children:(((p=c.coachProfile)==null?void 0:p.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80 mb-1",children:[e.jsx(un,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider",children:"Your Coach"})]}),e.jsx("h1",{className:"text-3xl font-bold",children:((f=c.coachProfile)==null?void 0:f.name)||"Your Coach"}),((g=c.coach)==null?void 0:g.headline)&&e.jsx("p",{className:"text-white/80 mt-1",children:c.coach.headline}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[((_=c.coach)==null?void 0:_.is_certified)&&e.jsx(ze,{className:"bg-yellow-400/20 text-yellow-100 border-yellow-300/30",children:"LevelUp Certified"}),e.jsx(ze,{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($je,{icon:uu,label:"Open action items",value:d.length}),e.jsx($je,{icon:Oc,label:"Completed",value:u}),e.jsx($je,{icon:yr,label:"Sessions",value:l.length})]}),((v=c.coach)==null?void 0:v.id)&&e.jsx(Ess,{coachId:c.coach.id,assignmentId:i}),e.jsxs(Br,{defaultValue:"actions",children:[e.jsxs(Fr,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(Kt,{value:"actions",children:[e.jsx(uu,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Kt,{value:"sessions",children:[e.jsx(yr,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Recaps"})]}),e.jsxs(Kt,{value:"goals",children:[e.jsx(Oc,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Goals"})]}),e.jsxs(Kt,{value:"kpis",children:[e.jsx(mo,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"KPIs"})]}),e.jsxs(Kt,{value:"messages",children:[e.jsx(Ei,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Messages"})]}),e.jsxs(Kt,{value:"files",children:[e.jsx(gf,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(is,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 text-center text-muted-foreground",children:"Your coach hasn't assigned any action items yet."})}):o.map(j=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-3 flex items-center gap-3",children:[e.jsx(ui,{checked:j.status==="done",onCheckedChange:async b=>{await q.from("coaching_action_items").update({status:b?"done":"open",completed_at:b?new Date().toISOString():null}).eq("id",j.id),a.invalidateQueries({queryKey:["coaching-action-items",i]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:j.status==="done"?"line-through text-muted-foreground":"font-medium",children:j.title}),j.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:j.description})]}),j.due_date&&e.jsx(ze,{variant:"outline",children:Ss(new Date(j.due_date),"MMM d")}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:j.priority})]})},j.id))}),e.jsx(is,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(j=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"font-medium",children:Ss(new Date(j.scheduled_at),"PPp")}),e.jsx(ze,{variant:"outline",className:"capitalize",children:j.status})]}),j.summary?e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:j.summary}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"Recap coming soon."})]})},j.id))}),e.jsx(is,{value:"goals",children:e.jsx(Gmt,{assignmentId:i,canEdit:!1})}),e.jsx(is,{value:"kpis",children:s&&e.jsx(Hmt,{agentUserId:s.id})}),e.jsx(is,{value:"messages",children:e.jsx(zmt,{assignmentId:i})}),e.jsx(is,{value:"files",children:e.jsx(Wmt,{assignmentId:i})})]})]})})}function $je({icon:s,label:t,value:n}){return e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:n}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:t})]})]})})}function Mss(){const s=Ht(),[t,n]=N.useState(""),[r,a]=N.useState([]),[i,l]=N.useState(null),{data:o=[],isLoading:c}=ct({queryKey:["admin-coaches"],queryFn:async()=>{const{data:h,error:p}=await q.from("coaches").select("*").order("created_at",{ascending:!1});if(p)throw p;if(!(h!=null&&h.length))return[];const f=h.map(v=>v.user_id),{data:g}=await q.from("profiles").select("id, name, email, avatar_url").in("id",f),_=new Map((g||[]).map(v=>[v.id,v]));return h.map(v=>({...v,profile:_.get(v.user_id)}))}});N.useEffect(()=>{const h=t.trim();if(h.length<2){a([]);return}const p=setTimeout(async()=>{const{data:f}=await q.from("profiles").select("id, email, name, avatar_url").or(`email.ilike.%${h}%,name.ilike.%${h}%`).limit(10);a(f||[])},250);return()=>clearTimeout(p)},[t]);const d=async h=>{const{error:p}=await q.functions.invoke("manage-user-roles",{body:{userId:h.id,role:"coach",action:"add"}});if(p)return ae.error(p.message);const{error:f}=await q.from("coaches").insert({user_id:h.id});if(f&&!String(f.message).includes("duplicate"))return ae.error(f.message);ae.success(`${h.name||h.email} is now a coach`),n(""),a([]),s.invalidateQueries({queryKey:["admin-coaches"]})},u=async(h,p)=>{const{error:f}=await q.from("coaches").update({is_certified:p}).eq("id",h);if(f)return ae.error(f.message);ae.success(p?"Marked Certified":"Removed certification"),s.invalidateQueries({queryKey:["admin-coaches"]})};return e.jsxs(Ts,{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(_d,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsx(Iss,{}),e.jsx(Lss,{}),e.jsx(fe,{children:e.jsxs(Ee,{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(Is,{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(fe,{children:e.jsx(Ee,{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 p,f,g;return e.jsx(fe,{children:e.jsxs(Ee,{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:((p=h.profile)==null?void 0:p.name)||((f=h.profile)==null?void 0:f.email)||h.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(g=h.profile)==null?void 0:g.email}),e.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[h.is_certified&&e.jsxs(ze,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"Certified"]}),h.accepting_clients&&e.jsx(ze,{variant:"outline",children:"Accepting clients"})]})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>l(h.id),children:[e.jsx(Fo,{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(bn,{checked:h.is_certified,onCheckedChange:_=>u(h.id,_)})]})]})},h.id)})})]})]}),e.jsx(Pss,{coachId:i,onClose:()=>l(null)})]})}function Iss(){const[s,t]=N.useState("1500"),[n,r]=N.useState(!1),[a,i]=N.useState(!1);N.useEffect(()=>{(async()=>{const{data:c}=await q.from("settings").select("value").eq("key","coaching_platform_fee_bps").maybeSingle();c!=null&&c.value&&t(String(c.value)),i(!0)})()},[]);const l=async()=>{const c=parseInt(s,10);if(isNaN(c)||c<0||c>5e3)return ae.error("Enter a value between 0 and 5000 bps (0–50%)");r(!0);const{error:d}=await q.from("settings").upsert({key:"coaching_platform_fee_bps",value:String(c)});if(r(!1),d)return ae.error(d.message);ae.success("Platform fee updated")};if(!a)return null;const o=(parseInt(s,10)/100).toFixed(2);return e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a4,{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 Pss({coachId:s,onClose:t}){const[n,r]=N.useState(""),[a,i]=N.useState([]),[l,o]=N.useState(!1),c=Ht();N.useEffect(()=>{if(!s){r(""),i([]);return}},[s]),N.useEffect(()=>{const u=n.trim();if(u.length<2){i([]);return}o(!0);const h=setTimeout(async()=>{const{data:p}=await q.from("profiles").select("id, name, email").or(`email.ilike.%${u}%,name.ilike.%${u}%`).limit(15);i(p||[]),o(!1)},250);return()=>clearTimeout(h)},[n]);const d=async u=>{const{error:h}=await q.from("coaching_assignments").insert({coach_id:s,agent_id:u,status:"active",source:"admin",pipeline_stage:"onboarding"});if(h)return ae.error(h.message);ae.success("Agent assigned"),c.invalidateQueries({queryKey:["coach-roster"]}),t()};return e.jsx(bs,{open:!!s,onOpenChange:u=>!u&&t(),children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{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(Xn,{children:e.jsx(B,{variant:"outline",onClick:t,children:"Close"})})]})})}function Lss(){const s=Ht(),[t,n]=N.useState("pending"),[r,a]=N.useState(null),{data:i=[],isLoading:l}=ct({queryKey:["coach-applications",t],queryFn:async()=>{let u=q.from("coach_applications").select("*").order("created_at",{ascending:!1});t!=="all"&&(u=u.eq("status",t));const{data:h,error:p}=await u;if(p)throw p;return h||[]}}),{data:o=0}=ct({queryKey:["coach-applications-pending-count"],queryFn:async()=>{const{count:u}=await q.from("coach_applications").select("id",{count:"exact",head:!0}).eq("status","pending");return u||0}}),c=async(u,h)=>{const{error:p}=await q.from("coach_applications").update({status:h,reviewed_at:new Date().toISOString()}).eq("id",u);if(p)return ae.error(p.message);ae.success(`Marked ${h}`),s.invalidateQueries({queryKey:["coach-applications"]}),s.invalidateQueries({queryKey:["coach-applications-pending-count"]}),a(null)},d=u=>u==="approved"?e.jsxs(ze,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:[e.jsx(Ir,{className:"h-3 w-3 mr-1"}),"Approved"]}):u==="rejected"?e.jsxs(ze,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),"Rejected"]}):e.jsxs(ze,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(gr,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(fe,{children:[e.jsxs(Ee,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Y2,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach Applications"}),o>0&&e.jsxs(ze,{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(Vs,{className:"h-3 w-3"}),u.email]}),u.brokerage&&e.jsxs("span",{children:["· ",u.brokerage]}),u.years_experience&&e.jsxs("span",{children:["· ",u.years_experience," yrs"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d(u.status),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(u.created_at).toLocaleDateString()})]})]})},u.id))})]}),e.jsx(bs,{open:!!r,onOpenChange:u=>!u&&a(null),children:e.jsx(vs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:r&&e.jsxs(e.Fragment,{children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-3",children:[r.full_name,d(r.status)]})}),e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(wI,{icon:Vs,label:"Email",value:r.email,link:`mailto:${r.email}`}),r.phone&&e.jsx(wI,{icon:Ar,label:"Phone",value:r.phone,link:`tel:${r.phone}`}),r.brokerage&&e.jsx(wI,{label:"Brokerage",value:r.brokerage}),r.years_experience&&e.jsx(wI,{label:"Years",value:r.years_experience}),r.website_url&&e.jsx(wI,{icon:tr,label:"Website",value:r.website_url,link:r.website_url}),r.linkedin_url&&e.jsx(wI,{icon:tr,label:"LinkedIn",value:r.linkedin_url,link:r.linkedin_url})]}),r.specialties&&e.jsx(Uje,{label:"Specialties",children:r.specialties}),e.jsx(Uje,{label:"Why they want to coach",children:r.why_coach}),r.results_story&&e.jsx(Uje,{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(Es,{defaultValue:r.admin_notes||"",rows:3,onBlur:async u=>{const h=u.target.value;h!==(r.admin_notes||"")&&(await q.from("coach_applications").update({admin_notes:h}).eq("id",r.id),s.invalidateQueries({queryKey:["coach-applications"]}))},placeholder:"Internal notes (saved on blur)…"})]})]}),e.jsxs(Xn,{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(Bn,{className:"h-4 w-4 mr-1"})," Reject"]}),r.status!=="pending"&&e.jsxs(B,{variant:"outline",onClick:()=>c(r.id,"pending"),children:[e.jsx(gr,{className:"h-4 w-4 mr-1"})," Move to pending"]}),r.status!=="approved"&&e.jsxs(B,{onClick:()=>c(r.id,"approved"),className:"bg-emerald-600 hover:bg-emerald-700",children:[e.jsx(Ir,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function wI({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 Uje({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 Dss(){const s=Mn(),{data:t}=mU(),n=Ht(),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(null),{data:d,refetch:u}=ct({queryKey:["coach-stripe-status",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:v}=await q.functions.invoke("coach-stripe-status");return v}}),{data:h=[]}=ct({queryKey:["coach-packages",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:v}=await q.from("coaching_packages").select("*").eq("coach_id",t.id).order("sort_order");return v||[]}});N.useEffect(()=>{const v=new URLSearchParams(window.location.search);(v.get("onboarded")||v.get("refresh"))&&u()},[u]);const p=async()=>{var S,A;a(!0);const{data:v,error:j}=await q.functions.invoke("coach-stripe-connect");a(!1);let b=v==null?void 0:v.error;if(!b&&j)try{const T=await((A=(S=j==null?void 0:j.context)==null?void 0:S.json)==null?void 0:A.call(S));b=(T==null?void 0:T.error)||j.message}catch{b=j.message}if(b)return ae.error(b,{duration:1e4});v!=null&&v.url&&(window.location.href=v.url)},f=d||{},g=!!(t!=null&&t.use_platform_stripe),_=g||f.connected&&f.charges_enabled;return e.jsx(Ts,{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(Hr,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Billing & Packages"})]}),e.jsx(fe,{children:e.jsxs(Ee,{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(pf,{className:"h-5 w-5"})," Stripe Connect"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:g?"Your coaching sales are billed through the main LevelUp Stripe account.":"Payouts go directly to your bank. LevelUp takes a small platform fee from each charge."})]}),_?e.jsxs(ze,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40 flex items-center gap-1",children:[e.jsx(xr,{className:"h-3 w-3"})," ",g?"Using LevelUp billing":"Connected"]}):f.connected?e.jsxs(ze,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(Gi,{className:"h-3 w-3"})," Setup incomplete"]}):e.jsx(ze,{variant:"outline",children:"Not connected"})]}),!g&&e.jsxs(B,{onClick:p,disabled:r,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[_?"Update Stripe details":f.connected?"Finish Stripe setup":"Connect Stripe",e.jsx(tr,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{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:!_,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," New Package"]})]}),!_&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect Stripe before creating packages."}),h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No packages yet."}):e.jsx("div",{className:"space-y-2",children:h.map(v=>e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[v.name,v.is_active&&v.accepting_clients===!1&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-amber-100 text-amber-800 font-semibold",children:"Booked full"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:["$",(v.price_cents/100).toFixed(0)," / ",v.billing_interval,!v.is_active&&" · Inactive"]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{c(v),l(!0)},children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{confirm("Delete this package?")&&(await q.from("coaching_packages").delete().eq("id",v.id),n.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]}))},children:e.jsx(_n,{className:"h-4 w-4"})})]},v.id))})]})}),e.jsx(Rss,{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 Rss({open:s,onOpenChange:t,coachId:n,pkg:r,onSaved:a}){const[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState("month"),[f,g]=N.useState(!0),[_,v]=N.useState(!0),[j,b]=N.useState(!1);N.useEffect(()=>{s&&(l((r==null?void 0:r.name)||""),c((r==null?void 0:r.description)||""),u(r?(r.price_cents/100).toString():""),p((r==null?void 0:r.billing_interval)||"month"),g((r==null?void 0:r.is_active)??!0),v((r==null?void 0:r.accepting_clients)??!0))},[s,r]);const S=async()=>{if(!i.trim()||!d)return ae.error("Name and price required");b(!0);const A={coach_id:n,name:i,description:o||null,price_cents:Math.round(Number(d)*100),billing_interval:h,is_active:f,accepting_clients:_},{error:T}=r!=null&&r.id?await q.from("coaching_packages").update(A).eq("id",r.id):await q.from("coaching_packages").insert(A);if(b(!1),T)return ae.error(T.message);ae.success("Saved"),a==null||a(),t(!1)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{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:A=>l(A.target.value)}),e.jsx(Es,{rows:3,placeholder:"What's included",value:o,onChange:A=>c(A.target.value)}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(ye,{type:"number",value:d,onChange:A=>u(A.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Interval"}),e.jsxs(ds,{value:h,onValueChange:p,children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"month",children:"Monthly"}),e.jsx(Qe,{value:"year",children:"Yearly"}),e.jsx(Qe,{value:"one_time",children:"One-time"})]})]})]})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:f,onChange:A=>g(A.target.checked)}),"Active (visible to agents)"]}),e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5",checked:_,onChange:A=>v(A.target.checked)}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Accepting new clients"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Uncheck if you're booked full — visitors will still see the package but can't sign up."})]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:S,disabled:j,children:r!=null&&r.id?"Save":"Create"})]})]})})}function $Ue({kind:s,value:t,onChange:n}){const r=N.useRef(null),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=N.useRef(null),h=N.useRef(null),p=N.useRef(null),f=N.useRef([]),[g,_]=N.useState(!1),v=s==="photo"?"image/*":"video/*",j=s==="photo"?10*1024*1024:200*1024*1024,b=async(M,F)=>{var J;const{data:z}=await q.auth.getUser(),V=(J=z.user)==null?void 0:J.id;if(!V)return ae.error("Not signed in");if(M.size>j)return ae.error(`File too large. Max ${s==="photo"?"10MB":"200MB"}.`);i(!0);const W=`${V}/${s}-${Date.now()}.${F}`,{error:Y}=await q.storage.from("coach-media").upload(W,M,{upsert:!0,contentType:M.type||(s==="photo"?"image/jpeg":"video/webm")});if(Y)return i(!1),ae.error(Y.message);const{data:K}=await q.storage.from("coach-media").createSignedUrl(W,60*60*24*365*10);i(!1),K!=null&&K.signedUrl&&(n(K.signedUrl),ae.success("Uploaded"),d(null))},S=async M=>{const F=M.name.split(".").pop()||(s==="photo"?"jpg":"webm");await b(M,F)},A=async()=>{try{const M=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0});h.current=M,_(!0),setTimeout(()=>{u.current&&(u.current.srcObject=M,u.current.play())},50);const F=new MediaRecorder(M,{mimeType:"video/webm"});f.current=[],F.ondataavailable=z=>z.data.size>0&&f.current.push(z.data),F.onstop=()=>{const z=new Blob(f.current,{type:"video/webm"});d(z),M.getTracks().forEach(V=>V.stop())},p.current=F,F.start(),o(!0)}catch(M){ae.error(M.message||"Could not access camera")}},T=()=>{var M;(M=p.current)==null||M.stop(),o(!1)},L=()=>{var M;(M=h.current)==null||M.getTracks().forEach(F=>F.stop()),_(!1),o(!1),d(null)},D=async()=>{c&&(await b(c,"webm"),L())};return N.useEffect(()=>()=>{var M;return(M=h.current)==null?void 0:M.getTracks().forEach(F=>F.stop())},[]),e.jsxs("div",{className:"space-y-2",children:[t&&e.jsx("div",{className:"rounded-lg overflow-hidden border bg-muted/30",children:s==="photo"?e.jsx("img",{src:t,alt:"Profile",className:"w-32 h-32 object-cover"}):e.jsx("video",{src:t,controls:!0,className:"w-full max-h-64"})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("input",{ref:r,type:"file",accept:v,className:"hidden",onChange:M=>{var z;const F=(z=M.target.files)==null?void 0:z[0];F&&S(F),M.target.value=""}}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{var M;return(M=r.current)==null?void 0:M.click()},children:[a?e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Na,{className:"h-4 w-4 mr-1"}),s==="photo"?"Upload photo":"Upload video"]}),s==="video"&&e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:A,disabled:a||g,children:[e.jsx(mf,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>n(""),children:[e.jsx(_n,{className:"h-4 w-4 mr-1"})," Remove"]})]}),g&&e.jsxs("div",{className:"rounded-lg border p-3 space-y-3 bg-background",children:[c?e.jsx("video",{src:URL.createObjectURL(c),controls:!0,className:"w-full max-h-64 rounded bg-black"}):e.jsx("video",{ref:u,muted:!0,playsInline:!0,className:"w-full max-h-64 rounded bg-black"}),e.jsxs("div",{className:"flex gap-2",children:[!c&&l&&e.jsxs(B,{type:"button",size:"sm",onClick:T,className:"bg-red-600 hover:bg-red-700",children:[e.jsx(ly,{className:"h-4 w-4 mr-1"})," Stop"]}),!c&&!l&&e.jsxs(B,{type:"button",size:"sm",onClick:()=>{var M;return(M=p.current)==null?void 0:M.start()},children:[e.jsx(br,{className:"h-4 w-4 mr-1"})," Start"]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{type:"button",size:"sm",onClick:D,disabled:a,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[a?e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Na,{className:"h-4 w-4 mr-1"}),"Use this recording"]}),e.jsx(B,{type:"button",size:"sm",variant:"outline",onClick:()=>{d(null),A()},children:"Re-record"})]}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:L,children:"Cancel"})]})]})]})}function Oss(){const s=Mn(),{data:t,isLoading:n}=mU(),r=Ht(),[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState(""),[g,_]=N.useState(!1),[v,j]=N.useState([]),[b,S]=N.useState(""),[A,T]=N.useState(!1);N.useEffect(()=>{if(!t)return;const z=t;i(z.slug||""),o(z.headline||""),d(z.bio||""),h(z.photo_url||""),f(z.intro_video_url||""),_(!!z.accepting_clients),j(z.specialties||[])},[t]);const L=async()=>{if(!t)return;T(!0);const{error:z}=await q.from("coaches").update({slug:a.trim()||null,headline:l||null,bio:c||null,photo_url:u||null,intro_video_url:p||null,accepting_clients:g,specialties:v}).eq("id",t.id);if(T(!1),z)return ae.error(z.message);ae.success("Profile saved"),r.invalidateQueries({queryKey:["my-coach-profile"]})},D=()=>{const z=b.trim();if(z){if(v.includes(z))return S("");j([...v,z]),S("")}};if(n)return e.jsx(Ts,{title:"Coach Settings",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Ts,{title:"Coach Settings",children:e.jsx("div",{className:"max-w-2xl mx-auto p-8 text-center text-muted-foreground",children:"You don't have a coach profile yet."})});const M=t,F=M.slug?`${window.location.origin}/coaches/${M.slug}`:null;return e.jsx(Ts,{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(Hr,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Coach Profile"})]}),e.jsxs("div",{className:"flex gap-2",children:[F&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(F,"_blank"),children:[e.jsx(tr,{className:"h-4 w-4 mr-1"})," View public"]}),e.jsxs(B,{onClick:L,disabled:A,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[e.jsx(qo,{className:"h-4 w-4 mr-1"})," ",A?"Saving…":"Save"]})]})]}),M.is_certified&&e.jsxs("div",{className:"rounded-lg border border-yellow-300/50 bg-yellow-50 dark:bg-yellow-950/20 px-4 py-3 text-sm",children:["✨ ",e.jsx("strong",{children:"LevelUp Certified"})," — Your profile displays a verified badge."]}),e.jsx(fe,{children:e.jsxs(Ee,{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(bn,{checked:g,onCheckedChange:_})]}),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:z=>i(z.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:z=>o(z.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(Es,{rows:6,value:c,onChange:z=>d(z.target.value),placeholder:"Tell agents who you are, what you've done, how you coach…"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Profile photo"}),e.jsx($Ue,{kind:"photo",value:u,onChange:h})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Intro video"}),e.jsx($Ue,{kind:"video",value:p,onChange:f})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:v.map(z=>e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[z,e.jsx("button",{onClick:()=>j(v.filter(V=>V!==z)),children:e.jsx(Bn,{className:"h-3 w-3"})})]},z))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:b,onChange:z=>S(z.target.value),placeholder:"Add a specialty…",onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),D())}}),e.jsx(B,{type:"button",variant:"outline",onClick:D,children:e.jsx(Is,{className:"h-4 w-4"})})]})]})]})}),e.jsx(fe,{children:e.jsx(Ee,{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(Fss,{coachId:M.id})]})})}function Fss({coachId:s}){const[t,n]=N.useState("");Ht();const{data:r=[],refetch:a}=ct({queryKey:["coach-invites",s],queryFn:async()=>{const{data:c}=await q.from("coaching_invites").select("*").eq("coach_id",s).order("created_at",{ascending:!1});return c||[]}}),i=async()=>{const c=t.trim().toLowerCase();if(!c)return ae.error("Email required");const{error:d}=await q.from("coaching_invites").insert({coach_id:s,email:c});if(d)return ae.error(d.message);n(""),ae.success("Invite created"),a()},l=c=>{const d=`${window.location.origin}/auth?coach_invite=${c}`;navigator.clipboard.writeText(d),ae.success("Link copied")},o=async c=>{confirm("Revoke this invite?")&&(await q.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(fe,{children:e.jsxs(Ee,{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(Jo,{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(Is,{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(Xr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(_n,{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 pH=[{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 zss(){const s=Mn(),t=Ht(),{data:n,isLoading:r}=mU(),[a,i]=N.useState("pending"),[l,o]=N.useState(""),[c,d]=N.useState(null),[u,h]=N.useState(!1),[p,f]=N.useState(""),[g,_]=N.useState(!1),[v,j]=N.useState(""),{data:b=[],isLoading:S}=ct({queryKey:["coaching-waitlist",n==null?void 0:n.id],enabled:!!(n!=null&&n.id),queryFn:async()=>{const{data:z,error:V}=await q.from("coaching_waitlist").select("*").eq("coach_id",n.id).order("created_at",{ascending:!1});if(V)throw V;return z||[]}}),A=N.useMemo(()=>b.filter(z=>{if(a!=="all"&&z.status!==a)return!1;if(l){const V=l.toLowerCase();return(z.name||"").toLowerCase().includes(V)||(z.email||"").toLowerCase().includes(V)||(z.brokerage||"").toLowerCase().includes(V)}return!0}),[b,a,l]),T=N.useMemo(()=>{const z={all:b.length};for(const V of pH)z[V.value]=0;for(const V of b)z[V.status]=(z[V.status]||0)+1;return z},[b]),L=async(z,V)=>{const{error:W}=await q.from("coaching_waitlist").update(V).eq("id",z);if(W)return ae.error(W.message);t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),(c==null?void 0:c.id)===z&&d(Y=>({...Y,...V}))},D=async z=>{if(!confirm("Remove this person from the waitlist?"))return;const{error:V}=await q.from("coaching_waitlist").delete().eq("id",z);if(V)return ae.error(V.message);ae.success("Removed"),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),d(null)},M=async()=>{if(!c)return;const{data:z,error:V}=await q.functions.invoke("coaching-waitlist-invite",{body:{waitlistId:c.id,message:p}});if(V||z!=null&&z.error)return ae.error((z==null?void 0:z.error)||(V==null?void 0:V.message)||"Could not send invite");ae.success(`Invite sent to ${c.name}`),h(!1),f(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})},F=async()=>{if(!n)return;const{data:z,error:V}=await q.functions.invoke("coaching-waitlist-invite",{body:{coachId:n.id,notifyAll:!0,message:v}});if(V||z!=null&&z.error)return ae.error((z==null?void 0:z.error)||(V==null?void 0:V.message)||"Could not notify");ae.success(`Notified ${(z==null?void 0:z.count)||0} agents`),_(!1),j(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})};return r?e.jsx(Ts,{title:"Waitlist",children:e.jsx("div",{className:"p-8",children:"Loading…"})}):n?e.jsxs(Ts,{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(Hr,{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(Dv,{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:()=>_(!0),disabled:!T.pending,title:T.pending?"":"No pending applicants",children:[e.jsx(oL,{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,")"]}),pH.map(z=>e.jsxs("button",{onClick:()=>i(z.value),className:`px-3 py-1.5 rounded-full text-sm border ${a===z.value?"bg-[#406E71] text-white border-[#406E71]":"bg-white hover:bg-muted"}`,children:[z.label," (",T[z.value]||0,")"]},z.value))]}),e.jsx(ye,{placeholder:"Search by name, email, brokerage…",value:l,onChange:z=>o(z.target.value),className:"max-w-md"}),S?e.jsx("div",{className:"text-muted-foreground",children:"Loading…"}):A.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"p-10 text-center text-muted-foreground",children:"No entries here yet."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:A.map(z=>{const V=pH.find(W=>W.value===z.status);return e.jsx(fe,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>d(z),children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold truncate",children:z.name}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:z.email}),z.brokerage&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:z.brokerage})]}),e.jsx(ze,{className:(V==null?void 0:V.tone)||"",children:(V==null?void 0:V.label)||z.status})]}),e.jsxs("div",{className:"flex items-center justify-between mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Joined ",Vo(new Date(z.created_at),{addSuffix:!0})]}),z.preferred_package&&e.jsxs("span",{className:"truncate ml-2",children:["→ ",z.preferred_package]})]})]})},z.id)})})]}),e.jsx(bs,{open:!!c,onOpenChange:z=>!z&&d(null),children:e.jsx(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:c&&e.jsxs(e.Fragment,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:c.name}),e.jsxs(Qn,{children:["Joined ",Vo(new Date(c.created_at),{addSuffix:!0})]})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(hF,{label:"Email",value:c.email}),e.jsx(hF,{label:"Phone",value:c.phone}),e.jsx(hF,{label:"Brokerage",value:c.brokerage}),e.jsx(hF,{label:"Years",value:c.years_in_business}),e.jsx(hF,{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 ",Vo(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(ds,{value:c.status,onValueChange:z=>L(c.id,{status:z}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:pH.map(z=>e.jsx(Qe,{value:z.value,children:z.label},z.value))})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Private notes"}),e.jsx(Es,{rows:3,defaultValue:c.coach_notes||"",onBlur:z=>{z.target.value!==(c.coach_notes||"")&&L(c.id,{coach_notes:z.target.value})}})]})]}),e.jsxs(Xn,{className:"flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",className:"text-destructive",onClick:()=>D(c.id),children:[e.jsx(_n,{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(Vs,{className:"h-4 w-4 mr-1"})," Email directly"]})}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>{f(""),h(!0)},children:[e.jsx(cr,{className:"h-4 w-4 mr-1"})," Invite to subscribe"]})]})]})})}),e.jsx(bs,{open:u,onOpenChange:h,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Invite to subscribe"}),e.jsxs(Qn,{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(Es,{rows:4,placeholder:"Hey! A spot just opened up and I'd love to work with you…",value:p,onChange:z=>f(z.target.value)})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:M,children:[e.jsx(cr,{className:"h-4 w-4 mr-1"})," Send invite"]})]})]})}),e.jsx(bs,{open:g,onOpenChange:_,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Notify all pending applicants"}),e.jsx(Qn,{children:"Send everyone with status “Pending” an email letting them know spots are opening up. They'll each be marked “Invited”."})]}),e.jsx(Es,{rows:4,placeholder:"Good news — I just opened up new coaching spots…",value:v,onChange:z=>j(z.target.value)}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:F,children:[e.jsx(oL,{className:"h-4 w-4 mr-1"})," Send to ",T.pending||0," agents"]})]})]})})]}):e.jsx(Ts,{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 hF({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 Bss(){const{data:s=[],isLoading:t}=ct({queryKey:["coaches-directory"],queryFn:async()=>{const{data:n,error:r}=await q.from("coaches").select("id, slug, headline, bio, specialties, photo_url, is_certified, accepting_clients, user_id").not("slug","is",null);if(r)throw r;const a=(n||[]).map(o=>o.user_id);if(a.length===0)return[];const{data:i}=await q.from("profiles").select("id, name, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return(n||[]).map(o=>({...o,profile:l.get(o.user_id)}))}});return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs("section",{className:"relative overflow-hidden bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white",children:[e.jsx("div",{className:"absolute -top-32 -left-24 h-96 w-96 rounded-full bg-[#5a9ea2]/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-32 -right-24 h-96 w-96 rounded-full bg-yellow-400/10 blur-3xl"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"22px 22px"}}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 py-20 md:py-28 text-center",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm border border-white/15 text-xs uppercase tracking-[0.18em] font-semibold mb-6",children:[e.jsx(un,{className:"h-3.5 w-3.5 text-yellow-300"}),"LevelUp Certified Coaches"]}),e.jsxs("h1",{className:"text-5xl md:text-7xl font-bold tracking-tight leading-[1.05]",children:["Coaching that ",e.jsx("span",{className:"bg-gradient-to-r from-yellow-300 to-yellow-100 bg-clip-text text-transparent",children:"moves the needle."})]}),e.jsx("p",{className:"text-white/75 mt-6 max-w-2xl mx-auto text-lg leading-relaxed",children:"Hand-picked real-estate coaches ready to help you hit your next breakthrough — from lead gen to listings to luxury."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-6 mt-10 text-sm text-white/70",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xr,{className:"h-4 w-4 text-yellow-300"})," Vetted by LevelUp"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vo,{className:"h-4 w-4 text-yellow-300"})," Top-producer experience"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ca,{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(Ln,{to:`/coaches/${n.slug||n.id}`,className:"group",children:e.jsx("article",{className:"relative h-full rounded-2xl bg-[#1c3447] overflow-hidden transition-all duration-300 hover:-translate-y-1 hover:shadow-[0_24px_60px_-20px_rgba(42,76,100,0.5)]",children:e.jsxs("div",{className:"relative aspect-[3/4] w-full overflow-hidden",children:[a?e.jsx("img",{src:a,alt:r,className:"absolute inset-0 h-full w-full object-cover object-top group-hover:scale-105 transition-transform duration-700"}):e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white text-6xl font-bold",children:r.charAt(0)}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0d1f2d] via-[#0d1f2d]/70 to-transparent"}),e.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-start justify-between gap-2",children:[n.is_certified?e.jsxs("div",{className:"inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-gradient-to-r from-yellow-400 to-yellow-300 text-[#2a4c64] text-[11px] font-semibold shadow-md",children:[e.jsx(un,{className:"h-3 w-3"})," Certified"]}):e.jsx("span",{}),e.jsxs("div",{className:`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-medium backdrop-blur-md ${n.accepting_clients?"bg-emerald-500/90 text-white":"bg-white/85 text-[#2a4c64]"}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${n.accepting_clients?"bg-white":"bg-amber-500"}`}),n.accepting_clients?"Accepting":"Waitlist"]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-5 text-white",children:[e.jsx("h3",{className:"text-xl font-bold leading-tight drop-shadow-sm",children:r}),n.headline&&e.jsx("p",{className:"text-sm text-yellow-200/90 font-medium mt-1 line-clamp-1",children:n.headline}),n.bio&&e.jsx("p",{className:"text-[13px] text-white/80 mt-2 line-clamp-2 leading-relaxed",children:n.bio}),n.specialties&&n.specialties.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-3",children:n.specialties.slice(0,2).map(o=>e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-white/15 backdrop-blur-sm text-white border border-white/20",children:o},o))}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-3 border-t border-white/15",children:[e.jsx("span",{className:"text-sm font-semibold text-white",children:"View profile"}),e.jsx("span",{className:"inline-flex items-center justify-center h-8 w-8 rounded-full bg-white/15 backdrop-blur-sm text-white group-hover:bg-yellow-300 group-hover:text-[#1c3447] transition-colors",children:e.jsx(Oa,{className:"h-4 w-4"})})]})]})]})})},n.id)})}),e.jsxs("div",{className:"mt-20 rounded-3xl bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white p-10 md:p-14 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"18px 18px"}}),e.jsx("div",{className:"absolute -top-24 -right-24 h-72 w-72 rounded-full bg-yellow-300/15 blur-3xl"}),e.jsxs("div",{className:"relative md:flex items-center gap-10",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 border border-white/15 text-[11px] uppercase tracking-[0.18em] font-semibold mb-5",children:[e.jsx(un,{className:"h-3.5 w-3.5 text-yellow-300"})," Coach Applications Open"]}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-bold leading-tight",children:["Are you the kind of agent ",e.jsx("span",{className:"text-yellow-300",children:"other agents need?"})]}),e.jsx("p",{className:"text-white/80 mt-4 max-w-xl leading-relaxed",children:"LevelUp Coaches are the top 1% — top producers, proven mentors, and category leaders making a measurable difference in agents' businesses. If that's you, we want to meet you."}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3 text-sm text-white/70",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(xr,{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(xr,{className:"h-4 w-4 text-yellow-300"})," Recurring revenue"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(xr,{className:"h-4 w-4 text-yellow-300"})," Certified status"]})]})]}),e.jsxs("div",{className:"mt-8 md:mt-0",children:[e.jsxs(Ln,{to:"/coaches/apply",className:"inline-flex items-center gap-2 bg-yellow-300 text-[#1c3447] hover:bg-yellow-200 font-bold px-7 py-4 rounded-xl shadow-lg shadow-yellow-300/20 transition-all hover:-translate-y-0.5",children:["Apply to coach ",e.jsx(Oa,{className:"h-5 w-5"})]}),e.jsx("p",{className:"text-xs text-white/60 mt-3 text-center md:text-left",children:"By application only."})]})]})]})]})]})}const $ss=Yw({name:go().trim().min(1,"Name required").max(120),email:go().trim().email("Invalid email").max(255),phone:go().trim().max(40).optional().or(jp("")),brokerage:go().trim().max(160).optional().or(jp("")),years_in_business:go().max(40).optional().or(jp("")),biggest_challenge:go().trim().max(1e3).optional().or(jp("")),preferred_package:go().max(120).optional().or(jp("")),message:go().trim().max(1500).optional().or(jp(""))});function Uss({open:s,onOpenChange:t,coachId:n,coachName:r,packages:a=[]}){const{user:i}=ys(),[l,o]=N.useState(!1),[c,d]=N.useState({name:"",email:(i==null?void 0:i.email)||"",phone:"",brokerage:"",years_in_business:"",biggest_challenge:"",preferred_package:"",message:""}),u=(p,f)=>d(g=>({...g,[p]:f})),h=async()=>{var g;const p=$ss.safeParse(c);if(!p.success){ae.error(((g=p.error.issues[0])==null?void 0:g.message)||"Please check your entries");return}o(!0);const{error:f}=await q.from("coaching_waitlist").insert({coach_id:n,agent_user_id:(i==null?void 0:i.id)||null,name:c.name.trim(),email:c.email.trim().toLowerCase(),phone:c.phone||null,brokerage:c.brokerage||null,years_in_business:c.years_in_business||null,biggest_challenge:c.biggest_challenge||null,preferred_package:c.preferred_package||null,message:c.message||null,status:"pending"});if(o(!1),f){ae.error(f.message||"Could not join waitlist");return}ae.success(`You're on the waitlist${r?` for ${r}`:""}. We'll be in touch when a spot opens.`),t(!1),d({...c,biggest_challenge:"",message:""})};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:["Join the waitlist",r?` — ${r}`:""]}),e.jsx(Qn,{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:p=>u("name",p.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email *"}),e.jsx(ye,{type:"email",value:c.email,onChange:p=>u("email",p.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:p=>u("phone",p.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Brokerage"}),e.jsx(ye,{value:c.brokerage,onChange:p=>u("brokerage",p.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(ds,{value:c.years_in_business,onValueChange:p=>u("years_in_business",p),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select…"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"< 1 year",children:"Less than 1 year"}),e.jsx(Qe,{value:"1-3 years",children:"1-3 years"}),e.jsx(Qe,{value:"4-7 years",children:"4-7 years"}),e.jsx(Qe,{value:"8-15 years",children:"8-15 years"}),e.jsx(Qe,{value:"15+ years",children:"15+ years"})]})]})]}),a.length>0&&e.jsxs("div",{children:[e.jsx(se,{children:"Preferred package"}),e.jsxs(ds,{value:c.preferred_package,onValueChange:p=>u("preferred_package",p),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Any"})}),e.jsx(cs,{children:a.map(p=>e.jsx(Qe,{value:p.name,children:p.name},p.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Biggest challenge right now"}),e.jsx(Es,{rows:2,value:c.biggest_challenge,onChange:p=>u("biggest_challenge",p.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Anything else?"}),e.jsx(Es,{rows:2,value:c.message,onChange:p=>u("message",p.target.value)})]})]}),e.jsxs(Xn,{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 qss(){var _;const{slug:s}=bi(),t=Mn(),{user:n}=ys(),[r,a]=N.useState(null),[i,l]=N.useState(!1),{data:o,isLoading:c}=ct({queryKey:["coach-public",s],enabled:!!s,queryFn:async()=>{const v=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s||""),j=q.from("coaches").select("*"),{data:b}=v?await j.eq("id",s).maybeSingle():await j.eq("slug",s).maybeSingle();if(!b)return null;const[{data:S},{data:A}]=await Promise.all([q.from("profiles").select("id, name, avatar_url").eq("id",b.user_id).maybeSingle(),q.from("coaching_packages").select("*").eq("coach_id",b.id).eq("is_active",!0).order("sort_order")]);return{coach:b,profile:S,packages:A||[]}}}),d=async v=>{if(!n){ae.error("Please sign in to subscribe"),t(`/auth?redirect=/coaches/${s}`);return}a(v);const{data:j,error:b}=await q.functions.invoke("create-coaching-checkout",{body:{packageId:v}});if(a(null),b||j!=null&&j.error){ae.error((j==null?void 0:j.error)||(b==null?void 0:b.message)||"Checkout failed");return}j!=null&&j.url&&(window.location.href=j.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:p}=o,f=u,g=(v,j)=>{const b=(v/100).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return j==="one_time"?b:`${b} / ${j}`};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(Hr,{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(ni,{src:f.photo_url||(h==null?void 0:h.avatar_url)}),e.jsx(aa,{className:"text-3xl bg-white/20",children:((h==null?void 0:h.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[f.is_certified&&e.jsxs("div",{className:"inline-flex items-center gap-1 bg-yellow-400/20 border border-yellow-300/30 text-yellow-100 px-2 py-1 rounded-full text-xs mb-2",children:[e.jsx(un,{className:"h-3 w-3"})," LevelUp Certified"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:(h==null?void 0:h.name)||"Coach"}),f.headline&&e.jsx("p",{className:"text-white/80 text-lg mt-2",children:f.headline}),((_=f.specialties)==null?void 0:_.length)>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-4",children:f.specialties.map(v=>e.jsx(ze,{className:"bg-white/15 text-white border-white/20",children:v},v))})]})]})]})}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 grid grid-cols-1 md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[f.intro_video_url&&e.jsx("div",{className:"aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("video",{src:f.intro_video_url,controls:!0,className:"w-full h-full"})}),f.bio&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold mb-3",children:"About"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap leading-relaxed",children:f.bio})]}),e.jsx(Tss,{coachId:f.id})]}),e.jsxs("div",{className:"space-y-4 md:sticky md:top-6 md:self-start",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Choose a plan"}),p.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 text-sm text-muted-foreground text-center",children:"No packages available yet."})}):p.map(v=>{const j=v.accepting_clients===!1;return e.jsx(fe,{className:`border-2 transition-colors ${j?"border-amber-200 bg-amber-50/30":"hover:border-[#406E71]"}`,children:e.jsxs(Ee,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:v.name}),j&&e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-bold px-2 py-1 rounded-full bg-amber-500 text-white shrink-0",children:"Booked Full"})]}),v.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:v.description}),e.jsx("div",{className:"text-2xl font-bold mt-3",children:g(v.price_cents,v.billing_interval)}),j?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(Dv,{className:"h-4 w-4 mr-1"})," Join Waitlist"]})]}):e.jsxs(B,{className:"w-full mt-4 bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>d(v.id),disabled:r===v.id,children:[r===v.id?"Loading…":"Get Started",e.jsx(Ir,{className:"h-4 w-4 ml-1"})]})]})},v.id)}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Secure checkout powered by Stripe."}),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-muted-foreground",onClick:()=>l(!0),children:[e.jsx(Dv,{className:"h-4 w-4 mr-1"})," Join the waitlist instead"]})]})]}),e.jsx(Uss,{open:i,onOpenChange:l,coachId:f.id,coachName:h==null?void 0:h.name,packages:p.map(v=>({id:v.id,name:v.name}))})]})}const Vss=Yw({full_name:go().trim().min(2,"Please enter your full name").max(100),email:go().trim().email("Enter a valid email").max(255),phone:go().trim().max(40).optional().or(jp("")),brokerage:go().trim().max(150).optional().or(jp("")),years_experience:go().trim().max(40).optional().or(jp("")),specialties:go().trim().max(500).optional().or(jp("")),why_coach:go().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:go().trim().max(2e3).optional().or(jp("")),website_url:go().trim().max(300).optional().or(jp("")),linkedin_url:go().trim().max(300).optional().or(jp(""))});function Hss(){const s=Mn(),[t,n]=N.useState(!1),[r,a]=N.useState(!1),[i,l]=N.useState({full_name:"",email:"",phone:"",brokerage:"",years_experience:"",specialties:"",why_coach:"",results_story:"",website_url:"",linkedin_url:""}),o=(d,u)=>l(h=>({...h,[d]:u})),c=async d=>{var p;d.preventDefault();const u=Vss.safeParse(i);if(!u.success){const f=(p=Object.values(u.error.flatten().fieldErrors)[0])==null?void 0:p[0];return ae.error(f||"Please check the form and try again")}n(!0);const{error:h}=await q.from("coach_applications").insert(u.data);if(n(!1),h)return ae.error(h.message||"Could not submit application");a(!0),window.scrollTo({top:0,behavior:"smooth"})};return r?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-xl text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center h-20 w-20 rounded-full bg-gradient-to-br from-yellow-400 to-yellow-300 text-[#1c3447] mb-6 shadow-2xl",children:e.jsx(xr,{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(Ln,{to:"/coaches",className:"inline-flex items-center gap-2 text-white/70 hover:text-white text-sm mb-8",children:[e.jsx(Hr,{className:"h-4 w-4"})," Back to coaches"]}),e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm border border-white/15 text-xs uppercase tracking-[0.18em] font-semibold mb-6",children:[e.jsx(un,{className:"h-3.5 w-3.5 text-yellow-300"}),"Coach Application — By Invitation & Application Only"]}),e.jsx("h1",{className:"text-4xl md:text-6xl font-bold tracking-tight leading-[1.05] max-w-3xl",children:"Join the most respected coaching program in real estate."}),e.jsx("p",{className:"text-white/80 mt-6 max-w-2xl text-lg leading-relaxed",children:"LevelUp Coaches don't just teach — they transform careers. We hand-pick top-producing agents and proven mentors who are ready to multiply their impact, build a recurring revenue stream, and help thousands of agents finally break through."}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-4 mt-12",children:[e.jsxs("div",{className:"rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-5",children:[e.jsx(Nn,{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(mo,{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(bc,{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(xr,{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(vo,{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(ca,{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(C_,{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(C_,{label:"Email *",children:e.jsx(ye,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(C_,{label:"Phone",children:e.jsx(ye,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(C_,{label:"Current brokerage",children:e.jsx(ye,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(C_,{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(C_,{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(C_,{label:"Website",children:e.jsx(ye,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(C_,{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(C_,{label:"Why do you want to coach with LevelUp? *",children:e.jsx(Es,{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(C_,{label:"Tell us about results you've created — for yourself or other agents.",children:e.jsx(Es,{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 C_({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 Gss="/assets/testimonial-avatar-1-BsCQFauB.jpg",Wss="/assets/testimonial-avatar-2-B6VPVc2t.jpg",Kss="/assets/testimonial-avatar-3-GuEFwYUE.jpg",Yss="/assets/testimonial-avatar-4-98iKMtkB.jpg",Zss="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",Qss=[Gss,Wss,Kss,Yss,Zss],Xss=Yw({name:go().trim().min(2,"Name must be at least 2 characters").max(100),email:go().trim().email("Please enter a valid email address").max(255),phone:go().trim().min(10,"Please enter a valid phone number").max(20).optional().or(jp("")),brokerage:go().trim().max(200).optional().or(jp(""))}),Jss=[{icon:Au,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:fl,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:yr,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Ql,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Nr,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Oi,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],ens=[{icon:Nn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:un,title:"Smart TouchPlans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Ar,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:cu,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ka,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:yo,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:gi,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:hh,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],tns=[{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."}],sns=()=>{const s=Mn(),[t,n]=N.useState(!1),[r,a]=N.useState({name:"",email:"",phone:"",brokerage:""}),[i,l]=N.useState({}),o=async c=>{var u,h;c.preventDefault(),l({});const d=Xss.safeParse(r);if(!d.success){const p={};d.error.issues.forEach(f=>{f.path[0]&&(p[f.path[0]]=f.message)}),l(p);return}n(!0);try{const p=typeof window<"u"&&localStorage.getItem("levelup_referral_code")||void 0,{data:f,error:g}=await q.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:p}});if(g){console.error("Trial signup error:",g),ae.error(g.message||"Something went wrong. Please try again.");return}if(f!=null&&f.error){ae.error(f.error);return}ae.success("🎉 Welcome aboard! Check your email to claim your account."),typeof window<"u"&&window.oaiq&&window.oaiq("measure","trial_started",{type:"plan_enrollment"}),typeof window<"u"&&window.fbq&&window.fbq("track","Lead",{content_name:"Trial Signup",value:0,currency:"USD"}),s("/trial/success")}catch(p){console.error("Trial signup error:",p),ae.error("Something went wrong. Please try again.")}finally{n(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(Go,{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:Cfe,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(un,{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(xr,{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(xr,{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:Qss.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(ca,{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(fe,{className:"bg-white shadow-2xl border-0",children:e.jsxs(Ee,{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(sx,{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(ts,{className:"mr-2 h-5 w-5 animate-spin"}),"Creating Your Account..."]}):e.jsxs(e.Fragment,{children:["Start My Free Trial",e.jsx(Oa,{className:"ml-2 h-5 w-5"})]})}),e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["By signing up, you agree to our"," ",e.jsx("a",{href:"/terms-of-service",className:"text-[#4a6b6d] hover:underline",children:"Terms"})," ","and"," ",e.jsx("a",{href:"/privacy-policy",className:"text-[#4a6b6d] hover:underline",children:"Privacy Policy"})]})]})]})})})]})})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),e.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[e.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),e.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),e.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."})]})})}),e.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:Jss.map((c,d)=>e.jsxs(fe,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Mt,{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(It,{className:"text-xl font-sans",children:c.title})]}),e.jsx(Ee,{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(un,{className:"w-4 h-4"}),"Included with Your Trial"]}),e.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",e.jsx("span",{className:"italic",children:"Agent OS"})]}),e.jsx("p",{className:"text-lg text-white/80",children:"Your relationship-first operating system. Never forget a follow-up, track every touchpoint, and turn your sphere into a referral machine."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:ens.map((c,d)=>e.jsxs(fe,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Mt,{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(It,{className:"text-lg font-semibold text-white",children:c.title})]}),e.jsx(Ee,{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:tns.map((c,d)=>e.jsx(fe,{className:"border hover:shadow-lg transition-shadow",children:e.jsxs(Ee,{className:"p-6",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(u=>e.jsx(ca,{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(dh,{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(hh,{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(Nn,{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(fe,{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(Ee,{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(Oa,{className:"ml-2 h-5 w-5"})]})]})]})})}),e.jsx("footer",{className:"bg-[#1e3a4c] py-12",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row justify-between items-center gap-6",children:[e.jsx("img",{src:lfe,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."})]})})})]})]})},nns=()=>{const s=Mn();return e.jsxs(e.Fragment,{children:[e.jsx(Go,{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:Cfe,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(fe,{className:"max-w-lg w-full bg-white shadow-2xl border-0",children:e.jsxs(Ee,{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(xr,{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(ch,{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(Vs,{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(Oa,{className:"ml-2 h-4 w-4"})]})]})})})})]}),e.jsx("footer",{className:"bg-[#1e3a4c] py-8",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row justify-between items-center gap-4",children:[e.jsx("img",{src:lfe,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},rns=Yw({viewerName:go().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:go().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:go().max(20,"Phone must be less than 20 characters").optional(),message:go().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function ans({shareToken:s,agentName:t,hasContact:n}){const[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(null),d=Dye({resolver:Rye(rns),defaultValues:{viewerName:"",viewerEmail:"",viewerPhone:"",message:""}}),u=async h=>{a(!0),c(null);try{const{data:p,error:f}=await q.functions.invoke("video-reply-notify",{body:{shareToken:s,viewerName:h.viewerName,viewerEmail:h.viewerEmail,viewerPhone:h.viewerPhone||void 0,message:h.message}});if(f)throw new Error(f.message);if(!(p!=null&&p.success))throw new Error((p==null?void 0:p.error)||"Failed to send reply");l(!0)}catch(p){console.error("Failed to submit reply:",p),c(p.message||"Something went wrong. Please try again.")}finally{a(!1)}};return i?e.jsx(fe,{className:"border-2 border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10",children:e.jsxs(Ee,{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(xr,{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(fe,{children:[e.jsxs(Mt,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ql,{className:"h-5 w-5 text-primary"}),e.jsx(It,{className:"text-lg",children:"Reply to this video"})]}),e.jsx(Vn,{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(Ee,{children:e.jsx(Oye,{...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(Nu,{control:d.control,name:"viewerName",render:({field:h})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Your Name *"}),e.jsx(au,{children:e.jsx(ye,{placeholder:"John Smith",...h})}),e.jsx(Yx,{})]})}),e.jsx(Nu,{control:d.control,name:"viewerEmail",render:({field:h})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Email *"}),e.jsx(au,{children:e.jsx(ye,{type:"email",placeholder:"john@example.com",...h})}),e.jsx(Yx,{})]})})]}),!n&&e.jsx(Nu,{control:d.control,name:"viewerPhone",render:({field:h})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Phone (optional)"}),e.jsx(au,{children:e.jsx(ye,{type:"tel",placeholder:"(555) 123-4567",...h})}),e.jsx(Yx,{})]})}),e.jsx(Nu,{control:d.control,name:"message",render:({field:h})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Message *"}),e.jsx(au,{children:e.jsx(Es,{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(Yx,{})]})}),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(ts,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const ins=()=>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(ca,{className:"absolute top-[5%] left-[8%] w-6 h-6 text-blue-600/30 fill-blue-600/20"}),e.jsx(ca,{className:"absolute top-[15%] left-[20%] w-4 h-4 text-blue-600/25 fill-blue-600/15"}),e.jsx(ca,{className:"absolute top-[8%] left-[28%] w-5 h-5 text-blue-600/30 fill-blue-600/20"}),e.jsx(ca,{className:"absolute top-[25%] left-[12%] w-4 h-4 text-blue-600/20 fill-blue-600/10"}),e.jsx(ca,{className:"absolute top-[20%] right-[15%] w-5 h-5 text-red-500/25 fill-red-500/15 animate-pulse"}),e.jsx(K2,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),ons=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-red-500/5 via-transparent to-blue-500/5"}),e.jsxs("div",{className:"absolute top-[10%] left-[15%] w-32 h-32",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-red-400/20 animate-ping",style:{animationDuration:"3s"}}),e.jsx(un,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 text-red-400/40"})]}),e.jsxs("div",{className:"absolute top-[5%] right-[20%] w-24 h-24",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-blue-400/20 animate-ping",style:{animationDuration:"4s",animationDelay:"1s"}}),e.jsx(ca,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-6 h-6 text-blue-400/40 fill-blue-400/20"})]}),e.jsxs("div",{className:"absolute top-[20%] left-[50%] w-20 h-20",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border border-white/10 animate-ping",style:{animationDuration:"3.5s",animationDelay:"0.5s"}}),e.jsx(un,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-5 h-5 text-amber-400/40"})]}),e.jsx(ca,{className:"absolute bottom-[25%] left-[10%] w-6 h-6 text-blue-500/25 fill-blue-500/15 animate-pulse"}),e.jsx(ca,{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(K2,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),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-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(ob,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(ob,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(ob,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(ob,{className:"w-16 h-16 text-pink-300 -rotate-6"})}),e.jsx(gi,{className:"absolute top-[15%] left-[30%] w-5 h-5 text-rose-300/40 fill-rose-300/20 animate-pulse"}),e.jsx(gi,{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(gi,{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"})]}),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-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(bc,{className:"absolute top-[8%] left-[12%] w-12 h-12 text-blue-600/15"}),e.jsx(ca,{className:"absolute top-[15%] left-[22%] w-5 h-5 text-amber-500/25 fill-amber-500/15"}),e.jsx(bc,{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(ca,{className:"absolute bottom-[25%] left-[15%] w-6 h-6 text-blue-500/20 fill-blue-500/10 animate-pulse"}),e.jsx(ca,{className:"absolute top-[20%] right-[22%] w-5 h-5 text-indigo-400/20 fill-indigo-400/10 animate-pulse",style:{animationDelay:"0.5s"}})]}),dns=()=>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(ob,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(ob,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx(tL,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),uns=()=>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(TA,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(TA,{className:"absolute top-[10%] right-[12%] w-12 h-12 text-purple-400/20 animate-pulse"}),e.jsxs("div",{className:"absolute bottom-[18%] left-[8%]",children:[e.jsx("div",{className:"w-14 h-12 rounded-full bg-orange-500/20"}),e.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 w-2 h-4 bg-green-600/25 rounded-t-full"})]}),e.jsxs("div",{className:"absolute bottom-[22%] right-[12%]",children:[e.jsx("div",{className:"w-12 h-10 rounded-full bg-orange-400/15"}),e.jsx("div",{className:"absolute -top-1.5 left-1/2 -translate-x-1/2 w-1.5 h-3 bg-green-600/20 rounded-t-full"})]}),e.jsx("div",{className:"absolute top-[15%] left-[40%] opacity-20",children:e.jsx("svg",{viewBox:"0 0 24 12",className:"w-10 h-5 text-slate-800 fill-current",children:e.jsx("path",{d:"M12 6c-2-4-6-6-12-6 4 2 6 4 6 6s-2 4-6 6c6 0 10-2 12-6zm0 0c2-4 6-6 12-6-4 2-6 4-6 6s2 4 6 6c-6 0-10-2-12-6z"})})}),e.jsx(un,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-purple-400/35 animate-pulse"}),e.jsx(un,{className:"absolute bottom-[28%] right-[25%] w-5 h-5 text-orange-400/30 animate-pulse",style:{animationDelay:"0.5s"}})]}),hns=()=>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(c4,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(c4,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(c4,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx(Ev,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx(Ev,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(Ev,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(Ev,{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(ca,{className:"absolute top-[3%] left-[50%] -translate-x-1/2 w-10 h-10 text-amber-400/35 fill-amber-400/25"})]}),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-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(gi,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-red-400/22 fill-red-400/12"}),e.jsx(gi,{className:"absolute top-[20%] right-[25%] w-5 h-5 text-orange-400/22 fill-orange-400/12"})]}),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-yellow-900/8 via-amber-900/4 to-purple-900/8"}),e.jsx(ca,{className:"absolute top-[5%] left-[15%] w-12 h-12 text-yellow-400/35 fill-yellow-400/25 animate-pulse"}),e.jsx(ca,{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(ca,{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(ca,{className:"absolute top-[12%] right-[35%] w-8 h-8 text-amber-300/28 fill-amber-300/18 animate-pulse",style:{animationDelay:"0.9s"}}),e.jsx("div",{className:"absolute top-[20%] left-[25%] w-4 h-4 rounded-full bg-pink-400/30"}),e.jsx("div",{className:"absolute top-[18%] right-[30%] w-3 h-3 rounded-full bg-sky-400/30"}),e.jsx("div",{className:"absolute top-[25%] left-[60%] w-2.5 h-2.5 rounded-full bg-emerald-400/30"}),e.jsx("div",{className:"absolute top-[22%] right-[42%] w-3 h-3 rounded-full bg-purple-400/30"}),e.jsx(un,{className:"absolute top-[3%] left-[50%] w-10 h-10 text-yellow-400/40"}),e.jsx(ch,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(ch,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),fns=()=>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(ca,{className:"absolute top-[8%] left-[50%] -translate-x-1/2 w-14 h-14 text-yellow-400/28 fill-yellow-400/18"}),e.jsx(un,{className:"absolute top-[5%] left-[20%] w-7 h-7 text-blue-400/35"}),e.jsx(un,{className:"absolute top-[10%] right-[18%] w-6 h-6 text-sky-400/30"})]}),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-green-900/12 via-emerald-900/6 to-teal-900/10"}),e.jsx(R2,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(R2,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(R2,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(R2,{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"})]})]})]}),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-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(ca,{className:"absolute top-[5%] left-[42%] w-10 h-10 text-amber-400/30 fill-amber-400/20"}),e.jsx(ca,{className:"absolute top-[15%] right-[25%] w-7 h-7 text-yellow-400/25 fill-yellow-400/15"}),e.jsx(bc,{className:"absolute bottom-[20%] right-[12%] w-12 h-12 text-blue-500/18"}),e.jsx(bc,{className:"absolute top-[18%] left-[28%] w-8 h-8 text-indigo-400/15"}),e.jsx(K2,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),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-amber-900/6 via-rose-900/6 to-purple-900/6"}),e.jsx(cu,{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(ch,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(Oi,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),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-rose-900/12 via-pink-900/8 to-red-900/12"}),e.jsx(gi,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-rose-400/28 fill-rose-400/18"}),e.jsx(gi,{className:"absolute top-[8%] right-[12%] w-14 h-14 text-pink-400/25 fill-pink-400/15"}),e.jsx(gi,{className:"absolute bottom-[15%] left-[12%] w-12 h-12 text-red-400/22 fill-red-400/12"}),e.jsx(gi,{className:"absolute bottom-[18%] right-[10%] w-13 h-13 text-rose-300/25 fill-rose-300/15"}),e.jsx(gi,{className:"absolute top-[15%] left-[30%] w-6 h-6 text-pink-300/35 fill-pink-300/20 animate-pulse"}),e.jsx(gi,{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(gi,{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(gi,{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"})]}),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-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(yb,{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(yb,{className:"absolute top-[15%] left-[18%] w-10 h-10 text-yellow-400/30"}),e.jsx(un,{className:"absolute top-[10%] left-[42%] w-7 h-7 text-amber-400/35"}),e.jsx(yb,{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"})]}),_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-teal-900/10 via-cyan-900/6 to-emerald-900/10"}),e.jsx(Or,{className:"absolute top-[8%] left-[10%] w-14 h-14 text-teal-500/22"}),e.jsx(Or,{className:"absolute bottom-[15%] right-[8%] w-16 h-16 text-emerald-500/18"}),e.jsx(Vg,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(Vg,{className:"absolute bottom-[22%] left-[22%] w-8 h-8 text-yellow-400/22"}),e.jsx(gi,{className:"absolute top-[18%] left-[40%] w-6 h-6 text-rose-400/22 fill-rose-400/12"}),e.jsx(gi,{className:"absolute top-[22%] right-[35%] w-5 h-5 text-teal-400/20 fill-teal-400/10"}),e.jsx(un,{className:"absolute top-[5%] left-[55%] w-8 h-8 text-teal-400/30"}),e.jsx(ch,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),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-emerald-900/10 via-teal-900/6 to-cyan-900/10"}),e.jsx(ch,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(ch,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(Vg,{className:"absolute bottom-[18%] left-[18%] w-12 h-12 text-amber-400/25"}),e.jsx(Or,{className:"absolute bottom-[15%] right-[12%] w-14 h-14 text-teal-500/18"}),e.jsx(un,{className:"absolute top-[15%] left-[42%] w-10 h-10 text-emerald-400/35"}),e.jsx(un,{className:"absolute top-[20%] right-[32%] w-7 h-7 text-cyan-400/30"}),e.jsx("div",{className:"absolute top-[25%] left-[55%] w-3 h-3 bg-amber-400/30 rounded-full"}),e.jsx("div",{className:"absolute top-[22%] right-[42%] w-2.5 h-2.5 bg-teal-400/30 rounded-full"}),e.jsx("div",{className:"absolute top-[28%] left-[35%] w-2 h-2 bg-emerald-400/30 rounded-full"})]}),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-amber-900/10 via-yellow-900/6 to-orange-900/10"}),e.jsx(Vg,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(Vg,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(Vg,{className:"absolute top-[12%] right-[15%] w-9 h-9 text-amber-300/25"}),e.jsx(Or,{className:"absolute top-[8%] left-[42%] w-12 h-12 text-teal-500/18"}),e.jsx(ch,{className:"absolute bottom-[22%] right-[18%] w-12 h-12 text-orange-400/18 rotate-12"}),e.jsx(un,{className:"absolute top-[5%] right-[35%] w-8 h-8 text-yellow-400/35"}),e.jsx(ca,{className:"absolute top-[18%] left-[28%] w-6 h-6 text-amber-400/25 fill-amber-400/15"})]}),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-teal-900/10 via-emerald-900/6 to-green-900/10"}),e.jsx(Or,{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(Vg,{className:"absolute top-[10%] right-[12%] w-10 h-10 text-amber-400/28"}),e.jsx(gi,{className:"absolute top-[8%] left-[18%] w-8 h-8 text-rose-400/25 fill-rose-400/15"}),e.jsx(un,{className:"absolute top-[12%] left-[45%] w-8 h-8 text-teal-400/30"}),e.jsx(xw,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),UUe=()=>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"})]}),kns=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(gi,{className:"absolute top-6 left-[12%] w-4 h-4 text-rose-300/50 fill-rose-300/30 animate-pulse"}),e.jsx(gi,{className:"absolute top-10 right-[18%] w-3 h-3 text-pink-300/50 fill-pink-300/30 animate-pulse delay-150"}),e.jsx(gi,{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(gi,{className:"absolute top-14 right-[35%] w-3.5 h-3.5 text-pink-300/40 fill-pink-300/20 animate-pulse delay-200"})]}),Sns=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(xw,{className:"absolute top-5 left-[10%] w-4 h-4 text-blue-400/50 animate-pulse"}),e.jsx(un,{className:"absolute top-10 right-[15%] w-3 h-3 text-amber-400/50 animate-pulse delay-100"}),e.jsx(Or,{className:"absolute top-8 left-[38%] w-3 h-3 text-teal-300/40 animate-pulse delay-200"})]}),Cns=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(ny,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx(dL,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(ny,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),mF=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(un,{className:"absolute top-5 left-[10%] w-4 h-4 text-emerald-400/50 animate-pulse"}),e.jsx(ch,{className:"absolute top-10 right-[12%] w-5 h-5 text-amber-400/50 animate-pulse delay-150"}),e.jsx(un,{className:"absolute top-8 left-[45%] w-3 h-3 text-sky-400/40 animate-pulse delay-300"})]}),qUe=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Or,{className:"absolute top-6 left-[12%] w-4 h-4 text-teal-400/40 animate-pulse"}),e.jsx(un,{className:"absolute top-10 right-[15%] w-3 h-3 text-emerald-400/50 animate-pulse delay-100"}),e.jsx(Or,{className:"absolute top-4 right-[40%] w-3 h-3 text-cyan-400/30 animate-pulse delay-200"})]}),vCe=[{id:"default",name:"Classic",description:"Clean, professional look for any occasion",icon:e.jsx(un,{className:"h-5 w-5"}),category:"general",headerText:()=>"Video Message",subText:"A personal video just for you",gradientClasses:"from-background to-muted/30",accentColor:"primary"},{id:"thank_you",name:"Thank You",description:"Express your gratitude",icon:e.jsx(gi,{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(kns,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(W7,{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(mF,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(ny,{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(Cns,{})},{id:"market_update",name:"Market Update",description:"Share real estate market insights",icon:e.jsx(yo,{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(Nn,{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(mF,{})},{id:"congratulations",name:"Congratulations",description:"Celebrate their achievements",icon:e.jsx(bc,{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(UUe,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(ka,{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(qUe,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx(dL,{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(mF,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(cu,{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(yns,{})},{id:"valentines_day",name:"Valentine's Day",description:"Show appreciation on this special day",icon:e.jsx(gi,{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(vns,{})},{id:"groundhog_day",name:"Groundhog Day",description:"A fun seasonal greeting",icon:e.jsx(yb,{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(bns,{})},{id:"new_years",name:"New Year's Day",description:"Ring in the new year",icon:e.jsx(ca,{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(pns,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx(tL,{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(dns,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(ob,{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(lns,{})},{id:"fathers_day",name:"Father's Day",description:"Celebrate the amazing dads",icon:e.jsx(bc,{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(cns,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(K2,{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(ins,{})},{id:"independence_day",name:"4th of July",description:"Celebrate Independence Day",icon:e.jsx(Dc,{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(ons,{})},{id:"labor_day",name:"Labor Day",description:"Celebrate the workers",icon:e.jsx(bc,{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(gns,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(TA,{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(uns,{})},{id:"thanksgiving",name:"Thanksgiving",description:"Express gratitude this season",icon:e.jsx(gi,{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(mns,{})},{id:"christmas",name:"Christmas",description:"Spread holiday cheer",icon:e.jsx(c4,{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(hns,{})},{id:"hanukkah",name:"Hanukkah",description:"Celebrate the Festival of Lights",icon:e.jsx(un,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Hanukkah, ${s}!`:"Happy Hanukkah!",subText:"Wishing you eight nights of light and joy",gradientClasses:"from-blue-50/70 via-indigo-50/50 to-sky-50/40 dark:from-blue-950/30 dark:via-indigo-950/20 dark:to-sky-950/20",accentColor:"blue",decorativeElement:e.jsx(fns,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(R2,{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(xns,{})},{id:"home_anniversary",name:"Home Anniversary",description:"Celebrate their home ownership milestone",icon:e.jsx(Or,{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(_ns,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(ch,{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(wns,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(yr,{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(qUe,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(Zl,{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(mF,{})},{id:"price_reduction",name:"Price Reduction",description:"Notify about a price change",icon:e.jsx(vb,{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(xw,{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(Sns,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(Vg,{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(jns,{})},{id:"move_in_day",name:"Move-in Day",description:"Welcome them to their new home",icon:e.jsx(Or,{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(Nns,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx(Vm,{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(mF,{})},{id:"pre_approval",name:"Pre-Approval Congrats",description:"Congratulate on pre-approval",icon:e.jsx(bc,{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(UUe,{})}],Tns=[{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 Ens(s){return vCe.filter(t=>t.category===s)}function IL(s){return vCe.find(t=>t.id===s)||vCe[0]}function VUe(){const{shareToken:s,recipientToken:t}=bi(),[n,r]=N.useState(null),[a,i]=N.useState(null),[l,o]=N.useState(null),[c,d]=N.useState(!0),[u,h]=N.useState(null),[p,f]=N.useState(!0),g=N.useRef(null),_=N.useRef(0),v=N.useRef(0),j=(()=>{const W=new URLSearchParams(window.location.search);return t||W.get("rt")||null})(),b=N.useCallback((W,Y=!1)=>{if(!j||W<=0)return;const K=Math.max(1,Math.round(W));if(K<=v.current)return;const ne=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(j)}&e=watch&ws=${K}`;Y&&navigator.sendBeacon?navigator.sendBeacon(ne):fetch(ne,{method:"GET",keepalive:Y}).catch(()=>{}),v.current=Math.max(v.current,K)},[j]);N.useEffect(()=>{var he;if(!p||!(n!=null&&n.playback_url)||!j)return;let W=!1;const Y=()=>{_.current>0&&b(_.current,!0)},K=()=>{document.visibilityState==="hidden"&&Y()},J=()=>{Y()},ne=()=>{var pe;if(W||!g.current||!((pe=window.playerjs)!=null&&pe.Player))return;const ce=new window.playerjs.Player(g.current);ce.on("timeupdate",le=>{const ve=Math.floor(Number((le==null?void 0:le.seconds)??0));!Number.isFinite(ve)||ve<=0||(_.current=Math.max(_.current,ve))}),ce.on("pause",()=>{_.current>0&&b(_.current)}),ce.on("ended",()=>{_.current>0&&b(_.current,!0)})},ie=document.querySelector('script[data-bunny-playerjs="true"]');if((he=window.playerjs)!=null&&he.Player)ne();else if(ie)ie.addEventListener("load",ne,{once:!0});else{const ce=document.createElement("script");ce.src="https://assets.mediadelivery.net/playerjs/playerjs-latest.min.js",ce.async=!0,ce.defer=!0,ce.dataset.bunnyPlayerjs="true",ce.onload=ne,document.body.appendChild(ce)}return document.addEventListener("visibilitychange",K),window.addEventListener("beforeunload",J),()=>{W=!0,document.removeEventListener("visibilitychange",K),window.removeEventListener("beforeunload",J),Y()}},[p,n==null?void 0:n.playback_url,j,b]),N.useEffect(()=>{_.current=0,v.current=0},[j,s]),N.useEffect(()=>{const W=()=>{['[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(ne=>{document.querySelectorAll(ne).forEach(ie=>{ie.style.display="none"})})};W();const Y=[setTimeout(W,500),setTimeout(W,1500),setTimeout(W,3e3)],K=new MutationObserver(W);return K.observe(document.body,{childList:!0,subtree:!0}),()=>{Y.forEach(clearTimeout),K.disconnect()}},[]),N.useEffect(()=>{(async()=>{if(!s){h("Invalid share link"),d(!1);return}const{data:Y,error:K}=await q.from("agent_videos").select("id, title, playback_url, thumbnail_url, preview_url, duration_seconds, share_token, owner_user_id, contact_id, page_template, recipient_name").eq("share_token",s).eq("is_deleted",!1).single();if(K||!Y){h("Video not found or has been removed"),d(!1);return}r(Y);try{await q.rpc("log_video_view",{p_video_id:Y.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch(J){console.warn("Failed to log video view:",J)}if(Y.owner_user_id){const{data:J}=await q.from("profiles").select("id, name, email, phone").eq("id",Y.owner_user_id).single();if(J){i(J);try{const{data:ne}=await q.storage.from("avatars").list(`${Y.owner_user_id}`);if(ne&&ne.length>0){const{data:ie}=q.storage.from("avatars").getPublicUrl(`${Y.owner_user_id}/${ne[0].name}`);o(ie.publicUrl)}}catch{}}}d(!1)})()},[s]);const S=W=>{if(!W)return"0:00";const Y=Math.floor(W/60),K=W%60;return`${Y}:${K.toString().padStart(2,"0")}`},A=W=>W.includes("iframe.mediadelivery.net/play/")?W.replace("/play/","/embed/")+"?autoplay=true&responsive=true":W,T=W=>{if(!W)return"?";const Y=W.split(" ");return Y.length>=2?`${Y[0][0]}${Y[1][0]}`.toUpperCase():W.substring(0,2).toUpperCase()},L=IL((n==null?void 0:n.page_template)||"default"),D=(n==null?void 0:n.recipient_name)||null,M=L.headerText(D),z=`https://dashboard.relevelup.com/share/video/${s}`;if(c)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsx(ts,{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(fe,{className:"max-w-md w-full",children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(br,{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 V=L.id!=="default";return e.jsxs(e.Fragment,{children:[e.jsxs(Go,{children:[e.jsx("title",{children:M}),e.jsx("meta",{name:"description",content:L.subText}),e.jsx("meta",{property:"og:title",content:M}),e.jsx("meta",{property:"og:description",content:L.subText}),e.jsx("meta",{property:"og:type",content:"video.other"}),e.jsx("meta",{property:"og:url",content:z}),n.preview_url&&e.jsx("meta",{property:"og:image",content:n.preview_url}),!n.preview_url&&n.thumbnail_url&&e.jsx("meta",{property:"og:image",content:n.thumbnail_url}),n.playback_url&&e.jsxs(e.Fragment,{children:[e.jsx("meta",{property:"og:video",content:n.playback_url}),e.jsx("meta",{property:"og:video:type",content:"text/html"}),e.jsx("meta",{property:"og:video:width",content:"1280"}),e.jsx("meta",{property:"og:video:height",content:"720"})]}),e.jsx("meta",{name:"twitter:card",content:"player"}),e.jsx("meta",{name:"twitter:title",content:M}),e.jsx("meta",{name:"twitter:description",content:L.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",L.gradientClasses),children:[V&&L.decorativeElement,e.jsxs("div",{className:"max-w-2xl w-full space-y-6 relative z-10",children:[V&&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",L.accentColor==="primary"&&"bg-primary/10 text-primary",L.accentColor==="amber"&&"bg-amber-100 text-amber-600 dark:bg-amber-900/50 dark:text-amber-400",L.accentColor==="teal"&&"bg-teal-100 text-teal-600 dark:bg-teal-900/50 dark:text-teal-400",L.accentColor==="rose"&&"bg-rose-100 text-rose-600 dark:bg-rose-900/50 dark:text-rose-400",L.accentColor==="emerald"&&"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/50 dark:text-emerald-400",L.accentColor==="yellow"&&"bg-yellow-100 text-yellow-600 dark:bg-yellow-900/50 dark:text-yellow-400",L.accentColor==="pink"&&"bg-pink-100 text-pink-600 dark:bg-pink-900/50 dark:text-pink-400",L.accentColor==="blue"&&"bg-blue-100 text-blue-600 dark:bg-blue-900/50 dark:text-blue-400",L.accentColor==="red"&&"bg-red-100 text-red-600 dark:bg-red-900/50 dark:text-red-400",L.accentColor==="orange"&&"bg-orange-100 text-orange-600 dark:bg-orange-900/50 dark:text-orange-400",L.accentColor==="green"&&"bg-green-100 text-green-600 dark:bg-green-900/50 dark:text-green-400",L.accentColor==="violet"&&"bg-violet-100 text-violet-600 dark:bg-violet-900/50 dark:text-violet-400",L.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:L.icon})})}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold mb-2",children:M}),e.jsx("p",{className:"text-muted-foreground",children:L.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(ni,{src:l||void 0,alt:a.name||"Agent"}),e.jsx(aa,{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:V?"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(Ar,{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(Vs,{className:"h-4 w-4"})})})]})]}),e.jsx(fe,{className:"overflow-hidden shadow-lg",children:p&&n.playback_url?e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:e.jsx("iframe",{ref:g,src:A(n.playback_url),title:n.title||"Video message",className:"absolute top-0 left-0 w-full h-full",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):e.jsxs("div",{className:"relative aspect-video bg-muted cursor-pointer group",onClick:()=>f(!0),children:[n.preview_url||n.thumbnail_url?e.jsx("img",{src:n.preview_url||n.thumbnail_url||"",alt:n.title?`${n.title} video preview`:"Video message preview",className:"w-full h-full object-cover",onError:W=>{var K;W.currentTarget.style.display="none";const Y=(K=W.currentTarget.parentElement)==null?void 0:K.querySelector(".video-fallback");Y&&(Y.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(br,{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(Al,{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:S(n.duration_seconds)})]})}),!V&&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:p?"Enjoy the video!":"Click to play the video"})]}),!p&&e.jsx("div",{className:"flex justify-center",children:e.jsxs(B,{size:"lg",onClick:()=>f(!0),className:"gap-2",children:[e.jsx(Al,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(ans,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!n.contact_id})]})]})]})}function Ans(){return N.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(Pat,{})}function Mns(){const{token:s}=bi();return N.useEffect(()=>{if(!s)return;const t=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/video-og-image?token=${s}`;window.location.replace(t)},[s]),e.jsx("main",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsx(ts,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Loading video preview…"})]})})}const Ins={office_exclusive:"Office Exclusive",coming_soon:"Coming Soon",pre_market:"Pre-Market",active:"Active"},Pns=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s||0);function Lns(){var ve;const[s]=gl(),t=s.get("r"),n=s.get("m"),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(!0),[d,u]=N.useState(0),[h,p]=N.useState(!1),[f,g]=N.useState(""),[_,v]=N.useState(""),[j,b]=N.useState(""),[S,A]=N.useState(""),[T,L]=N.useState("tour"),[D,M]=N.useState(!1),[F,z]=N.useState(!1),V=async()=>{if(!f.trim()||!_.trim()){ae.error("Please enter your name and email");return}M(!0);try{const Te=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-lead",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({r:t,m:n,name:f.trim(),email:_.trim(),phone:j.trim()||null,message:S.trim()||null,intent:T})}),Me=await Te.json();if(!Te.ok||!(Me!=null&&Me.success))throw new Error((Me==null?void 0:Me.error)||"Could not send");z(!0),ae.success("Sent! The agent will be in touch shortly.")}catch(ge){ae.error((ge==null?void 0:ge.message)||"Could not send")}finally{M(!1)}};if(N.useEffect(()=>{if(!t||!n){l("Invalid link"),c(!1);return}const ge=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-view?r=${encodeURIComponent(t)}&m=${encodeURIComponent(n)}`;fetch(ge).then(Te=>Te.json()).then(Te=>{Te.error?l("This private listing link is no longer valid."):a({listing:Te.listing,agent:Te.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(Go,{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(Kc,{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:W,agent:Y}=r,K=(ve=W.photos)!=null&&ve.length?W.photos:[],J=K[0],ne=Ins[W.status]||W.status,ie=(Y==null?void 0:Y.sender_name)||(Y==null?void 0:Y.name)||"Your Agent",he=(Y==null?void 0:Y.sender_email)||null,ce=encodeURIComponent(`Interested in ${W.address}`),pe=encodeURIComponent(`Hi ${ie}, I'd love to learn more about ${W.address}, ${W.city}. Thanks!`),le=Y!=null&&Y.booking_slug?`https://dashboard.relevelup.com/book/${Y.booking_slug}`:null;return e.jsxs(e.Fragment,{children:[e.jsxs(Go,{children:[e.jsxs("title",{children:["Private Listing · ",W.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(Kc,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"font-medium tracking-wide uppercase",children:["Private listing · Shared by ",ie]})]}),e.jsxs("div",{className:"relative",children:[J?e.jsx("button",{type:"button",className:"block w-full",onClick:()=>{u(0),p(!0)},children:e.jsx("img",{src:J,alt:W.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(ze,{className:"bg-indigo-600 text-white border-0 text-xs px-2.5 py-1 shadow",children:ne})}),K.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:[K.length," photos"]})]}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 -mt-10 relative z-10",children:[e.jsx(fe,{className:"shadow-xl border-slate-200",children:e.jsxs(Ee,{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:W.address}),e.jsxs("p",{className:"text-slate-600 mt-1 flex items-center gap-1.5",children:[e.jsx(ka,{className:"h-4 w-4"}),W.city,", ",W.state," ",W.zip]})]}),e.jsx("div",{className:"text-right",children:e.jsx("p",{className:"text-3xl sm:text-4xl font-bold text-indigo-600",children:Pns(W.price)})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mt-6",children:[W.bedrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(sy,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:W.bedrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Beds"})]}):null,W.bathrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(Cp,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:W.bathrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Baths"})]}):null,W.sqft?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(ly,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:W.sqft.toLocaleString()}),e.jsx("p",{className:"text-xs text-slate-500",children:"Sq Ft"})]}):null]}),W.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:W.description})]}),K.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:K.slice(0,9).map((ge,Te)=>e.jsx("button",{type:"button",onClick:()=>{u(Te),p(!0)},className:"aspect-[4/3] overflow-hidden rounded-lg bg-slate-100",children:e.jsx("img",{src:ge,alt:"",className:"w-full h-full object-cover hover:scale-105 transition"})},Te))})]})]})}),e.jsxs(fe,{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:[ie," will get back to you personally."]})]}),e.jsx(Ee,{className:"p-6 sm:p-8",children:F?e.jsxs("div",{className:"flex flex-col items-center text-center py-6",children:[e.jsx(xr,{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:[ie," 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(ge=>e.jsx("button",{type:"button",onClick:()=>L(ge.id),className:`px-3 py-2 rounded-lg border text-sm font-medium transition ${T===ge.id?"bg-indigo-600 text-white border-indigo-600":"bg-white text-slate-700 border-slate-200 hover:border-indigo-300"}`,children:ge.label},ge.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:f,onChange:ge=>g(ge.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:_,onChange:ge=>v(ge.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:j,onChange:ge=>b(ge.target.value),placeholder:"(555) 555-5555",maxLength:40})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pl-msg",children:"Message (optional)"}),e.jsx(Es,{id:"pl-msg",value:S,onChange:ge=>A(ge.target.value),placeholder:`I'd love to see ${W.address}…`,rows:4,maxLength:2e3})]}),e.jsx(B,{onClick:V,disabled:D,className:"w-full bg-indigo-600 hover:bg-indigo-700 h-11 text-base",children:D?"Sending…":"Send to "+ie.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(fe,{className:"mt-6 mb-12 shadow-lg border-slate-200",children:e.jsxs(Ee,{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:[Y!=null&&Y.avatar_url?e.jsx("img",{src:Y.avatar_url,alt:ie,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:ie.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:ie}),(Y==null?void 0:Y.brokerage_name)&&e.jsx("p",{className:"text-slate-600 text-sm",children:Y.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:[he&&e.jsx(B,{asChild:!0,className:"bg-indigo-600 hover:bg-indigo-700",children:e.jsxs("a",{href:`mailto:${he}?subject=${ce}&body=${pe}`,children:[e.jsx(Vs,{className:"h-4 w-4 mr-1.5"}),"Email"]})}),(Y==null?void 0:Y.phone)&&e.jsx(B,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:`tel:${Y.phone}`,children:[e.jsx(Ar,{className:"h-4 w-4 mr-1.5"}),Y.phone]})}),le&&e.jsx(B,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:le,target:"_blank",rel:"noreferrer",children:[e.jsx(om,{className:"h-4 w-4 mr-1.5"}),"Book a tour"]})})]})]})})]}),h&&K.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:()=>p(!1),"aria-label":"Close",children:e.jsx(Bn,{className:"h-6 w-6"})}),e.jsx("button",{className:"absolute left-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>u(ge=>(ge-1+K.length)%K.length),"aria-label":"Previous",children:e.jsx(pl,{className:"h-8 w-8"})}),e.jsx("img",{src:K[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(ge=>(ge+1)%K.length),"aria-label":"Next",children:e.jsx(xa,{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," / ",K.length]})]})]})]})}function Dns(){var i;const{slug:s}=bi(),{data:t,isLoading:n,error:r}=xct(s);if(N.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),N.useEffect(()=>{t!=null&&t.id&&ml(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(Ws,{className:"h-28 w-28 rounded-full"}),e.jsx(Ws,{className:"h-6 w-48"}),e.jsx(Ws,{className:"h-4 w-36"})]}),e.jsx(Ws,{className:"h-12 w-full"}),e.jsx(Ws,{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(Go,{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(tMe,{card:t})]})}const Rns="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",Ons="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",Fns="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",zns="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",Bns="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",$ns="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",Hme={"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:$ns},"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:Rns},"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:Ons},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:Fns},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:zns},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:Bns}},Uns=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function Kmt(s){return s&&s in Hme?Hme[s]:Hme["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 Ymt({slugOverride:s}={}){var Js;const{slug:t}=bi(),n=s||t,[r]=gl(),a=r.get("t"),[i,l]=N.useState(!0),[o,c]=N.useState(null),[d,u]=N.useState(null),h=N.useRef(null),p=N.useRef(null),[f,g]=N.useState(null),[_,v]=N.useState(null),[j,b]=N.useState(!1),[S,A]=N.useState(!1),[T,L]=N.useState(0),[D,M]=N.useState(!1),[F,z]=N.useState(""),[V,W]=N.useState(""),[Y,K]=N.useState(""),[J,ne]=N.useState(""),[ie,he]=N.useState(""),[ce,pe]=N.useState(""),[le,ve]=N.useState(""),[ge,Te]=N.useState(""),[Me,Ce]=N.useState(""),[Ae,De]=N.useState(""),[Ie,Fe]=N.useState(""),[qe,be]=N.useState(""),[Ze,Ne]=N.useState(""),[it,je]=N.useState([]),[Ge,Be]=N.useState([]),[Ye,We]=N.useState(""),[rt,tt]=N.useState(""),[at,He]=N.useState(""),[dt,bt]=N.useState([]);N.useEffect(()=>{vt()},[n,a]);const vt=async()=>{if(!n)return;l(!0);const{data:Cs,error:As}=await q.from("contact_intake_pages").select("*").eq("slug",n).eq("is_active",!0).maybeSingle();if(As||!Cs){M(!0),l(!1);return}u(Cs),p.current=Cs;const{data:rn}=await q.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",Cs.user_id).single();if(rn){let tn;if(rn.brokerage_id){const{data:In}=await q.from("brokerages").select("name").eq("id",rn.brokerage_id).single();tn=(In==null?void 0:In.name)||void 0}let er=rn.avatar_url||null;if(!er){const{data:In}=q.storage.from("avatars").getPublicUrl(`${Cs.user_id}/avatar.jpg`);In!=null&&In.publicUrl&&(er=`${In.publicUrl}?t=${Date.now()}`)}const gn={...rn,avatar_url:er,brokerage_name:tn};c(gn),h.current=gn}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",Cs.id);const{data:tn,error:er}=await q.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:Cs.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:tn,resolveErr:er}),!er&&(tn!=null&&tn.contact_id)){v(tn.contact_id);const gn=tn.contact;gn&&(g(gn),z(gn.first_name||""),W(gn.last_name||""),K(gn.email||""),ne(gn.phone||""),he(gn.address||""),pe(gn.city||""),ve(gn.state||""),Te(gn.zip||""),Ce(gn.birthday||""),De(gn.home_anniversary||""))}}catch(tn){console.error("Failed to resolve token:",tn)}l(!1)},Bt=async()=>{var Cs,As;if(!F.trim()){ae.error("Please enter your first name");return}if(!n){ae.error("Invalid page. Please refresh.");return}A(!0);try{let rn=(Cs=p.current)==null?void 0:Cs.id,tn=(As=p.current)==null?void 0:As.user_id;if(!rn||!tn){const{data:In}=await q.from("contact_intake_pages").select("id, user_id").eq("slug",n).eq("is_active",!0).maybeSingle();if(!In){ae.error("This page is no longer active. Please contact the agent directly."),A(!1);return}rn=In.id,tn=In.user_id}const er={intake_page_id:rn,agent_user_id:tn,existing_contact_id:_,first_name:F.trim(),last_name:V.trim()||null,email:Y.trim()||null,phone:J.trim()||null,address:ie.trim()||null,city:ce.trim()||null,state:le.trim()||null,zip:ge.trim()||null,birthday:Me||null,home_anniversary:Ae||null,real_estate_interest:Ie||null,message:qe.trim()||null,life_events:{spouse_name:Ze.trim()||null,kids:it.filter(In=>In.name.trim()),pets:Ge.filter(In=>In.name.trim()),favorite_spots:Ye.trim()||null,dream_neighborhood:rt.trim()||null,wedding_anniversary:at||null},referrals:dt.filter(In=>In.name.trim()&&In.contact.trim())},{error:gn}=await q.from("contact_intake_submissions").insert(er);if(console.log("[ConnectPage] Insert result:",{error:gn}),gn)throw gn;a&&await q.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const In=[F.trim(),V.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:tn,contactName:In,contactEmail:Y.trim()||null,contactPhone:J.trim()||null,slug:n})})}catch(In){console.warn("Connect page notification failed (non-blocking):",In)}b(!0)}catch(rn){console.error(rn),ae.error("Something went wrong. Please try again.")}finally{A(!1)}};if(i)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:e.jsx(ts,{className:"h-8 w-8 animate-spin text-slate-400"})});if(D)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(j)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(Go,{children:e.jsxs("title",{children:["Thank You | ",o==null?void 0:o.name]})}),e.jsxs(Yn.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(Yn.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(xr,{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(gi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const Zt=!!a&&!!f,Fs=(d==null?void 0:d.show_little_things)??!0,Rs=[{title:Zt?"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:F,onChange:Cs=>z(Cs.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:V,onChange:Cs=>W(Cs.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:Y,onChange:Cs=>K(Cs.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:J,onChange:Cs=>ne(Cs.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:ie,onChange:Cs=>he(Cs.target.value),placeholder:"123 Main St",className:"connect-input"})]}),e.jsxs("div",{className:"grid grid-cols-5 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"City"}),e.jsx("input",{type:"text",value:ce,onChange:Cs=>pe(Cs.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:le,onChange:Cs=>ve(Cs.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:ge,onChange:Cs=>Te(Cs.target.value),placeholder:"78701",className:"connect-input"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Birthday"}),e.jsx("input",{type:"date",value:Me,onChange:Cs=>Ce(Cs.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:Ae,onChange:Cs=>De(Cs.target.value),className:"connect-input"})]})]})]})},...Fs?[{title:"The Little Things",subtitle:"Optional — helps me remember what matters to you.",fields:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Spouse / partner's name"}),e.jsx("input",{type:"text",value:Ze,onChange:Cs=>Ne(Cs.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:at,onChange:Cs=>He(Cs.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:()=>je(Cs=>[...Cs,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(Is,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[it.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),it.map((Cs,As)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Cs.name,onChange:rn=>je(tn=>tn.map((er,gn)=>gn===As?{...er,name:rn.target.value}:er)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Cs.age,onChange:rn=>je(tn=>tn.map((er,gn)=>gn===As?{...er,age:rn.target.value}:er)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),e.jsx("button",{type:"button",onClick:()=>je(rn=>rn.filter((tn,er)=>er!==As)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(Bn,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},As))]})]}),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:()=>Be(Cs=>[...Cs,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(Is,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[Ge.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Ge.map((Cs,As)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Cs.name,onChange:rn=>Be(tn=>tn.map((er,gn)=>gn===As?{...er,name:rn.target.value}:er)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Cs.kind,onChange:rn=>Be(tn=>tn.map((er,gn)=>gn===As?{...er,kind:rn.target.value}:er)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),e.jsx("button",{type:"button",onClick:()=>Be(rn=>rn.filter((tn,er)=>er!==As)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(Bn,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},As))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Favorite local spots"}),e.jsx("input",{type:"text",value:Ye,onChange:Cs=>We(Cs.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:rt,onChange:Cs=>tt(Cs.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:()=>bt(Cs=>[...Cs,{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(Is,{className:"h-3 w-3"})," Add"]})]}),e.jsx("div",{className:"space-y-2",children:dt.map((Cs,As)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Cs.name,onChange:rn=>bt(tn=>tn.map((er,gn)=>gn===As?{...er,name:rn.target.value}:er)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Cs.contact,onChange:rn=>bt(tn=>tn.map((er,gn)=>gn===As?{...er,contact:rn.target.value}:er)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("button",{type:"button",onClick:()=>bt(rn=>rn.filter((tn,er)=>er!==As)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:e.jsx(Bn,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},As))})]})]})}]:[],{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(Cs=>e.jsxs("button",{type:"button",onClick:()=>Fe(Ie===Cs.value?"":Cs.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Ie===Cs.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:Cs.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:Cs.desc})]},Cs.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:qe,onChange:Cs=>be(Cs.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],ms=Rs.length,Pt=Kmt(d==null?void 0:d.theme),Jt=qns(Pt,(d==null?void 0:d.accent_color)||null),ft=(d==null?void 0:d.cover_image_url)||Pt.defaultCover,Vt=(d==null?void 0:d.headline)||"Let's stay connected",Ms=(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)||""),Xt=["deep-luxe"].includes((d==null?void 0:d.theme)||"");return e.jsxs("div",{className:"min-h-screen connect-shell",style:Jt,children:[e.jsxs(Go,{children:[e.jsxs("title",{children:["Connect with ",(o==null?void 0:o.name)||"Agent"]}),e.jsx("meta",{name:"description",content:`${Vt} — ${(o==null?void 0:o.name)||"your agent"}`}),ft&&e.jsx("meta",{property:"og:image",content:ft}),e.jsx("meta",{property:"og:title",content:`Connect with ${(o==null?void 0:o.name)||"me"}`}),e.jsx("meta",{property:"og:description",content:Vt}),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(Yn.img,{src:ft,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(Yn.h1,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},style:{color:"#fff",fontFamily:Pt.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:Vt}),Ms&&e.jsx(Yn.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:Ms})]})]}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 pb-12 -mt-12 relative",children:[e.jsxs(Yn.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:Pt.accent,color:Pt.accentText,border:"4px solid var(--c-surface)"},children:e.jsx("span",{className:"text-3xl font-bold",children:((Js=o==null?void 0:o.name)==null?void 0:Js.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(Ar,{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(Vs,{className:"h-4 w-4"})})]})]}),e.jsx(Yn.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:ms}).map((Cs,As)=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-all duration-500",style:{background:As<=T?"var(--c-accent)":"color-mix(in srgb, var(--c-text) 12%, transparent)"}},As))}),e.jsxs(Yn.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:Xt?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[e.jsx(Eye,{mode:"wait",children:e.jsxs(Yn.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),e.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:Rs[T].title})]}),Rs[T].subtitle&&e.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:Rs[T].subtitle})]}),Rs[T].fields]},T)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[T>0?e.jsx("button",{type:"button",onClick:()=>L(Cs=>Cs-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&&!F.trim()){ae.error("Please enter your first name");return}L(Cs=>Cs+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:()=>Bt(),disabled:S,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:S?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),T>0&&TL(Cs=>Cs+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(gi,{className:"h-3 w-3"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const KD=()=>({trackEngagement:N.useCallback(async(t,n,r,a="view")=>{try{const{data:{user:i}}=await q.auth.getUser();if(!i)return;await q.from("content_engagement_logs").insert({user_id:i.id,resource_type:t,resource_id:n,resource_title:r,action_type:a})}catch(i){console.error("Error tracking engagement:",i)}},[])});function pF({banners:s,autoPlayInterval:t=5e3,className:n}){const[r,a]=N.useState(0),[i,l]=N.useState(!1),{trackEngagement:o}=KD(),c=N.useCallback(f=>{o("newsletter",f.id,f.title,"click_link")},[o]),d=N.useCallback(()=>{a(f=>(f+1)%s.length)},[s.length]),u=N.useCallback(()=>{a(f=>(f-1+s.length)%s.length)},[s.length]),h=N.useCallback(f=>{a(f)},[]);if(N.useEffect(()=>{if(s.length<=1||i)return;const f=setInterval(d,t);return()=>clearInterval(f)},[s.length,i,t,d]),!s||s.length===0)return null;const p=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:p.image_url,alt:p.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(pl,{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(xa,{className:"h-6 w-6"})})]}),s.length>1&&e.jsx("div",{className:"absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-2",children:s.map((f,g)=>e.jsx("button",{onClick:()=>h(g),className:Et("w-2 h-2 rounded-full transition-all duration-300",g===r?"bg-white w-6":"bg-white/50 hover:bg-white/70"),"aria-label":`Go to slide ${g+1}`},g))})]}),e.jsxs("div",{className:"bg-foreground rounded-b-xl px-5 py-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-sm md:text-base font-semibold text-background truncate",children:p.title}),p.description&&e.jsx("p",{className:"text-xs text-background/70 truncate",children:p.description})]}),p.link_url&&e.jsx("a",{href:p.link_url,target:"_blank",rel:"noopener noreferrer",className:"shrink-0",onClick:()=>c(p),children:e.jsx(B,{size:"sm",className:"bg-primary text-primary-foreground font-semibold transition-colors hover:bg-background hover:text-foreground",children:p.link_text||"Learn More"})})]})]})}function Vns(s){return"EST"}function xB(s){const n=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),r=Vns();return`${n} ${r}`}function PL(s){const t=new Date,n=new Date(s),r=kP(n,-15),a=kP(n,30);return t>a?"ended":Z1(t,{start:n,end:a})?"live":Z1(t,{start:r,end:n})?"starting_soon":"upcoming"}function x6e(s){const t=PL(s);return t==="starting_soon"||t==="live"}const HUe=x6e,Hns=({events:s,registrations:t,onNavigateToEvents:n})=>{const[r,a]=N.useState(new Date);N.useEffect(()=>{const f=setInterval(()=>{a(new Date)},3e4);return()=>clearInterval(f)},[]);const i=s.filter(f=>x6e(f.event_date));if(i.length===0)return null;const l=i[0],o=PL(l.event_date),c=t.find(f=>f.event_id===l.id),d=(c==null?void 0:c.zoom_join_url)||l.zoom_link,u=!!c,h=o==="live",p=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 ${p.container} border`,children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-r ${p.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 ${p.indicator} opacity-75`}),e.jsx("span",{className:`relative flex h-3 w-3 rounded-full ${p.indicator}`})]}),e.jsx("div",{className:`flex items-center gap-2 ${p.text} font-bold text-sm uppercase tracking-wider`,children:h?e.jsxs(e.Fragment,{children:[e.jsx(_f,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(gr,{className:"h-4 w-4"}),"Starting Soon"]})})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg text-foreground line-clamp-1",children:l.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h?`Started at ${xB(new Date(l.event_date))}`:`Starts at ${xB(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:`${p.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:`${p.outlineButton} gap-2`,children:[e.jsx(Nn,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};function Oh(){const{user:s}=ys(),{data:t,isLoading:n}=ct({queryKey:["gmail-integration"],queryFn:async()=>{const{data:h,error:p}=await q.from("gmail_integrations").select("*").maybeSingle();if(p)throw p;return h}}),{data:r,isLoading:a}=ct({queryKey:["user-verified-ses-sender",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const{data:h}=await q.from("user_verified_senders").select("email, status").eq("user_id",s.id).eq("status","verified").order("verified_at",{ascending:!1}).limit(1).maybeSingle();return h}}),i=!!(t!=null&&t.is_active),l=(t==null?void 0:t.gmail_email)||null,o=!!(r!=null&&r.email),c=(r==null?void 0:r.email)||null;return{isGmailConnected:i,gmailEmail:l,hasVerifiedSes:o,sesEmail:c,canSendEmail:i||o,sendMethod:i?"gmail":o?"mass_email":"none",isLoading:n||a}}function Gns(){const{user:s}=ys(),{isGmailConnected:t,hasVerifiedSes:n,isLoading:r}=Oh(),[a,i]=N.useState(!1),[l,o]=N.useState(!1);N.useEffect(()=>{s!=null&&s.id&&q.from("onboarding_checklist_dismissed").select("id").eq("user_id",s.id).maybeSingle().then(({data:j})=>{i(!!j),o(!0)})},[s==null?void 0:s.id]);const{data:c,isLoading:d}=ct({queryKey:["new-agent-onboarding",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:3e4,queryFn:async()=>{const[j,b,S,A,T]=await Promise.all([q.from("profiles").select("avatar_url, phone, bio, name").eq("id",s.id).maybeSingle(),q.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),q.from("event_registrations").select("id",{count:"exact",head:!0}).eq("user_id",s.id),q.from("community_posts").select("id",{count:"exact",head:!0}).eq("user_id",s.id),q.from("events").select("id, title, event_date, image_url").eq("is_published",!0).gte("event_date",new Date().toISOString()).or("title.ilike.%onboarding%,title.ilike.%new member%,title.ilike.%welcome%,description.ilike.%new member onboarding%").order("event_date",{ascending:!0}).limit(1).maybeSingle()]),L=j.data,D=!!(L!=null&&L.avatar_url&&(L!=null&&L.phone)&&(L!=null&&L.bio)),M=b.count||0,F=(S.count||0)>0,z=A.count||0;return{profile:L,profileComplete:D,contactsCount:M,contactsComplete:M>=5,eventsRegistered:F,communityComplete:z>0,nextOnboardingEvent:T.data||null}}}),u=t||n,h=[{id:"profile",complete:!!(c!=null&&c.profileComplete)},{id:"email",complete:u},{id:"contacts",complete:!!(c!=null&&c.contactsComplete)},{id:"event",complete:!!(c!=null&&c.eventsRegistered)},{id:"community",complete:!!(c!=null&&c.communityComplete)}],p=h.filter(j=>j.complete).length,f=h.length;return{steps:h,completedCount:p,totalCount:f,allComplete:p===f,dismissed:a,dismiss:async()=>{s!=null&&s.id&&(i(!0),await q.from("onboarding_checklist_dismissed").insert({user_id:s.id}))},reopen:async()=>{s!=null&&s.id&&(i(!1),await q.from("onboarding_checklist_dismissed").delete().eq("user_id",s.id))},data:c,isGmailConnected:t,hasVerifiedSes:n,loading:d||r||!l}}const Wns={profile:{title:"Complete Your Profile",description:"Add your headshot, phone, and short bio so contacts recognize you.",icon:Xi,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:Vs,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:Nn,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:yr,accent:"from-[#8b5cf6] to-[#a78bfa]",cta:"Register"},community:{title:"Say Hi in the Community",description:"Introduce yourself and connect with other LevelUp agents.",icon:Ei,accent:"from-[#ec4899] to-[#f472b6]",cta:"Visit Community"}};function Kns(){var _,v;const s=Mn(),{user:t}=ys(),{steps:n,completedCount:r,totalCount:a,allComplete:i,dismissed:l,dismiss:o,data:c,loading:d}=Gns(),[u,h]=N.useState(!0);if(d||l||i)return null;const p=(((_=c==null?void 0:c.profile)==null?void 0:_.name)||((v=t==null?void 0:t.user_metadata)==null?void 0:v.name)||"there").split(" ")[0],f=r/a*100,g=async j=>{switch(j){case"profile":s("/profile");break;case"email":s("/mission-control/integrations");break;case"contacts":s("/mission-control/contacts");break;case"event":{const b=c==null?void 0:c.nextOnboardingEvent;if(!b){s("/events");return}if(!(t!=null&&t.id))return;const{error:S}=await q.from("event_registrations").insert({user_id:t.id,event_id:b.id});S&&!String(S.message).toLowerCase().includes("duplicate")?(ae.error("Could not register — opening events page."),s("/events")):ae.success(`You're registered for ${b.title}!`);break}case"community":s("/community");break}};return e.jsxs(fe,{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(Bn,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"hidden sm:flex h-12 w-12 rounded-xl bg-white/15 backdrop-blur items-center justify-center shrink-0",children:e.jsx(un,{className:"h-6 w-6 text-[#f5f0e0]"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h2",{className:"text-xl md:text-2xl font-bold",children:["Welcome to LevelUp, ",p,"! 👋"]}),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(pi,{value:f,className:"h-2 bg-white/20 [&>div]:bg-[#f5f0e0]"})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3",children:[e.jsxs(B,{onClick:()=>h(!0),className:"bg-[#f5f0e0] text-[#2a4c64] hover:bg-white font-semibold",children:["Continue Setup ",e.jsx(Oa,{className:"h-4 w-4 ml-1.5"})]}),e.jsx("button",{onClick:()=>h(j=>!j),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(tx,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["Show steps ",e.jsx(io,{className:"h-4 w-4"})]})})]})]})]})]}),u&&e.jsx(Ee,{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(j=>{const b=Wns[j.id],S=b.icon;return e.jsx("div",{className:Et("relative rounded-xl border p-4 transition-all group",j.complete?"bg-muted/40 border-muted":"bg-card hover:shadow-md hover:border-primary/40 cursor-pointer"),onClick:()=>!j.complete&&g(j.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",j.complete?"from-emerald-500 to-emerald-600":b.accent),children:j.complete?e.jsx(xr,{className:"h-5 w-5"}):e.jsx(S,{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",j.complete&&"text-muted-foreground line-through"),children:b.title})}),e.jsx("p",{className:Et("text-xs text-muted-foreground mt-1 leading-relaxed",j.complete&&"line-through"),children:b.description}),j.id==="event"&&!j.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"]}),!j.complete&&e.jsxs(B,{size:"sm",variant:"ghost",className:"mt-2 h-7 px-2 -ml-2 text-primary hover:text-primary hover:bg-primary/10",onClick:A=>{A.stopPropagation(),g(j.id)},children:[b.cta," ",e.jsx(Oa,{className:"h-3 w-3 ml-1"})]})]}),j.complete&&e.jsx("span",{className:"text-xs font-medium text-emerald-600 shrink-0",children:"✓ Done"})]})},j.id)})})})]})}const Sy=()=>ct({queryKey:["relationship-types"],queryFn:async()=>{const{data:s,error:t}=await q.from("relationship_types").select("*").order("sort_order");if(t)throw t;return s}}),ox=s=>{const t=ma(),n=1e3,r=async a=>{const i=[];let l=0;for(;;){const{data:o,error:c}=await a.range(l,l+n-1);if(c)throw c;const d=o??[];if(i.push(...d),d.length{let a=q.from("innercircle_contacts").select(` *, 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})},Yns=s=>ct({queryKey:["innercircle-contact",s],queryFn:async()=>{const{data:t,error:n}=await q.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),Zmt=()=>{const s=ma();return ct({queryKey:["innercircle-contact-counts",s],queryFn:async()=>{const{data:t,error:n}=await q.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(n)throw n;const r={};return t==null||t.forEach(a=>{var i;(i=a.tags)==null||i.forEach(l=>{r[l.relationship_type_id]=(r[l.relationship_type_id]||0)+1})}),r},enabled:!!s})},Uye=()=>{const s=Ht(),t=ma();return gt({mutationFn:async n=>{const{tagIds:r,...a}=n,i={...a,birthday:a.birthday||null,home_anniversary:a.home_anniversary||null,spouse_birthday:a.spouse_birthday||null,owner_user_id:t},{data:l,error:o}=await q.from("innercircle_contacts").insert(i).select().single();if(o)throw o;if(r&&r.length>0){const{error:c}=await q.from("innercircle_contact_tags").insert(r.map(d=>({contact_id:l.id,relationship_type_id:d})));if(c)throw c}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Pr({title:"Contact created successfully"})},onError:n=>{Pr({title:"Error creating contact",description:n.message,variant:"destructive"})}})},g6e=()=>{const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{tagIds:r,tags:a,...i}=n,l=["birthday","home_anniversary","spouse_birthday","wedding_anniversary","last_contacted_at","next_touch_date"],o={...i};for(const u of Object.keys(o)){const h=o[u];(h===""||typeof h=="string"&&l.includes(u)&&h.trim()==="")&&(o[u]=null)}const{data:c,error:d}=await q.from("innercircle_contacts").update(o).eq("id",t).select().single();if(d)throw d;if(r!==void 0&&(await q.from("innercircle_contact_tags").delete().eq("contact_id",t),r.length>0)){const{error:u}=await q.from("innercircle_contact_tags").insert(r.map(h=>({contact_id:t,relationship_type_id:h})));if(u)throw u}return c},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Pr({title:"Contact updated successfully"})},onError:t=>{Pr({title:"Error updating contact",description:t.message,variant:"destructive"})}})},Qmt=()=>{const s=Ht();return gt({mutationFn:async({contactId:t,spouseContactId:n})=>{if(n){const{error:r}=await q.from("innercircle_contacts").update({spouse_contact_id:n}).eq("id",t);if(r)throw r;const{error:a}=await q.from("innercircle_contacts").update({spouse_contact_id:t}).eq("id",n);if(a)throw a}else{const{data:r}=await q.from("innercircle_contacts").select("spouse_contact_id").eq("id",t).single(),a=r==null?void 0:r.spouse_contact_id,{error:i}=await q.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",t);if(i)throw i;if(a){const{error:l}=await q.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",a);if(l)throw l}}},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-spouse"]}),Pr({title:"Spouse link updated"})},onError:t=>{Pr({title:"Error linking spouse",description:t.message,variant:"destructive"})}})},y6e=()=>{const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("innercircle_contacts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Pr({title:"Contact deleted successfully"})},onError:t=>{Pr({title:"Error deleting contact",description:t.message,variant:"destructive"})}})},YD=()=>ct({queryKey:["action-types"],queryFn:async()=>{const{data:s,error:t}=await q.from("action_types").select("*").order("sort_order");if(t)throw t;return s}}),Zns=s=>ct({queryKey:["action-scripts",s],queryFn:async()=>{let t=q.from("action_scripts").select("*, action_type:action_types(*)");const{data:n,error:r}=await t;if(r)throw r;return n}}),Qns=()=>ct({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:s,error:t}=await q.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(t)throw t;return s}}),Xns=()=>{const s=Ht(),t=ma();return gt({mutationFn:async({name:n,description:r})=>{const{data:a,error:i}=await q.from("touchpoint_plans").insert({name:n,description:r,owner_user_id:t,active:!0,is_template:!1}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Pr({title:"Plan created successfully"})},onError:n=>{Pr({title:"Error creating plan",description:n.message,variant:"destructive"})}})},Jns=()=>{const s=Ht(),t=ma();return gt({mutationFn:async({sourcePlanId:n,newName:r})=>{const{data:a,error:i}=await q.from("touchpoint_plans").select(` *, items:touchpoint_plan_items(*) `).eq("id",n).single();if(i)throw i;if(!a)throw new Error("Source plan not found");const{data:l,error:o}=await q.from("touchpoint_plans").insert({name:r,description:a.description,owner_user_id:t,active:!0,is_template:!1}).select().single();if(o)throw o;if(a.items&&a.items.length>0){const c=a.items.map(u=>({plan_id:l.id,month_number:u.month_number,action_type_id:u.action_type_id,default_script_id:u.default_script_id,notes:u.notes})),{error:d}=await q.from("touchpoint_plan_items").insert(c);if(d)throw d}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Pr({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:n=>{Pr({title:"Error duplicating plan",description:n.message,variant:"destructive"})}})},ers=()=>{const s=Ht();return gt({mutationFn:async({id:t,name:n,description:r})=>{const{data:a,error:i}=await q.from("touchpoint_plans").update({name:n,description:r}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Pr({title:"Plan updated successfully"})}})},trs=()=>{const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("touchpoint_plans").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Pr({title:"Plan deleted successfully"})}})},srs=()=>{const s=Ht();return gt({mutationFn:async({planId:t,items:n})=>{if(await q.from("touchpoint_plan_items").delete().eq("plan_id",t),n.length>0){const{error:r}=await q.from("touchpoint_plan_items").insert(n.map(a=>({plan_id:t,month_number:a.month_number,action_type_id:a.action_type_id,default_script_id:a.default_script_id||null,notes:a.notes})));if(r)throw r}},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Pr({title:"Plan schedule updated"})}})},nrs=()=>{const s=Ht();return gt({mutationFn:async({actionTypeId:t,title:n,scriptBody:r,emailSubject:a,tone:i})=>{const{data:{user:l}}=await q.auth.getUser(),{data:o,error:c}=await q.from("action_scripts").insert({action_type_id:t,title:n,script_body:r,email_subject:a||null,tone:i||null,active:!0,user_id:l==null?void 0:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["action-scripts"]}),Pr({title:"Script created successfully"})},onError:t=>{Pr({title:"Error creating script",description:t.message,variant:"destructive"})}})},rrs=()=>{const s=ma();return ct({queryKey:["user-plan-enrollments",s],queryFn:async()=>{const{data:t,error:n}=await q.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(n)throw n;return t},enabled:!!s})},ars=()=>{const s=Ht(),t=ma();return gt({mutationFn:async({planId:n,relationshipTypeId:r,active:a})=>{const{data:i}=await q.from("user_plan_enrollments").select("id").eq("plan_id",n).eq("relationship_type_id",r).maybeSingle();if(i){const{error:l}=await q.from("user_plan_enrollments").update({active:a}).eq("id",i.id);if(l)throw l}else if(a){const{error:l}=await q.from("user_plan_enrollments").insert({owner_user_id:t,plan_id:n,relationship_type_id:r,active:!0,start_date:new Date().toISOString().split("T")[0]});if(l)throw l}},onSuccess:()=>{s.invalidateQueries({queryKey:["user-plan-enrollments"]}),Pr({title:"Plan enrollment updated"})}})},pU=(s=7)=>{const t=ma();return ct({queryKey:["contact-touch-logs",t,s],queryFn:async()=>{const n=new Date;n.setDate(n.getDate()-s);const{data:r,error:a}=await q.from("contact_touch_logs").select(` *, contact:innercircle_contacts(*), action_type:action_types(*) `).eq("owner_user_id",t).gte("completed_at",n.toISOString()).order("completed_at",{ascending:!1});if(a)throw a;return r},enabled:!!t})},Xmt=()=>{const s=ma();return ct({queryKey:["contacts-last-touch",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_touch_logs").select("contact_id, completed_at").eq("owner_user_id",s).order("completed_at",{ascending:!1});if(n)throw n;const r={};return t==null||t.forEach(a=>{r[a.contact_id]||(r[a.contact_id]=a.completed_at)}),r},enabled:!!s})},irs=(s=90)=>{const{data:t}=ox(),{data:n}=Xmt();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=Ht(),t=ma();return gt({mutationFn:async({contactId:n,actionTypeId:r,scriptUsedId:a,notes:i,completedAt:l})=>{const{data:o,error:c}=await q.from("contact_touch_logs").insert({owner_user_id:t,contact_id:n,action_type_id:r,script_used_id:a,notes:i,completed_at:l||new Date().toISOString()}).select().single();if(c)throw c;return o},onSuccess:async(n,r)=>{var a,i;s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),s.invalidateQueries({queryKey:["today-actions"]}),s.invalidateQueries({queryKey:["popby-logs"]}),Pr({title:"Action completed!"});try{const[l,o]=await Promise.all([q.from("innercircle_contacts").select("email").eq("id",r.contactId).single(),q.from("action_types").select("name").eq("id",r.actionTypeId).single()]),c=(a=l.data)==null?void 0:a.email,d=((i=o.data)==null?void 0:i.name)||"Touch";/pop[\s-]?by/i.test(d)&&q.from("popby_logs").insert({owner_user_id:t,contact_id:r.contactId,notes:r.notes??null,completed_at:r.completedAt||n.completed_at}).then(()=>{s.invalidateQueries({queryKey:["popby-logs"]})}),c&&q.functions.invoke("boldtrail-sync",{body:{action:"push_touch",contact_email:c,touch_type:d,touch_notes:r.notes||null,touch_date:r.completedAt||n.completed_at}}).catch(()=>{})}catch{}}})},Jmt="agentos_weekly_touch_goal",GUe=20,Pfe=()=>{if(typeof window>"u")return GUe;const s=localStorage.getItem(Jmt);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return GUe},ept=s=>{localStorage.setItem(Jmt,s.toString())},v6e=()=>{const{data:s}=pU(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=Pfe();return{actionsThisWeek:r,weeklyGoal:i,streak:a,progress:Math.min(r/i*100,100)}},ors=()=>{const s=ma();return ct({queryKey:["contact-plan-cycles",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_plan_cycles").select(` *, contact:innercircle_contacts(*), plan:touchpoint_plans( *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) ) `);if(n)throw n;return t},enabled:!!s})},lrs=()=>{const s=Ht();return ma(),gt({mutationFn:async()=>{var c;const{data:t}=await q.from("user_plan_enrollments").select("*").eq("active",!0);if(!t||t.length===0)return;const{data:n}=await q.auth.getUser(),r=(c=n==null?void 0:n.user)==null?void 0:c.id;if(!r)return;const{data:a}=await q.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `).eq("owner_user_id",r);if(!a)return;const{data:i}=await q.from("contact_plan_cycles").select("contact_id, plan_id"),l=new Set((i==null?void 0:i.map(d=>`${d.contact_id}-${d.plan_id}`))||[]),o=[];for(const d of a)for(const u of d.tags||[]){const h=t.find(p=>p.relationship_type_id===u.relationship_type_id);h&&!l.has(`${d.id}-${h.plan_id}`)&&o.push({contact_id:d.id,plan_id:h.plan_id,relationship_type_id:u.relationship_type_id})}if(o.length>0){const{error:d}=await q.from("contact_plan_cycles").insert(o);if(d)throw d}return o.length},onSuccess:t=>{s.invalidateQueries({queryKey:["contact-plan-cycles"]}),t&&t>0&&Pr({title:`${t} contact(s) enrolled in plans`})}})},tpt=()=>{const s=ma(),{data:t}=ors(),{data:n}=pU(30);return ct({queryKey:["today-actions",s,t==null?void 0:t.length,n==null?void 0:n.length],queryFn:async()=>{var g;if(!t||t.length===0)return[];const{data:r}=await q.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),a=new Set((r==null?void 0:r.map(_=>_.contact_id))||[]),i=new Date,l=[],o=new Date(i.getFullYear(),i.getMonth(),1),c=new Set((n==null?void 0:n.filter(_=>new Date(_.completed_at)>=o).map(_=>`${_.contact_id}-${_.action_type_id}`))||[]);for(const _ of t){if(!((g=_.plan)!=null&&g.items)||_.plan.items.length===0||!_.contact||a.has(_.contact_id))continue;const v=new Date(_.cycle_start_date),b=Math.floor((i.getTime()-v.getTime())/(30.44*24*60*60*1e3))%12+1,S=_.plan.items.find(A=>A.month_number===b);if(S&&S.action_type){const A=`${_.contact_id}-${S.action_type_id}`;if(!c.has(A)){const{data:T}=await q.from("relationship_types").select("name").eq("id",_.relationship_type_id).single();l.push({contact:_.contact,actionType:S.action_type,script:S.default_script||void 0,planName:_.plan.name,relationshipTypeName:(T==null?void 0:T.name)||"",monthNumber:b})}}}const d=5,u=i.getDate(),h=l.sort((_,v)=>_.contact.first_name.localeCompare(v.contact.first_name)),p=(u-1)%Math.max(1,h.length);return[...h.slice(p),...h.slice(0,p)].slice(0,d)},enabled:!!s&&!!t})};function crs(){const s=Mn(),{data:t,isLoading:n}=tpt(),{data:r}=ox(),a=v6e(),[i,l]=N.useState(Pfe()),[o,c]=N.useState(""),[d,u]=N.useState(!1);N.useEffect(()=>{l(Pfe())},[]);const h=()=>{const L=parseInt(o,10);if(isNaN(L)||L<1){Pr({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}l(L),ept(L),u(!1),Pr({title:"Goal updated",description:`Weekly touch goal set to ${L}`})},p=()=>{c(i.toString()),u(!0)},f=kf(new Date),g=Bl(f,7),_=L=>{if(!L)return null;const D=L.split(/[-/T]/);if(D.length<3)return null;const M=parseInt(D[1],10)-1,F=parseInt(D[2],10);return isNaN(M)||isNaN(F)?null:new Date(f.getFullYear(),M,F)},v=(r==null?void 0:r.map(L=>{const D=_(L.birthday),M=_(L.home_anniversary),F=[];return D&&D>=f&&D<=g&&F.push({contact:L,type:"birthday",date:D,isToday:Vl(D,f)}),M&&M>=f&&M<=g&&F.push({contact:L,type:"anniversary",date:M,isToday:Vl(M,f)}),F}).flat().sort((L,D)=>L.date.getTime()-D.date.getTime()).slice(0,3))||[],j=(r==null?void 0:r.filter(L=>{const D=_(L.birthday),M=_(L.home_anniversary);return D&&Vl(D,f)||M&&Vl(M,f)}).length)||0,b=(t==null?void 0:t.length)||0,S=j+b,A=(a==null?void 0:a.actionsThisWeek)||0,T=(a==null?void 0:a.streak)||0;return n?e.jsx(fe,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:e.jsx(Ee,{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(fe,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:[e.jsxs(Mt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5 text-primary"}),"Agent OS"]}),e.jsx("div",{className:"flex items-center gap-2",children:T>0&&e.jsxs(ze,{variant:"secondary",className:"gap-1 bg-orange-500/10 text-orange-600 border-orange-200",children:[e.jsx(Dc,{className:"h-3 w-3"}),T," day streak"]})})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[S>0?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-primary font-medium",children:[S," tasks"]})," for today"]}):"No tasks for today",A>0&&e.jsxs("span",{className:"ml-2",children:["• ",e.jsx("span",{className:"text-emerald-600 font-medium",children:A})," touches this week"]})]})]}),e.jsxs(Ee,{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:L=>{L.stopPropagation(),s("/mission-control/contacts?new=true")},children:[e.jsx(Fo,{className:"h-3.5 w-3.5"}),"Add Contact"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:L=>{L.stopPropagation(),s("/mission-control")},children:[e.jsx(Ar,{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:L=>{L.stopPropagation(),s("/mission-control/video/record")},children:[e.jsx(br,{className:"h-3.5 w-3.5"}),"Quick Video"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:L=>{L.stopPropagation(),s("/mission-control/popbys")},children:[e.jsx(ka,{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:L=>{L.stopPropagation(),s("/mission-control/pipeline")},children:[e.jsx(Z2,{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(Oc,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Weekly Goal"}),e.jsxs(bs,{open:d,onOpenChange:u,children:[e.jsx(Ai,{asChild:!0,children:e.jsx("button",{onClick:p,className:"p-0.5 rounded hover:bg-muted transition-colors","aria-label":"Edit weekly goal",children:e.jsx(Xo,{className:"h-3.5 w-3.5 text-muted-foreground hover:text-primary"})})}),e.jsxs(vs,{className:"sm:max-w-[360px]",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Set Weekly Goal"}),e.jsx(Qn,{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:L=>c(L.target.value),placeholder:"20",onKeyDown:L=>{L.key==="Enter"&&h()}})]}),e.jsx(B,{onClick:h,className:"w-full",children:"Save Goal"})]})]})]})]}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium text-primary",children:A}),e.jsxs("span",{className:"text-muted-foreground",children:[" / ",i," touches"]})]})]}),e.jsx(pi,{value:Math.min(A/i*100,100),className:"h-2 bg-muted [&>div]:bg-primary"}),A>=i&&e.jsxs("p",{className:"text-xs text-emerald-600 mt-1.5 flex items-center gap-1",children:[e.jsx("span",{children:"🎉"})," Goal achieved! Keep the momentum going."]}),A0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1.5",children:[i-A," more to hit your weekly goal"]})]}),v.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(cu,{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:v.map((L,D)=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${L.isToday?"bg-pink-500/10 hover:bg-pink-500/15":"bg-muted/50 hover:bg-muted"}`,onClick:M=>{M.stopPropagation(),s(`/mission-control/contacts/${L.contact.id}`)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[L.type==="birthday"?e.jsx(cu,{className:"h-3.5 w-3.5 text-pink-500"}):e.jsx(Or,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsxs("span",{className:"text-sm",children:[L.contact.first_name," ",L.contact.last_name]}),L.isToday&&e.jsx(ze,{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:L.isToday?L.type==="birthday"?"🎂":"🏠":Ss(L.date,"EEE, MMM d")}),e.jsx(xa,{className:"h-3 w-3"})]})]},`${L.contact.id}-${L.type}-${D}`))})]}),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(Oa,{className:"h-4 w-4"})]})]})]})}function drs(s){return ct({queryKey:["brokerage-content-categories",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("brokerage_content_categories").select("*").eq("brokerage_id",s).order("sort_order");if(n)throw n;return t},enabled:!!s})}function urs(s,t){return ct({queryKey:["brokerage-content",s,t],queryFn:async()=>{if(!s)return[];let n=q.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1});t&&(n=n.eq("category_id",t));const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!s})}function hrs(s,t=4){return ct({queryKey:["brokerage-content-recent",s,t],queryFn:async()=>{if(!s)return[];const{data:n,error:r}=await q.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(t);if(r)throw r;return n},enabled:!!s})}function mrs(s){const t=Ht();return gt({mutationFn:async n=>{const{data:r,error:a}=await q.from("brokerage_content").insert(n).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content"]}),t.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function prs(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("brokerage_content").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content"]}),s.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function frs(s){const t=Ht();return gt({mutationFn:async n=>{const{data:r,error:a}=await q.from("brokerage_content_categories").insert({...n,brokerage_id:s}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function xrs(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("brokerage_content_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function grs(s){const t=Ht();return gt({mutationFn:async()=>{const n=[{name:"Events",icon:"📅",sort_order:0,is_default:!0,brokerage_id:s},{name:"Videos",icon:"🎥",sort_order:1,is_default:!0,brokerage_id:s},{name:"Documents",icon:"📄",sort_order:2,is_default:!0,brokerage_id:s},{name:"Resources",icon:"🔗",sort_order:3,is_default:!0,brokerage_id:s},{name:"Graphics",icon:"🎨",sort_order:4,is_default:!0,brokerage_id:s}],{error:r}=await q.from("brokerage_content_categories").upsert(n,{onConflict:"brokerage_id,name"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}const yrs={video:Al,pdf:Nr,link:El,event:yr,graphic:fl},vrs={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 brs(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 _rs(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 wrs({item:s}){const t=Mn(),n=yrs[s.content_type]||El,r=vrs[s.content_type]||"",[a,i]=N.useState(null),l=s.thumbnail_url||(s.content_type==="graphic"&&s.file_url?s.file_url:null)||(s.content_type==="video"?brs(s.url):null);N.useEffect(()=>{l||!s.url||s.content_type!=="video"||!_rs(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(fe,{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(Ee,{className:"p-3",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsxs(ze,{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:Ss(new Date(s.event_date),"MMM d · h:mm a")})]})]})}function jrs(){const{brokerageId:s}=ys(),t=Mn(),{data:n=[],isLoading:r}=hrs(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(Va,{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(Oa,{className:"h-4 w-4"})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:n.map(a=>e.jsx(wrs,{item:a},a.id))})]})}const spt=()=>ct({queryKey:["listing-exchange-enabled"],queryFn:async()=>{const{data:s,error:t}=await q.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").maybeSingle();if(t)throw t;return(s==null?void 0:s.enabled)??!1}}),npt=s=>{const{user:t,brokerageId:n}=ys();return ct({queryKey:["listings",s,n],queryFn:async()=>{let r=q.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 q.from("profiles").select("id").eq("brokerage_id",n);if(o&&o.length>0){const c=o.map(h=>h.id);let d=q.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("share_with_brokerage",!0).eq("is_public",!1).in("agent_id",c);s!=null&&s.status&&(d=d.eq("status",s.status)),s!=null&&s.propertyType&&(d=d.eq("property_type",s.propertyType)),s!=null&&s.city&&(d=d.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(d=d.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(d=d.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(d=d.eq("open_to_referrals",!0));const{data:u}=await d;if(u){const h=new Set(l.map(f=>f.id)),p=u.filter(f=>!h.has(f.id));l=[...l,...p]}}}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}})},rpt=()=>{const{user:s}=ys();return ct({queryKey:["my-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("listings").select(` *, photos:listing_photos(*) `).eq("agent_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})},b6e=s=>{const{user:t}=ys();return ct({queryKey:["listing",s],queryFn:async()=>{const{data:n,error:r}=await q.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 q.from("listing_views").insert({listing_id:s,viewer_id:t.id}),n},enabled:!!s})},Nrs=()=>{const s=Ht(),{user:t}=ys();return gt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("listings").insert({...n,agent_id:t.id}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},krs=()=>{const s=Ht();return gt({mutationFn:async({agentId:t,...n})=>{const{data:r,error:a}=await q.from("listings").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["brokerage-listings"]})}})},Srs=()=>{const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("listings").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["listing",t.id]})}})},apt=()=>{const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("listings").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Crs=()=>{const s=Ht();return gt({mutationFn:async({listingId:t,photoUrl:n,isPrimary:r=!1})=>{const{data:a,error:i}=await q.from("listing_photos").insert({listing_id:t,photo_url:n,is_primary:r}).select().single();if(i)throw i;return a},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t.listing_id]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Trs=()=>{const s=Ht();return gt({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await q.from("listing_photos").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Ers=()=>{const s=Ht();return gt({mutationFn:async({photos:t})=>{var i;const n=t.map(l=>q.from("listing_photos").update({sort_order:l.sort_order,is_primary:l.is_primary}).eq("id",l.id)),a=(i=(await Promise.all(n)).find(l=>l.error))==null?void 0:i.error;if(a)throw a;return t},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Ars=()=>{const s=Ht();return gt({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await q.from("listing_photos").update({is_primary:!1}).eq("listing_id",n);if(r)throw r;const{error:a}=await q.from("listing_photos").update({is_primary:!0}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Mrs=()=>{const{user:s}=ys();return ct({queryKey:["saved-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("listing_saves").select(` *, listing:listings( *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id) ) `).eq("agent_id",s.id);if(n)throw n;return t},enabled:!!s})},ipt=()=>{const s=Ht(),{user:t}=ys();return gt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await q.from("listing_saves").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await q.from("listing_saves").delete().eq("id",r.id),{saved:!1}):(await q.from("listing_saves").insert({listing_id:n,agent_id:t.id}),{saved:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["saved-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})},opt=s=>{const{user:t}=ys();return ct({queryKey:["listing-saved",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await q.from("listing_saves").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},Irs=()=>{const s=Ht(),{user:t}=ys();return gt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await q.from("listing_follows").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await q.from("listing_follows").delete().eq("id",r.id),{following:!1}):(await q.from("listing_follows").insert({listing_id:n,agent_id:t.id}),{following:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["listing-following"]})}})},Prs=s=>{const{user:t}=ys();return ct({queryKey:["listing-following",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await q.from("listing_follows").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},Lrs=()=>{const{user:s}=ys();return gt({mutationFn:async({listingId:t,shareType:n})=>{if(!s)throw new Error("Not authenticated");const{error:r}=await q.from("listing_shares").insert({listing_id:t,sharing_agent_id:s.id,share_type:n});if(r)throw r}})},Drs=()=>{const{user:s}=ys();return ct({queryKey:["my-referrals",s==null?void 0:s.id],queryFn:async()=>{if(!s)return{sent:[],received:[]};const[t,n]=await Promise.all([q.from("listing_referrals").select(` *, listing:listings(*,photos:listing_photos(*)) `).eq("sender_agent_id",s.id).order("created_at",{ascending:!1}),q.from("listing_referrals").select(` *, sender:profiles!listing_referrals_sender_agent_id_fkey(id, name, email), listing:listings(*,photos:listing_photos(*)) `).eq("listing_agent_id",s.id).order("created_at",{ascending:!1})]);return{sent:t.data||[],received:n.data||[]}},enabled:!!s})},Rrs=()=>{const s=Ht(),{user:t}=ys();return gt({mutationFn:async({listingId:n,listingAgentId:r,buyerName:a,buyerType:i,notes:l})=>{if(!t)throw new Error("Not authenticated");const{data:o,error:c}=await q.from("listing_referrals").insert({listing_id:n,sender_agent_id:t.id,listing_agent_id:r,buyer_name:a,buyer_type:i,notes:l}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["my-referrals"]})}})},Ors=()=>ct({queryKey:["listing-leaderboard"],queryFn:async()=>{const{data:s}=await q.from("listing_shares").select("sharing_agent_id, profiles!listing_shares_agent_id_fkey(name)").order("created_at",{ascending:!1}),t=new Map;s==null||s.forEach(l=>{var d;const o=l.sharing_agent_id;if(!o)return;const c=t.get(o);c?c.count++:t.set(o,{name:((d=l.profiles)==null?void 0:d.name)||"Unknown",count:1})});const n=Array.from(t.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10),{data:r}=await q.from("listings").select("agent_id, agent:profiles!listings_agent_id_fkey(name)").eq("is_approved",!0),a=new Map;r==null||r.forEach(l=>{var c;const o=a.get(l.agent_id);o?o.count++:a.set(l.agent_id,{name:((c=l.agent)==null?void 0:c.name)||"Unknown",count:1})});const i=Array.from(a.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10);return{topSharers:n,topListers:i}}}),Frs=()=>{const{user:s,brokerageId:t}=ys();return ct({queryKey:["brokerage-listings",t],queryFn:async()=>{if(!s||!t)return[];const{data:n}=await q.from("profiles").select("id").eq("brokerage_id",t);if(!n||n.length===0)return[];const r=n.map(l=>l.id),{data:a,error:i}=await q.from("listings").select(` *, photos:listing_photos(*), 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})},lpt=({className:s,variant:t="default"})=>e.jsx(ze,{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"}),zrs={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"},Brs={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function $rs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function Urs(){const s=Mn(),{data:t,isLoading:n}=spt(),{data:r,isLoading:a}=npt({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(fe,{className:"bg-gradient-to-br from-emerald-500/5 via-emerald-500/10 to-emerald-500/5 border-emerald-500/20",children:e.jsx(Ee,{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(lpt,{})]}),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(Oa,{className:"h-4 w-4"})]})]}),c.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Or,{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 p,f;const h=((p=u.photos)==null?void 0:p.find(g=>g.is_primary))||((f=u.photos)==null?void 0:f[0]);return e.jsxs("div",{onClick:()=>s(`/mission-control/listings/${u.id}`),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsxs("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden relative",children:[h!=null&&h.photo_url?e.jsx("img",{src:h.photo_url,alt:`${u.city}, ${u.state}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Or,{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(ze,{className:"gap-1 bg-amber-500 text-white border-0 text-[10px] px-1.5 py-0.5",children:[e.jsx(ca,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]})}),e.jsx("div",{className:"absolute top-1.5 right-1.5",children:e.jsx(ze,{className:`text-[10px] px-1.5 py-0.5 ${zrs[u.status]}`,children:Brs[u.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:$rs(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 cpt(s=10,t){return ct({queryKey:["event-leaderboard",s,t],queryFn:async()=>{const{data:n}=await q.from("user_roles").select("user_id").eq("role","admin"),r=new Set((n==null?void 0:n.map(p=>p.user_id))||[]);let a=null;if(t){const{data:p}=await q.from("profiles").select("id").eq("brokerage_id",t);a=new Set((p==null?void 0:p.map(f=>f.id))||[])}const{data:i,error:l}=await q.from("agent_attendance_stats").select("user_id, total_points, total_events_attended, current_streak").order("total_points",{ascending:!1}).limit(s+r.size+50);if(l)throw l;if(!i||i.length===0)return[];let o=i.filter(p=>!r.has(p.user_id));a&&(o=o.filter(p=>a.has(p.user_id)));const c=o.slice(0,s),d=c.map(p=>p.user_id),{data:u}=await q.from("profiles").select("id, name").in("id",d),h=new Map((u==null?void 0:u.map(p=>[p.id,{name:p.name}]))||[]);return c.map(p=>({user_id:p.user_id,total_points:p.total_points,total_events_attended:p.total_events_attended,current_streak:p.current_streak,profile:h.get(p.user_id)||null}))}})}function dpt(s){return ct({queryKey:["user-attendance-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_attendance_stats").select("*").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return t},enabled:!!s})}function upt(s){return ct({queryKey:["user-badges",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("agent_badges").select("*").eq("user_id",s).order("earned_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function hpt(s,t){return ct({queryKey:["user-rank",s,t],queryFn:async()=>{if(!s)return null;const{data:n}=await q.from("agent_attendance_stats").select("total_points").eq("user_id",s).single();if(!n)return null;const{data:r}=await q.from("user_roles").select("user_id").eq("role","admin"),a=new Set((r==null?void 0:r.map(c=>c.user_id))||[]),{data:i,error:l}=await q.from("agent_attendance_stats").select("user_id, total_points").gt("total_points",n.total_points);if(l)throw l;let o=(i==null?void 0:i.filter(c=>!a.has(c.user_id)))||[];if(t){const{data:c}=await q.from("profiles").select("id").eq("brokerage_id",t),d=new Set((c==null?void 0:c.map(u=>u.id))||[]);o=o.filter(u=>d.has(u.user_id))}return o.length+1},enabled:!!s})}function qrs(){const{user:s,brokerageId:t,isAdmin:n}=ys();Mn();const r=!!t,[a,i]=N.useState("brokerage"),l=()=>{if(n)return null;if(r)return a==="global"?null:t},{data:o,isLoading:c}=cpt(5,l()),{data:d}=dpt(s==null?void 0:s.id),{data:u}=hpt(s==null?void 0:s.id,l()),{data:h}=upt(s==null?void 0:s.id),p=n||r,f=()=>n?"Agent Leaderboard":r?a==="global"?"All LevelUp":"My Brokerage":"My Points";if(c)return e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(vo,{className:"h-4 w-4 text-yellow-500"}),f()]})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-2",children:[...Array(p?5:3)].map((_,v)=>e.jsx(Ws,{className:"h-10 w-full"},v))})})]});const g=_=>_===0?e.jsx(vo,{className:"h-4 w-4 text-yellow-500 mx-auto"}):_===1?e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"2"}):_===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:_+1});if(p){const _=(o==null?void 0:o.slice(0,5))||[];return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"pb-2",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(vo,{className:"h-4 w-4 text-yellow-500"}),f()]}),!n&&r&&e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsx(B,{variant:a==="brokerage"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("brokerage"),children:"My Brokerage"}),e.jsx(B,{variant:a==="global"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("global"),children:"All LevelUp"})]})]}),e.jsxs(Ee,{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:[_.map((v,j)=>{var b,S,A;return e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg ${v.user_id===(s==null?void 0:s.id)?"bg-primary/10 border border-primary/20":j===0?"bg-yellow-500/10":""}`,children:[e.jsx("div",{className:"w-5 text-center",children:g(j)}),e.jsx(ra,{className:"h-6 w-6",children:e.jsx(aa,{className:"text-xs",children:((S=(b=v.profile)==null?void 0:b.name)==null?void 0:S.charAt(0))||"?"})}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:((A=v.profile)==null?void 0:A.name)||"Unknown"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:v.total_points})]},v.user_id)}),_.length===0&&e.jsx("div",{className:"text-center text-muted-foreground py-2 text-sm",children:"No data yet"})]}),e.jsxs(Ln,{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(Oi,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(xa,{className:"h-4 w-4"})]})]})]})}return e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(vo,{className:"h-4 w-4 text-yellow-500"}),"My Points"]})}),e.jsx(Ee,{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(Dc,{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(bc,{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(_=>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:_.badge_name},_.id)),h.length>4&&e.jsxs("span",{className:"text-xs text-muted-foreground px-2 py-1",children:["+",h.length-4," more"]})]})]}),e.jsxs(Ln,{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(Oi,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(xa,{className:"h-4 w-4"})]})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-4 text-sm",children:[e.jsx(ca,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/50"}),e.jsx("p",{children:"Attend events to earn points!"}),e.jsxs(Ln,{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(Oi,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx(xa,{className:"h-4 w-4"})]})]})})]})}const ZD=()=>ct({queryKey:["lead-sources"],queryFn:async()=>{const{data:s,error:t}=await q.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s}}),_6e=()=>{const s=Ht(),{user:t}=ys();return gt({mutationFn:async n=>{const{data:r}=await q.from("lead_sources").select("id, name").eq("is_active",!0).ilike("name",n.trim()),a=(r||[]).find(o=>o.name.toLowerCase()===n.trim().toLowerCase()&&!0);if(a)throw new Error(`Lead source "${a.name}" already exists`);const{data:i,error:l}=await q.from("lead_sources").insert({name:n,owner_user_id:t==null?void 0:t.id,sort_order:100}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ae.success("Lead source added")},onError:n=>{ae.error("Failed to add lead source"),console.error(n)}})},Vrs=()=>{const s=Ht();return gt({mutationFn:async({id:t,name:n})=>{const{error:r}=await q.from("lead_sources").update({name:n}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ae.success("Lead source updated")},onError:t=>{ae.error(t.message||"Failed to update lead source")}})},Hrs=()=>{const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("lead_sources").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ae.success("Lead source removed")},onError:t=>{ae.error(t.message||"Failed to remove lead source")}})},w6e=(s,t)=>{const{user:n,isAdmin:r}=ys(),a=r&&t?t:n==null?void 0:n.id;return ct({queryKey:["scorecard-transactions",s,a],queryFn:async()=>{let i=q.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",a).order("close_date",{ascending:!1});s&&(i=i.gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`));const{data:l,error:o}=await i;if(o)throw o;return l},enabled:!!a})},j6e=s=>{const{user:t,isAdmin:n}=ys(),r=n&&s?s:t==null?void 0:t.id;return ct({queryKey:["scorecard-transactions-all",r],queryFn:async()=>{const{data:a,error:i}=await q.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",r).order("close_date",{ascending:!1});if(i)throw i;return a},enabled:!!r})},qye=()=>{const s=Ht(),{user:t}=ys();return gt({mutationFn:async n=>{const{data:r,error:a}=await q.from("scorecard_transactions").insert({...n,owner_user_id:t.id}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ae.success("Transaction added")},onError:n=>{ae.error("Failed to add transaction"),console.error(n)}})},Grs=()=>{const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("scorecard_transactions").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ae.success("Transaction updated")},onError:t=>{ae.error("Failed to update transaction"),console.error(t)}})},Wrs=()=>{const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("scorecard_transactions").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ae.success("Transaction deleted")},onError:t=>{ae.error("Failed to delete transaction"),console.error(t)}})},mpt=(s,t)=>{const{user:n,isAdmin:r}=ys(),a=r&&t?t:n==null?void 0:n.id;return ct({queryKey:["scorecard-goals",s,a],queryFn:async()=>{const{data:i,error:l}=await q.from("scorecard_goals").select("*").eq("owner_user_id",a).eq("year",s).maybeSingle();if(l)throw l;return i},enabled:!!a})},Krs=()=>{const s=Ht(),{user:t}=ys();return gt({mutationFn:async n=>{const{data:r,error:a}=await q.from("scorecard_goals").upsert({...n,owner_user_id:t.id},{onConflict:"owner_user_id,year"}).select().single();if(a)throw a;return r},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["scorecard-goals",r.year]}),ae.success("Goals saved")},onError:n=>{ae.error("Failed to save goals"),console.error(n)}})},Vye=()=>{const{user:s}=ys();return ct({queryKey:["scorecard-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("scorecard_settings").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t},enabled:!!(s!=null&&s.id)})},Yrs=()=>{const s=Ht(),{user:t}=ys();return gt({mutationFn:async n=>{const{data:r,error:a}=await q.from("scorecard_settings").upsert({...n,user_id:t.id},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-settings"]}),ae.success("Settings saved")},onError:n=>{ae.error("Failed to save settings"),console.error(n)}})},ppt=(s,t)=>{const{data:n,isLoading:r}=w6e(s,t),{data:a,isLoading:i}=j6e(t),{data:l}=Vye(),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,p=d.reduce((T,L)=>T+Number(L.sale_price),0),f=d.reduce((T,L)=>T+(Number(L.commission_amount)||0),0),g=d.reduce((T,L)=>{const D=Number(L.commission_amount)||0;if(!D)return T;let M=D;return L.brokerage_split_pct&&(M-=D*(L.brokerage_split_pct/100)),L.team_split_pct&&(M-=D*(L.team_split_pct/100)),L.franchise_fee_pct&&(M-=D*(L.franchise_fee_pct/100)),L.referral_fee_pct&&(M-=D*(L.referral_fee_pct/100)),L.transaction_fee&&(M-=L.transaction_fee),T+Math.max(0,M)},0),_={};d.forEach(T=>{var D;const L=((D=T.lead_source)==null?void 0:D.name)||"Unknown";_[L]=(_[L]||0)+1});const v=Object.entries(_).map(([T,L])=>({name:T,count:L})).sort((T,L)=>L.count-T.count),j=v[0]||null,b={};d.forEach(T=>{const L=Cl(T.close_date).toLocaleString("default",{month:"short"});b[L]=(b[L]||0)+1});const A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(T=>({month:T,count:b[T]||0}));return{totalTransactions:d.length,buyerCount:u,sellerCount:h,totalVolume:p,averagePrice:d.length>0?p/d.length:0,totalCommission:o?f:0,totalNetToAgent:o?g:0,topLeadSource:j,transactionsByMonth:A,leadSourceBreakdown:v}};return{yearStats:c(n),lifetimeStats:c(a),isLoading:r||i,showCommission:o}},Zrs=()=>{const{isAdmin:s}=ys();return ct({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:t,error:n}=await q.from("scorecard_transactions").select("owner_user_id").order("owner_user_id");if(n)throw n;const r=[...new Set(t.map(l=>l.owner_user_id))],{data:a,error:i}=await q.from("profiles").select("id, name, email").in("id",r);if(i)throw i;return a},enabled:s})},Qk={recency:40,touchpoints:30,transactions:20,referrals:10},WUe={warm:70,cooling:40};function Qrs(s){return s===null?0:s<=14?Qk.recency:s<=30?Qk.recency*.85:s<=60?Qk.recency*.65:s<=90?Qk.recency*.4:s<=180?Qk.recency*.2:Qk.recency*.05}function Xrs(s){const t=Math.min(s/12,1);return Math.round(Qk.touchpoints*t)}function Jrs(s){return s?Qk.transactions:0}function eas(){return 0}function tas(s){return s>=WUe.warm?"warm":s>=WUe.cooling?"cooling":"at-risk"}function Hye(){const{data:s,isLoading:t}=ox(),{data:n}=Xmt(),{data:r}=pU(365),{data:a}=j6e(),i=N.useMemo(()=>{if(!s)return[];const o=new Date,c=GE(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 p=(n==null?void 0:n[h.id])||null,f=p?Wv(o,new Date(p)):null,g=d[h.id]||0,_=u.has(h.id),v=Qrs(f),j=Xrs(g),b=Jrs(_),S=eas(),A=Math.round(v+j+b+S),T={score:A,status:tas(A),breakdown:{recency:Math.round(v),touchpoints:Math.round(j),transactions:Math.round(b),referrals:Math.round(S)},lastTouchDate:p,daysSinceTouch:f,touchCountLast12Months:g,hasTransaction:_};return{...h,relationshipScore:T}})},[s,n,r,a]),l=N.useMemo(()=>{const o=i.filter(p=>p.relationshipScore.status==="warm").length,c=i.filter(p=>p.relationshipScore.status==="cooling").length,d=i.filter(p=>p.relationshipScore.status==="at-risk").length,u=i.length,h=u>0?Math.round(i.reduce((p,f)=>p+f.relationshipScore.score,0)/u):0;return{warm:o,cooling:c,atRisk:d,total:u,averageScore:h}},[i]);return{contactsWithScores:i,stats:l,isLoading:t}}function fpt(){const s=Mn(),{stats:t,contactsWithScores:n,isLoading:r}=Hye();if(r)return e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Ws,{className:"h-5 w-40"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx(Ws,{className:"h-20 w-full"}),e.jsx(Ws,{className:"h-16 w-full"})]})]});if(t.total===0)return e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(It,{className:"text-lg flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5"}),"Relationship Health"]})}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:[e.jsx(mo,{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(Ee,{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(pi,{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(pi,{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(pi,{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(vb,{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(xa,{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(xa,{className:"h-4 w-4 ml-1"})]})]})]})}const sas=()=>{var ne;const{user:s,isAdmin:t}=ys(),n=Mn(),[r,a]=N.useState([]),[i,l]=N.useState([]),[o,c]=N.useState([]),[d,u]=N.useState([]),[h,p]=N.useState([]),[f,g]=N.useState([]),[_,v]=N.useState(new Set),[j,b]=N.useState([]),[S,A]=N.useState([]),[T,L]=N.useState([]),[D,M]=N.useState(null),[F,z]=N.useState(!0);N.useEffect(()=>{V()},[s]);const V=async()=>{var ie,he,ce,pe,le;try{const[ve,ge,Te,Me,Ce,Ae,De,Ie,Fe,qe,be]=await Promise.all([q.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),q.from("app_tiles").select("*").order("name"),q.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),q.from("events").select("*").order("event_date",{ascending:!0}),q.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",s==null?void 0:s.id),q.from("canva_templates").select("id, name, preview_image_url, publish_date").order("publish_date",{ascending:!1}).limit(4),q.from("resource_kits").select("id, name, description, featured_image_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),q.from("academy_videos").select("id, title, description, thumbnail_url, duration, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),q.from("additional_services").select("id, name, description, preview_image_url, signup_link_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),q.from("dashboard_banners").select("id, title, description, image_url, link_url, link_text, placement, section_after").eq("is_active",!0).order("sort_order"),q.from("profiles").select("name").eq("id",s==null?void 0:s.id).single()]);(ie=be.data)!=null&&ie.name&&M(be.data.name);const Ze=((he=ve.data)==null?void 0:he.map(Ye=>Ye.tag))||[],Ne=new Set(((ce=Te.data)==null?void 0:ce.map(Ye=>Ye.app_id))||[]);v(Ne);const je=(((pe=ge.data)==null?void 0:pe.filter(Ye=>!Ye.required_tags||Ye.required_tags.length===0?!0:Ye.required_tags.some(We=>Ze.includes(We))))||[]).sort((Ye,We)=>Ye.name==="LevelUp Members Portal"?-1:We.name==="LevelUp Members Portal"?1:0);a(je.slice(0,6));const Ge=((le=Me.data)==null?void 0:le.filter(Ye=>PL(Ye.event_date)!=="ended"))||[];l(Ge.slice(0,4)),b(Ce.data||[]),c(Ae.data||[]),u(De.data||[]),p(Ie.data||[]),g(Fe.data||[]);const Be=qe.data||[];A(Be.filter(Ye=>Ye.placement==="top")),L(Be.filter(Ye=>Ye.placement==="between"))}catch(ve){console.error("Error loading dashboard:",ve),ae.error("Failed to load dashboard data")}finally{z(!1)}},W=async ie=>{var ce;const he=window.open("about:blank","_blank");try{await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:ie.app_id,app_name:ie.name,user_agent:navigator.userAgent});const{data:pe,error:le}=await q.functions.invoke("sso-launch",{body:{app_id:ie.app_id}});if(le)throw le;pe!=null&&pe.redirect_url?he&&!he.closed?(he.location.href=pe.redirect_url,(ce=he.focus)==null||ce.call(he)):window.location.assign(pe.redirect_url):(he==null||he.close(),ae.error("Launch link unavailable"))}catch(pe){he==null||he.close(),console.error("Error launching app:",pe),ae.error("Failed to launch app")}},Y=ie=>j==null?void 0:j.some(he=>he.event_id===ie),K=ie=>{const he=j==null?void 0:j.find(ce=>ce.event_id===ie);return he==null?void 0:he.zoom_join_url};if(F)return e.jsx(Ts,{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 J=ie=>T.filter(he=>he.section_after===ie);return e.jsxs(Ts,{title:"Dashboard",children:[e.jsx(Hns,{events:i,registrations:j,onNavigateToEvents:()=>n("/events")}),S.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(pF,{banners:S})}),e.jsx(Kns,{}),e.jsxs("div",{className:"mb-6",children:[e.jsxs("h2",{className:"text-2xl font-bold text-foreground",children:["Welcome back, ",(D||((ne=s==null?void 0:s.user_metadata)==null?void 0:ne.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(crs,{}),e.jsx(fpt,{}),e.jsx(qrs,{})]}),e.jsx(jrs,{}),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(Oa,{className:"h-4 w-4"})]})]}),i.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(yr,{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(ie=>{const he=Y(ie.id),ce=K(ie.id)||ie.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 ${HUe(ie.event_date)?"bg-red-500/5 border-l-2 border-l-red-500":""}`,onClick:()=>n("/events"),children:[HUe(ie.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(_f,{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(ie.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(ie.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:ie.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(ie.event_date))," at ",xB(new Date(ie.event_date))]})]}),e.jsx("div",{className:"hidden sm:flex flex-shrink-0",children:he?e.jsxs(B,{size:"sm",variant:"default",className:"gap-1",onClick:pe=>{pe.stopPropagation(),window.open(ce,"_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(xa,{className:"h-4 w-4"})]})})]},ie.id)})})]}),J("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(pF,{banners:J("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(Oa,{className:"h-4 w-4"})]})]}),h.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Au,{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(ie=>e.jsxs("div",{onClick:()=>n(`/academy/${ie.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:[ie.thumbnail_url?e.jsx("img",{src:ie.thumbnail_url,alt:ie.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(Au,{className:"h-8 w-8 text-muted-foreground/50"})}),ie.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:ie.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:ie.title})})]},ie.id))})]}),J("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(pF,{banners:J("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(Oa,{className:"h-4 w-4"})]})]}),d.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(gf,{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(ie=>e.jsxs("div",{onClick:()=>n(`/toolbox/${ie.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:ie.featured_image_url?e.jsx("img",{src:ie.featured_image_url,alt:ie.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(gf,{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:ie.name})})]},ie.id))})]}),J("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(pF,{banners:J("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(Oa,{className:"h-4 w-4"})]})]}),o.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(W2,{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(ie=>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:ie.preview_image_url?e.jsx("img",{src:ie.preview_image_url,alt:ie.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(W2,{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:ie.name})})]},ie.id))})]}),J("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(pF,{banners:J("templates")})}),e.jsx("div",{className:"mb-10",children:e.jsx(Urs,{})}),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(Oa,{className:"h-4 w-4"})]})]}),r.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ee,{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Lv,{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(ie=>{const he=_.has(ie.id);return e.jsxs("div",{onClick:()=>W(ie),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:ie.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:ie.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:ie.description})]}),he&&e.jsx(Lv,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},ie.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(Oa,{className:"h-4 w-4"})]})]}),f.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(un,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No additional services available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:f.map(ie=>e.jsxs("div",{onClick:()=>window.open(ie.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:ie.preview_image_url?e.jsx("img",{src:ie.preview_image_url,alt:ie.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(un,{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:ie.name}),ie.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:ie.description})]})]},ie.id))})]})]})};var xpt="AlertDialog",[nas,zxn]=pu(xpt,[Rot]),kN=Rot(),gpt=s=>{const{__scopeAlertDialog:t,...n}=s,r=kN(t);return e.jsx(tye,{...r,...n,modal:!0})};gpt.displayName=xpt;var ras="AlertDialogTrigger",ypt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=kN(n);return e.jsx(GAe,{...a,...r,ref:t})});ypt.displayName=ras;var aas="AlertDialogPortal",vpt=s=>{const{__scopeAlertDialog:t,...n}=s,r=kN(t);return e.jsx(sye,{...r,...n})};vpt.displayName=aas;var ias="AlertDialogOverlay",bpt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=kN(n);return e.jsx(zD,{...a,...r,ref:t})});bpt.displayName=ias;var LL="AlertDialogContent",[oas,las]=nas(LL),cas=Jnt("AlertDialogContent"),_pt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,children:r,...a}=s,i=kN(n),l=N.useRef(null),o=Si(t,l),c=N.useRef(null);return e.jsx(Q7t,{contentName:LL,titleName:wpt,docsSlug:"alert-dialog",children:e.jsx(oas,{scope:n,cancelRef:c,children:e.jsxs(BD,{role:"alertdialog",...i,...a,ref:o,onOpenAutoFocus:_r(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(cas,{children:r}),e.jsx(uas,{contentRef:l})]})})})});_pt.displayName=LL;var wpt="AlertDialogTitle",jpt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=kN(n);return e.jsx(Q$,{...a,...r,ref:t})});jpt.displayName=wpt;var Npt="AlertDialogDescription",kpt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=kN(n);return e.jsx(X$,{...a,...r,ref:t})});kpt.displayName=Npt;var das="AlertDialogAction",Spt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=kN(n);return e.jsx(J$,{...a,...r,ref:t})});Spt.displayName=das;var Cpt="AlertDialogCancel",Tpt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,{cancelRef:a}=las(Cpt,n),i=kN(n),l=Si(t,a);return e.jsx(J$,{...i,...r,ref:l})});Tpt.displayName=Cpt;var uas=({contentRef:s})=>{const t=`\`${LL}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${LL}\` by passing a \`${Npt}\` 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 \`${LL}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component. For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return N.useEffect(()=>{var r;document.getElementById((r=s.current)==null?void 0:r.getAttribute("aria-describedby"))||console.warn(t)},[t,s]),null},has=gpt,mas=ypt,pas=vpt,Ept=bpt,Apt=_pt,Mpt=Spt,Ipt=Tpt,Ppt=jpt,Lpt=kpt;const Oo=has,Ph=mas,fas=pas,Dpt=N.forwardRef(({className:s,...t},n)=>e.jsx(Ept,{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}));Dpt.displayName=Ept.displayName;const Co=N.forwardRef(({className:s,...t},n)=>e.jsxs(fas,{children:[e.jsx(Dpt,{}),e.jsx(Apt,{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})]}));Co.displayName=Apt.displayName;const To=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col space-y-2 text-center sm:text-left",s),...t});To.displayName="AlertDialogHeader";const Eo=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Eo.displayName="AlertDialogFooter";const Ao=N.forwardRef(({className:s,...t},n)=>e.jsx(Ppt,{ref:n,className:Et("text-lg font-semibold",s),...t}));Ao.displayName=Ppt.displayName;const Mo=N.forwardRef(({className:s,...t},n)=>e.jsx(Lpt,{ref:n,className:Et("text-sm text-muted-foreground",s),...t}));Mo.displayName=Lpt.displayName;const jo=N.forwardRef(({className:s,...t},n)=>e.jsx(Mpt,{ref:n,className:Et(v8(),s),...t}));jo.displayName=Mpt.displayName;const Io=N.forwardRef(({className:s,...t},n)=>e.jsx(Ipt,{ref:n,className:Et(v8({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));Io.displayName=Ipt.displayName;const xas=[{key:"contacts",label:"Contacts",icon:Ar,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:e4,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:gf,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:br,description:"View and upload videos"},{key:"listings",label:"Listings",icon:Or,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:Dv,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:ka,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:pf,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:Ou,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:iy,description:"Create and manage smart presentations"}];function gas(){var D;const{user:s}=ys(),[t,n]=N.useState([]),[r,a]=N.useState(!0),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState({email:"",name:"",password:""}),[f,g]=N.useState("create"),[_,v]=N.useState(!1),[j,b]=N.useState(null);N.useEffect(()=>{s&&S()},[s]);const S=async()=>{if(s){a(!0);try{const{data:M,error:F}=await q.from("agent_assistant_assignments").select("id, assistant_id, permissions, created_at").eq("agent_id",s.id);if(F)throw F;if(M&&M.length>0){const z=M.map(Y=>Y.assistant_id),{data:V}=await q.from("profiles").select("id, name, email").in("id",z),W=M.map(Y=>{const K=V==null?void 0:V.find(J=>J.id===Y.assistant_id);return{...Y,permissions:Y.permissions,assistant_profile:K?{name:K.name||"",email:K.email||""}:void 0}});n(W)}else n([])}catch(M){console.error("Error loading assistants:",M)}finally{a(!1)}}},A=async()=>{if(s){if(f==="link"){if(!h.email.trim()){ae.error("Please enter the assistant's email");return}v(!0);try{const{data:{session:M}}=await q.auth.getSession();if(!M)throw new Error("Not authenticated");const{data:F,error:z}=await q.from("profiles").select("id, name, email").eq("email",h.email.trim().toLowerCase()).single();if(z||!F){ae.error("No account found with that email. Try creating a new assistant instead.");return}const{data:V}=await q.from("agent_assistant_assignments").select("id").eq("agent_id",s.id).eq("assistant_id",F.id);if(V&&V.length>0){ae.error("This assistant is already assigned to you");return}const W=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.access_token}`},body:JSON.stringify({userId:F.id,role:"assistant",action:"add",agentId:s.id})}),Y=await W.json();if(!W.ok)throw new Error(Y.error||"Failed to assign assistant role");const{error:K}=await q.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:F.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(K)throw K;ae.success(`${F.name||F.email} linked as your assistant`),l(!1),p({email:"",name:"",password:""}),S()}catch(M){console.error("Error linking assistant:",M),ae.error(M.message||"Failed to link assistant")}finally{v(!1)}return}if(!h.email.trim()||!h.name.trim()||!h.password.trim()){ae.error("Please fill in all fields");return}if(h.password.length<6){ae.error("Password must be at least 6 characters");return}v(!0);try{const{data:{session:M}}=await q.auth.getSession();if(!M)throw new Error("Not authenticated");const F=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.access_token}`},body:JSON.stringify({email:h.email.trim(),password:h.password,name:h.name.trim(),purpose:"assistant"})}),z=await F.json();if(!F.ok)throw new Error(z.error||"Failed to create assistant account");const V=z.userId||z.id;if(!V)throw new Error("No user ID returned");const W=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.access_token}`},body:JSON.stringify({userId:V,role:"assistant",action:"add",agentId:s.id})}),Y=await W.json();if(!W.ok)throw new Error(Y.error||"Failed to assign assistant role");const{error:K}=await q.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:V,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(K)throw K;ae.success(`Assistant account created for ${h.name.trim()}`),l(!1),p({email:"",name:"",password:""}),S()}catch(M){console.error("Error adding assistant:",M),ae.error(M.message||"Failed to add assistant")}finally{v(!1)}}},T=async()=>{if(!(!d||!s))try{const{data:{session:M}}=await q.auth.getSession();if(!M)throw new Error("Not authenticated");const{error:F}=await q.from("agent_assistant_assignments").delete().eq("id",d.id);if(F)throw F;const{data:z}=await q.from("agent_assistant_assignments").select("id").eq("assistant_id",d.assistant_id);(!z||z.length===0)&&await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.access_token}`},body:JSON.stringify({userId:d.assistant_id,role:"assistant",action:"remove"})}),ae.success("Assistant removed"),c(!1),u(null),S()}catch(M){console.error("Error removing assistant:",M),ae.error(M.message||"Failed to remove assistant")}},L=async(M,F,z)=>{b(M);try{const V=t.find(K=>K.id===M);if(!V)return;const W={...V.permissions,[F]:z},{error:Y}=await q.from("agent_assistant_assignments").update({permissions:W}).eq("id",M);if(Y)throw Y;n(K=>K.map(J=>J.id===M?{...J,permissions:W}:J))}catch(V){console.error("Error updating permissions:",V),ae.error("Failed to update permissions")}finally{b(null)}};return r?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5"}),"My Assistants"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5"}),"My Assistants"]}),e.jsx(Vn,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs(B,{size:"sm",onClick:()=>{g("create"),l(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add Assistant"]})]})}),e.jsx(Ee,{children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No assistant assigned. Add one to help manage your contacts, deals, and more."}):e.jsx("div",{className:"space-y-4",children:t.map(M=>{var F,z,V,W;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(aa,{children:((z=(F=M.assistant_profile)==null?void 0:F.name)==null?void 0:z.split(" ").map(Y=>Y[0]).join("").toUpperCase())||"A"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((V=M.assistant_profile)==null?void 0:V.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((W=M.assistant_profile)==null?void 0:W.email)||""})]}),e.jsxs(ze,{variant:"secondary",className:"ml-2",children:[e.jsx(dh,{className:"h-3 w-3 mr-1"}),"Assistant"]})]}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>{u(M),c(!0)},children:e.jsx(_n,{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:xas.map(Y=>{const K=Y.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(K,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:Y.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Y.description})]})]}),e.jsx(bn,{checked:M.permissions[Y.key]||!1,onCheckedChange:J=>L(M.id,Y.key,J),disabled:j===M.id})]},Y.key)})})]})]},M.id)})})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Add Assistant"}),e.jsx(Qn,{children:f==="create"?"Create a new account for your assistant.":"Link an existing assistant account by their email."})]}),e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsxs(B,{variant:f==="create"?"default":"outline",size:"sm",onClick:()=>g("create"),children:[e.jsx(Is,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs(B,{variant:f==="link"?"default":"outline",size:"sm",onClick:()=>g("link"),children:[e.jsx(Jo,{className:"h-3 w-3 mr-1"}),"Link Existing"]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[f==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"assistant-name",children:"Name"}),e.jsx(ye,{id:"assistant-name",value:h.name,onChange:M=>p({...h,name:M.target.value}),placeholder:"Assistant's full name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"assistant-email",children:"Email"}),e.jsx(ye,{id:"assistant-email",type:"email",value:h.email,onChange:M=>p({...h,email:M.target.value}),placeholder:"assistant@email.com"})]}),f==="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:M=>p({...h,password:M.target.value}),placeholder:"Min 6 characters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your assistant can change this after their first login."})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(B,{onClick:A,disabled:_,children:[_&&e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),f==="create"?"Create Assistant":"Link Assistant"]})]})]})}),e.jsx(Oo,{open:o,onOpenChange:c,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Remove Assistant?"}),e.jsxs(Mo,{children:["This will remove ",(D=d==null?void 0:d.assistant_profile)==null?void 0:D.name,"'s access to your Agent OS. Their account will remain active but they won't be able to manage your data."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:T,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function ef(s){this.content=s}ef.prototype={constructor:ef,find:function(s){for(var t=0;t>1}};ef.from=function(s){if(s instanceof ef)return s;var t=[];if(s)for(var n in s)t.push(n,s[n]);return new ef(t)};function Rpt(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=Rpt(a.content,i.content,n+1);if(l!=null)return l}n+=a.nodeSize}}function Opt(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 Ox(r,a)}cutByIndex(t,n){return t==n?Ox.empty:t==0&&n==this.content.length?this:new Ox(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 Ox(a,i)}addToStart(t){return new Ox([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new Ox(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?fH(n+1,i):fH(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 Ox.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Ox(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return Ox.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}};nd.none=[];class Dfe extends Error{}class ja{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=zpt(this.content,t+this.openStart,n);return r&&new ja(r,this.openStart,this.openEnd)}removeBetween(t,n){return new ja(Fpt(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 ja.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 ja(qr.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 ja(t,r,a)}}ja.empty=new ja(qr.empty,0,0);function Fpt(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(Fpt(i.content,t-a-1,n-a-1)))}function zpt(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=zpt(l.content,t-i-1,n,l);return o&&s.replaceChild(a,l.copy(o))}function yas(s,t,n){if(n.openStart>s.depth)throw new Dfe("Inserted content deeper than insertion position");if(s.depth-n.openStart!=t.depth-n.openEnd)throw new Dfe("Inconsistent open depths");return Bpt(s,t,n,0)}function Bpt(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 nz(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&&(GA(s.nodeAfter,r),i++));for(let o=i;oa&&_Ce(s,t,a+1),l=r.depth>a&&_Ce(n,r,a+1),o=[];return nz(null,s,a,o),i&&l&&t.index(a)==n.index(a)?($pt(i,l),GA(WA(i,Upt(s,t,n,r,a+1)),o)):(i&&GA(WA(i,Rfe(s,t,a+1)),o),nz(t,n,a,o),l&&GA(WA(l,Rfe(n,r,a+1)),o)),nz(r,null,a,o),new qr(o)}function Rfe(s,t,n){let r=[];if(nz(null,s,n,r),s.depth>n){let a=_Ce(s,t,n+1);GA(WA(a,Rfe(s,t,n+1)),r)}return nz(t,null,n,r),new qr(r)}function vas(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(qr.from(a));return{start:a.resolveNoCache(s.openStart+n),end:a.resolveNoCache(a.content.size-s.openEnd-n)}}class gB{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 Ofe(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 gB(n,r,i)}static resolveCached(t,n){let r=KUe.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()+")"),qpt(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=qr.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=qr.fromJSON(t,n.content),i=t.nodeType(n.type).create(n.attrs,a,r);return i.type.checkAttrs(i.attrs),i}};x4.prototype.text=void 0;class Ffe extends x4{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):qpt(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 Ffe(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new Ffe(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 qpt(s,t){for(let n=s.length-1;n>=0;n--)t=s[n].type.name+"("+t+")";return t}class _M{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new jas(t,n);if(r.next==null)return _M.empty;let a=Vpt(r);r.next&&r.err("Unexpected trailing text");let i=Aas(Eas(a));return Mas(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(` `)}}_M.empty=new _M(!0);class jas{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 Vpt(s){let t=[];do t.push(Nas(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function Nas(s){let t=[];do t.push(kas(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function kas(s){let t=Tas(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=Sas(s,t);else break;return t}function YUe(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let t=Number(s.next);return s.pos++,t}function Sas(s,t){let n=YUe(s),r=n;return s.eat(",")&&(s.next!="}"?r=YUe(s):r=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:t}}function Cas(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 Tas(s){if(s.eat("(")){let t=Vpt(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=Cas(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 Eas(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 _M(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:Wpt(this.attrs,t)}create(t=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new x4(this,this.computeAttrs(t),qr.from(n),nd.setFrom(r))}createChecked(t=null,n,r){return n=qr.from(n),this.checkContent(n),new x4(this,this.computeAttrs(t),n,nd.setFrom(r))}createAndFill(t=null,n,r){if(t=this.computeAttrs(t),n=qr.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(qr.empty,!0);return i?new x4(this,t,n.append(i),nd.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 Zpt(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 Ias(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 Pas{constructor(t,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Ias(t,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Gye{constructor(t,n,r,a){this.name=t,this.rank=n,this.schema=r,this.spec=a,this.attrs=Ypt(t,a.attrs),this.excluded=null;let i=Gpt(this.attrs);this.instance=i?new nd(this,i):null}create(t=null){return!t&&this.instance?this.instance:new nd(this,Wpt(this.attrs,t))}static compile(t,n){let r=Object.create(null),a=0;return t.forEach((i,l)=>r[i]=new Gye(i,a++,n,l)),r}removeFromSet(t){for(var n=0;n-1}}class Qpt{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=ef.from(t.nodes),n.marks=ef.from(t.marks||{}),this.nodes=QUe.compile(this.spec.nodes,this),this.marks=Gye.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]=_M.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?XUe(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==""?[]:XUe(this,l.split(" "))}this.nodeFromJSON=a=>x4.fromJSON(this,a),this.markFromJSON=a=>nd.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 QUe){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 Ffe(r,r.defaultAttrs,t,nd.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 XUe(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 Las(s){return s.tag!=null}function Das(s){return s.style!=null}let rz=class jCe{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(a=>{if(Las(a))this.tags.push(a);else if(Das(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 eqe(this,n,!1);return r.addAll(t,nd.none,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new eqe(this,n,!0);return r.addAll(t,nd.none,n.from,n.to),ja.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=tqe(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=tqe(l)),l.node||l.ignore||l.mark||(l.node=a)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new jCe(t,jCe.schemaRules(t)))}};const Xpt={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},Ras={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Jpt={ol:!0,ul:!0},yB=1,NCe=2,az=4;function JUe(s,t,n){return t!=null?(t?yB:0)|(t==="full"?NCe:0):s&&s.whitespace=="pre"?yB|NCe:n&~az}class xH{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=nd.none,this.match=i||(l&az?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(qr.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&yB)){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=qr.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(qr.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&&!Xpt.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class eqe{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=JUe(null,n.preserveWhitespace,0)|(r?az:0);a?i=new xH(a.type,a.attrs,nd.none,!0,n.topMatch||a.type.contentMatch,l):r?i=new xH(null,null,nd.none,!0,null,l):i=new xH(t.schema.topNodeType,null,nd.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&NCe?"full":this.localPreserveWS||(a.options&yB)>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):sqe(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new xH(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|=yB)}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 Oas(s){for(let t=s.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&Jpt.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function Fas(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function tqe(s){let t={};for(let n in s)t[n]=s[n];return t}function sqe(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&&Gme(Vje(r),a(t,n),null,t.attrs)}static renderSpec(t,n,r=null,a){return Gme(t,n,r,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new WM(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=nqe(t.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(t){return nqe(t.marks)}}function nqe(s){let t={};for(let n in s){let r=s[n].spec.toDOM;r&&(t[n]=r)}return t}function Vje(s){return s.document||window.document}const rqe=new WeakMap;function zas(s){let t=rqe.get(s);return t===void 0&&rqe.set(s,t=Bas(s)),t}function Bas(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 p=h.indexOf(" ");p>0?c.setAttributeNS(h.slice(0,p),h.slice(p+1),d[h]):h=="style"&&c.style?c.style.cssText=d[h]:c.setAttribute(h,d[h])}}for(let h=u;hu)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:f,contentDOM:g}=Gme(s,p,n,r);if(c.appendChild(f),g){if(o)throw new RangeError("Multiple content holes");o=g}}}return{dom:c,contentDOM:o}}const eft=65535,tft=Math.pow(2,16);function $as(s,t){return s+t*tft}function aqe(s){return s&eft}function Uas(s){return(s-(s&eft))/tft}const sft=1,nft=2,Wme=4,rft=8;class kCe{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&rft)>0}get deletedBefore(){return(this.delInfo&(sft|Wme))>0}get deletedAfter(){return(this.delInfo&(nft|Wme))>0}get deletedAcross(){return(this.delInfo&Wme)>0}}class Z0{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&Z0.empty)return Z0.empty}recover(t){let n=0,r=aqe(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 p=d?t==c?-1:t==h?1:n:n,f=c+a+(p<0?0:u);if(r)return f;let g=t==(n<0?c:h)?null:$as(o/3,t-c),_=t==c?nft:t==h?sft:Wme;return(n<0?t!=c:t!=h)&&(_|=rft),new kCe(f,_,g)}a+=u-d}return r?t+a:new kCe(t+a,0,null)}touches(t,n){let r=0,a=aqe(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 vB;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 tm.fromReplace(t,this.from,this.to,i)}invert(){return new aw(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 IS(n.pos,r.pos,this.mark)}merge(t){return t instanceof IS&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new IS(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 IS(n.from,n.to,t.markFromJSON(n.mark))}}lx.jsonID("addMark",IS);class aw extends lx{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 ja(N6e(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),n.openStart,n.openEnd);return tm.fromReplace(t,this.from,this.to,r)}invert(){return new IS(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 aw(n.pos,r.pos,this.mark)}merge(t){return t instanceof aw&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new aw(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 aw(n.from,n.to,t.markFromJSON(n.mark))}}lx.jsonID("removeMark",aw);class PS extends lx{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return tm.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return tm.fromReplace(t,this.pos,this.pos+1,new ja(qr.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 Ep(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 Ep(n.from,n.to,n.gapFrom,n.gapTo,ja.fromJSON(t,n.slice),n.insert,!!n.structure)}}lx.jsonID("replaceAround",Ep);function SCe(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 qas(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 p=Math.max(d,t),f=Math.min(d+c.nodeSize,n),g=r.addToSet(h);for(let _=0;_s.step(c)),i.forEach(c=>s.step(c))}function Vas(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 Gye){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 aw(l.from,l.to,l.style)))}function k6e(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 Has(s,t,n){return(t==0||s.canReplace(t,s.childCount))&&(n==s.childCount||s.canReplace(0,n))}function QD(s){let n=s.parent.content.cutByIndex(s.startIndex,s.endIndex);for(let r=s.depth,a=0,i=0;;--r){let l=s.$from.node(r),o=s.$from.index(r)+a,c=s.$to.indexAfter(r)-i;if(rn;g--)_||r.index(g)>0?(_=!0,u=qr.from(r.node(g).copy(u)),h++):c--;let p=qr.empty,f=0;for(let g=i,_=!1;g>n;g--)_||a.after(g+1)=0;l--){if(r.size){let o=n[l].type.contentMatch.matchFragment(r);if(!o||!o.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=qr.from(n[l].type.create(n[l].attrs,r))}let a=t.start,i=t.end;s.step(new Ep(a,i,a,i,new ja(r,0,0),n.length,!0))}function Zas(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)&&Qas(s.doc,s.mapping.slice(i).map(o),r)){let d=null;if(r.schema.linebreakReplacement){let f=r.whitespace=="pre",g=!!r.contentMatch.matchType(r.schema.linebreakReplacement);f&&!g?d=!1:!f&&g&&(d=!0)}d===!1&&ift(s,l,o,i),k6e(s,s.mapping.slice(i).map(o,1),r,void 0,d===null);let u=s.mapping.slice(i),h=u.map(o,1),p=u.map(o+l.nodeSize,1);return s.step(new Ep(h,p,h+1,p-1,new ja(qr.from(r.create(c,null,l.marks)),0,0),1,!0)),d===!0&&aft(s,l,o,i),!1}})}function aft(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 ift(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 Qas(s,t,n){let r=s.resolve(t),a=r.index();return r.parent.canReplaceWith(a,a+1,n)}function Xas(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 Ep(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new ja(qr.from(l),0,0),1,!0))}function DL(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),p=a.index(d);if(h.type.spec.isolating)return!1;let f=h.content.cutByIndex(p,h.childCount),g=r&&r[u+1];g&&(f=f.replaceChild(0,g.type.create(g.attrs)));let _=r&&r[u]||h;if(!h.canReplace(p+1,h.childCount)||!_.type.validContent(f))return!1}let o=a.indexAfter(i),c=r&&r[0];return a.node(i).canReplaceWith(o,o,c?c.type:a.node(i+1).type)}function Jas(s,t,n=1,r){let a=s.doc.resolve(t),i=qr.empty,l=qr.empty;for(let o=a.depth,c=a.depth-n,d=n-1;o>c;o--,d--){i=qr.from(a.node(o).copy(i));let u=r&&r[d];l=qr.from(u?u.type.create(u.attrs,l):a.node(o).copy(l))}s.step(new Zh(t,t,new ja(i.append(l),n,n),!0))}function eC(s,t){let n=s.resolve(t),r=n.index();return oft(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function eis(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&&oft(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 tis(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);ift(s,u.node(),u.before(),o)}l.inlineContent&&k6e(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 Zh(d,c.map(t+n,-1),ja.empty,!0)),r===!0){let u=s.doc.resolve(d);aft(s,u.node(),u.before(),s.steps.length)}return s}function sis(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 Kye(s,t,n=t,r=ja.empty){if(t==n&&!r.size)return null;let a=s.resolve(t),i=s.resolve(n);return cft(a,i,r)?new Zh(t,n,r):new nis(a,i,r).fit()}function cft(s,t,n){return!n.openStart&&!n.openEnd&&s.start()==t.start()&&s.parent.canReplace(s.index(),t.index(),n.content)}class nis{constructor(t,n,r){this.$from=t,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=qr.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=qr.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 ja(i,l,o);return t>-1?new Ep(r.pos,t,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new Zh(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=Gje(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(qr.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=Gje(t,n);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new ja(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=Gje(t,n);if(a.childCount<=1&&n>0){let i=t.size-n<=n+a.size;this.unplaced=new ja(p7(t,n-1,1),n-1,i?n-1:r)}else this.unplaced=new ja(p7(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 _=0;_1||c==0||_.content.size)&&(h=v,u.push(dft(_.mark(p.allowedMarks(_.marks)),d==1?c:0,d==o.childCount?f:-1)))}let g=d==o.childCount;g||(f=-1),this.placed=f7(this.placed,n,qr.from(u)),this.frontier[n].match=h,g&&f<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let _=0,v=o;_1&&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=Wje(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=f7(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=f7(this.placed,this.depth,qr.from(t.create(n,r))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(qr.empty,!0);n.childCount&&(this.placed=f7(this.placed,this.frontier.length,n))}}function p7(s,t,n){return t==0?s.cutByIndex(n,s.childCount):s.replaceChild(0,s.firstChild.copy(p7(s.firstChild.content,t-1,n)))}function f7(s,t,n){return t==0?s.append(n):s.replaceChild(s.childCount-1,s.lastChild.copy(f7(s.lastChild.content,t-1,n)))}function Gje(s,t){for(let n=0;n1&&(r=r.replaceChild(0,dft(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(qr.empty,!0)))),s.copy(r)}function Wje(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&&!ris(n,i.content,l)?o:null}function ris(s,t,n){for(let r=n;r0;p--,f--){let g=a.node(p).type.spec;if(g.defining||g.definingAsContext||g.isolating)break;l.indexOf(p)>-1?o=p:a.before(p)==f&&l.splice(1,0,-p)}let c=l.indexOf(o),d=[],u=r.openStart;for(let p=r.content,f=0;;f++){let g=p.firstChild;if(d.push(g),f==r.openStart)break;p=g.content}for(let p=u-1;p>=0;p--){let f=d[p],g=ais(f.type);if(g&&!f.sameMarkup(a.node(Math.abs(o)-1)))u=p;else if(g||!f.type.isTextblock)break}for(let p=r.openStart;p>=0;p--){let f=(p+u+1)%(r.openStart+1),g=d[f];if(g)for(let _=0;_=0&&(s.replace(t,n,r),!(s.steps.length>h));p--){let f=l[p];f<0||(t=a.before(f),n=i.after(f))}}function uft(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(qr.empty,!0))}return s}function ois(s,t,n,r){if(!r.isInline&&t==n&&s.doc.resolve(t).parent.content.size){let a=sis(s.doc,t,r.type);a!=null&&(t=n=a)}s.replaceRange(t,n,new ja(qr.from(r),0,0))}function lis(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=hft(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 hft(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 RL extends lx{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 tm.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 tm.fromReplace(t,this.pos,this.pos+1,new ja(qr.from(a),0,n.isLeaf?0:1))}getMap(){return Z0.empty}invert(t){return new RL(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 RL(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 RL(n.pos,n.attr,n.value)}}lx.jsonID("attr",RL);class bB extends lx{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 tm.ok(r)}getMap(){return Z0.empty}invert(t){return new bB(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 bB(n.attr,n.value)}}lx.jsonID("docAttr",bB);let T8=class extends Error{};T8=function s(t){let n=Error.call(this,t);return n.__proto__=s.prototype,n};T8.prototype=Object.create(Error.prototype);T8.prototype.constructor=T8;T8.prototype.name="TransformError";let C6e=class{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new vB}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new T8(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=ja.empty){let a=Kye(this.doc,t,n,r);return a&&this.step(a),this}replaceWith(t,n,r){return this.replace(t,n,new ja(qr.from(r),0,0))}delete(t,n){return this.replace(t,n,ja.empty)}insert(t,n){return this.replaceWith(t,t,n)}replaceRange(t,n,r){return iis(this,t,n,r),this}replaceRangeWith(t,n,r){return ois(this,t,n,r),this}deleteRange(t,n){return lis(this,t,n),this}lift(t,n){return Gas(this,t,n),this}join(t,n=1){return tis(this,t,n),this}wrap(t,n){return Yas(this,t,n),this}setBlockType(t,n=t,r,a=null){return Zas(this,t,n,r,a),this}setNodeMarkup(t,n,r=null,a){return Xas(this,t,n,r,a),this}setNodeAttribute(t,n,r){return this.step(new RL(t,n,r)),this}setDocAttribute(t,n){return this.step(new bB(t,n)),this}addNodeMark(t,n){return this.step(new PS(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 nd)n.isInSet(r.marks)&&this.step(new wM(t,n));else{let a=r.marks,i,l=[];for(;i=n.isInSet(a);)l.push(new wM(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 Jas(this,t,n,r),this}addMark(t,n,r){return qas(this,t,n,r),this}removeMark(t,n,r){return Vas(this,t,n,r),this}clearIncompatible(t,n,r){return k6e(this,t,n,r),this}};const Kje=Object.create(null);class no{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new mft(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?oP(t.node(0),t.node(i),t.before(i+1),t.index(i),n,r):oP(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 Uv(t.node(0))}static atStart(t){return oP(t,t,0,0,1)||new Uv(t)}static atEnd(t){return oP(t,t,t.content.size,t.childCount,-1)||new Uv(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Kje[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 Kje)throw new RangeError("Duplicate use of selection JSON ID "+t);return Kje[t]=n,n.prototype.jsonID=t,n}getBookmark(){return Ki.between(this.$anchor,this.$head).getBookmark()}}no.prototype.visible=!0;class mft{constructor(t,n){this.$from=t,this.$to=n}}let oqe=!1;function lqe(s){!oqe&&!s.parent.inlineContent&&(oqe=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class Ki extends no{constructor(t,n=t){lqe(t),lqe(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 no.near(r);let a=t.resolve(n.map(this.anchor));return new Ki(a.parent.inlineContent?a:r,r)}replace(t,n=ja.empty){if(super.replace(t,n),n==ja.empty){let r=this.$from.marksAcross(this.$to);r&&t.ensureMarks(r)}}eq(t){return t instanceof Ki&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new Yye(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 Ki(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=no.findFrom(n,r,!0)||no.findFrom(n,-r,!0);if(i)n=i.$head;else return no.near(n,r)}return t.parent.inlineContent||(a==0?t=n:(t=(no.findFrom(t,-r,!0)||no.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&&Fi.isSelectable(o))return Fi.create(s,n-(a<0?o.nodeSize:0))}else{let c=oP(s,o,n+a,a<0?o.childCount:0,a,i);if(c)return c}n+=o.nodeSize*a}return null}function cqe(s,t,n){let r=s.steps.length-1;if(r{l==null&&(l=u)}),s.setSelection(no.near(s.doc.resolve(l),n))}const dqe=1,gH=2,uqe=4;class dis extends C6e{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|=gH,this}ensureMarks(t){return nd.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&gH)>0}addStep(t,n){super.addStep(t,n),this.updated=this.updated&~gH,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)||nd.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(no.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|=uqe,this}get scrolledIntoView(){return(this.updated&uqe)>0}}function hqe(s,t){return!t||!s?s:s.bind(t)}class x7{constructor(t,n,r){this.name=t,this.init=hqe(n.init,r),this.apply=hqe(n.apply,r)}}const uis=[new x7("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new x7("selection",{init(s,t){return s.selection||no.atStart(t.doc)},apply(s){return s.selection}}),new x7("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,n,r){return r.selection.$cursor?s.storedMarks:null}}),new x7("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class Yje{constructor(t,n){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=uis.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 x7(r.key,r.spec.state,r))})}}class AP{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 Yje(t.schema,t.plugins),i=new AP(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=x4.fromJSON(t.schema,n.doc);else if(l.name=="selection")i.selection=no.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 pft(s,t,n){for(let r in s){let a=s[r];a instanceof Function?a=a.bind(t):r=="handleDOMEvents"&&(a=pft(a,t,{})),n[r]=a}return n}class Ym{constructor(t){this.spec=t,this.props={},t.props&&pft(t.props,this,this.props),this.key=t.key?t.key.key:fft("plugin")}getState(t){return t[this.key]}}const Zje=Object.create(null);function fft(s){return s in Zje?s+"$"+ ++Zje[s]:(Zje[s]=0,s+"$")}class cx{constructor(t="key"){this.key=fft(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const rf=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},E8=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let CCe=null;const w2=function(s,t,n){let r=CCe||(CCe=document.createRange());return r.setEnd(s,n??s.nodeValue.length),r.setStart(s,t||0),r},his=function(){CCe=null},jM=function(s,t,n,r){return n&&(mqe(s,t,n,r,-1)||mqe(s,t,n,r,1))},mis=/^(img|br|input|textarea|hr)$/i;function mqe(s,t,n,r,a){for(var i;;){if(s==n&&t==r)return!0;if(t==(a<0?0:jv(s))){let l=s.parentNode;if(!l||l.nodeType!=1||xU(s)||mis.test(s.nodeName)||s.contentEditable=="false")return!1;t=rf(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?jv(s):0}else return!1}}function jv(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function pis(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=jv(s)}else if(s.parentNode&&!xU(s))t=rf(s),s=s.parentNode;else return null}}function fis(s,t){for(;;){if(s.nodeType==3&&t2),yv=A8||(Pw?/Mac/.test(Pw.platform):!1),yft=Pw?/Win/.test(Pw.platform):!1,F2=/Android \d/.test(tC),gU=!!pqe&&"webkitFontSmoothing"in pqe.documentElement.style,vis=gU?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function bis(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 r2(s,t){return typeof s=="number"?s:s[t]}function _is(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 fqe(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=E8(l);continue}let o=l,c=o==i.body,d=c?bis(i):_is(o),u=0,h=0;if(t.topd.bottom-r2(r,"bottom")&&(h=t.bottom-t.top>d.bottom-d.top?t.top+r2(a,"top")-d.top:t.bottom-d.bottom+r2(a,"bottom")),t.leftd.right-r2(r,"right")&&(u=t.right-d.right+r2(a,"right")),u||h)if(c)i.defaultView.scrollBy(u,h);else{let f=o.scrollLeft,g=o.scrollTop;h&&(o.scrollTop+=h),u&&(o.scrollLeft+=u);let _=o.scrollLeft-f,v=o.scrollTop-g;t={left:t.left-_,top:t.top-v,right:t.right-_,bottom:t.bottom-v}}let p=c?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(p))break;l=p=="absolute"?l.offsetParent:E8(l)}}function wis(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:vft(s.dom)}}function vft(s){let t=[],n=s.ownerDocument;for(let r=s;r&&(t.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),s!=n);r=E8(r));return t}function jis({refDOM:s,refTop:t,stack:n}){let r=s?s.getBoundingClientRect().top:0;bft(n,r==0?0:r-t)}function bft(s,t){for(let n=0;n=o){l=Math.max(g.bottom,l),o=Math.min(g.top,o);let _=g.left>t.left?g.left-t.left:g.right=(g.left+g.right)/2?1:0));continue}}else g.top>t.top&&!c&&g.left<=t.left&&g.right>=t.left&&(c=u,d={left:Math.max(g.left,Math.min(g.right,t.left)),top:g.top});!n&&(t.left>=g.right&&t.top>=g.top||t.left>=g.left&&t.top>=g.bottom)&&(i=h+1)}}return!n&&c&&(n=c,a=d,r=0),n&&n.nodeType==3?kis(n,a):!n||r&&n.nodeType==1?{node:s,offset:i}:_ft(n,a)}function kis(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 E6e(s,t){return s.left>=t.left-1&&s.left<=t.right+1&&s.top>=t.top-1&&s.top<=t.bottom+1}function Sis(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 Tis(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 wft(s,t,n){let r=s.childNodes.length;if(r&&n.topt.top&&a++}let d;gU&&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=Tis(s,r,a,t))}o==null&&(o=Cis(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function xqe(s){return s.top=0&&a==r.nodeValue.length?(c--,u=1):n<0?c--:d++,fF(Uk(w2(r,c,d),u),u<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(n<0||a==jv(r))){let c=r.childNodes[a-1];if(c.nodeType==1)return Qje(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(n<0||a==jv(r))){let c=r.childNodes[a-1],d=c.nodeType==3?w2(c,jv(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return fF(Uk(d,1),!1)}if(i==null&&a=0)}function fF(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 Qje(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 Nft(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 Mis(s,t,n){let r=t.selection,a=n=="up"?r.$from:r.$to;return Nft(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=jft(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=w2(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 Iis=/[\u0590-\u08ac]/;function Pis(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?!Iis.test(r.parent.textContent)||!o.modify?n=="left"||n=="backward"?i:l:Nft(s,t,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:h}=s.domSelectionRange(),p=o.caretBidiLevel;o.modify("move",n,"character");let f=r.depth?s.docView.domAfterPos(r.before()):s.dom,{focusNode:g,focusOffset:_}=s.domSelectionRange(),v=g&&!f.contains(g.nodeType==1?g:g.parentNode)||c==g&&d==_;try{o.collapse(u,h),c&&(c!=u||d!=h)&&o.extend&&o.extend(c,d)}catch{}return p!=null&&(o.caretBidiLevel=p),v}):r.pos==r.start()||r.pos==r.end()}let gqe=null,yqe=null,vqe=!1;function Lis(s,t,n){return gqe==t&&yqe==n?vqe:(gqe=t,yqe=n,vqe=n=="up"||n=="down"?Mis(s,t,n):Pis(s,t,n))}const Vv=0,bqe=1,ZE=2,Lw=3;class yU{constructor(t,n,r,a){this.parent=t,this.children=n,this.dom=r,this.contentDOM=a,this.dirty=Vv,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;nrf(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 Sft){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 kft&&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?rf(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 p=this.children[h-1];if(p.size&&p.dom.parentNode==this.contentDOM&&!p.emptyChildAt(1)){a=rf(p.dom)+1;break}t-=p.size}a==-1&&(a=0)}if(a>-1&&(d>n||o==this.children.length-1)){n=d;for(let u=o+1;ug&&ln){let g=o;o=c,c=g}let f=document.createRange();f.setEnd(c.node,c.offset),f.setStart(o.node,o.offset),d.removeAllRanges(),d.addRange(f)}}ignoreMutation(t){return!this.contentDOM&&t.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,n){for(let r=0,a=0;a=r:tr){let o=r+i.border,c=l-i.border;if(t>=o&&n<=c){this.dirty=t==r||n==l?ZE:bqe,t==o&&n==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=Lw:i.markDirty(t-o,n-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?ZE:Lw}r=l}this.dirty=ZE}markParentsDirty(){let t=1;for(let n=this.parent;n;n=n.parent,t++){let r=t==1?ZE:bqe;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==Vv&&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 Dis extends yU{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 NM extends yU{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=WM.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new NM(t,n,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&Lw||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=Lw&&this.mark.eq(t)}markDirty(t,n){if(super.markDirty(t,n),this.dirty!=Vv){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(i=ICe(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}=WM.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 p=u;return u=Eft(u,r,n),d?c=new Ris(t,n,r,a,u,h||null,p,d,i,l+1):n.isText?new Qye(t,n,r,a,u,p,i):new y4(t,n,r,a,u,h||null,p,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=()=>qr.empty)}return t}matchesNode(t,n,r){return this.dirty==Vv&&t.eq(this.node)&&zfe(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 Fis(this,l&&l.node,t);$is(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?nd.none:this.node.child(u).marks,r,t,u),c.placeWidget(d,t,a)},(d,u,h,p)=>{c.syncToMarks(d.marks,r,t,p);let f;c.findNodeMatch(d,u,h,p)||o&&t.state.selection.from>a&&t.state.selection.to-1&&c.updateNodeAt(d,u,h,f,t)||c.updateNextNode(d,u,h,t,p,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==ZE)&&(l&&this.protectLocalComposition(t,l),Cft(this.contentDOM,this.children,t),A8&&Uis(this.dom))}localCompositionInfo(t,n){let{from:r,to:a}=t.state.selection;if(!(t.state.selection instanceof Ki)||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=qis(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 Dis(this,i,n,a);t.input.compositionNodes.push(l),this.children=ICe(this.children,r,r+a.length,t,l)}update(t,n,r,a){return this.dirty==Lw||!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=Vv}updateOuterDeco(t){if(zfe(t,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Tft(this.dom,this.nodeDOM,MCe(this.outerDeco,this.node,n),MCe(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 _qe(s,t,n,r,a){Eft(r,t,s);let i=new y4(void 0,s,t,n,r,r,r,a,0);return i.contentDOM&&i.updateChildren(a,0),i}class Qye extends y4{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==Lw||this.dirty!=Vv&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=Vv||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=Vv,!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 Qye(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=Lw)}get domAtom(){return!1}isText(t){return this.node.text==t}}class Sft extends yU{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==Vv&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Ris extends y4{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==Lw)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 Cft(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=NM.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 NM)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 Bis(s,t){return s.type.side-t.type.side}function $is(s,t,n,r){let a=t.locals(s),i=0;if(a.length==0){for(let d=0;di;)o.push(a[l++]);let g=i+p.nodeSize;if(p.isText){let v=g;l!v.inline):o.slice();r(p,_,t.forChild(i,p),f),i=g}}function Uis(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 qis(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 ICe(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 A6e(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(Zye(n)){for(c=l;a&&!a.node;)a=a.parent;let h=a.node;if(a&&h.isAtom&&Fi.isSelectable(h)&&a.parent&&!(h.isInline&&xis(n.focusNode,n.focusOffset,a.dom))){let p=a.posBefore;d=new Fi(l==p?o:r.resolve(p))}}else{if(n instanceof s.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let h=l,p=l;for(let f=0;f{(n.anchorNode!=r||n.anchorOffset!=a)&&(t.removeEventListener("selectionchange",s.input.hideSelectionGuard),setTimeout(()=>{(!Aft(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function His(s){let t=s.domSelection();if(!t)return;let n=s.cursorWrapper.dom,r=n.nodeName=="IMG";r?t.collapse(n.parentNode,rf(n)+1):t.collapse(n,0),!r&&!s.state.selection.visible&&Wg&&g4<=11&&(n.disabled=!0,n.disabled=!1)}function Mft(s,t){if(t instanceof Fi){let n=s.docView.descAt(t.from);n!=s.lastSelectedViewDesc&&(Sqe(s),n&&n.selectNode(),s.lastSelectedViewDesc=n)}else Sqe(s)}function Sqe(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function M6e(s,t,n,r){return s.someProp("createSelectionBetween",a=>a(s,t,n))||Ki.between(t,n,r)}function Cqe(s){return s.editable&&!s.hasFocus()?!1:Ift(s)}function Ift(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 Gis(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),n=s.domSelectionRange();return jM(t.node,t.offset,n.anchorNode,n.anchorOffset)}function PCe(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&&no.findFrom(i,t)}function Xk(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function Tqe(s,t,n){let r=s.state.selection;if(r instanceof Ki)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 Xk(s,new Ki(r.$anchor,l))}else if(r.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=PCe(s.state,t);return a&&a instanceof Fi?Xk(s,a):!1}else if(!(yv&&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?Fi.isSelectable(i)?Xk(s,new Fi(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):gU?Xk(s,new Ki(s.state.doc.resolve(t<0?o:o+i.nodeSize))):!1:!1}}else return!1;else{if(r instanceof Fi&&r.node.isInline)return Xk(s,new Ki(t>0?r.$to:r.$from));{let a=PCe(s.state,t);return a?Xk(s,a):!1}}}function Bfe(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function oz(s,t){let n=s.pmViewDesc;return n&&n.size==0&&(t<0||s.nextSibling||s.nodeName!="BR")}function NI(s,t){return t<0?Wis(s):Kis(s)}function Wis(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a,i,l=!1;for(qv&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let o=n.childNodes[r-1];if(oz(o,-1))a=n,i=--r;else if(o.nodeType==3)n=o,r=n.nodeValue.length;else break}}else{if(Pft(n))break;{let o=n.previousSibling;for(;o&&oz(o,-1);)a=n.parentNode,i=rf(o),o=o.previousSibling;if(o)n=o,r=Bfe(n);else{if(n=n.parentNode,n==s.dom)break;r=0}}}l?LCe(s,n,r):a&&LCe(s,a,i)}function Kis(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a=Bfe(n),i,l;for(;;)if(r{s.state==a&&tN(s)},50)}function Eqe(s,t){let n=s.state.doc.resolve(t);if(!(uf||yft)&&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 Aqe(s,t,n){let r=s.state.selection;if(r instanceof Ki&&!r.empty||n.indexOf("s")>-1||yv&&n.indexOf("m")>-1)return!1;let{$from:a,$to:i}=r;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=PCe(s.state,t);if(l&&l instanceof Fi)return Xk(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=r instanceof Uv?no.near(l,t):no.findFrom(l,t);return o?Xk(s,o):!1}return!1}function Mqe(s,t){if(!(s.state.selection instanceof Ki))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 Iqe(s,t,n){s.domObserver.stop(),t.contentEditable=n,s.domObserver.start()}function Qis(s){if(!rx||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;Iqe(s,r,"true"),setTimeout(()=>Iqe(s,r,"false"),20)}return!1}function Xis(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function Jis(s,t){let n=t.keyCode,r=Xis(t);if(n==8||yv&&n==72&&r=="c")return Mqe(s,-1)||NI(s,-1);if(n==46&&!t.shiftKey||yv&&n==68&&r=="c")return Mqe(s,1)||NI(s,1);if(n==13||n==27)return!0;if(n==37||yv&&n==66&&r=="c"){let a=n==37?Eqe(s,s.state.selection.from)=="ltr"?-1:1:-1;return Tqe(s,a,r)||NI(s,a)}else if(n==39||yv&&n==70&&r=="c"){let a=n==39?Eqe(s,s.state.selection.from)=="ltr"?1:-1:1;return Tqe(s,a,r)||NI(s,a)}else{if(n==38||yv&&n==80&&r=="c")return Aqe(s,-1,r)||NI(s,-1);if(n==40||yv&&n==78&&r=="c")return Qis(s)||Aqe(s,1,r)||NI(s,1);if(r==(yv?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function I6e(s,t){s.someProp("transformCopied",f=>{t=f(t,s)});let n=[],{content:r,openStart:a,openEnd:i}=t;for(;a>1&&i>1&&r.childCount==1&&r.firstChild.childCount==1;){a--,i--;let f=r.firstChild;n.push(f.type.name,f.attrs!=f.type.defaultAttrs?f.attrs:null),r=f.content}let l=s.someProp("clipboardSerializer")||WM.fromSchema(s.state.schema),o=zft(),c=o.createElement("div");c.appendChild(l.serializeFragment(r,{document:o}));let d=c.firstChild,u,h=0;for(;d&&d.nodeType==1&&(u=Fft[d.nodeName.toLowerCase()]);){for(let f=u.length-1;f>=0;f--){let g=o.createElement(u[f]);for(;c.firstChild;)g.appendChild(c.firstChild);c.appendChild(g),h++}d=c.firstChild}d&&d.nodeType==1&&d.setAttribute("data-pm-slice",`${a} ${i}${h?` -${h}`:""} ${JSON.stringify(n)}`);let p=s.someProp("clipboardTextSerializer",f=>f(t,s))||t.content.textBetween(0,t.content.size,` `);return{dom:c,text:p,slice:t}}function Lft(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",p=>{t=p(t,i||r,s)}),i)return o=new ja(qr.from(s.state.schema.text(t.replace(/\r\n?/g,` `))),0,0),s.someProp("transformPasted",p=>{o=p(o,s,!0)}),o;let h=s.someProp("clipboardTextParser",p=>p(t,a,r,s));if(h)o=h;else{let p=a.marks(),{schema:f}=s.state,g=WM.fromSchema(f);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(_=>{let v=l.appendChild(document.createElement("p"));_&&v.appendChild(g.serializeNode(f.text(_,p)))})}}else s.someProp("transformPastedHTML",h=>{n=h(n,s)}),l=nos(n),gU&&ros(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 p=l.firstChild;for(;p&&p.nodeType!=1;)p=p.nextSibling;if(!p)break;l=p}if(o||(o=(s.someProp("clipboardParser")||s.someProp("domParser")||rz.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||u),context:a,ruleFromNode(p){return p.nodeName=="BR"&&!p.nextSibling&&p.parentNode&&!eos.test(p.parentNode.nodeName)?{ignore:!0}:null}})),u)o=aos(Pqe(o,+u[1],+u[2]),u[4]);else if(o=ja.maxOpen(tos(o.content,a),!0),o.openStart||o.openEnd){let h=0,p=0;for(let f=o.content.firstChild;h{o=h(o,s,c)}),o}const eos=/^(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 tos(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&&Rft(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=Oft(l[l.length-1],i.length));let u=Dft(o,c);l.push(u),a=a.matchType(u.type),i=c}}),l)return qr.from(l)}return s}function Dft(s,t,n=0){for(let r=t.length-1;r>=n;r--)s=t[r].create(null,qr.from(s));return s}function Rft(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(qr.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function Pqe(s,t,n){return tn})),Jje.createHTML(s)):s}function nos(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let n=zft().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(s),a;if((a=r&&Fft[r[1].toLowerCase()])&&(s=a.map(i=>"<"+i+">").join("")+s+a.map(i=>"").reverse().join("")),n.innerHTML=sos(s),a)for(let i=0;i=0;o-=2){let c=n.nodes[r[o]];if(!c||c.hasRequiredAttrs())break;a=qr.from(c.create(r[o+1],a)),i++,l++}return new ja(a,i,l)}const rg={},ag={},ios={touchstart:!0,touchmove:!0};class oos{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 los(s){for(let t in rg){let n=rg[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=r=>{dos(s,r)&&!P6e(s,r)&&(s.editable||!(r.type in ag))&&n(s,r)},ios[t]?{passive:!0}:void 0)}rx&&s.dom.addEventListener("input",()=>null),RCe(s)}function LS(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function cos(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 RCe(s){s.someProp("handleDOMEvents",t=>{for(let n in t)s.input.eventHandlers[n]||s.dom.addEventListener(n,s.input.eventHandlers[n]=r=>P6e(s,r))})}function P6e(s,t){return s.someProp("handleDOMEvents",n=>{let r=n[t.type];return r?r(s,t)||t.defaultPrevented:!1})}function dos(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 uos(s,t){!P6e(s,t)&&rg[t.type]&&(s.editable||!(t.type in ag))&&rg[t.type](s,t)}ag.keydown=(s,t)=>{let n=t;if(s.input.shiftKey=n.keyCode==16||n.shiftKey,!$ft(s,n)&&(s.input.lastKeyCode=n.keyCode,s.input.lastKeyCodeTime=Date.now(),!(F2&&uf&&n.keyCode==13)))if(n.keyCode!=229&&s.domObserver.forceFlush(),A8&&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,BE(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",r=>r(s,n))||Jis(s,n)?n.preventDefault():LS(s,"key")};ag.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};ag.keypress=(s,t)=>{let n=t;if($ft(s,n)||!n.charCode||n.ctrlKey&&!n.altKey||yv&&n.metaKey)return;if(s.someProp("handleKeyPress",a=>a(s,n))){n.preventDefault();return}let r=s.state.selection;if(!(r instanceof Ki)||!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 Xye(s){return{left:s.clientX,top:s.clientY}}function hos(s,t){let n=t.x-s.clientX,r=t.y-s.clientY;return n*n+r*r<100}function L6e(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 OL(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 mos(s,t){if(t==-1)return!1;let n=s.state.doc.resolve(t),r=n.nodeAfter;return r&&r.isAtom&&Fi.isSelectable(r)?(OL(s,new Fi(n)),!0):!1}function pos(s,t){if(t==-1)return!1;let n=s.state.selection,r,a;n instanceof Fi&&(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(Fi.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?(OL(s,Fi.create(s.state.doc,a)),!0):!1}function fos(s,t,n,r,a){return L6e(s,"handleClickOn",t,n,r)||s.someProp("handleClick",i=>i(s,t,r))||(a?pos(s,n):mos(s,n))}function xos(s,t,n,r){return L6e(s,"handleDoubleClickOn",t,n,r)||s.someProp("handleDoubleClick",a=>a(s,t,r))}function gos(s,t,n,r){return L6e(s,"handleTripleClickOn",t,n,r)||s.someProp("handleTripleClick",a=>a(s,t,r))||yos(s,n,r)}function yos(s,t,n){if(n.button!=0)return!1;let r=s.state.doc;if(t==-1)return r.inlineContent?(OL(s,Ki.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)OL(s,Ki.create(r,o+1,o+1+l.content.size));else if(Fi.isSelectable(l))OL(s,Fi.create(r,o));else continue;return!0}}function D6e(s){return $fe(s)}const Bft=yv?"metaKey":"ctrlKey";rg.mousedown=(s,t)=>{let n=t;s.input.shiftKey=n.shiftKey;let r=D6e(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&&hos(n,s.input.lastClick)&&!n[Bft]&&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(Xye(n));l&&(i=="singleClick"?(s.input.mouseDown&&s.input.mouseDown.done(),s.input.mouseDown=new vos(s,l,n,!!r)):(i=="doubleClick"?xos:gos)(s,l.pos,l.inside,n)?n.preventDefault():LS(s,"pointer"))};class vos{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[Bft],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 Fi&&d.from<=l&&d.to>l)&&(this.mightDrag={node:i,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&qv&&!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)),LS(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(()=>tN(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(Xye(t))),this.updateAllowDefault(t),this.allowDefault||!n?LS(this.view,"pointer"):fos(this.view,n.pos,n.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||rx&&this.mightDrag&&!this.mightDrag.node.isAtom||uf&&!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)?(OL(this.view,no.near(this.view.state.doc.resolve(n.pos))),t.preventDefault()):LS(this.view,"pointer")}move(t){this.updateAllowDefault(t),LS(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)}}rg.touchstart=s=>{s.input.lastTouch=Date.now(),D6e(s),LS(s,"pointer")};rg.touchmove=s=>{s.input.lastTouch=Date.now(),LS(s,"pointer")};rg.contextmenu=s=>D6e(s);function $ft(s,t){return s.composing?!0:rx&&Math.abs(t.timeStamp-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const bos=F2?5e3:-1;ag.compositionstart=ag.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:t}=s,n=t.selection.$to;if(t.selection instanceof Ki&&(t.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||uf&&yft&&_os(s)))s.markCursor=s.state.storedMarks||n.marks(),$fe(s,!0),s.markCursor=null;else if($fe(s,!t.selection.empty),qv&&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}Uft(s,bos)};function _os(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"}ag.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++,Uft(s,20))};function Uft(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>$fe(s),t))}function qft(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=jos());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function wos(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let n=pis(t.focusNode,t.focusOffset),r=fis(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 jos(){let s=document.createEvent("Event");return s.initEvent("event",!0,!0),s.timeStamp}function $fe(s,t=!1){if(!(F2&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),qft(s),t||s.docView&&s.docView.dirty){let n=A6e(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 Nos(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 _B=Wg&&g4<15||A8&&vis<604;rg.copy=ag.cut=(s,t)=>{let n=t,r=s.state.selection,a=n.type=="cut";if(r.empty)return;let i=_B?null:n.clipboardData,l=r.content(),{dom:o,text:c}=I6e(s,l);i?(n.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):Nos(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function kos(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function Sos(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?wB(s,r.value,null,a,t):wB(s,r.textContent,r.innerHTML,a,t)},50)}function wB(s,t,n,r,a){let i=Lft(s,t,n,r,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,a,i||ja.empty)))return!0;if(!i)return!1;let l=kos(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 Vft(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," "):""}ag.paste=(s,t)=>{let n=t;if(s.composing&&!F2)return;let r=_B?null:n.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;r&&wB(s,Vft(r),r.getData("text/html"),a,n)?n.preventDefault():Sos(s,n)};class Hft{constructor(t,n,r){this.slice=t,this.move=n,this.node=r}}const Cos=yv?"altKey":"ctrlKey";function Gft(s,t){let n;return s.someProp("dragCopies",r=>{n=n||r(t)}),n!=null?!n:!t[Cos]}rg.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(Xye(n)),l;if(!(i&&i.pos>=a.from&&i.pos<=(a instanceof Fi?a.to-1:a.to))){if(r&&r.mightDrag)l=Fi.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=Fi.create(s.state.doc,h.posBefore))}}let o=(l||s.state.selection).content(),{dom:c,text:d,slice:u}=I6e(s,o);(!n.dataTransfer.files.length||!uf||gft>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(_B?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",_B||n.dataTransfer.setData("text/plain",d),s.dragging=new Hft(u,Gft(s,n),l)};rg.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};ag.dragover=ag.dragenter=(s,t)=>t.preventDefault();ag.drop=(s,t)=>{try{Tos(s,t,s.dragging)}finally{s.dragging=null}};function Tos(s,t,n){if(!t.dataTransfer)return;let r=s.posAtCoords(Xye(t));if(!r)return;let a=s.state.doc.resolve(r.pos),i=n&&n.slice;i?s.someProp("transformPasted",f=>{i=f(i,s,!1)}):i=Lft(s,Vft(t.dataTransfer),_B?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(n&&Gft(s,t));if(s.someProp("handleDrop",f=>f(s,t,i||ja.empty,l))){t.preventDefault();return}if(!i)return;t.preventDefault();let o=i?lft(s.state.doc,a.pos,i):a.pos;o==null&&(o=a.pos);let c=s.state.tr;if(l){let{node:f}=n;f?f.replace(c):c.deleteSelection()}let d=c.mapping.map(o),u=i.openStart==0&&i.openEnd==0&&i.content.childCount==1,h=c.doc;if(u?c.replaceRangeWith(d,d,i.content.firstChild):c.replaceRange(d,d,i),c.doc.eq(h))return;let p=c.doc.resolve(d);if(u&&Fi.isSelectable(i.content.firstChild)&&p.nodeAfter&&p.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new Fi(p));else{let f=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((g,_,v,j)=>f=j),c.setSelection(M6e(s,p,c.doc.resolve(f)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}rg.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())&&tN(s)},20))};rg.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)};rg.beforeinput=(s,t)=>{if(uf&&F2&&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,BE(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 ag)rg[s]=ag[s];function jB(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 Ufe{constructor(t,n){this.toDOM=t,this.spec=n||KA,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 Zx(i-r,i-r,this)}valid(){return!0}eq(t){return this==t||t instanceof Ufe&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&jB(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class v4{constructor(t,n){this.attrs=t,this.spec=n||KA}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 Zx(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==Wf||t.maps.length==0?this:this.mapInner(t,n,0,0,r||KA)}mapInner(t,n,r,a,i){let l;for(let o=0;o{let d=c+r,u;if(u=Kft(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 v4){let d=Math.max(i,c.from)-i,u=Math.min(l,c.to)-i;da.map(t,n,KA));return hS.from(r)}forChild(t,n){if(n.isLeaf)return ah.empty;let r=[];for(let a=0;an instanceof ah)?t:t.reduce((n,r)=>n.concat(r instanceof ah?r:r.members),[]))}}forEachSet(t){for(let n=0;n{let v=_-g-(f-p);for(let j=0;jb+u-h)continue;let S=o[j]+u-h;f>=S?o[j+1]=p<=S?-2:-1:p>=u&&v&&(o[j]+=v,o[j+1]+=v)}h+=v}),u=n.maps[d].map(u,-1)}let c=!1;for(let d=0;d=r.content.size){c=!0;continue}let p=n.map(s[d+1]+i,-1),f=p-a,{index:g,offset:_}=r.content.findIndex(h),v=r.maybeChild(g);if(v&&_==h&&_+v.nodeSize==f){let j=o[d+2].mapInner(n,v,u+1,s[d]+i+1,l);j!=Wf?(o[d]=h,o[d+1]=f,o[d+2]=j):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=Aos(o,s,t,n,a,i,l),u=qfe(d,r,0,l);t=u.local;for(let h=0;hn&&l.to{let d=Kft(s,o,c+n);if(d){i=!0;let u=qfe(d,o,n+c+1,r);u!=Wf&&a.push(c,c+o.nodeSize,u)}});let l=Wft(i?Yft(s):s,-n).sort(YA);for(let o=0;o0;)t++;s.splice(t,0,n)}function e2e(s){let t=[];return s.someProp("decorations",n=>{let r=n(s.state);r&&r!=Wf&&t.push(r)}),s.cursorWrapper&&t.push(ah.create(s.state.doc,[s.cursorWrapper.deco])),hS.from(t)}const Mos={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Ios=Wg&&g4<=11;class Pos{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 Los{constructor(t,n){this.view=t,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Pos,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():rx&&t.composing&&r.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Ios&&(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,Mos)),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(Cqe(this.view)){if(this.suppressingSelectionUpdates)return tN(this.view);if(Wg&&g4<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&jM(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=E8(i))n.add(i);for(let i=t.anchorNode;i;i=E8(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)&&Cqe(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(qv&&c.length){let u=c.filter(h=>h.nodeName=="BR");if(u.length==2){let[h,p]=u;h.parentNode&&h.parentNode.parentNode==p.parentNode?p.remove():h.remove()}else{let{focusNode:h}=this.currentSelection;for(let p of u){let f=p.parentNode;f&&f.nodeName=="LI"&&(!h||Oos(t,h)!=f)&&p.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),Dos(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,Fos(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(r)||tN(t),this.currentSelection.set(r))}registerMutation(t,n){if(n.indexOf(t.target)>-1)return null;let r=this.view.docView.nearestDesc(t.target);if(t.type=="attributes"&&(r==this.view.docView||t.attributeName=="contenteditable"||t.attributeName=="style"&&!t.oldValue&&!t.target.getAttribute("style"))||!r||r.ignoreMutation(t))return null;if(t.type=="childList"){for(let u=0;ua;v--){let j=r.childNodes[v-1],b=j.pmViewDesc;if(j.nodeName=="BR"&&!b){i=v;break}if(!b||b.size)break}let h=s.state.doc,p=s.someProp("domParser")||rz.fromSchema(s.state.schema),f=h.resolve(l),g=null,_=p.parse(r,{topNode:f.parent,topMatch:f.parent.contentMatchAt(f.index()),topOpen:!0,from:a,to:i,preserveWhitespace:f.parent.type.whitespace=="pre"?"full":!0,findPositions:d,ruleFromNode:Bos,context:f});if(d&&d[0].pos!=null){let v=d[0].pos,j=d[1]&&d[1].pos;j==null&&(j=v),g={anchor:v+l,head:j+l}}return{doc:_,sel:g,from:l,to:o}}function Bos(s){let t=s.pmViewDesc;if(t)return t.parseRule();if(s.nodeName=="BR"&&s.parentNode){if(rx&&/^(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||rx&&/^(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 $os=/^(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 Uos(s,t,n,r,a){let i=s.input.compositionPendingChanges||(s.composing?s.input.compositionID:0);if(s.input.compositionPendingChanges=0,t<0){let D=s.input.lastSelectionTime>Date.now()-50?s.input.lastSelectionOrigin:null,M=A6e(s,D);if(M&&!s.state.selection.eq(M)){if(uf&&F2&&s.input.lastKeyCode===13&&Date.now()-100z(s,BE(13,"Enter"))))return;let F=s.state.tr.setSelection(M);D=="pointer"?F.setMeta("pointer",!0):D=="key"&&F.scrollIntoView(),i&&F.setMeta("composition",i),s.dispatch(F)}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=zos(s,t,n),u=s.state.doc,h=u.slice(d.from,d.to),p,f;s.input.lastKeyCode===8&&Date.now()-100Date.now()-225||F2)&&a.some(D=>D.nodeType==1&&!$os.test(D.nodeName))&&(!g||g.endA>=g.endB)&&s.someProp("handleKeyDown",D=>D(s,BE(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!g)if(r&&c instanceof Ki&&!c.empty&&c.$head.sameParent(c.$anchor)&&!s.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))g={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let D=zqe(s,s.state.doc,d.sel);if(D&&!D.eq(s.state.selection)){let M=s.state.tr.setSelection(D);i&&M.setMeta("composition",i),s.dispatch(M)}}return}s.state.selection.froms.state.selection.from&&g.start<=s.state.selection.from+2&&s.state.selection.from>=d.from?g.start=s.state.selection.from:g.endA=s.state.selection.to-2&&s.state.selection.to<=d.to&&(g.endB+=s.state.selection.to-g.endA,g.endA=s.state.selection.to)),Wg&&g4<=11&&g.endB==g.start+1&&g.endA==g.start&&g.start>d.from&&d.doc.textBetween(g.start-d.from-1,g.start-d.from+1)=="  "&&(g.start--,g.endA--,g.endB--);let _=d.doc.resolveNoCache(g.start-d.from),v=d.doc.resolveNoCache(g.endB-d.from),j=u.resolve(g.start),b=_.sameParent(v)&&_.parent.inlineContent&&j.end()>=g.endA;if((A8&&s.input.lastIOSEnter>Date.now()-225&&(!b||a.some(D=>D.nodeName=="DIV"||D.nodeName=="P"))||!b&&_.posD(s,BE(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>g.start&&Vos(u,g.start,g.endA,_,v)&&s.someProp("handleKeyDown",D=>D(s,BE(8,"Backspace")))){F2&&uf&&s.domObserver.suppressSelectionUpdates();return}uf&&g.endB==g.start&&(s.input.lastChromeDelete=Date.now()),F2&&!b&&_.start()!=v.start()&&v.parentOffset==0&&_.depth==v.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==g.endA&&(g.endB-=2,v=d.doc.resolveNoCache(g.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(D){return D(s,BE(13,"Enter"))})},20));let S=g.start,A=g.endA,T=D=>{let M=D||s.state.tr.replace(S,A,d.doc.slice(g.start-d.from,g.endB-d.from));if(d.sel){let F=zqe(s,M.doc,d.sel);F&&!(uf&&s.composing&&F.empty&&(g.start!=g.endB||s.input.lastChromeDeletetN(s),20));let D=T(s.state.tr.delete(S,A)),M=u.resolve(g.start).marksAcross(u.resolve(g.endA));M&&D.ensureMarks(M),s.dispatch(D)}else if(g.endA==g.endB&&(L=qos(_.parent.content.cut(_.parentOffset,v.parentOffset),j.parent.content.cut(j.parentOffset,g.endA-j.start())))){let D=T(s.state.tr);L.type=="add"?D.addMark(S,A,L.mark):D.removeMark(S,A,L.mark),s.dispatch(D)}else if(_.parent.child(_.index()).isText&&_.index()==v.index()-(v.textOffset?0:1)){let D=_.parent.textBetween(_.parentOffset,v.parentOffset),M=()=>T(s.state.tr.insertText(D,S,A));s.someProp("handleTextInput",F=>F(s,S,A,D,M))||s.dispatch(M())}else s.dispatch(T());else s.dispatch(T())}function zqe(s,t,n){return Math.max(n.anchor,n.head)>t.content.size?null:M6e(s,t.resolve(n.anchor),t.resolve(n.head))}function qos(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||t2e(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 Hos(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 Zft{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 oos,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(Hqe),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=qqe(this),Uqe(this),this.nodeViews=Vqe(this),this.docView=_qe(this.state.doc,$qe(this),e2e(this),this.dom,this),this.domObserver=new Los(this,(r,a,i,l)=>Uos(this,r,a,i,l)),this.domObserver.start(),los(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&&RCe(this);let n=this._props;this._props=t,t.plugins&&(t.plugins.forEach(Hqe),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&&(qft(this),l=!0),this.state=t;let o=a.plugins!=t.plugins||this._props.plugins!=n.plugins;if(o||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let f=Vqe(this);Wos(f,this.nodeViews)&&(this.nodeViews=f,i=!0)}(o||n.handleDOMEvents!=this._props.handleDOMEvents)&&RCe(this),this.editable=qqe(this),Uqe(this);let c=e2e(this),d=$qe(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 p=u=="preserve"&&l&&this.dom.style.overflowAnchor==null&&wis(this);if(l){this.domObserver.stop();let f=h&&(Wg||uf)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&Gos(a.selection,t.selection);if(h){let g=uf?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=wos(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=_qe(t.doc,d,c,this.dom,this)),g&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(f=!0)}f||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&Gis(this))?tN(this,f):(Mft(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():p&&jis(p)}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 Fi){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&fqe(this,n.getBoundingClientRect(),t)}else fqe(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 Eis(this,t)}coordsAtPos(t,n=1){return jft(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 Lis(this,n||this.state,t)}pasteHTML(t,n){return wB(this,"",t,!1,n||new ClipboardEvent("paste"))}pasteText(t,n){return wB(this,t,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(t){return I6e(this,t)}destroy(){this.docView&&(cos(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],e2e(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,his())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return uos(this,t)}domSelectionRange(){let t=this.domSelection();return t?rx&&this.root.nodeType===11&&gis(this.dom.ownerDocument)==this.dom&&Ros(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}Zft.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function $qe(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"),[Zx.node(0,s.state.doc.content.size,t)]}function Uqe(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:Zx.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function qqe(s){return!s.someProp("editable",t=>t(s.state)===!1)}function Gos(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 Vqe(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 Wos(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 Hqe(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 R4={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:"'"},Vfe={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},Kos=typeof navigator<"u"&&/Mac/.test(navigator.platform),Yos=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var af=0;af<10;af++)R4[48+af]=R4[96+af]=String(af);for(var af=1;af<=24;af++)R4[af+111]="F"+af;for(var af=65;af<=90;af++)R4[af]=String.fromCharCode(af+32),Vfe[af]=String.fromCharCode(af);for(var s2e in R4)Vfe.hasOwnProperty(s2e)||(Vfe[s2e]=R4[s2e]);function Zos(s){var t=Kos&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||Yos&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",n=!t&&s.key||(s.shiftKey?Vfe:R4)[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 Qos=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),Xos=typeof navigator<"u"&&/Win/.test(navigator.platform);function Jos(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 Qft(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("backward",s):n.parentOffset>0)?null:n}const nls=(s,t,n)=>{let r=Qft(s,n);if(!r)return!1;let a=z6e(r);if(!a){let l=r.blockRange(),o=l&&QD(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(txt(s,a,t,-1))return!0;if(r.parent.content.size==0&&(M8(i,"end")||Fi.isSelectable(i)))for(let l=r.depth;;l--){let o=Kye(s.doc,r.before(l),r.after(l),ja.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},rls=(s,t,n)=>{let r=Qft(s,n);if(!r)return!1;let a=z6e(r);return a?Xft(s,a,t):!1},als=(s,t,n)=>{let r=Jft(s,n);if(!r)return!1;let a=B6e(r);return a?Xft(s,a,t):!1};function Xft(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=Kye(s.doc,i,c,ja.empty);if(!d||d.from!=i||d instanceof Zh&&d.slice.size>=c-i)return!1;if(n){let u=s.tr.step(d);u.setSelection(Ki.create(u.doc,i)),n(u.scrollIntoView())}return!0}function M8(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 ils=(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=z6e(r)}let l=i&&i.nodeBefore;return!l||!Fi.isSelectable(l)?!1:(t&&t(s.tr.setSelection(Fi.create(s.doc,i.pos-l.nodeSize)).scrollIntoView()),!0)};function z6e(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 Jft(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("forward",s):n.parentOffset{let r=Jft(s,n);if(!r)return!1;let a=B6e(r);if(!a)return!1;let i=a.nodeAfter;if(txt(s,a,t,1))return!0;if(r.parent.content.size==0&&(M8(i,"start")||Fi.isSelectable(i))){let l=Kye(s.doc,r.before(),r.after(),ja.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 Fi,a;if(r){if(n.node.isTextblock||!eC(s.doc,n.from))return!1;a=n.from}else if(a=Wye(s.doc,n.from,-1),a==null)return!1;if(t){let i=s.tr.join(a);r&&i.setSelection(Fi.create(i.doc,a-s.doc.resolve(a).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},dls=(s,t)=>{let n=s.selection,r;if(n instanceof Fi){if(n.node.isTextblock||!eC(s.doc,n.to))return!1;r=n.to}else if(r=Wye(s.doc,n.to,1),r==null)return!1;return t&&t(s.tr.join(r).scrollIntoView()),!0},uls=(s,t)=>{let{$from:n,$to:r}=s.selection,a=n.blockRange(r),i=a&&QD(a);return i==null?!1:(t&&t(s.tr.lift(a,i).scrollIntoView()),!0)},hls=(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 ext(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=ext(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(no.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},pls=(s,t)=>{let n=s.selection,{$from:r,$to:a}=n;if(n instanceof Uv||r.parent.inlineContent||a.parent.inlineContent)return!1;let i=ext(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(DL(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let r=n.blockRange(),a=r&&QD(r);return a==null?!1:(t&&t(s.tr.lift(r,a).scrollIntoView()),!0)},xls=(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(Fi.create(s.doc,a))),!0)};function gls(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||eC(s.doc,t.pos))?!1:(n&&n(s.tr.join(t.pos).scrollIntoView()),!0)}function txt(s,t,n,r){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&gls(s,t,n))return!0;let d=!c&&t.parent.canReplace(t.index(),t.index()+1);if(d&&(l=(o=a.contentMatchAt(a.childCount)).findWrapping(i.type))&&o.matchType(l[0]||i.type).validEnd){if(n){let f=t.pos+i.nodeSize,g=qr.empty;for(let j=l.length-1;j>=0;j--)g=qr.from(l[j].create(null,g));g=qr.from(a.copy(g));let _=s.tr.step(new Ep(t.pos-1,f,t.pos,f,new ja(g,1,0),l.length,!0)),v=_.doc.resolve(f+2*l.length);v.nodeAfter&&v.nodeAfter.type==a.type&&eC(_.doc,v.pos)&&_.join(v.pos),n(_.scrollIntoView())}return!0}let u=i.type.spec.isolating||r>0&&c?null:no.findFrom(t,1),h=u&&u.$from.blockRange(u.$to),p=h&&QD(h);if(p!=null&&p>=t.depth)return n&&n(s.tr.lift(h,p).scrollIntoView()),!0;if(d&&M8(i,"start",!0)&&M8(a,"end")){let f=a,g=[];for(;g.push(f),!f.isTextblock;)f=f.lastChild;let _=i,v=1;for(;!_.isTextblock;_=_.firstChild)v++;if(f.canReplace(f.childCount,f.childCount,_.content)){if(n){let j=qr.empty;for(let S=g.length-1;S>=0;S--)j=qr.from(g[S].copy(j));let b=s.tr.step(new Ep(t.pos-g.length,t.pos+i.nodeSize,t.pos+v,t.pos+i.nodeSize-v,new ja(j,g.length,0),0,!0));n(b.scrollIntoView())}return!0}}return!1}function sxt(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(Ki.create(t.doc,s<0?a.start(i):a.end(i)))),!0):!1}}const yls=sxt(-1),vls=sxt(1);function bls(s,t=null){return function(n,r){let{$from:a,$to:i}=n.selection,l=a.blockRange(i),o=l&&S6e(l,s,t);return o?(r&&r(n.tr.wrap(l,o).scrollIntoView()),!0):!1}}function Gqe(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 Ofe(c,c,t.depth),t.endIndex=0;u--)i=qr.from(n[u].type.create(n[u].attrs,i));s.step(new Ep(t.start-(r?2:0),t.end,t.start,t.end,new ja(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?kls(t,n,s,i):Sls(t,n,i):!0:!1}}function kls(s,t,n,r){let a=s.tr,i=r.end,l=r.$to.end(r.depth);i_;g--)f-=a.child(g).nodeSize,r.delete(f-1,f+1);let i=r.doc.resolve(n.start),l=i.nodeAfter;if(r.mapping.map(n.end)!=n.start+i.nodeAfter.nodeSize)return!1;let o=n.startIndex==0,c=n.endIndex==a.childCount,d=i.node(-1),u=i.index(-1);if(!d.canReplace(u+(o?0:1),u+1,l.content.append(c?qr.empty:qr.from(a))))return!1;let h=i.pos,p=h+l.nodeSize;return r.step(new Ep(h-(o?1:0),p+(c?1:0),h+1,p-1,new ja((o?qr.empty:qr.from(a.copy(qr.empty))).append(c?qr.empty:qr.from(a.copy(qr.empty))),o?0:1,c?0:1),o?0:1)),t(r.scrollIntoView()),!0}function Cls(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=qr.from(d?s.create():null),h=new ja(qr.from(s.create(null,qr.from(o.type.create(null,u)))),d?3:1,0),p=i.start,f=i.end;n(t.tr.step(new Ep(p-(d?3:1),f,p,f,h,1,!0)).scrollIntoView())}return!0}}function Jye(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}}}class eve{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(p=>p===!0)),h={...Object.fromEntries(Object.entries(r).map(([p,f])=>[p,(..._)=>{const v=this.buildProps(d,n),j=f(..._)(v);return o.push(j),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:Jye({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}}let Tls=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 ci(s,t,n){return s.config[t]===void 0&&s.parent?ci(s.parent,t,n):typeof s.config[t]=="function"?s.config[t].bind({...n,parent:s.parent?ci(s.parent,t,n):null}):s.config[t]}function tve(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 nxt(s){const t=[],{nodeExtensions:n,markExtensions:r}=tve(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=ci(l,"addGlobalAttributes",o);if(!c)return;c().forEach(u=>{u.types.forEach(h=>{Object.entries(u.attributes).forEach(([p,f])=>{t.push({type:h,name:p,attribute:{...i,...f}})})})})}),a.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage},c=ci(l,"addAttributes",o);if(!c)return;const d=c();Object.entries(d).forEach(([u,h])=>{const p={...i,...h};typeof(p==null?void 0:p.default)=="function"&&(p.default=p.default()),p!=null&&p.isRequired&&(p==null?void 0:p.default)===void 0&&delete p.default,t.push({type:l.name,name:u,attribute:p})})}),t}function Mp(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 mu(...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,p]=u.split(":").map(f=>f.trim());d.set(h,p)}),o.forEach(u=>{const[h,p]=u.split(":").map(f=>f.trim());d.set(h,p)}),r[a]=Array.from(d.entries()).map(([u,h])=>`${u}: ${h}`).join("; ")}else r[a]=i}),r},{})}function OCe(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)=>mu(n,r),{})}function rxt(s){return typeof s=="function"}function Qo(s,t=void 0,...n){return rxt(s)?t?s.bind(t)(...n):s(...n):s}function Els(s={}){return Object.keys(s).length===0&&s.constructor===Object}function Als(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function Wqe(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):Als(n.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...r,...a}}}}function Kqe(s){return Object.fromEntries(Object.entries(s).filter(([t,n])=>t==="attrs"&&Els(n)?!1:n!=null))}function Mls(s,t){var n;const r=nxt(s),{nodeExtensions:a,markExtensions:i}=tve(s),l=(n=a.find(d=>ci(d,"topNode")))===null||n===void 0?void 0:n.name,o=Object.fromEntries(a.map(d=>{const u=r.filter(j=>j.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},p=s.reduce((j,b)=>{const S=ci(b,"extendNodeSchema",h);return{...j,...S?S(d):{}}},{}),f=Kqe({...p,content:Qo(ci(d,"content",h)),marks:Qo(ci(d,"marks",h)),group:Qo(ci(d,"group",h)),inline:Qo(ci(d,"inline",h)),atom:Qo(ci(d,"atom",h)),selectable:Qo(ci(d,"selectable",h)),draggable:Qo(ci(d,"draggable",h)),code:Qo(ci(d,"code",h)),whitespace:Qo(ci(d,"whitespace",h)),linebreakReplacement:Qo(ci(d,"linebreakReplacement",h)),defining:Qo(ci(d,"defining",h)),isolating:Qo(ci(d,"isolating",h)),attrs:Object.fromEntries(u.map(j=>{var b;return[j.name,{default:(b=j==null?void 0:j.attribute)===null||b===void 0?void 0:b.default}]}))}),g=Qo(ci(d,"parseHTML",h));g&&(f.parseDOM=g.map(j=>Wqe(j,u)));const _=ci(d,"renderHTML",h);_&&(f.toDOM=j=>_({node:j,HTMLAttributes:OCe(j,u)}));const v=ci(d,"renderText",h);return v&&(f.toText=v),[d.name,f]})),c=Object.fromEntries(i.map(d=>{const u=r.filter(v=>v.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},p=s.reduce((v,j)=>{const b=ci(j,"extendMarkSchema",h);return{...v,...b?b(d):{}}},{}),f=Kqe({...p,inclusive:Qo(ci(d,"inclusive",h)),excludes:Qo(ci(d,"excludes",h)),group:Qo(ci(d,"group",h)),spanning:Qo(ci(d,"spanning",h)),code:Qo(ci(d,"code",h)),attrs:Object.fromEntries(u.map(v=>{var j;return[v.name,{default:(j=v==null?void 0:v.attribute)===null||j===void 0?void 0:j.default}]}))}),g=Qo(ci(d,"parseHTML",h));g&&(f.parseDOM=g.map(v=>Wqe(v,u)));const _=ci(d,"renderHTML",h);return _&&(f.toDOM=v=>_({mark:v,HTMLAttributes:OCe(v,u)})),[d.name,f]}));return new Qpt({topNode:l,nodes:o,marks:c})}function r2e(s,t){return t.nodes[s]||t.marks[s]||null}function Yqe(s,t){return Array.isArray(t)?t.some(n=>(typeof n=="string"?n:n.name)===s.name):t}function $6e(s,t){const n=WM.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(n),a.innerHTML}const Ils=(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 U6e(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class sve{constructor(t){this.find=t.find,this.handler=t.handler}}const Pls=(s,t)=>{if(U6e(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 yH(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(p=>p.type.spec.code))return!1;let u=!1;const h=Ils(d)+i;return l.forEach(p=>{if(u)return;const f=Pls(h,p.find);if(!f)return;const g=c.state.tr,_=Jye({state:c.state,transaction:g}),v={from:r-(f[0].length-i.length),to:a},{commands:j,chain:b,can:S}=new eve({editor:n,state:_});p.handler({state:_,range:v,match:f,commands:j,chain:b,can:S})===null||!g.steps.length||(g.setMeta(o,{transform:g,from:r,to:a,text:i}),c.dispatch(g),u=!0)}),u}function Lls(s){const{editor:t,rules:n}=s,r=new Ym({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=$6e(qr.from(u),l.schema);const{from:h}=c,p=h+u.length;yH({editor:t,from:h,to:p,text:u,rules:n,plugin:r})}),a.selectionSet||a.docChanged?null:i}},props:{handleTextInput(a,i,l,o){return yH({editor:t,from:i,to:l,text:o,rules:n,plugin:r})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&yH({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?yH({editor:t,from:l.pos,to:l.pos,text:` `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function Dls(s){return Object.prototype.toString.call(s).slice(8,-1)}function vH(s){return Dls(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function nve(s,t){const n={...s};return vH(s)&&vH(t)&&Object.keys(t).forEach(r=>{vH(t[r])&&vH(s[r])?n[r]=nve(s[r],t[r]):n[r]=t[r]}),n}class Eb{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=Qo(ci(this,"addOptions",{name:this.name}))),this.storage=Qo(ci(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new Eb(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>nve(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new Eb(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=Qo(ci(n,"addOptions",{name:n.name})),n.storage=Qo(ci(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 Rls(s){return typeof s=="number"}class Ols{constructor(t){this.find=t.find,this.handler=t.handler}}const Fls=(s,t,n)=>{if(U6e(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 zls(s){const{editor:t,state:n,from:r,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:u}=new eve({editor:t,state:n}),h=[];return n.doc.nodesBetween(r,a,(f,g)=>{if(!f.isTextblock||f.type.spec.code)return;const _=Math.max(r,g),v=Math.min(a,g+f.content.size),j=f.textBetween(_-g,v-g,void 0,"");Fls(j,i.find,l).forEach(S=>{if(S.index===void 0)return;const A=_+S.index+1,T=A+S[0].length,L={from:n.tr.mapping.map(A),to:n.tr.mapping.map(T)},D=i.handler({state:n,range:L,match:S,commands:c,chain:d,can:u,pasteEvent:l,dropEvent:o});h.push(D)})}),h.every(f=>f!==null)}let bH=null;const Bls=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 $ls(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:p,rule:f,pasteEvt:g})=>{const _=u.tr,v=Jye({state:u,transaction:_});if(!(!zls({editor:t,state:v,from:Math.max(h-1,0),to:p.b-1,rule:f,pasteEvent:g,dropEvent:o})||!_.steps.length)){try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}return l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,_}};return n.map(u=>new Ym({view(h){const p=g=>{var _;r=!((_=h.dom.parentElement)===null||_===void 0)&&_.contains(g.target)?h.dom.parentElement:null,r&&(bH=t)},f=()=>{bH&&(bH=null)};return window.addEventListener("dragstart",p),window.addEventListener("dragend",f),{destroy(){window.removeEventListener("dragstart",p),window.removeEventListener("dragend",f)}}},props:{handleDOMEvents:{drop:(h,p)=>{if(i=r===h.dom.parentElement,o=p,!i){const f=bH;f!=null&&f.isEditable&&setTimeout(()=>{const g=f.state.selection;g&&f.commands.deleteRange({from:g.from,to:g.to})},10)}return!1},paste:(h,p)=>{var f;const g=(f=p.clipboardData)===null||f===void 0?void 0:f.getData("text/html");return l=p,a=!!(g!=null&&g.includes("data-pm-slice")),!1}}},appendTransaction:(h,p,f)=>{const g=h[0],_=g.getMeta("uiEvent")==="paste"&&!a,v=g.getMeta("uiEvent")==="drop"&&!i,j=g.getMeta("applyPasteRules"),b=!!j;if(!_&&!v&&!b)return;if(b){let{text:T}=j;typeof T=="string"?T=T:T=$6e(qr.from(T),f.schema);const{from:L}=j,D=L+T.length,M=Bls(T);return c({rule:u,state:f,from:L,to:{b:D},pasteEvt:M})}const S=p.doc.content.findDiffStart(f.doc.content),A=p.doc.content.findDiffEnd(f.doc.content);if(!(!Rls(S)||!A||S===A.b))return c({rule:u,state:f,from:S,to:A,pasteEvt:l})}}))}function Uls(s){const t=s.filter((n,r)=>s.indexOf(n)!==r);return Array.from(new Set(t))}class MP{constructor(t,n){this.splittableMarks=[],this.editor=n,this.extensions=MP.resolve(t),this.schema=Mls(this.extensions,n),this.setupExtensions()}static resolve(t){const n=MP.sort(MP.flatten(t)),r=Uls(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=ci(n,"addExtensions",r);return a?[n,...this.flatten(a())]:n}).flat(10)}static sort(t){return t.sort((r,a)=>{const i=ci(r,"priority")||100,l=ci(a,"priority")||100;return i>l?-1:i{const r={name:n.name,options:n.options,storage:n.storage,editor:this.editor,type:r2e(n.name,this.schema)},a=ci(n,"addCommands",r);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,n=MP.sort([...this.extensions].reverse()),r=[],a=[],i=n.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:r2e(l.name,this.schema)},c=[],d=ci(l,"addKeyboardShortcuts",o);let u={};if(l.type==="mark"&&ci(l,"exitable",o)&&(u.ArrowRight=()=>Eb.handleExit({editor:t,mark:l})),d){const _=Object.fromEntries(Object.entries(d()).map(([v,j])=>[v,()=>j({editor:t})]));u={...u,..._}}const h=tls(u);c.push(h);const p=ci(l,"addInputRules",o);Yqe(l,t.options.enableInputRules)&&p&&r.push(...p());const f=ci(l,"addPasteRules",o);Yqe(l,t.options.enablePasteRules)&&f&&a.push(...f());const g=ci(l,"addProseMirrorPlugins",o);if(g){const _=g();c.push(..._)}return c}).flat();return[Lls({editor:t,rules:r}),...$ls({editor:t,rules:a}),...i]}get attributes(){return nxt(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:n}=tve(this.extensions);return Object.fromEntries(n.filter(r=>!!ci(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:Mp(r.name,this.schema)},l=ci(r,"addNodeView",i);if(!l)return[];const o=(c,d,u,h,p)=>{const f=OCe(c,a);return l()({node:c,view:d,getPos:u,decorations:h,innerDecorations:p,editor:t,extension:r,HTMLAttributes:f})};return[r.name,o]}))}setupExtensions(){this.extensions.forEach(t=>{var n;this.editor.extensionStorage[t.name]=t.storage;const r={name:t.name,options:t.options,storage:t.storage,editor:this.editor,type:r2e(t.name,this.schema)};t.type==="mark"&&(!((n=Qo(ci(t,"keepOnSplit",r)))!==null&&n!==void 0)||n)&&this.splittableMarks.push(t.name);const a=ci(t,"onBeforeCreate",r),i=ci(t,"onCreate",r),l=ci(t,"onUpdate",r),o=ci(t,"onSelectionUpdate",r),c=ci(t,"onTransaction",r),d=ci(t,"onFocus",r),u=ci(t,"onBlur",r),h=ci(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 Cf{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=Qo(ci(this,"addOptions",{name:this.name}))),this.storage=Qo(ci(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new Cf(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>nve(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new Cf({...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=Qo(ci(n,"addOptions",{name:n.name})),n.storage=Qo(ci(n,"addStorage",{name:n.name,options:n.options})),n}}function axt(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 p;c.isBlock&&d>r&&(o+=i);const f=l==null?void 0:l[c.type.name];if(f)return u&&(o+=f({node:c,pos:d,parent:u,index:h,range:t})),!1;c.isText&&(o+=(p=c==null?void 0:c.text)===null||p===void 0?void 0:p.slice(Math.max(r,d)-d,a-d))}),o}function ixt(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}const qls=Cf.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new Ym({key:new cx("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=ixt(n);return axt(r,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),Vls=()=>({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),Hls=(s=!1)=>({commands:t})=>t.setContent("",s),Gls=()=>({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)),p=d.resolve(u.map(c+o.nodeSize)),f=h.blockRange(p);if(!f)return;const g=QD(f);if(o.type.isTextblock){const{defaultType:_}=h.parent.contentMatchAt(h.index());t.setNodeMarkup(f.start,_)}(g||g===0)&&t.lift(f,g)})}),!0},Wls=s=>t=>s(t),Kls=()=>({state:s,dispatch:t})=>pls(s,t),Yls=(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 Ki(r.doc.resolve(Math.max(l-1,0)))),!0},Zls=()=>({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},Qls=s=>({tr:t,state:n,dispatch:r})=>{const a=Mp(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},Xls=s=>({tr:t,dispatch:n})=>{const{from:r,to:a}=s;return n&&t.delete(r,a),!0},Jls=()=>({state:s,dispatch:t})=>sls(s,t),ecs=()=>({commands:s})=>s.keyboardShortcut("Enter"),tcs=()=>({state:s,dispatch:t})=>mls(s,t);function Hfe(s,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(a=>n.strict?t[a]===s[a]:U6e(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function oxt(s,t,n={}){return s.find(r=>r.type===t&&Hfe(Object.fromEntries(Object.keys(n).map(a=>[a,r.attrs[a]])),n))}function Zqe(s,t,n={}){return!!oxt(s,t,n)}function q6e(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),!oxt([...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&&Zqe([...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=sC(s,r.schema),{doc:l,selection:o}=n,{$from:c,from:d,to:u}=o;if(a){const h=q6e(c,i,t);if(h&&h.from<=d&&h.to>=u){const p=Ki.create(l,h.from,h.to);n.setSelection(p)}}return!0},ncs=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=()=>{(Gfe()||Qqe())&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),rcs()&&!Gfe()&&!Qqe()&&r.dom.focus({preventScroll:!0}))})};if(r.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!lxt(n.state.selection))return l(),!0;const o=cxt(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},ics=(s,t)=>n=>s.every((r,a)=>t(r,{...n,index:a})),ocs=(s,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},s,t),dxt=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&&dxt(r)}return s};function _H(s){const t=`${s}`,n=new window.DOMParser().parseFromString(t,"text/html").body;return dxt(n)}function NB(s,t,n){if(s instanceof x4||s instanceof qr)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 qr.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),NB("",t,n)}if(a){if(n.errorOnInvalidContent){let l=!1,o="";const c=new Qpt({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?rz.fromSchema(c).parseSlice(_H(s),n.parseOptions):rz.fromSchema(c).parse(_H(s),n.parseOptions),n.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=rz.fromSchema(t);return n.slice?i.parseSlice(_H(s),n.parseOptions).content:i.parse(_H(s),n.parseOptions)}return NB("",t,n)}function lcs(s,t,n){const r=s.steps.length-1;if(r{l===0&&(l=u)}),s.setSelection(no.near(s.doc.resolve(l),n))}const ccs=s=>!("type"in s),dcs=(s,t,n)=>({tr:r,dispatch:a,editor:i})=>{var l;if(a){n={parseOptions:i.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let o;const c=v=>{i.emit("contentError",{editor:i,error:v,disableCollaboration:()=>{i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},d={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{NB(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(v){c(v)}try{o=NB(t,i.schema,{parseOptions:d,errorOnInvalidContent:(l=n.errorOnInvalidContent)!==null&&l!==void 0?l:i.options.enableContentCheck})}catch(v){return c(v),!1}let{from:u,to:h}=typeof s=="number"?{from:s,to:s}:{from:s.from,to:s.to},p=!0,f=!0;if((ccs(o)?o:[o]).forEach(v=>{v.check(),p=p?v.isText&&v.marks.length===0:!1,f=f?v.isBlock:!1}),u===h&&f){const{parent:v}=r.doc.resolve(u);v.isTextblock&&!v.type.spec.code&&!v.childCount&&(u-=1,h+=1)}let _;if(p){if(Array.isArray(t))_=t.map(v=>v.text||"").join("");else if(t instanceof qr){let v="";t.forEach(j=>{j.text&&(v+=j.text)}),_=v}else typeof t=="object"&&t&&t.text?_=t.text:_=t;r.insertText(_,u,h)}else _=o,r.replaceWith(u,h,_);n.updateSelection&&lcs(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:_}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:_})}return!0},ucs=()=>({state:s,dispatch:t})=>cls(s,t),hcs=()=>({state:s,dispatch:t})=>dls(s,t),mcs=()=>({state:s,dispatch:t})=>nls(s,t),pcs=()=>({state:s,dispatch:t})=>ols(s,t),fcs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=Wye(s.doc,s.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},xcs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=Wye(s.doc,s.selection.$from.pos,1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},gcs=()=>({state:s,dispatch:t})=>rls(s,t),ycs=()=>({state:s,dispatch:t})=>als(s,t);function uxt(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function vcs(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=vcs(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 kB(s,t,n={}){const{from:r,to:a,empty:i}=s.selection,l=t?Mp(t,s.schema):null,o=[];s.doc.nodesBetween(r,a,(h,p)=>{if(h.isText)return;const f=Math.max(r,p),g=Math.min(a,p+h.nodeSize);o.push({node:h,from:f,to:g})});const c=a-r,d=o.filter(h=>l?l.name===h.node.type.name:!0).filter(h=>Hfe(h.node.attrs,n,{strict:!1}));return i?!!d.length:d.reduce((h,p)=>h+p.to-p.from,0)>=c}const _cs=(s,t={})=>({state:n,dispatch:r})=>{const a=Mp(s,n.schema);return kB(n,a,t)?uls(n,r):!1},wcs=()=>({state:s,dispatch:t})=>fls(s,t),jcs=s=>({state:t,dispatch:n})=>{const r=Mp(s,t.schema);return Nls(r)(t,n)},Ncs=()=>({state:s,dispatch:t})=>hls(s,t);function rve(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function Xqe(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 kcs=(s,t)=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=rve(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=Mp(s,r.schema)),o==="mark"&&(l=sC(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,Xqe(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(h=>{l===h.type&&n.addMark(u,u+d.nodeSize,l.create(Xqe(h.attrs,t)))})})}),!0):!1},Scs=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),Ccs=()=>({tr:s,dispatch:t})=>{if(t){const n=new Uv(s.doc);s.setSelection(n)}return!0},Tcs=()=>({state:s,dispatch:t})=>ils(s,t),Ecs=()=>({state:s,dispatch:t})=>lls(s,t),Acs=()=>({state:s,dispatch:t})=>xls(s,t),Mcs=()=>({state:s,dispatch:t})=>vls(s,t),Ics=()=>({state:s,dispatch:t})=>yls(s,t);function FCe(s,t,n={},r={}){return NB(s,t,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}const Pcs=(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=FCe(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 hxt(s,t){const n=sC(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 Lcs(s,t){const n=new C6e(s);return t.forEach(r=>{r.steps.forEach(a=>{n.step(a)})}),n}function Dcs(s){for(let t=0;t{n(a)&&r.push({node:a,pos:i})}),r}function mxt(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 V6e(s){return t=>mxt(t.$from,s)}function Ocs(s,t){const n={from:0,to:s.content.size};return axt(s,n,t)}function Fcs(s,t){const n=Mp(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 pxt(s,t){const n=rve(typeof t=="string"?t:t.name,s.schema);return n==="node"?Fcs(s,t):n==="mark"?hxt(s,t):{}}function zcs(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 Bcs(s){const t=zcs(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 $cs(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),p=t.invert().map(u);r.push({oldRange:{from:h,to:p},newRange:{from:d,to:u}})})}),Bcs(r)}function H6e(s,t,n){const r=[];return s===t?n.resolve(s).marks().forEach(a=>{const i=n.resolve(s),l=q6e(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 Kme(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 zCe(s,t,n={}){const{empty:r,ranges:a}=s.selection,i=t?sC(t,s.schema):null;if(r)return!!(s.storedMarks||s.selection.$from.marks()).filter(h=>i?i.name===h.type.name:!0).find(h=>Hfe(h.attrs,n,{strict:!1}));let l=0;const o=[];if(a.forEach(({$from:h,$to:p})=>{const f=h.pos,g=p.pos;s.doc.nodesBetween(f,g,(_,v)=>{if(!_.isText&&!_.marks.length)return;const j=Math.max(f,v),b=Math.min(g,v+_.nodeSize),S=b-j;l+=S,o.push(..._.marks.map(A=>({mark:A,from:j,to:b})))})}),l===0)return!1;const c=o.filter(h=>i?i.name===h.mark.type.name:!0).filter(h=>Hfe(h.mark.attrs,n,{strict:!1})).reduce((h,p)=>h+p.to-p.from,0),d=o.filter(h=>i?h.mark.type!==i&&h.mark.type.excludes(i):!0).reduce((h,p)=>h+p.to-p.from,0);return(c>0?c+d:c)>=l}function Ucs(s,t,n={}){if(!t)return kB(s,null,n)||zCe(s,null,n);const r=rve(t,s.schema);return r==="node"?kB(s,t,n):r==="mark"?zCe(s,t,n):!1}function Jqe(s,t){const{nodeExtensions:n}=tve(t),r=n.find(l=>l.name===s);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},i=Qo(ci(r,"group",a));return typeof i!="string"?!1:i.split(" ").includes("list")}function G6e(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&&(G6e(i,{ignoreWhitespace:n,checkChildren:t})||(a=!1))}),a}return!1}function qcs(s){return s instanceof Fi}function Vcs(s,t,n){var r;const{selection:a}=t;let i=null;if(lxt(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,p)=>{if(d)return!1;if(u.isInline){const f=!p||p.type.allowsMarkType(n),g=!!n.isInSet(u.marks)||!u.marks.some(_=>_.type.excludes(n));d=f&&g}return!d}),d})}const Hcs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{const{selection:i}=n,{empty:l,ranges:o}=i,c=sC(s,r.schema);if(a)if(l){const d=hxt(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,(p,f)=>{const g=Math.max(f,u),_=Math.min(f+p.nodeSize,h);p.marks.find(j=>j.type===c)?p.marks.forEach(j=>{c===j.type&&n.addMark(g,_,c.create({...j.attrs,...t}))}):n.addMark(g,_,c.create(t))})});return Vcs(r,n,c)},Gcs=(s,t)=>({tr:n})=>(n.setMeta(s,t),!0),Wcs=(s,t={})=>({state:n,dispatch:r,chain:a})=>{const i=Mp(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})=>Gqe(i,{...l,...t})(n)?!0:o.clearNodes()).command(({state:o})=>Gqe(i,{...l,...t})(o,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Kcs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,a=XE(s,0,r.content.size),i=Fi.create(r,a);t.setSelection(i)}return!0},Ycs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:a,to:i}=typeof s=="number"?{from:s,to:s}:s,l=Ki.atStart(r).from,o=Ki.atEnd(r).to,c=XE(a,l,o),d=XE(i,l,o),u=Ki.create(r,c,d);t.setSelection(u)}return!0},Zcs=s=>({state:t,dispatch:n})=>{const r=Mp(s,t.schema);return Cls(r)(t,n)};function eVe(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 Qcs=({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=Kme(d,o.node().type.name,o.node().attrs);if(i instanceof Fi&&i.node.isBlock)return!o.parentOffset||!DL(l,o.pos)?!1:(r&&(s&&eVe(n,a.extensionManager.splittableMarks),t.split(o.pos).scrollIntoView()),!0);if(!o.parent.isBlock)return!1;const h=c.parentOffset===c.parent.content.size,p=o.depth===0?void 0:Dcs(o.node(-1).contentMatchAt(o.indexAfter(-1)));let f=h&&p?[{type:p,attrs:u}]:void 0,g=DL(t.doc,t.mapping.map(o.pos),1,f);if(!f&&!g&&DL(t.doc,t.mapping.map(o.pos),1,p?[{type:p}]:void 0)&&(g=!0,f=p?[{type:p,attrs:u}]:void 0),r){if(g&&(i instanceof Ki&&t.deleteSelection(),t.split(t.mapping.map(o.pos),1,f),p&&!h&&!o.parentOffset&&o.parent.type!==p)){const _=t.mapping.map(o.before()),v=t.doc.resolve(_);o.node(-1).canReplaceWith(v.index(),v.index()+1,p)&&t.setNodeMarkup(t.mapping.map(o.before()),p)}s&&eVe(n,a.extensionManager.splittableMarks),t.scrollIntoView()}return g},Xcs=(s,t={})=>({tr:n,state:r,dispatch:a,editor:i})=>{var l;const o=Mp(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 p=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 j=qr.empty;const b=c.index(-1)?1:c.index(-2)?2:3;for(let M=c.depth-b;M>=c.depth-3;M-=1)j=qr.from(c.node(M).copy(j));const S=c.indexAfter(-1){if(D>-1)return!1;M.isTextblock&&M.content.size===0&&(D=F+1)}),D>-1&&n.setSelection(Ki.near(n.doc.resolve(D))),n.scrollIntoView()}return!0}const f=d.pos===c.end()?h.contentMatchAt(0).defaultType:null,g={...Kme(p,h.type.name,h.attrs),...t},_={...Kme(p,c.node().type.name,c.node().attrs),...t};n.delete(c.pos,d.pos);const v=f?[{type:o,attrs:g},{type:f,attrs:_}]:[{type:o,attrs:g}];if(!DL(n.doc,c.pos,2))return!1;if(a){const{selection:j,storedMarks:b}=r,{splittableMarks:S}=i.extensionManager,A=b||j.$to.parentOffset&&j.$from.marks();if(n.split(c.pos,2,v).scrollIntoView(),!A||!a)return!0;const T=A.filter(L=>S.includes(L.type.name));n.ensureMarks(T)}return!0},a2e=(s,t)=>{const n=V6e(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)&&eC(s.doc,n.pos)&&s.join(n.pos),!0},i2e=(s,t)=>{const n=V6e(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)&&eC(s.doc,r)&&s.join(r),!0},Jcs=(s,t,n,r={})=>({editor:a,tr:i,state:l,dispatch:o,chain:c,commands:d,can:u})=>{const{extensions:h,splittableMarks:p}=a.extensionManager,f=Mp(s,l.schema),g=Mp(t,l.schema),{selection:_,storedMarks:v}=l,{$from:j,$to:b}=_,S=j.blockRange(b),A=v||_.$to.parentOffset&&_.$from.marks();if(!S)return!1;const T=V6e(L=>Jqe(L.type.name,h))(_);if(S.depth>=1&&T&&S.depth-T.depth<=1){if(T.node.type===f)return d.liftListItem(g);if(Jqe(T.node.type.name,h)&&f.validContent(T.node.content)&&o)return c().command(()=>(i.setNodeMarkup(T.pos,f),!0)).command(()=>a2e(i,f)).command(()=>i2e(i,f)).run()}return!n||!A||!o?c().command(()=>u().wrapInList(f,r)?!0:d.clearNodes()).wrapInList(f,r).command(()=>a2e(i,f)).command(()=>i2e(i,f)).run():c().command(()=>{const L=u().wrapInList(f,r),D=A.filter(M=>p.includes(M.type.name));return i.ensureMarks(D),L?!0:d.clearNodes()}).wrapInList(f,r).command(()=>a2e(i,f)).command(()=>i2e(i,f)).run()},eds=(s,t={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:i=!1}=n,l=sC(s,r.schema);return zCe(r,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},tds=(s,t,n={})=>({state:r,commands:a})=>{const i=Mp(s,r.schema),l=Mp(t,r.schema),o=kB(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})},sds=(s,t={})=>({state:n,commands:r})=>{const a=Mp(s,n.schema);return kB(n,a,t)?r.lift(a):r.wrapIn(a,t)},nds=()=>({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},rds=()=>({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},ads=(s,t={})=>({tr:n,state:r,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=n,c=sC(s,r.schema),{$from:d,empty:u,ranges:h}=o;if(!a)return!0;if(u&&l){let{from:p,to:f}=o;const g=(i=d.marks().find(v=>v.type===c))===null||i===void 0?void 0:i.attrs,_=q6e(d,c,g);_&&(p=_.from,f=_.to),n.removeMark(p,f,c)}else h.forEach(p=>{n.removeMark(p.$from.pos,p.$to.pos,c)});return n.removeStoredMark(c),!0},ids=(s,t={})=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=rve(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=Mp(s,r.schema)),o==="mark"&&(l=sC(s,r.schema)),a&&n.selection.ranges.forEach(c=>{const d=c.$from.pos,u=c.$to.pos;let h,p,f,g;n.selection.empty?r.doc.nodesBetween(d,u,(_,v)=>{i&&i===_.type&&(f=Math.max(v,d),g=Math.min(v+_.nodeSize,u),h=v,p=_)}):r.doc.nodesBetween(d,u,(_,v)=>{v=d&&v<=u&&(i&&i===_.type&&n.setNodeMarkup(v,void 0,{..._.attrs,...t}),l&&_.marks.length&&_.marks.forEach(j=>{if(l===j.type){const b=Math.max(v,d),S=Math.min(v+_.nodeSize,u);n.addMark(b,S,l.create({...j.attrs,...t}))}}))}),p&&(h!==void 0&&n.setNodeMarkup(h,void 0,{...p.attrs,...t}),l&&p.marks.length&&p.marks.forEach(_=>{l===_.type&&n.addMark(f,g,l.create({..._.attrs,...t}))}))}),!0):!1},ods=(s,t={})=>({state:n,dispatch:r})=>{const a=Mp(s,n.schema);return bls(a,t)(n,r)},lds=(s,t={})=>({state:n,dispatch:r})=>{const a=Mp(s,n.schema);return _ls(a,t)(n,r)};var cds=Object.freeze({__proto__:null,blur:Vls,clearContent:Hls,clearNodes:Gls,command:Wls,createParagraphNear:Kls,cut:Yls,deleteCurrentNode:Zls,deleteNode:Qls,deleteRange:Xls,deleteSelection:Jls,enter:ecs,exitCode:tcs,extendMarkRange:scs,first:ncs,focus:acs,forEach:ics,insertContent:ocs,insertContentAt:dcs,joinBackward:mcs,joinDown:hcs,joinForward:pcs,joinItemBackward:fcs,joinItemForward:xcs,joinTextblockBackward:gcs,joinTextblockForward:ycs,joinUp:ucs,keyboardShortcut:bcs,lift:_cs,liftEmptyBlock:wcs,liftListItem:jcs,newlineInCode:Ncs,resetAttributes:kcs,scrollIntoView:Scs,selectAll:Ccs,selectNodeBackward:Tcs,selectNodeForward:Ecs,selectParentNode:Acs,selectTextblockEnd:Mcs,selectTextblockStart:Ics,setContent:Pcs,setMark:Hcs,setMeta:Gcs,setNode:Wcs,setNodeSelection:Kcs,setTextSelection:Ycs,sinkListItem:Zcs,splitBlock:Qcs,splitListItem:Xcs,toggleList:Jcs,toggleMark:eds,toggleNode:tds,toggleWrap:sds,undoInputRule:nds,unsetAllMarks:rds,unsetMark:ads,updateAttributes:ids,wrapIn:ods,wrapInList:lds});const dds=Cf.create({name:"commands",addCommands(){return{...cds}}}),uds=Cf.create({name:"drop",addProseMirrorPlugins(){return[new Ym({key:new cx("tiptapDrop"),props:{handleDrop:(s,t,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),hds=Cf.create({name:"editable",addProseMirrorPlugins(){return[new Ym({key:new cx("editable"),props:{editable:()=>this.editor.options.editable}})]}}),mds=new cx("focusEvents"),pds=Cf.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new Ym({key:mds,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}}}})]}}),fds=Cf.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:p,parent:f}=h,g=h.parent.isTextblock&&p>0?o.doc.resolve(p-1):h,_=g.parent.type.spec.isolating,v=h.pos-h.parentOffset,j=_&&g.parent.childCount===1?v===h.pos:no.atStart(d).from===p;return!u||!f.type.isTextblock||f.textContent.length||!j||j&&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 Gfe()||uxt()?i:a},addProseMirrorPlugins(){return[new Ym({key:new cx("clearDocument"),appendTransaction:(s,t,n)=>{if(s.some(_=>_.getMeta("composition")))return;const r=s.some(_=>_.docChanged)&&!t.doc.eq(n.doc),a=s.some(_=>_.getMeta("preventClearDocument"));if(!r||a)return;const{empty:i,from:l,to:o}=t.selection,c=no.atStart(t.doc).from,d=no.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!G6e(n.doc))return;const p=n.tr,f=Jye({state:n,transaction:p}),{commands:g}=new eve({editor:this.editor,state:f});if(g.clearNodes(),!!p.steps.length)return p}})]}}),xds=Cf.create({name:"paste",addProseMirrorPlugins(){return[new Ym({key:new cx("tiptapPaste"),props:{handlePaste:(s,t,n)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:n})}}})]}}),gds=Cf.create({name:"tabindex",addProseMirrorPlugins(){return[new Ym({key:new cx("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class $E{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 $E(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 $E(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 $E(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 $E(o,this.editor,a,a?n:null);a&&(c.actualDepth=this.depth+1),t.push(new $E(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 yds=`.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 vds(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 bds extends Tls{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=vds(yds,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=rxt(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?[hds,qls.configure({blockSeparator:(n=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||n===void 0?void 0:n.blockSeparator}),dds,pds,fds,gds,uds,xds].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 MP(a,this)}createCommandManager(){this.commandManager=new eve({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let n;try{n=FCe(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=FCe(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const r=cxt(n,this.options.autofocus);this.view=new Zft(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:AP.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 pxt(this.state,t)}isActive(t,n){const r=typeof t=="string"?t:null,a=typeof t=="string"?n:t;return Ucs(this.state,r,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return $6e(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:n=` `,textSerializers:r={}}=t||{};return Ocs(this.state.doc,{blockSeparator:n,textSerializers:{...ixt(this.schema),...r}})}get isEmpty(){return G6e(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 $E(n,this)}get $doc(){return this.$pos(0)}}function I8(s){return new sve({find:s.find,handler:({state:t,range:n,match:r})=>{const a=Qo(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(H6e(n.from,n.to,t.doc).filter(f=>f.mark.type.excluded.find(_=>_===s.type&&_!==f.mark.type)).filter(f=>f.to>d).length)return null;un.from&&i.delete(n.from+c,d);const p=n.from+c+l.length;i.addMark(n.from+c,p,s.type.create(a||{})),i.removeStoredMark(s.type)}}})}function fxt(s){return new sve({find:s.find,handler:({state:t,range:n,match:r})=>{const a=Qo(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 BCe(s){return new sve({find:s.find,handler:({state:t,range:n,match:r})=>{const a=t.doc.resolve(n.from),i=Qo(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 SB(s){return new sve({find:s.find,handler:({state:t,range:n,match:r,chain:a})=>{const i=Qo(s.getAttributes,void 0,r)||{},l=t.tr.delete(n.from,n.to),c=l.doc.resolve(n.from).blockRange(),d=c&&S6e(c,s.type,i);if(!d)return null;if(l.wrap(c,d),s.keepMarks&&s.editor){const{selection:h,storedMarks:p}=t,{splittableMarks:f}=s.editor.extensionManager,g=p||h.$to.parentOffset&&h.$from.marks();if(g){const _=g.filter(v=>f.includes(v.type.name));l.ensureMarks(_)}}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&&eC(l.doc,n.from-1)&&(!s.joinPredicate||s.joinPredicate(r,u))&&l.join(n.from-1)}})}let dx=class $Ce{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=Qo(ci(this,"addOptions",{name:this.name}))),this.storage=Qo(ci(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new $Ce(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>nve(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new $Ce(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=Qo(ci(n,"addOptions",{name:n.name})),n.storage=Qo(ci(n,"addStorage",{name:n.name,options:n.options})),n}};function kM(s){return new Ols({find:s.find,handler:({state:t,range:n,match:r,pasteEvent:a})=>{const i=Qo(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),p=h+o.length;if(H6e(n.from,n.to,t.doc).filter(g=>g.mark.type.excluded.find(v=>v===s.type&&v!==g.mark.type)).filter(g=>g.to>h).length)return null;pn.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 _ds(s,t){const{selection:n}=s,{$from:r}=n;if(n instanceof Fi){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 wds(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var xxt={exports:{}},o2e={};/** * @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 tVe;function jds(){if(tVe)return o2e;tVe=1;var s=St;function t(h,p){return h===p&&(h!==0||1/h===1/p)||h!==h&&p!==p}var n=typeof Object.is=="function"?Object.is:t,r=s.useState,a=s.useEffect,i=s.useLayoutEffect,l=s.useDebugValue;function o(h,p){var f=p(),g=r({inst:{value:f,getSnapshot:p}}),_=g[0].inst,v=g[1];return i(function(){_.value=f,_.getSnapshot=p,c(_)&&v({inst:_})},[h,f,p]),a(function(){return c(_)&&v({inst:_}),h(function(){c(_)&&v({inst:_})})},[h]),l(f),f}function c(h){var p=h.getSnapshot;h=h.value;try{var f=p();return!n(h,f)}catch{return!0}}function d(h,p){return p()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:o;return o2e.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:u,o2e}xxt.exports=jds();var W6e=xxt.exports;const Nds=(...s)=>t=>{s.forEach(n=>{typeof n=="function"?n(t):n&&(n.current=t)})},kds=({contentComponent:s})=>{const t=W6e.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return St.createElement(St.Fragment,null,Object.values(t))};function Sds(){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]:aAe.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 Cds extends St.Component{constructor(t){var n;super(t),this.editorContentRef=St.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=Sds(),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 St.createElement(St.Fragment,null,St.createElement("div",{ref:Nds(n,this.editorContentRef),...r}),(t==null?void 0:t.contentComponent)&&St.createElement(kds,{contentComponent:t.contentComponent}))}}const Tds=N.forwardRef((s,t)=>{const n=St.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return St.createElement(Cds,{key:n,innerRef:t,...s})}),K6e=St.memo(Tds);var Eds=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},Ads=wds(Eds),gxt={exports:{}},l2e={};/** * @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 sVe;function Mds(){if(sVe)return l2e;sVe=1;var s=St,t=W6e;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 l2e.useSyncExternalStoreWithSelector=function(d,u,h,p,f){var g=i(null);if(g.current===null){var _={hasValue:!1,value:null};g.current=_}else _=g.current;g=o(function(){function j(L){if(!b){if(b=!0,S=L,L=p(L),f!==void 0&&_.hasValue){var D=_.value;if(f(D,L))return A=D}return A=L}if(D=A,r(S,L))return D;var M=p(L);return f!==void 0&&f(D,M)?D:(S=L,A=M)}var b=!1,S,A,T=h===void 0?null:h;return[function(){return j(u())},T===null?void 0:function(){return j(T())}]},[u,h,p,f]);var v=a(d,g[0],g[1]);return l(function(){_.hasValue=!0,_.value=v},[v]),c(v),v},l2e}gxt.exports=Mds();var Ids=gxt.exports;const Pds=typeof window<"u"?N.useLayoutEffect:N.useEffect;class Lds{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 Dds(s){var t;const[n]=N.useState(()=>new Lds(s.editor)),r=Ids.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:Ads);return Pds(()=>n.watch(s.editor),[s.editor,n]),N.useDebugValue(r),r}const Rds=!1,UCe=typeof window>"u",Ods=UCe||!!(typeof window<"u"&&window.next);class Y6e{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 UCe||Ods?null:this.createEditor();if(this.options.current.immediatelyRender&&UCe&&Rds)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 bds(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?Y6e.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 Z6e(s={},t=[]){const n=N.useRef(s);n.current=s;const[r]=N.useState(()=>new Y6e(n)),a=W6e.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return N.useDebugValue(a),N.useEffect(r.onRender(t)),Dds({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const Fds=N.createContext({editor:null});Fds.Consumer;const zds=N.createContext({onDragStart:void 0}),Bds=()=>N.useContext(zds);St.forwardRef((s,t)=>{const{onDragStart:n}=Bds(),r=s.as||"div";return St.createElement(r,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...s.style}})});const $ds=/^\s*>\s$/,Uds=dx.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",mu(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[SB({find:$ds,type:this.type})]}}),qds=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,Vds=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,Hds=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,Gds=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,Wds=Eb.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",mu(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[I8({find:qds,type:this.type}),I8({find:Hds,type:this.type})]},addPasteRules(){return[kM({find:Vds,type:this.type}),kM({find:Gds,type:this.type})]}}),Kds="listItem",nVe="textStyle",rVe=/^\s*([-+*])\s$/,Yds=dx.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",mu(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(Kds,this.editor.getAttributes(nVe)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=SB({find:rVe,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=SB({find:rVe,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(nVe),editor:this.editor})),[s]}}),Zds=/(^|[^`])`([^`]+)`(?!`)/,Qds=/(^|[^`])`([^`]+)`(?!`)/g,Xds=Eb.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",mu(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[I8({find:Zds,type:this.type})]},addPasteRules(){return[kM({find:Qds,type:this.type})]}}),Jds=/^```([a-z]+)?[\s\n]$/,eus=/^~~~([a-z]+)?[\s\n]$/,tus=dx.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",mu(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(no.near(r.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[BCe({find:Jds,type:this.type,getAttributes:s=>({language:s[1]})}),BCe({find:eus,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new Ym({key:new cx("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(Ki.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),s.dispatch(l),!0}}})]}}),sus=dx.create({name:"doc",topNode:!0,content:"block+"});function nus(s={}){return new Ym({view(t){return new rus(t,s)}})}class rus{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,p=t.nodeAfter;if(h||p){let f=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(f){let g=f.getBoundingClientRect(),_=h?g.bottom:g.top;h&&p&&(_=(_+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let v=this.width/2*o;r={left:g.left,right:g.right,top:_-v,bottom:_+v}}}}if(!r){let h=this.editorView.coordsAtPos(this.cursorPos),p=this.width/2*l;r={left:h.left-p,right:h.left+p,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(),p=h.width/c.offsetWidth,f=h.height/c.offsetHeight;d=h.left-c.scrollLeft*p,u=h.top-c.scrollTop*f}this.element.style.left=(r.left-d)/l+"px",this.element.style.top=(r.top-u)/o+"px",this.element.style.width=(r.right-r.left)/l+"px",this.element.style.height=(r.bottom-r.top)/o+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}dragover(t){if(!this.editorView.editable)return;let n=this.editorView.posAtCoords({left:t.clientX,top:t.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),a=r&&r.type.spec.disableDropCursor,i=typeof a=="function"?a(this.editorView,n,t):a;if(n&&!i){let l=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let o=lft(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 aus=Cf.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[nus(this.options)]}});class ih extends no{constructor(t){super(t,t)}map(t,n){let r=t.resolve(n.map(this.head));return ih.valid(r)?new ih(r):no.near(r)}content(){return ja.empty}eq(t){return t instanceof ih&&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 ih(t.resolve(n.pos))}getBookmark(){return new Q6e(this.anchor)}static valid(t){let n=t.parent;if(n.inlineContent||!ius(t)||!ous(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&&ih.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(ih.valid(c))return c}for(;;){let l=n>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!Fi.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(ih.valid(o))return o}return null}}}ih.prototype.visible=!1;ih.findFrom=ih.findGapCursorFrom;no.jsonID("gapcursor",ih);class Q6e{constructor(t){this.pos=t}map(t){return new Q6e(t.map(this.pos))}resolve(t){let n=t.resolve(this.pos);return ih.valid(n)?new ih(n):no.near(n)}}function yxt(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function ius(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||yxt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function ous(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||yxt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function lus(){return new Ym({props:{decorations:hus,createSelectionBetween(s,t,n){return t.pos==n.pos&&ih.valid(n)?new ih(n):null},handleClick:dus,handleKeyDown:cus,handleDOMEvents:{beforeinput:uus}}})}const cus=F6e({ArrowLeft:wH("horiz",-1),ArrowRight:wH("horiz",1),ArrowUp:wH("vert",-1),ArrowDown:wH("vert",1)});function wH(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 Ki){if(!i.endOfTextblock(n)||o.depth==0)return!1;c=!1,o=r.doc.resolve(t>0?o.after():o.before())}let d=ih.findGapCursorFrom(o,t,c);return d?(a&&a(r.tr.setSelection(new ih(d))),!0):!1}}function dus(s,t,n){if(!s||!s.editable)return!1;let r=s.state.doc.resolve(t);if(!ih.valid(r))return!1;let a=s.posAtCoords({left:n.clientX,top:n.clientY});return a&&a.inside>-1&&Fi.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new ih(r))),!0)}function uus(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof ih))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=qr.empty;for(let l=r.length-1;l>=0;l--)a=qr.from(r[l].createAndFill(null,a));let i=s.state.tr.replace(n.pos,n.pos,new ja(a,0,0));return i.setSelection(Ki.near(i.doc.resolve(n.pos+1))),s.dispatch(i),!1}function hus(s){if(!(s.selection instanceof ih))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",ah.create(s.doc,[Zx.widget(s.selection.head,t,{key:"gapcursor"})])}const mus=Cf.create({name:"gapCursor",addProseMirrorPlugins(){return[lus()]},extendNodeSchema(s){var t;const n={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(t=Qo(ci(s,"allowGapCursor",n)))!==null&&t!==void 0?t:null}}}),pus=dx.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",mu(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(p=>o.includes(p.type.name));d.ensureMarks(h)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),fus=dx.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]}`,mu(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=>BCe({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var Wfe=200,Ap=function(){};Ap.prototype.append=function(t){return t.length?(t=Ap.from(t),!this.length&&t||t.length=n?Ap.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};Ap.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};Ap.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)};Ap.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};Ap.from=function(t){return t instanceof Ap?t:t&&t.length?new vxt(t):Ap.empty};var vxt=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<=Wfe)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=Wfe)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}(Ap);Ap.empty=new vxt([]);var xus=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}(Ap);const gus=500;class ab{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,p)=>{if(!h.step){a||(a=this.remapping(r,p+1),i=a.maps.length),i--,u.push(h);return}if(a){u.push(new Ck(h.map));let f=h.step.map(a.slice(i)),g;f&&l.maybeStep(f).doc&&(g=l.mapping.maps[l.mapping.maps.length-1],d.push(new Ck(g,void 0,void 0,d.length+u.length))),i--,g&&a.appendMap(g,i)}else l.maybeStep(h.step);if(h.selection)return o=a?h.selection.map(a.slice(i)):h.selection,c=new ab(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;uvus&&(o=yus(o,d),l-=d),new ab(o.append(i),l)}remapping(t,n){let r=new vB;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 ab(this.items.append(t.map(n=>new Ck(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(p=>{p.selection&&o--},a);let c=n;this.items.forEach(p=>{let f=i.getMirror(--c);if(f==null)return;l=Math.min(l,f);let g=i.maps[f];if(p.step){let _=t.steps[f].invert(t.docs[f]),v=p.selection&&p.selection.map(i.slice(c+1,f));v&&o++,r.push(new Ck(g,_,v))}else r.push(new Ck(g))},a);let d=[];for(let p=n;pgus&&(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 Ck(d.invert(),c,u),p,f=a.length-1;(p=a.length&&a[f].merge(h))?a[f]=p:a.push(h)}}else l.map&&r--},this.items.length,0),new ab(Ap.from(a.reverse()),i)}}ab.empty=new ab(Ap.empty,0);function yus(s,t){let n;return s.forEach((r,a)=>{if(r.selection&&t--==0)return n=a,!1}),s.slice(n)}let Ck=class bxt{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 bxt(n.getMap().invert(),n,this.selection)}}};class Jk{constructor(t,n,r,a,i){this.done=t,this.undone=n,this.prevRanges=r,this.prevTime=a,this.prevComposition=i}}const vus=20;function bus(s,t,n,r){let a=n.getMeta(ZA),i;if(a)return a.historyState;n.getMeta(jus)&&(s=new Jk(s.done,s.undone,null,0,-1));let l=n.getMeta("appendedTransaction");if(n.steps.length==0)return s;if(l&&l.getMeta(ZA))return l.getMeta(ZA).redo?new Jk(s.done.addTransform(n,void 0,r,Yme(t)),s.undone,aVe(n.mapping.maps),s.prevTime,s.prevComposition):new Jk(s.done,s.undone.addTransform(n,void 0,r,Yme(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||!_us(n,s.prevRanges)),d=l?c2e(s.prevRanges,n.mapping):aVe(n.mapping.maps);return new Jk(s.done.addTransform(n,c?t.selection.getBookmark():void 0,r,Yme(t)),ab.empty,d,n.time,o??s.prevComposition)}else return(i=n.getMeta("rebased"))?new Jk(s.done.rebased(n,i),s.undone.rebased(n,i),c2e(s.prevRanges,n.mapping),s.prevTime,s.prevComposition):new Jk(s.done.addMaps(n.mapping.maps),s.undone.addMaps(n.mapping.maps),c2e(s.prevRanges,n.mapping),s.prevTime,s.prevComposition)}function _us(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 aVe(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 c2e(s,t){if(!s)return null;let n=[];for(let r=0;r{let a=ZA.getState(n);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(r){let i=wus(a,n,s);i&&r(t?i.scrollIntoView():i)}return!0}}const wxt=_xt(!1,!0),jxt=_xt(!0,!0),kus=Cf.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>wxt(s,t),redo:()=>({state:s,dispatch:t})=>jxt(s,t)}},addProseMirrorPlugins(){return[Nus(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()}}}),Sus=dx.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",mu(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!_ds(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}):qcs(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(Ki.create(l.doc,d.pos+1)):d.nodeAfter.isBlock?l.setSelection(Fi.create(l.doc,d.pos)):l.setSelection(Ki.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(Ki.create(l.doc,u+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[fxt({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),Cus=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,Tus=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,Eus=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Aus=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,Mus=Eb.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",mu(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[I8({find:Cus,type:this.type}),I8({find:Eus,type:this.type})]},addPasteRules(){return[kM({find:Tus,type:this.type}),kM({find:Aus,type:this.type})]}}),Ius=dx.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",mu(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)}}}),Pus="listItem",oVe="textStyle",lVe=/^(\d+)\.\s$/,Lus=dx.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",mu(this.options.HTMLAttributes,n),0]:["ol",mu(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(Pus,this.editor.getAttributes(oVe)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=SB({find:lVe,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=SB({find:lVe,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(oVe)}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1],editor:this.editor})),[s]}}),Dus=dx.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",mu(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),Rus=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Ous=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,Fus=Eb.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",mu(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[I8({find:Rus,type:this.type})]},addPasteRules(){return[kM({find:Ous,type:this.type})]}}),zus=dx.create({name:"text",group:"inline"}),X6e=Cf.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(Wds.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(Uds.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(Yds.configure(this.options.bulletList)),this.options.code!==!1&&s.push(Xds.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(tus.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(sus.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(aus.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(mus.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(pus.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(fus.configure(this.options.heading)),this.options.history!==!1&&s.push(kus.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(Sus.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(Mus.configure(this.options.italic)),this.options.listItem!==!1&&s.push(Ius.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(Lus.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(Dus.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(Fus.configure(this.options.strike)),this.options.text!==!1&&s.push(zus.configure(this.options.text)),s}}),Bus="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",$us="ελ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",qCe="numeric",VCe="ascii",HCe="alpha",lz="asciinumeric",g7="alphanumeric",GCe="domain",Nxt="emoji",Uus="scheme",qus="slashscheme",u2e="whitespace";function Vus(s,t){return s in t||(t[s]=[]),t[s]}function JE(s,t,n){t[qCe]&&(t[lz]=!0,t[g7]=!0),t[VCe]&&(t[lz]=!0,t[HCe]=!0),t[lz]&&(t[g7]=!0),t[HCe]&&(t[g7]=!0),t[g7]&&(t[GCe]=!0),t[Nxt]&&(t[GCe]=!0);for(const r in t){const a=Vus(r,n);a.indexOf(s)<0&&a.push(s)}}function Hus(s,t){const n={};for(const r in t)t[r].indexOf(s)>=0&&(n[r]=!0);return n}function Lg(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}Lg.groups={};Lg.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),Qu=(s,t,n,r,a)=>s.tr(t,n,r,a),cVe=(s,t,n,r,a)=>s.ts(t,n,r,a),Wr=(s,t,n,r,a)=>s.tt(t,n,r,a),x2="WORD",WCe="UWORD",kxt="ASCIINUMERICAL",Sxt="ALPHANUMERICAL",CB="LOCALHOST",KCe="TLD",YCe="UTLD",Zme="SCHEME",cP="SLASH_SCHEME",J6e="NUM",ZCe="WS",eIe="NL",cz="OPENBRACE",dz="CLOSEBRACE",Kfe="OPENBRACKET",Yfe="CLOSEBRACKET",Zfe="OPENPAREN",Qfe="CLOSEPAREN",Xfe="OPENANGLEBRACKET",Jfe="CLOSEANGLEBRACKET",exe="FULLWIDTHLEFTPAREN",txe="FULLWIDTHRIGHTPAREN",sxe="LEFTCORNERBRACKET",nxe="RIGHTCORNERBRACKET",rxe="LEFTWHITECORNERBRACKET",axe="RIGHTWHITECORNERBRACKET",ixe="FULLWIDTHLESSTHAN",oxe="FULLWIDTHGREATERTHAN",lxe="AMPERSAND",cxe="APOSTROPHE",dxe="ASTERISK",eS="AT",uxe="BACKSLASH",hxe="BACKTICK",mxe="CARET",mS="COLON",tIe="COMMA",pxe="DOLLAR",B_="DOT",fxe="EQUALS",sIe="EXCLAMATION",mv="HYPHEN",uz="PERCENT",xxe="PIPE",gxe="PLUS",yxe="POUND",hz="QUERY",nIe="QUOTE",Cxt="FULLWIDTHMIDDLEDOT",rIe="SEMI",$_="SLASH",mz="TILDE",vxe="UNDERSCORE",Txt="EMOJI",bxe="SYM";var Ext=Object.freeze({__proto__:null,ALPHANUMERICAL:Sxt,AMPERSAND:lxe,APOSTROPHE:cxe,ASCIINUMERICAL:kxt,ASTERISK:dxe,AT:eS,BACKSLASH:uxe,BACKTICK:hxe,CARET:mxe,CLOSEANGLEBRACKET:Jfe,CLOSEBRACE:dz,CLOSEBRACKET:Yfe,CLOSEPAREN:Qfe,COLON:mS,COMMA:tIe,DOLLAR:pxe,DOT:B_,EMOJI:Txt,EQUALS:fxe,EXCLAMATION:sIe,FULLWIDTHGREATERTHAN:oxe,FULLWIDTHLEFTPAREN:exe,FULLWIDTHLESSTHAN:ixe,FULLWIDTHMIDDLEDOT:Cxt,FULLWIDTHRIGHTPAREN:txe,HYPHEN:mv,LEFTCORNERBRACKET:sxe,LEFTWHITECORNERBRACKET:rxe,LOCALHOST:CB,NL:eIe,NUM:J6e,OPENANGLEBRACKET:Xfe,OPENBRACE:cz,OPENBRACKET:Kfe,OPENPAREN:Zfe,PERCENT:uz,PIPE:xxe,PLUS:gxe,POUND:yxe,QUERY:hz,QUOTE:nIe,RIGHTCORNERBRACKET:nxe,RIGHTWHITECORNERBRACKET:axe,SCHEME:Zme,SEMI:rIe,SLASH:$_,SLASH_SCHEME:cP,SYM:bxe,TILDE:mz,TLD:KCe,UNDERSCORE:vxe,UTLD:YCe,UWORD:WCe,WORD:x2,WS:ZCe});const a2=/[a-z]/,xF=new RegExp("\\p{L}","u"),h2e=new RegExp("\\p{Emoji}","u"),i2=/\d/,m2e=/\s/,dVe="\r",p2e=` `,Gus="️",Wus="‍",f2e="";let jH=null,NH=null;function Kus(s=[]){const t={};Lg.groups=t;const n=new Lg;jH==null&&(jH=uVe(Bus)),NH==null&&(NH=uVe($us)),Wr(n,"'",cxe),Wr(n,"{",cz),Wr(n,"}",dz),Wr(n,"[",Kfe),Wr(n,"]",Yfe),Wr(n,"(",Zfe),Wr(n,")",Qfe),Wr(n,"<",Xfe),Wr(n,">",Jfe),Wr(n,"(",exe),Wr(n,")",txe),Wr(n,"「",sxe),Wr(n,"」",nxe),Wr(n,"『",rxe),Wr(n,"』",axe),Wr(n,"<",ixe),Wr(n,">",oxe),Wr(n,"&",lxe),Wr(n,"*",dxe),Wr(n,"@",eS),Wr(n,"`",hxe),Wr(n,"^",mxe),Wr(n,":",mS),Wr(n,",",tIe),Wr(n,"$",pxe),Wr(n,".",B_),Wr(n,"=",fxe),Wr(n,"!",sIe),Wr(n,"-",mv),Wr(n,"%",uz),Wr(n,"|",xxe),Wr(n,"+",gxe),Wr(n,"#",yxe),Wr(n,"?",hz),Wr(n,'"',nIe),Wr(n,"/",$_),Wr(n,";",rIe),Wr(n,"~",mz),Wr(n,"_",vxe),Wr(n,"\\",uxe),Wr(n,"・",Cxt);const r=Qu(n,i2,J6e,{[qCe]:!0});Qu(r,i2,r);const a=Qu(r,a2,kxt,{[lz]:!0}),i=Qu(r,xF,Sxt,{[g7]:!0}),l=Qu(n,a2,x2,{[VCe]:!0});Qu(l,i2,a),Qu(l,a2,l),Qu(a,i2,a),Qu(a,a2,a);const o=Qu(n,xF,WCe,{[HCe]:!0});Qu(o,a2),Qu(o,i2,i),Qu(o,xF,o),Qu(i,i2,i),Qu(i,a2),Qu(i,xF,i);const c=Wr(n,p2e,eIe,{[u2e]:!0}),d=Wr(n,dVe,ZCe,{[u2e]:!0}),u=Qu(n,m2e,ZCe,{[u2e]:!0});Wr(n,f2e,u),Wr(d,p2e,c),Wr(d,f2e,u),Qu(d,m2e,u),Wr(u,dVe),Wr(u,p2e),Qu(u,m2e,u),Wr(u,f2e,u);const h=Qu(n,h2e,Txt,{[Nxt]:!0});Wr(h,"#"),Qu(h,h2e,h),Wr(h,Gus,h);const p=Wr(h,Wus);Wr(p,"#"),Qu(p,h2e,h);const f=[[a2,l],[i2,a]],g=[[a2,null],[xF,o],[i2,i]];for(let _=0;__[0]>v[0]?1:-1);for(let _=0;_=0?b[GCe]=!0:a2.test(v)?i2.test(v)?b[lz]=!0:b[VCe]=!0:b[qCe]=!0,cVe(n,v,v,b)}return cVe(n,"localhost",CB,{ascii:!0}),n.jd=new Lg(bxe),{start:n,tokens:Object.assign({groups:t},Ext)}}function Axt(s,t){const n=Yus(t.replace(/[A-Z]/g,o=>o.toLowerCase())),r=n.length,a=[];let i=0,l=0;for(;l=0&&(h+=n[l].length,p++),d+=n[l].length,i+=n[l].length,l++;i-=h,l-=p,d-=h,a.push({t:u.t,v:t.slice(i-d,i),s:i-d,e:i})}return a}function Yus(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 Tk(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 TB={defaultProtocol:"http",events:null,format:hVe,formatHref:hVe,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function aIe(s,t=null){let n=Object.assign({},TB);s&&(n=Object.assign(n,s instanceof aIe?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=TB.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 ave(s,t){class n extends Mxt{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 mVe=ave("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),pVe=ave("text"),Zus=ave("nl"),kH=ave("url",{isLink:!0,toHref(s=TB.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==CB&&s[1].t===mS}}),nv=s=>new Lg(s);function Qus({groups:s}){const t=s.domain.concat([lxe,dxe,eS,uxe,hxe,mxe,pxe,fxe,mv,J6e,uz,xxe,gxe,yxe,$_,bxe,mz,vxe]),n=[cxe,mS,tIe,B_,sIe,uz,hz,nIe,rIe,Xfe,Jfe,cz,dz,Yfe,Kfe,Zfe,Qfe,exe,txe,sxe,nxe,rxe,axe,ixe,oxe],r=[lxe,cxe,dxe,uxe,hxe,mxe,pxe,fxe,mv,cz,dz,uz,xxe,gxe,yxe,hz,$_,bxe,mz,vxe],a=nv(),i=Wr(a,mz);Zo(i,r,i),Zo(i,s.domain,i);const l=nv(),o=nv(),c=nv();Zo(a,s.domain,l),Zo(a,s.scheme,o),Zo(a,s.slashscheme,c),Zo(l,r,i),Zo(l,s.domain,l);const d=Wr(l,eS);Wr(i,eS,d),Wr(o,eS,d),Wr(c,eS,d);const u=Wr(i,B_);Zo(u,r,i),Zo(u,s.domain,i);const h=nv();Zo(d,s.domain,h),Zo(h,s.domain,h);const p=Wr(h,B_);Zo(p,s.domain,h);const f=nv(mVe);Zo(p,s.tld,f),Zo(p,s.utld,f),Wr(d,CB,f);const g=Wr(h,mv);Wr(g,mv,g),Zo(g,s.domain,h),Zo(f,s.domain,h),Wr(f,B_,p),Wr(f,mv,g);const _=Wr(f,mS);Zo(_,s.numeric,mVe);const v=Wr(l,mv),j=Wr(l,B_);Wr(v,mv,v),Zo(v,s.domain,l),Zo(j,r,i),Zo(j,s.domain,l);const b=nv(kH);Zo(j,s.tld,b),Zo(j,s.utld,b),Zo(b,s.domain,l),Zo(b,r,i),Wr(b,B_,j),Wr(b,mv,v),Wr(b,eS,d);const S=Wr(b,mS),A=nv(kH);Zo(S,s.numeric,A);const T=nv(kH),L=nv();Zo(T,t,T),Zo(T,n,L),Zo(L,t,T),Zo(L,n,L),Wr(b,$_,T),Wr(A,$_,T);const D=Wr(o,mS),M=Wr(c,mS),F=Wr(M,$_),z=Wr(F,$_);Zo(o,s.domain,l),Wr(o,B_,j),Wr(o,mv,v),Zo(c,s.domain,l),Wr(c,B_,j),Wr(c,mv,v),Zo(D,s.domain,T),Wr(D,$_,T),Wr(D,hz,T),Zo(z,s.domain,T),Zo(z,t,T),Wr(z,$_,T);const V=[[cz,dz],[Kfe,Yfe],[Zfe,Qfe],[Xfe,Jfe],[exe,txe],[sxe,nxe],[rxe,axe],[ixe,oxe]];for(let W=0;W=0&&p++,a++,u++;if(p<0)a-=u,a0&&(i.push(x2e(pVe,t,l)),l=[]),a-=p,u-=p;const f=h.t,g=n.slice(a-u,a);i.push(x2e(f,t,g))}}return l.length>0&&i.push(x2e(pVe,t,l)),i}function x2e(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 Jus=typeof console<"u"&&console&&console.warn||(()=>{}),ehs="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",Dd={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function ths(){return Lg.groups={},Dd.scanner=null,Dd.parser=null,Dd.tokenQueue=[],Dd.pluginQueue=[],Dd.customSchemes=[],Dd.initialized=!1,Dd}function fVe(s,t=!1){if(Dd.initialized&&Jus(`linkifyjs: already initialized - will not register custom scheme "${s}" ${ehs}`),!/^[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`);Dd.customSchemes.push([s,t])}function shs(){Dd.scanner=Kus(Dd.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=Lcs(n.doc,[...t]);if($cs(o).forEach(({newRange:d})=>{const u=Rcs(r.doc,d,f=>f.isTextblock);let h,p;if(u.length>1)h=u[0],p=r.doc.textBetween(h.pos,h.pos+h.node.nodeSize,void 0," ");else if(u.length){const f=r.doc.textBetween(d.from,d.to," "," ");if(!rhs.test(f))return;h=u[0],p=r.doc.textBetween(h.pos,d.to,void 0," ")}if(h&&p){const f=p.split(nhs).filter(Boolean);if(f.length<=0)return!1;const g=f[f.length-1],_=h.pos+p.lastIndexOf(g);if(!g)return!1;const v=iIe(g).map(j=>j.toObject(s.defaultProtocol));if(!ihs(v))return!1;v.filter(j=>j.isLink).map(j=>({...j,from:_+j.start+1,to:_+j.end+1})).filter(j=>r.schema.marks.code?!r.doc.rangeHasMark(j.from,j.to,r.schema.marks.code):!0).filter(j=>s.validate(j.value)).filter(j=>s.shouldAutoLink(j.value)).forEach(j=>{H6e(j.from,j.to,r.doc).some(b=>b.mark.type===s.type)||l.addMark(j.from,j.to,s.type.create({href:j.href}))})}}),!!l.steps.length)return l}})}function lhs(s){return new Ym({key:new cx("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(p=>p.nodeName==="A"))return!1;const c=pxt(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 chs(s){return new Ym({key:new cx("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=Ixt(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 u3(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(ahs,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const lIe=Eb.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"){fVe(s);return}fVe(s.scheme,s.optionalSlashes)})},onDestroy(){ths()},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)=>!!u3(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=>!!u3(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=>!!u3(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",mu(this.options.HTMLAttributes,s),0]:["a",mu(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:n}=s;return this.options.isAllowedUri(n,{defaultValidate:r=>!!u3(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=>!!u3(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[kM({find:s=>{const t=[];if(s){const{protocols:n,defaultProtocol:r}=this.options,a=Ixt(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!u3(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(ohs({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:a=>!!u3(a,t),protocols:t,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(lhs({type:this.type})),this.options.linkOnPaste&&s.push(chs({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),cIe=Cf.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")}}}),dhs=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}`)})},dIe=Eb.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&dhs(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",mu(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}}}}),uhs=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,hhs=dx.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",mu(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[fxt({find:uhs,type:this.type,getAttributes:s=>{const[,,t,n,r]=s;return{src:n,alt:t,title:r}}})]}});let QCe,XCe;if(typeof WeakMap<"u"){let s=new WeakMap;QCe=t=>s.get(t),XCe=(t,n)=>(s.set(t,n),n)}else{const s=[];let n=0;QCe=r=>{for(let a=0;a(n==10&&(n=0),s[n++]=r,s[n++]=a)}var oh=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:j-S});break}const A=a+S*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 fhs(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 ghs(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 Pb(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 ive(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=SM(t.$head)||yhs(t.$head);if(n)return n;throw new RangeError(`No cell found around position ${t.head}`)}function yhs(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 JCe(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function vhs(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function uIe(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function Pxt(s,t,n){const r=s.node(-1),a=oh.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 CM(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 Lxt(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 p=i+u+1;return new mft(o.resolve(p),o.resolve(p+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(JCe(r)&&JCe(a)&&uIe(r,a)){const i=this.$anchorCell.node(-1)!=r.node(-1);return i&&this.isRowSelection()?g2.rowSelection(r,a):i&&this.isColSelection()?g2.colSelection(r,a):new g2(r,a)}return Ki.between(r,a)}content(){const t=this.$anchorCell.node(-1),n=oh.get(t),r=this.$anchorCell.start(-1),a=n.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),i={},l=[];for(let c=a.top;c0||v>0){let j=g.attrs;if(_>0&&(j=CM(j,0,_)),v>0&&(j=CM(j,j.colspan-v,v)),f.lefta.bottom){const j={...g.attrs,rowspan:Math.min(f.bottom,a.bottom)-Math.max(f.top,a.top)};f.top0)return!1;const r=t+this.$anchorCell.nodeAfter.attrs.rowspan,a=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,a)==this.$headCell.node(-1).childCount}static colSelection(t,n=t){const r=t.node(-1),a=oh.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 g2&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,n=t){const r=t.node(-1),a=oh.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(Zx.node(r,r+n.nodeSize,{class:"selectedCell"}))}),ah.create(s.doc,t)}function jhs({$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 Nhs({$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 khs(s,t,n){const r=(t||s).selection,a=(t||s).doc;let i,l;if(r instanceof Fi&&(l=r.node.type.spec.tableRole)){if(l=="cell"||l=="header_cell")i=jd.create(a,r.from);else if(l=="row"){const o=a.resolve(r.from+1);i=jd.rowSelection(o,o)}else if(!n){const o=oh.get(r.node),c=r.from+1,d=c+o.map[o.width*o.height-1];i=jd.create(a,c+1,d)}}else r instanceof Ki&&jhs(r)?i=Ki.create(a,r.from):r instanceof Ki&&Nhs(r)&&(i=Ki.create(a,r.$from.start(),r.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const Shs=new cx("fix-tables");function Rxt(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=Chs(s,a,i,n))};return t?t.doc!=s.doc&&Rxt(t.doc,s.doc,0,r):s.doc.descendants(r),n}function Chs(s,t,n,r){const a=oh.get(t);if(!a.problems)return r;r||(r=s.tr);const i=[];for(let c=0;c0){let f="cell";u.firstChild&&(f=u.firstChild.type.spec.tableRole);const g=[];for(let v=0;v0?-1:0;bhs(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;Ihs(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 p=n.nodeAt(h).attrs;s.setNodeMarkup(s.mapping.slice(o).map(h+r),null,{...p,rowspan:p.rowspan-1}),d+=p.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=xVe(d)?c+1:u;i.replaceWith(h+r.tableStart,u+r.tableStart,o)}i.setSelection(new jd(i.doc.resolve(c+r.tableStart))),t(i)}return!0}function yVe(s,t){const n=ax(s.schema);return Fhs(({node:r})=>n[r.type.spec.tableRole])(s,t)}function Fhs(s){return(t,n)=>{const r=t.selection;let a,i;if(r instanceof jd){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;a=r.$anchorCell.nodeAfter,i=r.$anchorCell.pos}else{var l;if(a=ghs(r.$from),!a)return!1;i=(l=SM(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=Qw(t),h=t.tr;for(let f=0;f{l.attrs[s]!==t&&i.setNodeMarkup(o,null,{...l.attrs,[s]:t})}):i.setNodeMarkup(a.pos,null,{...a.nodeAfter.attrs,[s]:t}),r(i)}return!0}}function Bhs(s){return function(t,n){if(!Pb(t))return!1;if(n){const r=ax(t.schema),a=Qw(t),i=t.tr,l=a.map.cellsInRect(s=="column"?{left:a.left,top:0,right:a.right,bottom:a.map.height}:s=="row"?{left:0,top:a.top,right:a.map.width,bottom:a.bottom}:a),o=l.map(c=>a.table.nodeAt(c));for(let c=0;c{const f=p+i.tableStart,g=l.doc.nodeAt(f);g&&l.setNodeMarkup(f,h,g.attrs)}),r(l)}return!0}}EB("row",{useDeprecatedLogic:!0});EB("column",{useDeprecatedLogic:!0});const $hs=EB("cell",{useDeprecatedLogic:!0});function Uhs(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 SH(s,t){const n=s.selection;if(!(n instanceof jd))return!1;if(t){const r=s.tr,a=ax(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 ja(a,0,0))}),r.docChanged&&t(r)}return!0}function Vhs(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(qr.empty),n[a]r&&(p=p.type.createChecked(CM(p.attrs,p.attrs.colspan,u+p.attrs.colspan-r),p.content)),d.push(p),u+=p.attrs.colspan;for(let f=1;fa&&(h=h.type.create({...h.attrs,rowspan:Math.max(1,a-h.attrs.rowspan)},h.content)),c.push(h)}i.push(qr.from(c))}n=i,t=a}return{width:s,height:t,rows:n}}function Whs(s,t,n,r,a,i,l){const o=s.doc.type.schema,c=ax(o);let d,u;if(a>t.width)for(let h=0,p=0;ht.height){const h=[];for(let g=0,_=(t.height-1)*t.width;g=t.width?!1:n.nodeAt(t.map[_+g]).type==c.header_cell;h.push(v?u||(u=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const p=c.row.create(null,qr.from(h)),f=[];for(let g=t.height;g{if(!a)return!1;const i=n.selection;if(i instanceof jd)return Qme(n,r,no.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=Bxt(a,s,t);if(l==null)return!1;if(s=="horiz")return Qme(n,r,no.near(n.doc.resolve(i.head+t),t));{const o=n.doc.resolve(l),c=Pxt(o,s,t);let d;return c?d=no.near(c,1):t<0?d=no.near(n.doc.resolve(o.before(-1)),-1):d=no.near(n.doc.resolve(o.after(-1)),1),Qme(n,r,d)}}}function TH(s,t){return(n,r,a)=>{if(!a)return!1;const i=n.selection;let l;if(i instanceof jd)l=i;else{const c=Bxt(a,s,t);if(c==null)return!1;l=new jd(n.doc.resolve(c))}const o=Pxt(l.$headCell,s,t);return o?Qme(n,r,new jd(l.$anchorCell,o)):!1}}function Yhs(s,t){const n=s.state.doc,r=SM(n.resolve(t));return r?(s.dispatch(s.state.tr.setSelection(new jd(r))),!0):!1}function Zhs(s,t,n){if(!Pb(s.state))return!1;let r=Vhs(n);const a=s.state.selection;if(a instanceof jd){r||(r={width:1,height:1,rows:[qr.from(e3e(ax(s.state.schema).cell,n))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=oh.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return r=Ghs(r,o.right-o.left,o.bottom-o.top),jVe(s.state,s.dispatch,l,o,r),!0}else if(r){const i=ive(s.state),l=i.start(-1);return jVe(s.state,s.dispatch,l,oh.get(i.node(-1)).findCell(i.pos-l),r),!0}else return!1}function Qhs(s,t){var n;if(t.button!=0||t.ctrlKey||t.metaKey)return;const r=NVe(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof jd)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&r&&(a=SM(s.state.selection.$anchor))!=null&&((n=g2e(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=g2e(s,d);const h=pS.getState(s.state)==null;if(!u||!uIe(c,u))if(h)u=c;else return;const p=new jd(c,u);if(h||!s.state.selection.eq(p)){const f=s.state.tr.setSelection(p);h&&f.setMeta(pS,c.pos),s.dispatch(f)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),pS.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(pS,-1))}function o(c){const d=c,u=pS.getState(s.state);let h;if(u!=null)h=s.state.doc.resolve(u);else if(NVe(s,d.target)!=r&&(h=g2e(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 Bxt(s,t,n){if(!(s.state.selection instanceof Ki))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 NVe(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function g2e(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&&SM(s.state.doc.resolve(r))||SM(s.state.doc.resolve(a))}var Xhs=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")),t3e(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,t3e(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function t3e(s,t,n,r,a,i){let l=0,o=!0,c=t.firstChild;const d=s.firstChild;if(d){for(let h=0,p=0;hnew r(h,n,p)),new ems(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=Q0.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{tms(l,o,s,a)},mouseleave:l=>{sms(l)},mousedown:(l,o)=>{nms(l,o,t,n)}},decorations:l=>{const o=Q0.getState(l);if(o&&o.activeHandle>-1)return lms(l,o.activeHandle)},nodeViews:{}}});return i}var ems=class Xme{constructor(t,n){this.activeHandle=t,this.dragging=n}apply(t){const n=this,r=t.getMeta(Q0);if(r&&r.setHandle!=null)return new Xme(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new Xme(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&t.docChanged){let a=t.mapping.map(n.activeHandle,-1);return JCe(t.doc.resolve(a))||(a=-1),new Xme(a,n.dragging)}return n}};function tms(s,t,n,r){if(!s.editable)return;const a=Q0.getState(s.state);if(a&&!a.dragging){const i=ams(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=n?l=kVe(s,t,"left",n):c-t.clientX<=n&&(l=kVe(s,t,"right",n))}if(l!=a.activeHandle){if(!r&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=oh.get(c),u=o.start(-1);if(d.colCount(o.pos-u)+o.nodeAfter.attrs.colspan-1==d.width-1)return}$xt(s,l)}}}function sms(s){if(!s.editable)return;const t=Q0.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&$xt(s,-1)}function nms(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=Q0.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=rms(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta(Q0,{setDragging:{startX:t.clientX,startWidth:c}}));function d(h){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",u);const p=Q0.getState(s.state);p!=null&&p.dragging&&(ims(s,p.activeHandle,SVe(p.dragging,h,n)),s.dispatch(s.state.tr.setMeta(Q0,{setDragging:null})))}function u(h){if(!h.which)return d(h);const p=Q0.getState(s.state);if(p&&p.dragging){const f=SVe(p.dragging,h,n);CVe(s,p.activeHandle,f,r)}}return CVe(s,l.activeHandle,c,r),i.addEventListener("mouseup",d),i.addEventListener("mousemove",u),t.preventDefault(),!0}function rms(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 mms(s,t,n,r,a){const i=hms(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!pms(t))return!1;let n=0;const r=mxt(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},fms=dx.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:dms,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}=ums(s,this.options.cellMinWidth),i=["table",mu(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=mms(i.schema,s,t,n);if(a){const o=r.selection.from+1;r.replaceSelectionWith(l).scrollIntoView().setSelection(Ki.near(r.doc.resolve(o)))}return!0},addColumnBefore:()=>({state:s,dispatch:t})=>Ths(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>Ehs(s,t),deleteColumn:()=>({state:s,dispatch:t})=>Mhs(s,t),addRowBefore:()=>({state:s,dispatch:t})=>Phs(s,t),addRowAfter:()=>({state:s,dispatch:t})=>Lhs(s,t),deleteRow:()=>({state:s,dispatch:t})=>Rhs(s,t),deleteTable:()=>({state:s,dispatch:t})=>qhs(s,t),mergeCells:()=>({state:s,dispatch:t})=>gVe(s,t),splitCell:()=>({state:s,dispatch:t})=>yVe(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>EB("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>EB("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>$hs(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>gVe(s,t)?!0:yVe(s,t),setCellAttribute:(s,t)=>({state:n,dispatch:r})=>zhs(s,t)(n,r),goToNextCell:()=>({state:s,dispatch:t})=>bVe(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>bVe(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&Oxt(s),!0),setCellSelection:s=>({tr:t,dispatch:n})=>{if(n){const r=jd.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:EH,"Mod-Backspace":EH,Delete:EH,"Mod-Delete":EH}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[Jhs({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],cms({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:Qo(ci(s,"tableRole",t))}}}),xms=dx.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",mu(this.options.HTMLAttributes,s),0]}}),gms=dx.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",mu(this.options.HTMLAttributes,s),0]}}),yms=dx.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",mu(this.options.HTMLAttributes,s),0]}});function Lb({content:s,onChange:t,placeholder:n="Enter content...",minHeight:r="150px",compact:a=!1}){const[i,l]=N.useState(!1),[o,c]=N.useState(""),[d,u]=N.useState(!0),h=Z6e({extensions:[X6e,lIe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),cIe.configure({types:["heading","paragraph"]}),dIe,hhs.extend({addAttributes(){var _;return{...(_=this.parent)==null?void 0:_.call(this),width:{default:null},height:{default:null},style:{default:null}}}}).configure({inline:!0,allowBase64:!0}),fms.extend({addAttributes(){var _;return{...(_=this.parent)==null?void 0:_.call(this),style:{default:null},width:{default:null},cellpadding:{default:null},cellspacing:{default:null},border:{default:null}}}}).configure({resizable:!1}),xms.extend({addAttributes(){var _;return{...(_=this.parent)==null?void 0:_.call(this),style:{default:null}}}}),gms.extend({addAttributes(){var _;return{...(_=this.parent)==null?void 0:_.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1},valign:{default:null}}}}),yms.extend({addAttributes(){var _;return{...(_=this.parent)==null?void 0:_.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1}}}})],content:s,onUpdate:({editor:_})=>{t(_.getHTML())},editorProps:{attributes:{class:"outline-none","data-placeholder":n},handlePaste:(_,v)=>{var b;const j=(b=v.clipboardData)==null?void 0:b.items;if(!j)return!1;for(const S of Array.from(j))if(S.type.startsWith("image/")){v.preventDefault();const A=S.getAsFile();if(!A)continue;const T=new FileReader;return T.onload=L=>{var M;const D=(M=L.target)==null?void 0:M.result;_.dispatch(_.state.tr.replaceSelectionWith(_.state.schema.nodes.image.create({src:D})))},T.readAsDataURL(A),!0}return!1}}});N.useEffect(()=>{h&&s!==h.getHTML()&&h.commands.setContent(s)},[s,h]);const p=()=>{if(!h)return;const _=h.getAttributes("link").href||"",v=h.getAttributes("link").target;c(_),u(v==="_blank"),l(!0)},f=()=>{h&&(o===""?h.chain().focus().extendMarkRange("link").unsetLink().run():h.chain().focus().extendMarkRange("link").setLink({href:o,target:d?"_blank":null,rel:d?"noopener noreferrer nofollow":null}).run(),l(!1),c(""))},g=()=>{h&&h.chain().focus().extendMarkRange("link").unsetLink().run()};return h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleHeading({level:1}).run(),className:h.isActive("heading",{level:1})?"bg-muted":"",title:"Heading 1",children:e.jsx(nL,{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(rL,{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(KS,{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(JS,{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(Tp,{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(Ov,{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(_A,{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(bA,{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(wA,{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:p,className:h.isActive("link")?"bg-muted":"",title:"Add Link",children:e.jsx(Jo,{className:"h-4 w-4"})}),h.isActive("link")&&e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:g,title:"Remove Link",children:e.jsx(Jo,{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(d4,{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(o4,{className:"h-4 w-4"})})]}),e.jsx(K6e,{editor:h,className:"prose prose-sm max-w-none p-3 focus:outline-none [&_.ProseMirror]:outline-none [&_.ProseMirror_img]:max-w-none [&_.ProseMirror_table]:border-none [&_.ProseMirror_table]:border-collapse [&_.ProseMirror_td]:border-none [&_.ProseMirror_td]:p-0 [&_.ProseMirror_td]:align-top [&_.ProseMirror_th]:border-none [&_.ProseMirror_th]:p-0 [&_.ProseMirror_tr]:border-none",style:{minHeight:r}})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Insert Link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"link-url",children:"URL"}),e.jsx(ye,{id:"link-url",value:o,onChange:_=>c(_.target.value),placeholder:"https://example.com"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(bn,{id:"link-new-tab",checked:d,onCheckedChange:u}),e.jsx(se,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:f,children:o?"Apply Link":"Remove Link"})]})]})})]}):null}var vms=Object.defineProperty,bms=(s,t,n)=>t in s?vms(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,su=(s,t,n)=>bms(s,typeof t!="symbol"?t+"":t,n);const _xe={x:0,y:0,width:0,height:0,unit:"px"},kI=(s,t,n)=>Math.min(Math.max(s,t),n),_ms=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),AVe=(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 wms(s,t,n,r){const a=U_(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==="%"?tS(a,n,r):a}function jms(s,t,n){const r=U_(s,t,n);return r.x=(t-r.width)/2,r.y=(n-r.height)/2,s.unit==="%"?tS(r,t,n):r}function tS(s,t,n){return s.unit==="%"?{..._xe,...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 U_(s,t,n){return s.unit?s.unit==="px"?{..._xe,...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}:{..._xe,...s,unit:"px"}}function MVe(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),p=Math.min(o,r),f=Math.min(c,a);t&&(t>1?(u=l?l*t:u,h=u/t,p=o*t):(h=i?i/t:h,u=h*t,f=c/t)),d.y<0&&(d.height=Math.max(d.height+d.y,h),d.y=0),d.x<0&&(d.width=Math.max(d.width+d.x,u),d.x=0);const g=r-(d.x+d.width);g<0&&(d.x=Math.min(d.x,r-u),d.width+=g);const _=a-(d.y+d.height);if(_<0&&(d.y=Math.min(d.y,a-h),d.height+=_),d.widthp&&((n==="sw"||n=="nw")&&(d.x-=p-d.width),d.width=p),d.height>f&&((n==="nw"||n=="ne")&&(d.y-=f-d.height),d.height=f),t){const v=d.width/d.height;if(vt){const j=Math.max(d.height*t,u);(n==="sw"||n=="nw")&&(d.x-=j-d.width),d.width=j}}return d}function Nms(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 SI={capture:!0,passive:!1};let kms=0;const qk=class $1 extends N.PureComponent{constructor(){super(...arguments),su(this,"docMoveBound",!1),su(this,"mouseDownOnCrop",!1),su(this,"dragStarted",!1),su(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0}),su(this,"componentRef",N.createRef()),su(this,"mediaRef",N.createRef()),su(this,"resizeObserver"),su(this,"initChangeCalled",!1),su(this,"instanceId",`rc-${kms++}`),su(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1}),su(this,"onCropPointerDown",t=>{const{crop:n,disabled:r}=this.props,a=this.getBox();if(!n)return;const i=U_(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 p=t.clientX-a.x,f=t.clientY-a.y;let g=0,_=0;l==="ne"||l=="e"?(g=p-(i.x+i.width),_=f-i.y,u=i.x,h=i.y+i.height):l==="se"||l==="s"?(g=p-(i.x+i.width),_=f-(i.y+i.height),u=i.x,h=i.y):l==="sw"||l=="w"?(g=p-i.x,_=f-(i.y+i.height),u=i.x+i.width,h=i.y):(l==="nw"||l=="n")&&(g=p-i.x,_=f-i.y,u=i.x+i.width,h=i.y+i.height),c=u+a.x+g,d=h+a.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})}),su(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(U_(u,o.width,o.height),tS(u,o.width,o.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})}),su(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(),AVe(n,c)||a(U_(c,l.width,l.height),tS(c,l.width,l.height))}),su(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)?$1.nudgeStepLarge:t.shiftKey?$1.nudgeStepMedium:$1.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=kI(d.x,0,c.width-d.width),d.y=kI(d.y,0,c.height-d.height);const h=U_(d,c.width,c.height),p=tS(d,c.width,c.height);a(h,p),i&&i(h,p)}}),su(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,p=this.getBox();if(i||!a)return;if(t.key==="ArrowUp"||t.key==="ArrowDown"||t.key==="ArrowLeft"||t.key==="ArrowRight")t.stopPropagation(),t.preventDefault();else return;const f=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?$1.nudgeStepLarge:t.shiftKey?$1.nudgeStepMedium:$1.nudgeStep,g=U_(a,p.width,p.height),_=Nms(g,t.key,f,n),v=MVe(_,r,n,p.width,p.height,l,o,c,d);if(!AVe(a,v)){const j=tS(v,p.width,p.height);u(v,j),h&&h(v,j)}}),su(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(U_(n,l.width,l.height),tS(n,l.width,l.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))}),su(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(U_(n,a,i),tS(n,a,i))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.document.addEventListener("pointermove",this.onDocPointerMove,SI),this.document.addEventListener("pointerup",this.onDocPointerDone,SI),this.document.addEventListener("pointercancel",this.onDocPointerDone,SI),this.docMoveBound=!0)}unbindDocMove(){this.docMoveBound&&(this.document.removeEventListener("pointermove",this.onDocPointerMove,SI),this.document.removeEventListener("pointerup",this.onDocPointerDone,SI),this.document.removeEventListener("pointercancel",this.onDocPointerDone,SI),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=kI(t.startCropX+a,0,n.width-r.width),r.y=kI(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,p=t.clientY-t.startClientY;(l&&u==="nw"||u==="w"||u==="sw")&&(h=Math.min(h,-l)),(o&&u==="nw"||u==="n"||u==="ne")&&(p=Math.min(p,-o));const f={unit:"px",x:0,y:0,width:0,height:0};d==="ne"?(f.x=t.startCropX,f.width=h,n?(f.height=f.width/n,f.y=t.startCropY-f.height):(f.height=Math.abs(p),f.y=t.startCropY-f.height)):d==="se"?(f.x=t.startCropX,f.y=t.startCropY,f.width=h,n?f.height=f.width/n:f.height=p):d==="sw"?(f.x=t.startCropX+h,f.y=t.startCropY,f.width=Math.abs(h),n?f.height=f.width/n:f.height=p):d==="nw"&&(f.x=t.startCropX+h,f.width=Math.abs(h),n?(f.height=f.width/n,f.y=t.startCropY-f.height):(f.height=Math.abs(p),f.y=t.startCropY+p));const g=MVe(f,n,d,i.width,i.height,l,o,r,a);return n||$1.xyOrds.indexOf(u)>-1?c=g:$1.xOrds.indexOf(u)>-1?(c.x=g.x,c.width=g.width):$1.yOrds.indexOf(u)>-1&&(c.y=g.y,c.height=g.height),c.x=kI(c.x,0,i.width-c.width),c.y=kI(c.y,0,i.height-c.height),c}renderCropSelection(){const{ariaLabels:t=$1.defaultProps.ariaLabels,disabled:n,locked:r,renderSelectionAddon:a,ruleOfThirds:i,crop:l}=this.props,o=this.getCropStyle();if(l)return St.createElement("div",{style:o,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":t.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!n&&!r&&St.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},St.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),St.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),St.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),St.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),St.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"}),St.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"}),St.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"}),St.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"}),St.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"}),St.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"}),St.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"}),St.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&&St.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:c=>c.stopPropagation()},a(this.state)),i&&St.createElement(St.Fragment,null,St.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),St.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(t){const n={..._xe,...this.props.crop||{}};return U_(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,p=i?this.renderCropSelection():null,f=_ms("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 St.createElement("div",{ref:this.componentRef,className:f,style:c},St.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},n),i?St.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},St.createElement("defs",null,St.createElement("mask",{id:`hole-${this.instanceId}`},St.createElement("rect",{width:"100%",height:"100%",fill:"white"}),r?St.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"}):St.createElement("rect",{x:`${i.x}${i.unit}`,y:`${i.y}${i.unit}`,width:`${i.width}${i.unit}`,height:`${i.height}${i.unit}`,fill:"black"}))),St.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,p)}};su(qk,"xOrds",["e","w"]),su(qk,"yOrds",["n","s"]),su(qk,"xyOrds",["nw","ne","se","sw"]),su(qk,"nudgeStep",1),su(qk,"nudgeStepMedium",10),su(qk,"nudgeStepLarge",100),su(qk,"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 Sms=qk;function Cms(s,t,n){return jms(wms({unit:"%",width:90},n,s,t),s,t)}const hIe=({open:s,onClose:t,imageSrc:n,onCropComplete:r,aspectRatio:a=1})=>{const i=N.useRef(null),[l,o]=N.useState(),[c,d]=N.useState(),[u,h]=N.useState(1),[p,f]=N.useState(0),g=N.useCallback(j=>{const{width:b,height:S}=j.currentTarget;o(Cms(b,S,a))},[a]),_=N.useCallback(async()=>{const j=i.current;if(!j||!c)return;const b=document.createElement("canvas"),S=b.getContext("2d");if(!S)return;const A=j.naturalWidth/j.width,T=j.naturalHeight/j.height,L=400;b.width=L,b.height=L,S.imageSmoothingQuality="high";const D=c.x*A,M=c.y*T,F=c.width*A,z=c.height*T,V=p*Math.PI/180,W=b.width/2,Y=b.height/2;return S.save(),S.translate(W,Y),S.rotate(V),S.scale(u,u),S.translate(-W,-Y),S.drawImage(j,D,M,F,z,0,0,L,L),S.restore(),new Promise((K,J)=>{b.toBlob(ne=>{ne?K(ne):J(new Error("Canvas is empty"))},"image/jpeg",.95)})},[c,u,p]),v=async()=>{try{const j=await _();j&&(r(j),t())}catch(j){console.error("Error cropping image:",j)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Crop Your Photo"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"relative max-h-[400px] overflow-hidden rounded-lg bg-muted flex items-center justify-center",children:e.jsx(Sms,{crop:l,onChange:(j,b)=>o(b),onComplete:j=>d(j),aspect:a,circularCrop:!0,className:"max-h-[400px]",children:e.jsx("img",{ref:i,src:n,alt:"Crop preview",style:{transform:`scale(${u}) rotate(${p}deg)`,maxHeight:"400px",width:"auto"},onLoad:g})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(NL,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Bm,{value:[u],min:.5,max:3,step:.1,onValueChange:([j])=>h(j),className:"flex-1"}),e.jsx(u4,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(zA,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Bm,{value:[p],min:-180,max:180,step:1,onValueChange:([j])=>f(j),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[p,"°"]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(B,{onClick:v,children:"Save Photo"})]})]})})},Tms=()=>{const{user:s}=ys(),{toast:t}=Ba(),[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(null);N.useEffect(()=>{s&&c()},[s]);const c=async()=>{r(!0);try{const{data:h}=await q.from("profiles").select("subscription_status, subscription_product_id, subscription_end_date, is_grandfathered").eq("id",s==null?void 0:s.id).single();h&&o({status:h.subscription_status||"none",productId:h.subscription_product_id,endDate:h.subscription_end_date,isGrandfathered:h.is_grandfathered||!1})}catch(h){console.error("Error loading subscription:",h)}finally{r(!1)}},d=async()=>{i(!0);try{const{data:{session:h}}=await q.auth.getSession();if(!h)throw new Error("Not authenticated");const{data:p,error:f}=await q.functions.invoke("customer-portal",{headers:{Authorization:`Bearer ${h.access_token}`}});if(f)throw f;p!=null&&p.url&&window.open(p.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(ze,{className:"bg-amber-500",children:"Grandfathered"});switch(l==null?void 0:l.status){case"active":return e.jsx(ze,{className:"bg-green-500",children:"Active"});case"trialing":return e.jsx(ze,{className:"bg-blue-500",children:"Trial"});case"past_due":return e.jsx(ze,{variant:"destructive",children:"Past Due"});case"canceled":return e.jsx(ze,{variant:"secondary",children:"Canceled"});default:return e.jsx(ze,{variant:"outline",children:"No Subscription"})}};return n?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(pf,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(pf,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(Vn,{children:"Manage your subscription and billing"})]}),e.jsxs(Ee,{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(ts,{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."})]})]})},Ems=()=>{const{user:s}=ys(),t=Mn(),{toast:n}=Ba(),[r]=gl(),a=r.get("setup")==="true",i=r.get("reset")==="true",{isSupported:l,isSubscribed:o,isLoading:c,subscribe:d,unsubscribe:u}=Rmt(),[h,p]=N.useState(!1),[f,g]=N.useState(""),[_,v]=N.useState(!1),[j,b]=N.useState(!1),[S,A]=N.useState(""),[T,L]=N.useState({name:"",email:"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1}),[D,M]=N.useState(!1),[F,z]=N.useState(!1),[V,W]=N.useState(!1),[Y,K]=N.useState(!1),[J,ne]=N.useState(!1),[ie,he]=N.useState({newPassword:"",confirmPassword:""});N.useEffect(()=>{s&&ce()},[s]),N.useEffect(()=>{i&&s&&setTimeout(()=>{var Te;(Te=document.getElementById("change-password-section"))==null||Te.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const ce=async()=>{var Te,Me,Ce,Ae;if(!(s!=null&&s.id)){console.log("No user ID available yet");return}try{console.log("Loading profile for user:",s.id);const{data:De,error:Ie}=await q.from("profiles").select("name, email, phone, digest_opt_out, event_invite_opt_out, title, bio, areas_served, years_experience, brokerage_id, brokerage_name, instagram_url, facebook_url, linkedin_url, email_signature, use_email_signature, brokerages(name)").eq("id",s.id).maybeSingle();if(Ie)throw console.error("Profile query error:",Ie),Ie;if(De){console.log("Profile loaded successfully:",De);const qe=((Te=De.brokerages)==null?void 0:Te.name)||"";M(!!De.brokerage_id),L({name:De.name||"",email:De.email||"",phone:De.phone||"",title:De.title||"",bio:De.bio||"",areas_served:De.areas_served||"",years_experience:((Me=De.years_experience)==null?void 0:Me.toString())||"",brokerage_name:De.brokerage_id?qe:De.brokerage_name||"",instagram_url:De.instagram_url||"",facebook_url:De.facebook_url||"",linkedin_url:De.linkedin_url||"",email_signature:De.email_signature||"",use_email_signature:De.use_email_signature||!1}),z(De.digest_opt_out||!1),K(De.event_invite_opt_out||!1)}else console.warn("No profile found for user"),L({name:((Ce=s.user_metadata)==null?void 0:Ce.name)||((Ae=s.email)==null?void 0:Ae.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:Fe}=await q.storage.from("avatars").list(`${s.id}`);if(Fe&&Fe.length>0){const{data:qe}=q.storage.from("avatars").getPublicUrl(`${s.id}/${Fe[0].name}`);g(qe.publicUrl)}}catch(De){console.error("Error loading profile:",De),n({title:"Error",description:De.message||"Failed to load profile",variant:"destructive"})}},pe=Te=>{var Ae;const Me=(Ae=Te.target.files)==null?void 0:Ae[0];if(!Me)return;const Ce=new FileReader;Ce.onloadend=()=>{A(Ce.result),b(!0)},Ce.readAsDataURL(Me),Te.target.value=""},le=async Te=>{if(s){v(!0);try{const{data:Me}=await q.storage.from("avatars").list(`${s.id}`);Me&&Me.length>0&&await q.storage.from("avatars").remove(Me.map(qe=>`${s.id}/${qe.name}`));const Ae=`${s.id}/avatar.jpg`,{error:De}=await q.storage.from("avatars").upload(Ae,Te,{upsert:!0,contentType:"image/jpeg"});if(De)throw De;const{data:Ie}=q.storage.from("avatars").getPublicUrl(Ae),Fe=Ie.publicUrl;g(`${Fe}?t=${Date.now()}`),await q.from("profiles").update({avatar_url:Fe}).eq("id",s.id),n({title:"Success",description:"Profile photo updated successfully"})}catch(Me){console.error("Error uploading avatar:",Me),n({title:"Error",description:Me.message||"Failed to upload photo",variant:"destructive"})}finally{v(!1)}}},ve=async()=>{if(!T.name.trim()||!T.email.trim()){n({title:"Error",description:"Name and email are required",variant:"destructive"});return}p(!0);try{const{error:Te}=await q.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,...D?{}:{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(Te)throw Te;n({title:"Success",description:"Profile updated successfully"})}catch(Te){console.error("Error updating profile:",Te),n({title:"Error",description:Te.message||"Failed to update profile",variant:"destructive"})}finally{p(!1)}},ge=async()=>{if(!ie.newPassword){n({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(ie.newPassword.length<6){n({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(ie.newPassword!==ie.confirmPassword){n({title:"Error",description:"Passwords do not match",variant:"destructive"});return}p(!0);try{const{error:Te}=await q.auth.updateUser({password:ie.newPassword});if(Te)throw Te;n({title:"Success",description:"Password updated successfully"}),he({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(Te){console.error("Error updating password:",Te),n({title:"Error",description:Te.message||"Failed to update password",variant:"destructive"})}finally{p(!1)}};return e.jsx(Ts,{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 Te;(Te=document.getElementById("change-password-section"))==null||Te.scrollIntoView({behavior:"smooth",block:"center"})},className:"gap-2",children:[e.jsx(IA,{className:"h-4 w-4"}),"Change Password"]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Profile Photo"}),e.jsx(Vn,{children:"Upload a professional photo for your profile"})]}),e.jsxs(Ee,{className:"flex items-center gap-6",children:[e.jsxs(ra,{className:"h-24 w-24",children:[e.jsx(ni,{src:f}),e.jsx(aa,{className:"text-2xl",children:T.name.split(" ").map(Te=>Te[0]).join("").toUpperCase()||"U"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:pe,disabled:_}),e.jsxs(B,{variant:"outline",onClick:()=>{var Te;return(Te=document.getElementById("avatar-upload"))==null?void 0:Te.click()},disabled:_,children:[e.jsx(Na,{className:"mr-2 h-4 w-4"}),_?"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(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Personal Information"}),e.jsx(Vn,{children:"Update your profile details"})]}),e.jsxs(Ee,{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:Te=>L({...T,name:Te.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:Te=>L({...T,email:Te.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:Te=>L({...T,phone:Te.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:Te=>L({...T,title:Te.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(Es,{id:"bio",value:T.bio,onChange:Te=>L({...T,bio:Te.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:Te=>L({...T,areas_served:Te.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:Te=>L({...T,years_experience:Te.target.value}),placeholder:"e.g., 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"brokerage_name",children:["Brokerage ",D&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(managed)"})]}),e.jsx(ye,{id:"brokerage_name",value:T.brokerage_name,onChange:Te=>L({...T,brokerage_name:Te.target.value}),placeholder:"e.g., Keller Williams Realty",disabled:D,maxLength:150}),e.jsx("p",{className:"text-xs text-muted-foreground",children:D?"Your brokerage is managed by your office and can't be changed here.":"Used as your brokerage name across ReelFlow, branding, and email signatures."})]}),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:Te=>L({...T,linkedin_url:Te.target.value}),placeholder:"LinkedIn URL"}),e.jsx(ye,{value:T.instagram_url,onChange:Te=>L({...T,instagram_url:Te.target.value}),placeholder:"Instagram URL"}),e.jsx(ye,{value:T.facebook_url,onChange:Te=>L({...T,facebook_url:Te.target.value}),placeholder:"Facebook URL"})]})]}),e.jsxs(B,{onClick:ve,disabled:h,children:[e.jsx(qo,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(sb,{className:"h-5 w-5"}),"Email Signature"]}),e.jsx(Vn,{children:"Add a signature that will be appended to emails sent via Gmail"})]}),e.jsxs(Ee,{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(bn,{checked:T.use_email_signature,onCheckedChange:Te=>L({...T,use_email_signature:Te})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Signature"}),e.jsx(Lb,{content:T.email_signature,onChange:Te=>L({...T,email_signature:Te}),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:ve,disabled:h,children:[e.jsx(qo,{className:"mr-2 h-4 w-4"}),"Save Signature"]})]})]}),e.jsxs(fe,{id:"change-password-section",children:[e.jsxs(Mt,{children:[e.jsx(It,{children:a?"Set Your Password":"Change Password"}),e.jsx(Vn,{children:a?"Create a secure password for your account":"Update your password to keep your account secure"})]}),e.jsxs(Ee,{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:ie.newPassword,onChange:Te=>he({...ie,newPassword:Te.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:ie.confirmPassword,onChange:Te=>he({...ie,confirmPassword:Te.target.value}),placeholder:"Re-enter your new password"})]}),e.jsxs(B,{onClick:ge,disabled:h,children:[e.jsx(qo,{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(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[o?e.jsx(im,{className:"h-5 w-5"}):e.jsx(pw,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(Vn,{children:"Receive browser notifications when new content is added"})]}),e.jsx(Ee,{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(bn,{checked:o,onCheckedChange:Te=>{Te?d():u()},disabled:c})]}):e.jsxs("div",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"Push notifications are not available in this browser."}),e.jsxs("p",{className:"text-xs space-y-1",children:[e.jsx("strong",{children:"Desktop:"})," Use Chrome, Firefox, or Edge.",e.jsx("br",{}),e.jsx("strong",{children:"Android:"})," Use Chrome or Firefox.",e.jsx("br",{}),e.jsx("strong",{children:"iPhone/iPad:"})," Push notifications on iOS ",e.jsx("em",{children:"only"})," work when this site is installed as an app from ",e.jsx("strong",{children:"Safari"}),". Open this site in Safari → tap the ",e.jsx("strong",{children:"Share"})," button → ",e.jsx("strong",{children:"Add to Home Screen"}),". Other browsers (Chrome, Firefox, etc.) on iOS do not support push notifications due to Apple restrictions."]})]})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[F?e.jsx(cL,{className:"h-5 w-5"}):e.jsx(Vs,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(Vn,{children:"Manage your email subscription settings"})]}),e.jsxs(Ee,{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:F?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),e.jsx(bn,{checked:!F,onCheckedChange:async Te=>{W(!0);try{const{error:Me}=await q.from("profiles").update({digest_opt_out:!Te}).eq("id",s==null?void 0:s.id);if(Me)throw Me;z(!Te),n({title:Te?"Subscribed":"Unsubscribed",description:Te?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(Me){n({title:"Error",description:Me.message||"Failed to update preference",variant:"destructive"})}finally{W(!1)}},disabled:V})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 mt-4 border-t",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Event Invite Emails"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Y?"You won't receive event invite emails (weekly digest is unaffected)":"Get invited to LevelUp live trainings and special events"})]}),e.jsx(bn,{checked:!Y,onCheckedChange:async Te=>{ne(!0);try{const{error:Me}=await q.from("profiles").update({event_invite_opt_out:!Te}).eq("id",s==null?void 0:s.id);if(Me)throw Me;K(!Te),n({title:Te?"Subscribed":"Unsubscribed",description:Te?"You will now receive event invite emails":"You will no longer receive event invite emails"})}catch(Me){n({title:"Error",description:Me.message||"Failed to update preference",variant:"destructive"})}finally{ne(!1)}},disabled:J})]})]})]}),e.jsx(gas,{}),e.jsx(Tms,{})]}),e.jsx(hIe,{open:j,onClose:()=>b(!1),imageSrc:S,onCropComplete:le,aspectRatio:1})]})})};var Ams="AspectRatio",Uxt=N.forwardRef((s,t)=>{const{ratio:n=1/1,style:r,...a}=s;return e.jsx("div",{style:{position:"relative",width:"100%",paddingBottom:`${100/n}%`},"data-radix-aspect-ratio-wrapper":"",children:e.jsx(Jr.div,{...a,ref:t,style:{...r,position:"absolute",top:0,right:0,bottom:0,left:0}})})});Uxt.displayName=Ams;var Mms=Uxt;const Ims=Mms;function Pms(){const{user:s}=ys(),t=Ht(),[n,r]=N.useState(!1),[a,i]=N.useState(!1),{data:l,isLoading:o}=ct({queryKey:["calendar-token",s==null?void 0:s.id],queryFn:async()=>{const{data:g,error:_}=await q.from("profiles").select("calendar_token").eq("id",s==null?void 0:s.id).single();if(_)throw _;return g},enabled:!!s&&a}),c=gt({mutationFn:async()=>{const g=new Uint8Array(12);crypto.getRandomValues(g);const _=btoa(String.fromCharCode(...g)).replace(/\+/g,"x").replace(/\//g,"y").replace(/=/g,"").substring(0,16),{error:v}=await q.from("profiles").update({calendar_token:_}).eq("id",s==null?void 0:s.id);if(v)throw v;return _},onSuccess:()=>{t.invalidateQueries({queryKey:["calendar-token",s==null?void 0:s.id]}),ae.success("Calendar subscription URL generated!")},onError:g=>{ae.error("Failed to generate calendar URL: "+g.message)}}),d=l!=null&&l.calendar_token?`https://dashboard.relevelup.com/api/calendar/${l.calendar_token}.ics`:null,u=async()=>{d&&(await navigator.clipboard.writeText(d),r(!0),ae.success("Calendar URL copied to clipboard!"),setTimeout(()=>r(!1),2e3))},h=()=>{d&&(window.location.href=d.replace("https://","webcal://"))},p=()=>{if(d){const g=d.replace("https://","webcal://"),_=`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(g)}`;window.open(_,"_blank")}},f=()=>{if(d){const g=`https://outlook.live.com/calendar/0/addfromweb?url=${encodeURIComponent(d)}&name=Level%20Up%20Events`;window.open(g,"_blank")}};return e.jsxs(bs,{open:a,onOpenChange:i,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-5 w-5 text-primary"}),"Subscribe to Events Calendar"]}),e.jsx(Qn,{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(ts,{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(Ir,{className:"h-4 w-4 text-green-500"}):e.jsx(Xr,{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:p,children:[e.jsxs("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:[e.jsx("path",{d:"M19.5 22h-15A2.5 2.5 0 0 1 2 19.5v-15A2.5 2.5 0 0 1 4.5 2H9v2H4.5a.5.5 0 0 0-.5.5v15a.5.5 0 0 0 .5.5h15a.5.5 0 0 0 .5-.5V15h2v4.5a2.5 2.5 0 0 1-2.5 2.5z"}),e.jsx("path",{d:"M12 2v8.5a1.5 1.5 0 0 0 1.5 1.5H22V2h-10z",fill:"#4285F4"}),e.jsx("path",{d:"M12 12V2H4.5A2.5 2.5 0 0 0 2 4.5V12h10z",fill:"#34A853"}),e.jsx("path",{d:"M2 12v7.5A2.5 2.5 0 0 0 4.5 22H12v-10H2z",fill:"#FBBC05"}),e.jsx("path",{d:"M12 22h7.5a2.5 2.5 0 0 0 2.5-2.5V12h-10v10z",fill:"#EA4335"})]}),"Add to Google Calendar",e.jsx(tr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(B,{variant:"outline",className:"w-full justify-start gap-2",onClick:f,children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M7.88 12.04q0 .45-.11.87-.1.41-.33.74-.22.33-.58.52-.37.2-.87.2t-.85-.2q-.35-.21-.57-.55-.22-.33-.33-.75-.1-.42-.1-.86t.1-.87q.1-.43.34-.76.22-.34.59-.54.36-.2.87-.2t.86.2q.35.21.57.55.22.34.31.77.1.43.1.88zM24 12v9.38q0 .46-.33.8-.33.32-.8.32H7.13q-.46 0-.8-.33-.32-.33-.32-.8V18H1q-.41 0-.7-.3-.3-.29-.3-.7V7q0-.41.3-.7Q.58 6 1 6h6.5V2.55q0-.44.3-.75.3-.3.75-.3h12.9q.44 0 .75.3.3.3.3.75V12zm-6-8.25v3h3v-3zm0 4.5v3h3v-3zm0 4.5v1.83l3.05-1.83zm-5.25-9v3h3.75v-3zm0 4.5v3h3.75v-3zm0 4.5v2.03l2.41 1.5 1.34-.81v-2.72zM9 3.75V6h2l.13.01.12.04v-2.3zM5.98 15.98q.9 0 1.6-.3.7-.32 1.19-.86.48-.55.73-1.28.25-.74.25-1.61 0-.83-.25-1.55-.24-.71-.71-1.24t-1.15-.83q-.68-.3-1.55-.3-.92 0-1.64.3-.71.3-1.2.85-.5.54-.75 1.3-.25.74-.25 1.63 0 .85.26 1.56.26.72.74 1.23.48.52 1.17.81.69.3 1.56.3zM7.5 21h12.39L12 16.08V17q0 .41-.3.7-.29.3-.7.3H7.5zm15-.13v-7.24l-5.9 3.54Z"})}),"Add to Outlook",e.jsx(tr,{className:"h-3 w-3 ml-auto opacity-50"})]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center pt-2",children:"Events sync automatically. If your membership expires, the calendar will show as empty."})]}):e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate your personal calendar subscription URL to get started."}),e.jsx(B,{onClick:()=>c.mutate(),disabled:c.isPending,className:"w-full",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const Lms={first_timer:ca,regular:Q2,dedicated:bc,veteran:vo,streak_master:Dc,century:vo},Dms={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 IVe(s){return s===1?e.jsx(vo,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(Q2,{className:"h-5 w-5 text-gray-400"}):s===3?e.jsx(bc,{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 qxt({showUserStats:s=!0,compact:t=!1,brokerageId:n,title:r="Event Leaderboard"}){const{user:a}=ys(),{data:i,isLoading:l}=cpt(t?5:10,n),{data:o}=dpt(a==null?void 0:a.id),{data:c}=hpt(a==null?void 0:a.id),{data:d}=upt(a==null?void 0:a.id);return l?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(vo,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((u,h)=>e.jsx(Ws,{className:"h-12 w-full"},h))})})]}):e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(vo,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsxs(Ee,{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(ze,{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(Dc,{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=Lms[u.badge_type]||ca;return e.jsxs(ze,{variant:"outline",className:`text-xs ${Dms[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(ze,{variant:"outline",className:"text-xs",children:["+",d.length-4," more"]})]})]}),e.jsxs(Br,{defaultValue:"points",className:"w-full",children:[e.jsxs(Fr,{className:"w-full mb-3",children:[e.jsx(Kt,{value:"points",className:"flex-1",children:"By Points"}),e.jsx(Kt,{value:"events",className:"flex-1",children:"By Events"})]}),e.jsx(is,{value:"points",className:"mt-0",children:e.jsxs("div",{className:"space-y-2",children:[i==null?void 0:i.map((u,h)=>{var p,f,g;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${u.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${h===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:IVe(h+1)}),e.jsx(ra,{className:"h-8 w-8",children:e.jsx(aa,{className:"text-xs",children:((f=(p=u.profile)==null?void 0:p.name)==null?void 0:f.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((g=u.profile)==null?void 0:g.name)||"Unknown",u.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.total_events_attended," events"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold text-primary",children:u.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"pts"})]})]},u.user_id)}),(!i||i.length===0)&&e.jsx("div",{className:"text-center text-muted-foreground py-4 text-sm",children:"No attendance data yet. Attend an event to get on the leaderboard!"})]})}),e.jsx(is,{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 p,f,g;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${u.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${h===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:IVe(h+1)}),e.jsx(ra,{className:"h-8 w-8",children:e.jsx(aa,{className:"text-xs",children:((f=(p=u.profile)==null?void 0:p.name)==null?void 0:f.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((g=u.profile)==null?void 0:g.name)||"Unknown",u.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.total_points," points"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold",children:u.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"events"})]})]},u.user_id)})})})]})]})]})}function Rms(){const s=Mn(),{user:t,isAdmin:n}=ys(),r=Ht(),{data:a,isLoading:i}=ct({queryKey:["public-events"],queryFn:async()=>{const{data:_,error:v}=await q.from("events").select("*").order("event_date",{ascending:!0});if(v)throw v;return _}}),{data:l}=ct({queryKey:["my-registrations"],queryFn:async()=>{if(!t)return[];const{data:_,error:v}=await q.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",t.id);if(v)throw v;return _},enabled:!!t}),{data:o}=ct({queryKey:["event-registration-counts"],queryFn:async()=>{let _=[],v=0;const j=1e3;for(;;){const{data:S,error:A}=await q.from("event_registrations").select("event_id").range(v,v+j-1);if(A)throw A;if(!S||S.length===0||(_=_.concat(S),S.length{b[S.event_id]=(b[S.event_id]||0)+1}),b}}),c=gt({mutationFn:async _=>{await q.auth.refreshSession();const{data:v,error:j}=await q.functions.invoke("zoom-register",{body:{event_id:_}});if(j)throw j;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:_=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),_!=null&&_.join_url?ae.success("Successfully registered! You'll receive a Zoom confirmation email."):ae.success("Successfully registered for the event!")},onError:_=>{ae.error("Failed to register: "+_.message)}}),d=gt({mutationFn:async _=>{const{data:v,error:j}=await q.functions.invoke("zoom-unregister",{body:{event_id:_}});if(j)throw j;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),ae.success("Registration cancelled and removed from Zoom")},onError:_=>{ae.error("Failed to cancel: "+_.message)}}),u=_=>l==null?void 0:l.some(v=>v.event_id===_),h=_=>{const v=l==null?void 0:l.find(j=>j.event_id===_);return v==null?void 0:v.zoom_join_url},p=_=>_.capacity?((o==null?void 0:o[_.id])||0)>=_.capacity:!1,f=(a==null?void 0:a.filter(_=>PL(_.event_date)!=="ended"))||[],g=(a==null?void 0:a.filter(_=>PL(_.event_date)==="ended"))||[];return e.jsx(Ts,{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(Pms,{}),n&&e.jsx(B,{variant:"outline",onClick:()=>s("/admin/events"),children:"Manage Events"})]})]}),e.jsxs("div",{className:`grid grid-cols-1 ${n?"lg:grid-cols-3":""} gap-6`,children:[e.jsxs("div",{className:n?"lg:col-span-2":"",children:[i?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading events..."}):f.length===0?e.jsx(fe,{className:"text-center py-12",children:e.jsx(Ee,{children:e.jsx("p",{className:"text-muted-foreground",children:"No upcoming events at the moment. Check back soon!"})})}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2",children:f.map(_=>{const v=PL(_.event_date),j=x6e(_.event_date),b=v==="live",S=v==="starting_soon";return e.jsxs(fe,{className:`flex flex-col overflow-hidden cursor-pointer hover:shadow-lg transition-all ${b?"border-red-500 ring-2 ring-red-500/20":S?"border-amber-500 ring-2 ring-amber-500/20":"hover:border-primary/50"}`,onClick:()=>s(`/events/${_.id}`),children:[j&&e.jsxs("div",{className:`${b?"bg-red-500":"bg-amber-500"} text-white px-3 py-1.5 flex items-center gap-2 text-sm font-medium`,children:[e.jsxs("span",{className:"relative flex h-2 w-2",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-white opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-white"})]}),b?e.jsxs(e.Fragment,{children:[e.jsx(_f,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(gr,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),_.image_url&&e.jsxs(Ims,{ratio:16/9,className:"overflow-hidden relative bg-neutral-900",children:[e.jsx("img",{src:_.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:_.image_url,alt:_.title,className:"relative w-full h-full object-contain group-hover:scale-[1.03] transition-transform"})]}),e.jsxs(Mt,{children:[e.jsx(It,{className:"line-clamp-2",children:_.title}),_.description&&e.jsx(Vn,{className:"line-clamp-2",children:_.description.replace(/<[^>]*>/g,"")})]}),e.jsxs(Ee,{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(yr,{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(_.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(gr,{className:"h-4 w-4"}),xB(new Date(_.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Nn,{className:"h-4 w-4"}),(o==null?void 0:o[_.id])||0," registered",_.capacity&&` / ${_.capacity} spots`]})]}),e.jsx(ez,{className:"flex gap-2",onClick:A=>A.stopPropagation(),children:u(_.id)?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>d.mutate(_.id),disabled:d.isPending,children:[e.jsx(Bn,{className:"h-4 w-4 mr-2"}),"Cancel"]}),e.jsxs(B,{className:"flex-1",onClick:()=>window.open(h(_.id)||_.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(_.id),disabled:c.isPending||p(_),children:p(_)?"Event Full":e.jsxs(e.Fragment,{children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Register"]})})})]},_.id)})}),g.length>0&&e.jsxs("div",{className:"mt-12",children:[e.jsx("h3",{className:"text-xl font-semibold mb-4 text-muted-foreground",children:"Past Events"}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:g.map(_=>e.jsx(fe,{className:"opacity-60 cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>s(`/events/${_.id}`),children:e.jsxs(Mt,{children:[e.jsx(It,{className:"text-base line-clamp-1",children:_.title}),e.jsx(Vn,{children:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(_.event_date))})]})},_.id))})]})]}),n&&e.jsx("div",{className:"lg:col-span-1",children:e.jsx(qxt,{showUserStats:!0})})]})]})})}const y2e=[{value:"all",label:"All Roles",icon:Nn},{value:"newest",label:"Newest Members",icon:gr},{value:"brokerage_manager",label:"Brokerage Managers",icon:O9},{value:"admin",label:"Admins",icon:dh}];function Oms({open:s,onOpenChange:t,resourceType:n,resourceId:r,resourceTitle:a}){var Fe,qe;const{user:i,isAdmin:l,isBrokerageManager:o}=ys(),[c,d]=N.useState([]),[u,h]=N.useState([]),[p,f]=N.useState([]),[g,_]=N.useState([]),[v,j]=N.useState(""),[b,S]=N.useState(""),[A,T]=N.useState(""),[L,D]=N.useState(!1),[M,F]=N.useState(!1),[z,V]=N.useState("agents"),[W,Y]=N.useState("all"),[K,J]=N.useState({}),ne=l||o;N.useEffect(()=>{s&&i&&(l?ie():he())},[s,i,l]),N.useEffect(()=>{s||(f([]),_([]),j(""),S(""),T(""),V("agents"),Y("all"))},[s]);const ie=async()=>{if(i){D(!0);try{const{data:be,error:Ze}=await q.from("brokerages").select("id, name").order("name");if(Ze)throw Ze;const Ne=1e3,it={};let je=0,Ge=!0;for(;Ge;){const{data:We,error:rt}=await q.from("profiles").select("brokerage_id").range(je*Ne,(je+1)*Ne-1);if(rt)throw rt;We==null||We.forEach(tt=>{tt.brokerage_id&&(it[tt.brokerage_id]=(it[tt.brokerage_id]||0)+1)}),Ge=(We==null?void 0:We.length)===Ne,je++}h((be==null?void 0:be.map(We=>({...We,agent_count:it[We.id]||0})))||[]);const Be=[];for(je=0,Ge=!0;Ge;){const{data:We,error:rt}=await q.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(je*Ne,(je+1)*Ne-1);if(rt)throw rt;We&&Be.push(...We),Ge=(We==null?void 0:We.length)===Ne,je++}const Ye={};for(je=0,Ge=!0;Ge;){const{data:We,error:rt}=await q.from("user_roles").select("user_id, role").range(je*Ne,(je+1)*Ne-1);if(rt)throw rt;We==null||We.forEach(tt=>{Ye[tt.user_id]||(Ye[tt.user_id]=[]),Ye[tt.user_id].push(tt.role)}),Ge=(We==null?void 0:We.length)===Ne,je++}J(Ye),d(Be.map(We=>{var rt;return{id:We.id,name:We.name,email:We.email,brokerage_name:((rt=We.brokerages)==null?void 0:rt.name)||"No Brokerage",roles:Ye[We.id]||[],created_at:We.created_at}}))}catch(be){console.error("Error loading data:",be),ae.error("Failed to load agents and brokerages")}finally{D(!1)}}},he=async()=>{if(i){D(!0);try{const{data:be}=await q.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(be!=null&&be.brokerage_id)){ae.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:Ze,error:Ne}=await q.from("profiles").select("id, name, email").eq("brokerage_id",be.brokerage_id).neq("id",i.id).order("name");if(Ne)throw Ne;d(Ze||[])}catch(be){console.error("Error loading agents:",be),ae.error("Failed to load agents")}finally{D(!1)}}},ce=c.filter(be=>{var Ne;const Ze=be.name.toLowerCase().includes(v.toLowerCase())||be.email.toLowerCase().includes(v.toLowerCase())||((Ne=be.brokerage_name)==null?void 0:Ne.toLowerCase().includes(v.toLowerCase()));if(l&&W!=="all"&&W!=="newest"){const it=K[be.id]||[];return Ze&&it.includes(W)}return Ze}).sort((be,Ze)=>W==="newest"?(Ze.created_at||"").localeCompare(be.created_at||""):0),pe=u.filter(be=>be.name.toLowerCase().includes(b.toLowerCase())),le=()=>{p.length===ce.length?f([]):f(ce.map(be=>be.id))},ve=()=>{g.length===pe.length?_([]):_(pe.map(be=>be.id))},ge=be=>{if(!ne){f([be]);return}f(Ze=>Ze.includes(be)?Ze.filter(Ne=>Ne!==be):[...Ze,be])},Te=be=>{_(Ze=>Ze.includes(be)?Ze.filter(Ne=>Ne!==be):[...Ze,be])},Me=async()=>{if(!(p.length>0||g.length>0)){ae.error("Please select at least one agent or brokerage to share with");return}F(!0);try{const{data:Ze,error:Ne}=await q.functions.invoke("send-share-notification",{body:{recipientIds:p,brokerageIds:g,resourceType:n,resourceId:r,resourceTitle:a,message:A.trim()||void 0}});if(Ne)throw Ne;const it=(Ze==null?void 0:Ze.sharesCreated)||p.length;ae.success(`Shared with ${it} agent${it!==1?"s":""}`),t(!1)}catch(Ze){console.error("Error sharing resource:",Ze),ae.error("Failed to share resource")}finally{F(!1)}},Ce=be=>be.split(" ").map(Ze=>Ze[0]).join("").toUpperCase().slice(0,2),Ae=be=>{const Ze=K[be]||[];return Ze.includes("admin")?e.jsx(ze,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Admin"}):Ze.includes("brokerage_manager")?e.jsx(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:"Manager"}):null},De=p.length+g.length,Ie=W!=="all"&&W!=="newest"?ce.length:null;return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(ws,{className:"flex-shrink-0",children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(cr,{className:"h-5 w-5 text-primary"}),"Share Resource"]}),e.jsxs(Qn,{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(Br,{value:z,onValueChange:V,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(Fr,{className:"grid w-full grid-cols-2 flex-shrink-0",children:[e.jsxs(Kt,{value:"agents",className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),e.jsx("span",{children:"Agents"}),p.length>0&&e.jsx(ze,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:p.length})]}),e.jsxs(Kt,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(Va,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),g.length>0&&e.jsx(ze,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:g.length})]})]}),e.jsxs(is,{value:"agents",className:"flex-1 flex flex-col space-y-3 mt-3 overflow-hidden",children:[e.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, or brokerage...",value:v,onChange:be=>j(be.target.value),className:"pl-9"})]}),e.jsxs(ds,{value:W,onValueChange:Y,children:[e.jsxs(ls,{className:"w-[180px]",children:[e.jsx(Rv,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(us,{placeholder:"Filter by role"})]}),e.jsx(cs,{children:y2e.map(be=>e.jsx(Qe,{value:be.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be.icon,{className:"h-4 w-4"}),e.jsx("span",{children:be.label})]})},be.value))})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:le,className:"text-xs h-8",disabled:ce.length===0,children:[e.jsx(Nn,{className:"h-3.5 w-3.5 mr-1.5"}),p.length===ce.length&&ce.length>0?"Deselect All":"Select All"]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[Ie!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[Ie," ",(Fe=y2e.find(be=>be.value===W))==null?void 0:Fe.label]}),e.jsxs("span",{className:"font-medium",children:[p.length," selected"]})]})]}),e.jsx(hi,{className:"h-[300px] border rounded-lg",children:L?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ce.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(Nn,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:W!=="all"?`No ${(qe=y2e.find(be=>be.value===W))==null?void 0:qe.label.toLowerCase()} found`:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ce.map(be=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${p.includes(be.id)?"bg-accent":""}`,onClick:()=>ge(be.id),children:[e.jsx(ui,{checked:p.includes(be.id),onCheckedChange:()=>ge(be.id),className:"flex-shrink-0"}),e.jsx(ra,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(aa,{className:"text-xs bg-primary/10 text-primary",children:Ce(be.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:be.name}),Ae(be.id)]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[be.email,be.brokerage_name&&e.jsxs("span",{className:"ml-1 opacity-75",children:["• ",be.brokerage_name]})]})]})]},be.id))})})]}),e.jsxs(is,{value:"brokerages",className:"flex-1 flex flex-col space-y-3 mt-3 overflow-hidden",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search brokerages...",value:b,onChange:be=>S(be.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:ve,className:"text-xs h-8",disabled:pe.length===0,children:[e.jsx(Va,{className:"h-3.5 w-3.5 mr-1.5"}),g.length===pe.length&&pe.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[g.length," selected"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground px-1 flex-shrink-0",children:"Selecting a brokerage will send to all agents in that brokerage."}),e.jsx(hi,{className:"h-[250px] border rounded-lg",children:L?e.jsx("div",{className:"flex items-center justify-center h-[180px]",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):pe.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[180px] text-muted-foreground",children:[e.jsx(Va,{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:pe.map(be=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${g.includes(be.id)?"bg-accent":""}`,onClick:()=>Te(be.id),children:[e.jsx(ui,{checked:g.includes(be.id),onCheckedChange:()=>Te(be.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(Va,{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:be.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[be.agent_count," agent",be.agent_count!==1?"s":""]})]})]},be.id))})})]})]}):e.jsxs("div",{className:"flex-1 flex flex-col space-y-3 overflow-hidden",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents...",value:v,onChange:be=>j(be.target.value),className:"pl-9"})]}),ne&&e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:le,className:"text-xs h-8",disabled:ce.length===0,children:[e.jsx(Nn,{className:"h-3.5 w-3.5 mr-1.5"}),p.length===ce.length&&ce.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[p.length," selected"]})]}),e.jsx(hi,{className:"h-[300px] border rounded-lg",children:L?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ce.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(Nn,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ce.map(be=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${p.includes(be.id)?"bg-accent":""}`,onClick:()=>ge(be.id),children:[e.jsx(ui,{checked:p.includes(be.id),onCheckedChange:()=>ge(be.id),className:"flex-shrink-0"}),e.jsx(ra,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(aa,{className:"text-xs bg-primary/10 text-primary",children:Ce(be.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:be.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:be.email})]})]},be.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(Es,{id:"message",placeholder:"I thought you might find this useful...",value:A,onChange:be=>T(be.target.value),rows:2,className:"resize-none"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 flex-shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:Me,disabled:De===0||M,children:M?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function XD({resourceType:s,resourceId:t,resourceTitle:n,variant:r="outline",size:a="sm",className:i=""}){const[l,o]=N.useState(!1),{user:c}=ys();return c?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:r,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(Hl,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(Oms,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:n})]}):null}function Fms(){const{eventId:s}=bi(),t=Mn(),{user:n}=ys(),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(0),[d,u]=N.useState(!0),[h,p]=N.useState(!1);N.useEffect(()=>{s&&f()},[s,n]);const f=async()=>{try{const{data:S,error:A}=await q.from("events").select("*").eq("id",s).single();if(A)throw A;a(S);const{count:T}=await q.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",s);if(c(T||0),n){const{data:L}=await q.from("event_registrations").select("id, zoom_join_url").eq("event_id",s).eq("user_id",n.id).maybeSingle();l(L)}}catch(S){console.error("Error loading event:",S),ae.error("Failed to load event"),t("/events")}finally{u(!1)}},g=async()=>{if(!(!n||!r)){p(!0);try{const{error:S}=await q.auth.refreshSession();if(S){console.error("Session refresh failed:",S),ae.error("Your session has expired. Please log in again.");return}if(i){const{error:A}=await q.functions.invoke("zoom-unregister",{body:{event_id:r.id}});if(A)throw A;ae.success("Successfully cancelled registration"),l(null),c(T=>T-1)}else{const{data:A,error:T}=await q.functions.invoke("zoom-register",{body:{event_id:r.id}});if(T)throw T;ae.success("Successfully registered for event!"),l({id:A.registration_id,zoom_join_url:A.zoom_join_url}),c(L=>L+1)}}catch(S){console.error("Registration error:",S),ae.error(i?"Failed to cancel registration":"Failed to register for event")}finally{p(!1)}}},_=S=>{var A,T,L;if(S.includes("iframe.mediadelivery.net")||S.includes("video.bunnycdn.com")){const D=S.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(D)return`https://iframe.mediadelivery.net/embed/${D[1]}/${D[2]}?autoplay=false&preload=true`}if(S.includes("youtube.com")||S.includes("youtu.be")){const D=S.includes("youtu.be")?(A=S.split("youtu.be/")[1])==null?void 0:A.split("?")[0]:(T=S.split("v=")[1])==null?void 0:T.split("&")[0];if(D)return`https://www.youtube.com/embed/${D}`}if(S.includes("vimeo.com")){const D=(L=S.split("vimeo.com/")[1])==null?void 0:L.split("?")[0];if(D)return`https://player.vimeo.com/video/${D}`}return S};if(d)return e.jsx(Ts,{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(Ts,{title:"Event Not Found",children:e.jsxs("div",{className:"text-center py-16",children:[e.jsx("p",{className:"text-muted-foreground",children:"Event not found"}),e.jsx(B,{onClick:()=>t("/events"),className:"mt-4",children:"Back to Events"})]})});const v=ww(new Date(r.event_date)),j=r.capacity&&o>=r.capacity,b=(i==null?void 0:i.zoom_join_url)||r.zoom_link;return e.jsx(Ts,{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(Hr,{className:"h-4 w-4"}),"Back to Events"]}),r.image_url&&e.jsxs("div",{className:"relative aspect-video rounded-xl overflow-hidden mb-6",children:[e.jsx("img",{src:r.image_url,alt:r.title,className:"w-full h-full object-cover"}),v&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(ze,{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(XD,{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(Au,{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:_(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(fe,{children:e.jsxs(Ee,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(yr,{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:xB(new Date(r.event_date))})]})]}),r.capacity&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Nn,{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(Ri,{className:"h-5 w-5 text-green-600"}),e.jsx("span",{className:"text-sm font-medium text-green-700",children:"You're registered!"})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[!v&&e.jsx(e.Fragment,{children:i?e.jsxs(e.Fragment,{children:[e.jsxs(B,{className:"w-full gap-2",onClick:()=>window.open(b,"_blank"),children:[e.jsx(tr,{className:"h-4 w-4"}),"Join Event"]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:g,disabled:h,children:[h?e.jsx(ts,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):e.jsx(B,{className:"w-full gap-2",onClick:g,disabled:h||(j??!1),children:h?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):j?"Event Full":"Register Now"})}),v&&i&&e.jsxs(B,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(r.zoom_link,"_blank"),children:[e.jsx(tr,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const zms=[{id:"quickvid",name:"QuickVid",description:"Record, manage, and share personalized video messages",icon:e.jsx(br,{className:"h-6 w-6"}),path:"/mission-control/video/record",category:"Marketing",color:"bg-rose-500/15 text-rose-600"},{id:"smart-card",name:"Smart Card",description:"Your digital business card — share your info with a single link",icon:e.jsx(pf,{className:"h-6 w-6"}),path:"/mission-control/my-card",category:"Marketing",color:"bg-sky-500/15 text-sky-600"},{id:"smart-presentations",name:"Smart Presentations",description:"Create beautiful listing and buyer presentations",icon:e.jsx(iy,{className:"h-6 w-6"}),path:"/mission-control/presentations",category:"Marketing",color:"bg-amber-500/15 text-amber-600"},{id:"landing-pages",name:"Landing Pages",description:"Build custom landing pages to capture leads",icon:e.jsx(Nr,{className:"h-6 w-6"}),path:"/mission-control/landing-pages",category:"Marketing",color:"bg-emerald-500/15 text-emerald-600"},{id:"guest-book",name:"Guest Book",description:"Digital open house sign-in to capture visitor info",icon:e.jsx(Ou,{className:"h-6 w-6"}),path:"/mission-control/guest-book",category:"Open House",color:"bg-orange-500/15 text-orange-600"},{id:"card-studio",name:"Card Studio",description:"Send beautiful animated digital cards for birthdays, anniversaries & milestones",icon:e.jsx(un,{className:"h-6 w-6"}),path:"/mission-control/card-studio",category:"Marketing",color:"bg-pink-500/15 text-pink-600"},{id:"direct-mail",name:"Direct Mail",description:"Send professional postcards to your contacts via direct mail",icon:e.jsx(Vs,{className:"h-6 w-6"}),path:"/mission-control/direct-mail",category:"Marketing",adminOnly:!0,beta:!0,color:"bg-indigo-500/15 text-indigo-600"},{id:"reelflow",name:"ReelFlow",description:"Turn property photos into cinematic video clips and reels — powered by AI",icon:e.jsx(Ah,{className:"h-6 w-6"}),path:"/admin/beta/homereel",category:"Marketing",beta:!0,isNew:!0,color:"bg-violet-500/15 text-violet-600"},{id:"mass-emails",name:"Mass Emails",description:"Create and send bulk email campaigns to your contacts",icon:e.jsx(cr,{className:"h-6 w-6"}),path:"/admin/email-campaigns",category:"Marketing",beta:!0,color:"bg-teal-500/15 text-teal-600"},{id:"listing-studio",name:"Listing Studio",description:"Generate MLS descriptions, luxury copy, open house blurbs and more — powered by AI",icon:e.jsx(sb,{className:"h-6 w-6"}),path:"/mission-control/listing-studio",category:"Marketing",isNew:!0,color:"bg-fuchsia-500/15 text-fuchsia-600"},{id:"website-apps",name:"Website Apps",description:"Drop-in conversion widgets for your website — Video Greeter & more",icon:e.jsx(mL,{className:"h-6 w-6"}),path:"/website-apps",category:"Website",isNew:!0,color:"bg-cyan-500/15 text-cyan-600"},{id:"newsletter-pro",name:"Newsletter Pro",description:"Design and send beautiful branded newsletters to your database",icon:e.jsx(ay,{className:"h-6 w-6"}),path:"/newsletters",category:"Marketing",color:"bg-yellow-500/15 text-yellow-600"},{id:"cma",name:"CMA Reports",description:"Build interactive CMAs with live comps, share with clients, and auto-create deals",icon:e.jsx(yo,{className:"h-6 w-6"}),path:"/mission-control/cma",category:"Marketing",isNew:!0,requiresLeadSiteMLS:!0,color:"bg-blue-500/15 text-blue-600"}],Bms=()=>{const{user:s,isAdmin:t}=ys(),n=Mn(),[r,a]=N.useState([]),[i,l]=N.useState(!0),[o,c]=N.useState(""),[d,u]=N.useState("all"),[h,p]=N.useState(new Set),[f,g]=N.useState(new Set),[_,v]=N.useState(!1);N.useEffect(()=>{j()},[s]);const j=async()=>{try{const{data:V}=await q.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),W=(V==null?void 0:V.map(ge=>ge.tag))||[],{data:Y,error:K}=await q.from("app_tiles").select("*").order("name");if(K)throw K;const[{data:J},{data:ne},{data:ie}]=await Promise.all([q.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),q.from("user_tool_favorites").select("tool_id").eq("user_id",s==null?void 0:s.id),q.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",s==null?void 0:s.id)]),he=(ie||[]).some(ge=>ge.is_active&&ge.mls_provider_id&&!ge.no_mls_mode);v(he);const ce=new Set((J==null?void 0:J.map(ge=>ge.app_id))||[]);p(ce);const pe=new Set((ne||[]).map(ge=>ge.tool_id));g(pe);const ve=((Y==null?void 0:Y.filter(ge=>ge.app_id==="newsletter_studio"?!1:!ge.required_tags||ge.required_tags.length===0?!0:ge.required_tags.some(Te=>W.includes(Te))))||[]).sort((ge,Te)=>ge.name==="LevelUp Members Portal"?-1:Te.name==="LevelUp Members Portal"?1:0);a(ve)}catch(V){console.error("Error loading apps:",V),ae.error("Failed to load apps")}finally{l(!1)}},b=async V=>{var Y;try{const K=new URL(V.target_url);if(new Set([window.location.hostname,"dashboard.relevelup.com"]).has(K.hostname)){await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:V.app_id,app_name:V.name,user_agent:navigator.userAgent}),n(K.pathname+K.search+K.hash);return}}catch{}const W=window.open("about:blank","_blank");try{const{data:K,error:J}=await q.auth.getSession();if(J||!K.session){W==null||W.close(),ae.error("Session expired. Please refresh the page and try again.");return}const ne=K.session.access_token;await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:V.app_id,app_name:V.name,user_agent:navigator.userAgent});const{data:ie,error:he}=await q.functions.invoke("sso-launch",{body:{app_id:V.app_id},headers:{Authorization:`Bearer ${ne}`}});if(he)throw he;ie!=null&&ie.redirect_url?W&&!W.closed?(W.location.href=ie.redirect_url,(Y=W.focus)==null||Y.call(W)):window.location.assign(ie.redirect_url):(W==null||W.close(),ae.error("Launch link unavailable"))}catch(K){W==null||W.close(),console.error("Error launching app:",K),ae.error("Failed to launch app. Please try again.")}},S=async(V,W)=>{V.stopPropagation();const Y=h.has(W);try{if(Y){const{error:K}=await q.from("user_favorites").delete().eq("user_id",s==null?void 0:s.id).eq("app_id",W);if(K)throw K;p(J=>{const ne=new Set(J);return ne.delete(W),ne}),ae.success("Removed from favorites")}else{const{error:K}=await q.from("user_favorites").insert({user_id:s==null?void 0:s.id,app_id:W});if(K)throw K;p(J=>new Set(J).add(W)),ae.success("Added to favorites")}}catch(K){console.error("Error toggling favorite:",K),ae.error("Failed to update favorites")}},A=async(V,W)=>{V.stopPropagation();const Y=f.has(W);try{if(Y){const{error:K}=await q.from("user_tool_favorites").delete().eq("user_id",s==null?void 0:s.id).eq("tool_id",W);if(K)throw K;g(J=>{const ne=new Set(J);return ne.delete(W),ne}),ae.success("Removed from favorites")}else{const{error:K}=await q.from("user_tool_favorites").insert({user_id:s==null?void 0:s.id,tool_id:W});if(K)throw K;g(J=>new Set(J).add(W)),ae.success("Added to favorites")}}catch(K){console.error("Error toggling tool favorite:",K),ae.error("Failed to update favorites")}},T=r.filter(V=>{var Y;const W=V.name.toLowerCase().includes(o.toLowerCase())||((Y=V.description)==null?void 0:Y.toLowerCase().includes(o.toLowerCase()));return d==="favorites"?W&&h.has(V.id):W}),L=zms.filter(V=>{if(V.adminOnly&&!t||V.requiresLeadSiteMLS&&!_&&!t)return!1;const W=V.name.toLowerCase().includes(o.toLowerCase())||V.description.toLowerCase().includes(o.toLowerCase());return d==="favorites"?W&&f.has(V.id):W}),D=L.reduce((V,W)=>(V[W.category]||(V[W.category]=[]),V[W.category].push(W),V),{}),M=[{id:"all",label:"All"},{id:"tools",label:"Built-in Tools"},{id:"apps",label:"Connected Apps"},{id:"favorites",label:"Favorites"}];if(i)return e.jsx(Ts,{title:"Apps & Tools",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading apps & tools..."})]})})});const F=d==="all"||d==="tools"||d==="favorites",z=d==="all"||d==="apps"||d==="favorites";return e.jsxs(Ts,{title:"Apps & Tools",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Apps & Tools"}),e.jsxs("div",{className:"relative max-w-sm w-full",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search apps & tools...",className:"pl-10 bg-muted/50 border-0 focus-visible:ring-1",value:o,onChange:V=>c(V.target.value)})]})]}),e.jsx("div",{className:"flex gap-6 border-b border-border mb-8",children:M.map(V=>e.jsxs("button",{onClick:()=>u(V.id),className:Et("pb-3 text-sm font-medium transition-colors relative",d===V.id?"text-primary":"text-muted-foreground hover:text-foreground"),children:[V.label,d===V.id&&e.jsx("span",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-primary"})]},V.id))}),F&&Object.keys(D).length>0&&e.jsxs("div",{className:"mb-10",children:[d==="all"&&e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx(_b,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Built-in Tools"})]}),Object.entries(D).map(([V,W])=>e.jsxs("div",{className:"mb-6",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground bg-muted px-2.5 py-1 rounded-full",children:V})}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:W.map(Y=>{const K=f.has(Y.id);return e.jsxs("div",{onClick:()=>n(Y.path),className:Et("group flex items-start gap-4 p-5 bg-card rounded-xl border transition-all duration-200 hover:shadow-lg cursor-pointer relative overflow-hidden",Y.isNew?"border-primary/40 ring-1 ring-primary/20 hover:border-primary/60":"border-border hover:border-primary/30"),children:[Y.isNew&&e.jsx("div",{className:"absolute top-0 right-0 bg-gradient-to-r from-violet-500 to-indigo-500 text-white text-[10px] font-bold uppercase px-3 py-0.5 rounded-bl-lg tracking-wider shadow-sm",children:"✨ New"}),e.jsx("div",{className:Et("flex-shrink-0 w-14 h-14 rounded-xl flex items-center justify-center transition-transform group-hover:scale-105",Y.color||"bg-primary/10 text-primary"),children:Y.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors truncate flex items-center gap-2",children:[Y.name,Y.beta&&e.jsx("span",{className:"text-[10px] font-semibold bg-amber-100 text-amber-700 px-1.5 py-0.5 rounded-full border border-amber-200",children:"Beta"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:Y.description})]}),e.jsx("button",{className:Et("flex-shrink-0 p-1 transition-colors",K?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:J=>A(J,Y.id),children:e.jsx(Lv,{className:Et("h-5 w-5",K&&"fill-current")})})]},Y.id)})})]},V))]}),z&&e.jsxs("div",{children:[d==="all"&&T.length>0&&e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx(tr,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Connected Apps"})]}),T.length===0&&d!=="all"&&!(d==="favorites"&&L.length>0)?e.jsx("div",{className:"flex flex-col items-center justify-center py-16 bg-card rounded-xl border border-border",children:d==="favorites"?e.jsxs(e.Fragment,{children:[e.jsx(Lv,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No favorites yet"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:"Click the bookmark icon on any app or tool to add it to your favorites"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Kc,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No apps available"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:t?"Get started by adding apps in the admin panel":"Contact your administrator to get access to apps"}),t&&e.jsx(B,{className:"mt-4",onClick:()=>n("/admin/apps"),children:"Add Apps"})]})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:T.map(V=>{const W=h.has(V.id),Y=V.name.toLowerCase().includes("agent review")||V.app_id==="agent_review";return e.jsxs("div",{className:"group flex flex-col p-5 bg-card rounded-xl border border-border transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsxs("div",{className:"flex items-start gap-4 cursor-pointer",onClick:()=>b(V),children:[e.jsx("div",{className:"flex-shrink-0 w-14 h-14 rounded-xl bg-primary/10 flex items-center justify-center text-3xl",children:V.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors truncate",children:V.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:V.description})]}),e.jsx("button",{className:Et("flex-shrink-0 p-1 transition-colors",W?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:K=>S(K,V.id),children:e.jsx(Lv,{className:Et("h-5 w-5",W&&"fill-current")})})]}),Y&&e.jsx("a",{href:"https://forms.gle/vXnrzgSnPbw7CKPV6",target:"_blank",rel:"noopener noreferrer",onClick:K=>K.stopPropagation(),className:"mt-3 text-sm text-primary hover:underline flex items-center gap-1",children:"Create your account with this link →"})]},V.id)})})]}),F&&z&&T.length===0&&L.length===0&&o&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 bg-card rounded-xl border border-border",children:[e.jsx(vr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No results found"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:"Try a different search term"})]})]})},$ms=()=>{var S;const s=Mn(),{isAdmin:t}=ys(),[n,r]=N.useState(""),[a,i]=N.useState("all"),[l,o]=N.useState("all"),[c,d]=N.useState("grid"),{data:u=[]}=ct({queryKey:["template-categories"],queryFn:async()=>{const{data:A,error:T}=await q.from("template_categories").select("*").order("name");if(T)throw T;return A}}),{data:h=[]}=ct({queryKey:["template-types"],queryFn:async()=>{const{data:A,error:T}=await q.from("template_types").select("*").order("name");if(T)throw T;return A}}),{data:p=[],isLoading:f}=ct({queryKey:["canva-templates",t],queryFn:async()=>{const{data:A,error:T}=await q.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:L,error:D}=await q.from("template_links").select("*").order("sort_order");if(D)throw D;const M=async J=>{let ie=0;const he=[];for(;;){const{data:ce,error:pe}=await J().range(ie,ie+1e3-1);if(pe)throw pe;if(!ce||ce.length===0||(he.push(...ce),ce.length<1e3))break;ie+=1e3}return he},F=await M(()=>q.from("template_likes").select("template_id")),z=await M(()=>q.from("template_comments").select("template_id")),V=new Map;F.forEach(J=>{V.set(J.template_id,(V.get(J.template_id)||0)+1)});const W=new Map;z.forEach(J=>{W.set(J.template_id,(W.get(J.template_id)||0)+1)});const Y=new Map;return t&&(await M(()=>q.from("content_engagement_logs").select("resource_id").eq("resource_type","template").eq("action_type","view"))).forEach(ne=>{Y.set(ne.resource_id,(Y.get(ne.resource_id)||0)+1)}),(A||[]).map(J=>({...J,links:(L||[]).filter(ne=>ne.template_id===J.id)||[],likesCount:V.get(J.id)||0,commentsCount:W.get(J.id)||0,viewsCount:Y.get(J.id)||0}))}}),g=p.filter(A=>{var M;const T=A.name.toLowerCase().includes(n.toLowerCase())||((M=A.description)==null?void 0:M.toLowerCase().includes(n.toLowerCase())),L=a==="all"||A.category_id===a,D=l==="all"||A.type_id===l;return T&&L&&D}),_=()=>{r(""),i("all"),o("all")},v=n||a!=="all"||l!=="all",j=(S=[...p].sort((A,T)=>new Date(T.publish_date||T.created_at).getTime()-new Date(A.publish_date||A.created_at).getTime())[0])==null?void 0:S.id,b=A=>{s(`/templates/${A}`)};return e.jsx(Ts,{title:"Canva Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-bold text-foreground text-5xl",children:"Canva Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse and use our collection of professionally designed templates"})]}),!f&&p.filter(A=>A.is_featured).length>0&&e.jsxs("div",{className:"rounded-xl p-5 space-y-3",style:{backgroundColor:"#9aa8b2"},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ca,{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:p.filter(A=>A.is_featured).slice(0,4).map(A=>e.jsxs(fe,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer relative",onClick:()=>b(A.id),children:[e.jsxs("div",{className:"aspect-[3/2] relative overflow-hidden bg-muted",children:[A.id===j&&e.jsx(ze,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:A.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"})]}),e.jsxs(Ee,{className:"p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 text-sm",children:A.name}),A.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:Xz(A.description)})]})]},A.id))})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(vr,{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:A=>r(A.target.value),className:"pl-9"})]}),e.jsxs(ds,{value:a,onValueChange:i,children:[e.jsx(ls,{className:"w-full sm:w-48",children:e.jsx(us,{placeholder:"All Categories"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Categories"}),u.map(A=>e.jsx(Qe,{value:A.id,children:A.name},A.id))]})]}),e.jsxs(ds,{value:l,onValueChange:o,children:[e.jsx(ls,{className:"w-full sm:w-48",children:e.jsx(us,{placeholder:"All Types"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Types"}),h.map(A=>e.jsx(Qe,{value:A.id,children:A.name},A.id))]})]}),e.jsxs("div",{className:"flex gap-2",children:[v&&e.jsx(B,{variant:"outline",size:"sm",onClick:_,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(yf,{className:"h-4 w-4"})}),e.jsx(B,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(Tp,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[g.length," template",g.length!==1?"s":""," found"]}),f&&e.jsx("div",{className:c==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(8)].map((A,T)=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx(Ws,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Ws,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ws,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ws,{className:"h-5 w-16"}),e.jsx(Ws,{className:"h-5 w-20"})]})]})},T))}),!f&&g.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:v?"No templates match your filters":"No templates available yet"}),v&&e.jsx(B,{variant:"outline",onClick:_,children:"Clear Filters"})]}),!f&&g.length>0&&e.jsx("div",{className:c==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:g.map(A=>e.jsxs(fe,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${c==="list"?"flex flex-row":""}`,onClick:()=>b(A.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${c==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[A.id===j&&e.jsx(ze,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:A.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),A.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(ze,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm !text-secondary",children:[e.jsx(Jo,{className:"h-3 w-3"}),A.links.length]})})]}),e.jsxs(Ee,{className:`p-4 flex flex-col ${c==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:A.name}),A.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:Xz(A.description)}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[A.category&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:A.category.name}),A.type&&e.jsx(ze,{variant:"outline",className:"text-xs",children:A.type.name})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vm,{className:"h-3.5 w-3.5"}),A.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"}),A.commentsCount]}),t&&e.jsxs("span",{className:"flex items-center gap-1",title:"Total views (admin only)",children:[e.jsx(Er,{className:"h-3.5 w-3.5"}),A.viewsCount]})]}),e.jsxs(B,{size:"sm",className:"w-full gap-2",onClick:T=>{T.stopPropagation(),b(A.id)},children:[e.jsx(tr,{className:"h-4 w-4"}),"View Template"]})]})]},A.id))})]})})};var Ums="Separator",PVe="horizontal",qms=["horizontal","vertical"],Vxt=N.forwardRef((s,t)=>{const{decorative:n,orientation:r=PVe,...a}=s,i=Vms(r)?r:PVe,o=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return e.jsx(Jr.div,{"data-orientation":i,...o,...a,ref:t})});Vxt.displayName=Ums;function Vms(s){return qms.includes(s)}var Hxt=Vxt;const ll=N.forwardRef(({className:s,orientation:t="horizontal",decorative:n=!0,...r},a)=>e.jsx(Hxt,{ref:a,decorative:n,orientation:t,className:Et("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...r}));ll.displayName=Hxt.displayName;const Hms=()=>{const{templateId:s}=bi(),t=Mn(),{user:n,isAdmin:r}=ys(),{toast:a}=Ba(),i=Ht(),{trackEngagement:l}=KD(),[o,c]=N.useState(""),{data:d,isLoading:u}=ct({queryKey:["template-detail",s],queryFn:async()=>{const{data:A,error:T}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("id",s).single();if(T)throw T;const{data:L}=await q.from("template_links").select("*").eq("template_id",s).order("sort_order"),{data:D}=await q.from("template_guides").select("*").eq("template_id",s).order("sort_order");return{...A,links:L||[],guides:D||[]}},enabled:!!s}),{data:h=[]}=ct({queryKey:["template-linked-toolkits",s],queryFn:async()=>{const{data:A,error:T}=await q.from("resource_kit_templates").select("kit_id, resource_kits:kit_id(id, name, featured_image_url)").eq("template_id",s);if(T)throw T;return(A||[]).map(L=>L.resource_kits).filter(Boolean)},enabled:!!s});N.useEffect(()=>{d&&l("template",d.id,d.name,"view")},[d==null?void 0:d.id]);const{data:p=[]}=ct({queryKey:["template-likes",s],queryFn:async()=>{const{data:A,error:T}=await q.from("template_likes").select("*").eq("template_id",s);if(T)throw T;return A},enabled:!!s}),{data:f=[]}=ct({queryKey:["template-comments",s],queryFn:async()=>{const{data:A,error:T}=await q.from("template_comments").select("*").eq("template_id",s).order("created_at",{ascending:!1});if(T)throw T;const L=[...new Set(A.map(F=>F.user_id))],{data:D}=await q.from("profiles").select("id, name").in("id",L),M=new Map((D==null?void 0:D.map(F=>[F.id,F.name]))||[]);return A.map(F=>({...F,user_name:M.get(F.user_id)||"Unknown User"}))},enabled:!!s}),g=gt({mutationFn:async A=>{const{error:T}=await q.from("template_comments").insert({template_id:s,user_id:n.id,content:A});if(T)throw T},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),c(""),a({title:"Comment added!"})},onError:A=>{a({title:"Error adding comment",description:A.message,variant:"destructive"})}}),_=gt({mutationFn:async A=>{const{error:T}=await q.from("template_comments").delete().eq("id",A);if(T)throw T},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),a({title:"Comment deleted"})}}),v=gt({mutationFn:async()=>{const A=p.find(T=>T.user_id===(n==null?void 0:n.id));if(A){const{error:T}=await q.from("template_likes").delete().eq("id",A.id);if(T)throw T}else{const{error:T}=await q.from("template_likes").insert({template_id:s,user_id:n.id});if(T)throw T}},onSuccess:()=>{i.invalidateQueries({queryKey:["template-likes",s]})}}),j=p.some(A=>A.user_id===(n==null?void 0:n.id)),b=A=>A.split(" ").map(T=>T[0]).join("").toUpperCase().slice(0,2),S=A=>{A.preventDefault(),!(!o.trim()||!n)&&g.mutate(o.trim())};return u?e.jsx(Ts,{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(Ts,{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(Ln,{to:"/templates",children:[e.jsx(Hr,{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(ze,{variant:"secondary",children:d.category.name}),d.type&&e.jsx(ze,{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(Ln,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(_a,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(XD,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs(B,{variant:j?"default":"outline",className:"gap-2 rounded-full",onClick:()=>v.mutate(),disabled:!n||v.isPending,children:[e.jsx(Vm,{className:`h-4 w-4 ${j?"fill-current":""}`}),p.length," ",p.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(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Jo,{className:"h-4 w-4"}),d.links.length===1?"Template Link":"Template Links"]}),e.jsx("div",{className:"grid gap-2",children:d.links.map(A=>e.jsxs(B,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_canva"),window.open(A.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:A.title}),e.jsx(tr,{className:"h-4 w-4 text-muted-foreground"})]},A.id))})]})}),d.video_url&&e.jsx(fe,{children:e.jsx(Ee,{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(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Nr,{className:"h-4 w-4"}),"Guide Files"]}),e.jsx("div",{className:"grid gap-2",children:d.guides.map(A=>e.jsxs(B,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_pdf"),window.open(A.file_url,"_blank")},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:A.name}),A.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",(A.file_size/1024).toFixed(0)," KB)"]})]}),e.jsx(Pa,{className:"h-4 w-4 text-muted-foreground"})]},A.id))})]})}),h.length>0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Rc,{className:"h-4 w-4"}),"Related Toolkits"]}),e.jsx("div",{className:"grid gap-2",children:h.map(A=>e.jsxs(B,{variant:"outline",className:"w-full justify-start gap-3 h-auto py-3",onClick:()=>t(`/toolbox/${A.id}`),children:[A.featured_image_url?e.jsx("img",{src:A.featured_image_url,alt:"",className:"w-10 h-10 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(Rc,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"font-medium",children:A.name})]},A.id))})]})}),e.jsx(ll,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ql,{className:"h-5 w-5"}),"Comments (",f.length,")"]}),n?e.jsxs("form",{onSubmit:S,className:"flex gap-2",children:[e.jsx(Es,{placeholder:"Add a comment...",value:o,onChange:A=>c(A.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(B,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||g.isPending,children:e.jsx(cr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:f.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):f.map(A=>e.jsx(fe,{children:e.jsx(Ee,{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(aa,{className:"text-sm",children:b(A.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:A.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Vo(new Date(A.created_at),{addSuffix:!0})}),A.user_id===(n==null?void 0:n.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>_.mutate(A.id),children:e.jsx(_n,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:A.content})]})]})})},A.id))})]})]})}):e.jsx(Ts,{title:"Templates",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Jo,{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(Ln,{to:"/templates",children:"Back to Templates"})})]})})},Gms=["reserved","scheduled_for_charge","paid","payment_failed","completed"],AB=s=>!!s&&(s.access_override||Gms.includes(s.status)),Eu=(s,t="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase(),maximumFractionDigits:s%100===0?0:2}).format(s/100),MB=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`},n3e=(s,t="usd",n)=>`One-time payment: ${Eu(s,t)} for the ${MB(n)}`,Gxt=[{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}],wxe=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:[]}},Wms=(s,t)=>!s.hidden.includes(t),LVe=(s,t)=>s.required.includes(t)&&!s.hidden.includes(t),ql=(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,ove=s=>{const t=Date.now(),n=s!=null&&s.enrollment_open_at?new Date(s.enrollment_open_at).getTime():null,r=s!=null&&s.enrollment_close_at?new Date(s.enrollment_close_at).getTime():null;return{notOpenYet:!!n&&n>t,closed:!!r&&rct({queryKey:["programs"],queryFn:async()=>{const{data:s,error:t}=await q.from("programs").select("*").eq("status","published").order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0});if(t)throw t;return s||[]}}),mIe=s=>ct({queryKey:["program",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("programs").select("*").eq("slug",s).maybeSingle();if(n)throw n;return t||null}}),Wxt=s=>ct({queryKey:["program-seats",s],enabled:!!s,refetchInterval:6e4,queryFn:async()=>{const{data:t,error:n}=await q.rpc("program_seats_remaining",{_program_id:s});if(n)throw n;return t??0}}),Kxt=()=>{const{user:s}=ys();return ct({queryKey:["program-enrollments",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:t,error:n}=await q.from("program_enrollments").select("*").eq("user_id",s.id);if(n)throw n;return t||[]}})},pIe=s=>{const{data:t=[],...n}=Kxt();return{...n,data:s&&t.find(r=>r.program_id===s)||null}},Yms=()=>{const{user:s}=ys(),t=Ht();return gt({mutationFn:async n=>{const{data:r,error:a}=await q.from("program_intake_responses").upsert({...n,user_id:s.id},{onConflict:"program_id,user_id"}).select("*").single();if(a)throw a;return r},onSuccess:()=>t.invalidateQueries({queryKey:["program-intake"]}),onError:n=>ae.error(n.message||"Could not save your answers")})},Zms=s=>{const{user:t}=ys();return ct({queryKey:["program-intake",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await q.from("program_intake_responses").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n}})},Qms=()=>{const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("program_claim_seat",{_program_id:t});if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["program-enrollments"]}),s.invalidateQueries({queryKey:["program-seats"]})}})},Xms=s=>{const{user:t}=ys();return ct({queryKey:["program-workspace",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const[n,r,a,i,l,o,c,d,u,h]=await Promise.all([q.from("program_weeks").select("*").eq("program_id",s).order("week_number"),q.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),q.from("program_resources").select("*").eq("program_id",s).order("sort_order"),q.from("program_events").select("*").eq("program_id",s).order("starts_at"),q.from("program_announcements").select("*").eq("program_id",s).order("published_at",{ascending:!1}),q.from("program_lesson_completions").select("*").eq("program_id",s).eq("user_id",t.id),q.from("program_weekly_progress").select("*").eq("program_id",s).eq("user_id",t.id).order("week_number"),q.from("program_video_logs").select("*").eq("program_id",s).eq("user_id",t.id).order("posted_at",{ascending:!1}),q.from("program_badge_awards").select("*").eq("program_id",s).eq("user_id",t.id),q.from("program_profile_analyses").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle()]);return{weeks:n.data||[],lessons:r.data||[],resources:a.data||[],events:i.data||[],announcements:l.data||[],completions:o.data||[],progress:c.data||[],videoLogs:d.data||[],badges:u.data||[],analysis:h.data||null}}})},Jms=s=>{const{user:t}=ys(),n=Ht();return gt({mutationFn:async({lessonId:r,done:a})=>{if(a){const{error:i}=await q.from("program_lesson_completions").insert({lesson_id:r,program_id:s,user_id:t.id});if(i&&!i.message.includes("duplicate"))throw i}else{const{error:i}=await q.from("program_lesson_completions").delete().eq("lesson_id",r).eq("user_id",t.id);if(i)throw i}},onSuccess:()=>n.invalidateQueries({queryKey:["program-workspace"]}),onError:r=>ae.error(r.message||"Could not update progress")})},eps=s=>{const{user:t}=ys(),n=Ht();return gt({mutationFn:async r=>{const{error:a}=await q.from("program_video_logs").insert({...r,program_id:s,user_id:t.id});if(a)throw a},onSuccess:()=>{ae.success("Video logged — nice work"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>ae.error(r.message||"Could not log the video")})},tps=s=>{const{user:t}=ys(),n=Ht();return gt({mutationFn:async r=>{const{error:a}=await q.from("program_weekly_progress").upsert({...r,program_id:s,user_id:t.id},{onConflict:"program_id,user_id,week_number"});if(a)throw a},onSuccess:()=>{ae.success("Weekly check-in saved"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>ae.error(r.message||"Could not save your check-in")})},sps=s=>{const{user:t}=ys(),n=Ht();return gt({mutationFn:async({eventId:r,optIn:a})=>{const{error:i}=await q.from("program_event_attendance").upsert({event_id:r,program_id:s,user_id:t.id,reminder_opt_in:a},{onConflict:"event_id,user_id"});if(i)throw i},onSuccess:()=>n.invalidateQueries({queryKey:["program-workspace"]}),onError:r=>ae.error(r.message||"Could not update your RSVP")})},nps=s=>ct({queryKey:["program-discount-codes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_discount_codes").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}}),rps=s=>{const t=Ht();return gt({mutationFn:async n=>{const r={program_id:s,code:(n.code||"").trim().toUpperCase(),label:n.label||null,percent_off:n.percent_off??null,amount_off_cents:n.amount_off_cents??null,max_redemptions:n.max_redemptions??null,starts_at:n.starts_at||null,expires_at:n.expires_at||null,is_active:n.is_active??!0};if(n.id){const{error:a}=await q.from("program_discount_codes").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_discount_codes").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Discount code saved"),t.invalidateQueries({queryKey:["program-discount-codes"]})},onError:n=>{var r;return ae.error((r=n.message)!=null&&r.includes("duplicate")?"That code already exists for this program":n.message||"Could not save the code")}})},aps=()=>{const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("program_discount_codes").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ae.success("Discount code deleted"),s.invalidateQueries({queryKey:["program-discount-codes"]})},onError:t=>ae.error(t.message||"Could not delete the code")})},ips=()=>gt({mutationFn:async({enrollmentId:s,code:t})=>{const{data:n,error:r}=await q.rpc("program_apply_discount",{_enrollment_id:s,_code:t});if(r)throw r;const a=n;if(!(a!=null&&a.ok))throw new Error((a==null?void 0:a.error)||"That code could not be applied");return a}}),ops=()=>gt({mutationFn:async s=>{const{error:t}=await q.rpc("program_clear_discount",{_enrollment_id:s});if(t)throw t}}),lps=s=>ct({queryKey:["admin-program-events",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_events").select("*").eq("program_id",s).order("starts_at",{ascending:!0});if(n)throw n;return t||[]}}),cps=s=>{const t=Ht();return gt({mutationFn:async n=>{const r={program_id:s,title:(n.title||"").trim(),description:n.description||null,event_kind:n.event_kind||"mastermind",starts_at:n.starts_at,duration_minutes:n.duration_minutes??60,speaker:n.speaker||null,meeting_link:n.meeting_link||null,replay_url:n.replay_url||null,is_published:n.is_published??!0};if(n.id){const{error:a}=await q.from("program_events").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_events").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Session saved"),t.invalidateQueries({queryKey:["admin-program-events"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ae.error(n.message||"Could not save the session")})},dps=()=>{const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("program_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ae.success("Session removed"),s.invalidateQueries({queryKey:["admin-program-events"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the session")})},ups=s=>ct({queryKey:["admin-program-lessons",s],enabled:!!s,queryFn:async()=>{const[t,n]=await Promise.all([q.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),q.from("program_weeks").select("id, week_number, title").eq("program_id",s).order("week_number")]);if(t.error)throw t.error;return{lessons:t.data||[],weeks:n.data||[]}}}),hps=s=>{const t=Ht();return gt({mutationFn:async n=>{const r={program_id:s,week_id:n.week_id||null,title:(n.title||"").trim(),summary:n.summary||null,duration_minutes:n.duration_minutes??null,video_url:n.video_url||null,worksheet_url:n.worksheet_url||null,action_assignment:n.action_assignment||null,status:n.status||"published",publish_at:n.publish_at||null,sort_order:n.sort_order??0};if(n.id){const{error:a}=await q.from("program_lessons").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_lessons").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Video saved"),t.invalidateQueries({queryKey:["admin-program-lessons"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ae.error(n.message||"Could not save the video")})},mps=()=>{const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("program_lessons").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ae.success("Video removed"),s.invalidateQueries({queryKey:["admin-program-lessons"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the video")})},Yxt=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},pps=[{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"}],fIe="event-images",Zxt=s=>{if(s.file_path){const{data:t}=q.storage.from(fIe).getPublicUrl(s.file_path);return t.publicUrl}return s.url||null},fps=s=>ct({queryKey:["admin-program-resources",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_resources").select("*").eq("program_id",s).order("sort_order");if(n)throw n;return t||[]}}),xps=s=>{const t=Ht();return gt({mutationFn:async n=>{const r={program_id:s,title:(n.title||"").trim(),description:n.description||null,category:(n.category||"Resources").trim()||"Resources",resource_kind:n.resource_kind||"pdf",url:n.url||null,file_path:n.file_path||null,status:n.status||"published",sort_order:n.sort_order??0};if(n.id){const{error:a}=await q.from("program_resources").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_resources").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Resource saved"),t.invalidateQueries({queryKey:["admin-program-resources"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ae.error(n.message||"Could not save the resource")})},gps=()=>{const s=Ht();return gt({mutationFn:async t=>{t.file_path&&await q.storage.from(fIe).remove([t.file_path]);const{error:n}=await q.from("program_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{ae.success("Resource removed"),s.invalidateQueries({queryKey:["admin-program-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the resource")})},yps=s=>{const{user:t}=ys();return ct({queryKey:["program-interest",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await q.from("program_interest").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n||null}})},vps=s=>{const t=Ht(),{user:n}=ys();return gt({mutationFn:async r=>{if(!(n!=null&&n.id)||!s)throw new Error("You need to be signed in.");if(r){const{error:a}=await q.from("program_interest").upsert({program_id:s,user_id:n.id,source:"program_detail"},{onConflict:"program_id,user_id"});if(a)throw a}else{const{error:a}=await q.from("program_interest").delete().eq("program_id",s).eq("user_id",n.id);if(a)throw a}return r},onSuccess:r=>{ae.success(r?"You're on the list — we'll email you when enrollment opens.":"Removed from the notify list"),t.invalidateQueries({queryKey:["program-interest"]}),t.invalidateQueries({queryKey:["admin-program-interest"]})},onError:r=>ae.error(r.message||"Could not update your notify preference")})},bps=s=>ct({queryKey:["admin-program-interest",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_interest").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;const r=t||[];if(!r.length)return[];const a=Array.from(new Set(r.map(o=>o.user_id))),{data:i}=await q.from("profiles").select("id, name, email, phone, brokerage_name").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return r.map(o=>{const c=l.get(o.user_id)||{};return{...o,full_name:c.name??null,email:c.email??null,phone:c.phone??null,brokerage:c.brokerage_name??null}})}}),DVe=({program:s,enrolled:t})=>{const{notOpenYet:n,closed:r,opensLabel:a}=ove(s);return e.jsxs(fe,{className:"group overflow-hidden border-border/60 transition-all hover:border-primary/40 hover:shadow-lg",children:[e.jsxs("div",{className:"relative aspect-[16/9] overflow-hidden bg-muted",children:[s.cover_image_url?e.jsx("img",{src:s.cover_image_url,alt:`${s.name} program cover`,loading:"lazy",className:"h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"}):e.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gradient-to-br from-primary/15 via-background to-accent/20",children:e.jsx(un,{className:"h-10 w-10 text-primary/60"})}),e.jsxs("div",{className:"absolute left-3 top-3 flex gap-2",children:[s.is_featured&&e.jsx(ze,{className:"shadow-sm",children:"Featured"}),t&&e.jsxs(ze,{variant:"secondary",className:"shadow-sm",children:[e.jsx(xr,{className:"mr-1 h-3 w-3"})," Enrolled"]})]})]}),e.jsxs(Ee,{className:"space-y-4 p-5",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("h2",{className:"text-lg font-semibold leading-tight",children:s.name}),s.subtitle&&e.jsx("p",{className:"text-sm text-muted-foreground",children:s.subtitle})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1.5 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(gr,{className:"h-3.5 w-3.5"}),s.duration_weeks," weeks"]}),s.kickoff_at&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Tl,{className:"h-3.5 w-3.5"}),"Starts ",ql(s.kickoff_at)]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Nn,{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":Eu(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 ",MB(s.duration_weeks)," — no subscription",s.charge_at?` · charged ${ql(s.charge_at)}`:""]}):null]}),e.jsx(B,{asChild:!0,size:"sm",children:e.jsxs(Ln,{to:t?`/programs/${s.slug}/workspace`:`/programs/${s.slug}`,children:[t?"Open program":n?"Preview details":"View details",e.jsx(Oa,{className:"ml-1.5 h-4 w-4"})]})})]})]})]})},_ps=()=>{const{data:s=[],isLoading:t}=Kms(),{data:n=[]}=Kxt(),r=new Set(n.filter(l=>AB(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(Ts,{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(Ws,{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(DVe,{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(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(un,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No programs are open right now"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"New cohorts are announced inside the Hub. Check back soon — seats are limited when they open."})]})}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:i.map(l=>e.jsx(DVe,{program:l,enrolled:!1},l.id))})]})]})]})})},wps=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},jps=({url:s,headline:t,posterUrl:n})=>{const[r,a]=N.useState(!1),i=(s||"").trim();if(!i)return null;const l=wps(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(Au,{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 Db="Accordion",Nps=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[xIe,kps,Sps]=TD(Db),[lve,Vxn]=pu(Db,[Sps,Kht]),gIe=Kht(),Qxt=St.forwardRef((s,t)=>{const{type:n,...r}=s,a=r,i=r;return e.jsx(xIe.Provider,{scope:s.__scopeAccordion,children:n==="multiple"?e.jsx(Aps,{...i,ref:t}):e.jsx(Eps,{...a,ref:t})})});Qxt.displayName=Db;var[Xxt,Cps]=lve(Db),[Jxt,Tps]=lve(Db,{collapsible:!1}),Eps=St.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},collapsible:i=!1,...l}=s,[o,c]=hm({prop:n,defaultProp:r??"",onChange:a,caller:Db});return e.jsx(Xxt,{scope:s.__scopeAccordion,value:St.useMemo(()=>o?[o]:[],[o]),onItemOpen:c,onItemClose:St.useCallback(()=>i&&c(""),[i,c]),children:e.jsx(Jxt,{scope:s.__scopeAccordion,collapsible:i,children:e.jsx(egt,{...l,ref:t})})})}),Aps=St.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=hm({prop:n,defaultProp:r??[],onChange:a,caller:Db}),c=St.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=St.useCallback(u=>o((h=[])=>h.filter(p=>p!==u)),[o]);return e.jsx(Xxt,{scope:s.__scopeAccordion,value:l,onItemOpen:c,onItemClose:d,children:e.jsx(Jxt,{scope:s.__scopeAccordion,collapsible:!0,children:e.jsx(egt,{...i,ref:t})})})}),[Mps,cve]=lve(Db),egt=St.forwardRef((s,t)=>{const{__scopeAccordion:n,disabled:r,dir:a,orientation:i="vertical",...l}=s,o=St.useRef(null),c=Si(o,t),d=kps(n),h=NN(a)==="ltr",p=_r(s.onKeyDown,f=>{var M;if(!Nps.includes(f.key))return;const g=f.target,_=d().filter(F=>{var z;return!((z=F.ref.current)!=null&&z.disabled)}),v=_.findIndex(F=>F.ref.current===g),j=_.length;if(v===-1)return;f.preventDefault();let b=v;const S=0,A=j-1,T=()=>{b=v+1,b>A&&(b=S)},L=()=>{b=v-1,b{const{__scopeAccordion:n,value:r,...a}=s,i=cve(jxe,n),l=Cps(jxe,n),o=gIe(n),c=dm(),d=r&&l.value.includes(r)||!1,u=i.disabled||s.disabled;return e.jsx(Ips,{scope:n,open:d,disabled:u,triggerId:c,children:e.jsx(Qht,{"data-orientation":i.orientation,"data-state":ogt(d),...o,...a,ref:t,disabled:u,open:d,onOpenChange:h=>{h?l.onItemOpen(r):l.onItemClose(r)}})})});tgt.displayName=jxe;var sgt="AccordionHeader",ngt=St.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=cve(Db,n),i=yIe(sgt,n);return e.jsx(Jr.h3,{"data-orientation":a.orientation,"data-state":ogt(i.open),"data-disabled":i.disabled?"":void 0,...r,ref:t})});ngt.displayName=sgt;var r3e="AccordionTrigger",rgt=St.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=cve(Db,n),i=yIe(r3e,n),l=Tps(r3e,n),o=gIe(n);return e.jsx(xIe.ItemSlot,{scope:n,children:e.jsx(wes,{"aria-disabled":i.open&&!l.collapsible||void 0,"data-orientation":a.orientation,id:i.triggerId,...o,...r,ref:t})})});rgt.displayName=r3e;var agt="AccordionContent",igt=St.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=cve(Db,n),i=yIe(agt,n),l=gIe(n);return e.jsx(jes,{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}})});igt.displayName=agt;function ogt(s){return s?"open":"closed"}var Pps=Qxt,Lps=tgt,Dps=ngt,lgt=rgt,cgt=igt;const vIe=Pps,dve=N.forwardRef(({className:s,...t},n)=>e.jsx(Lps,{ref:n,className:Et("border-b",s),...t}));dve.displayName="AccordionItem";const uve=N.forwardRef(({className:s,children:t,...n},r)=>e.jsx(Dps,{className:"flex",children:e.jsxs(lgt,{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(io,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));uve.displayName=lgt.displayName;const hve=N.forwardRef(({className:s,children:t,...n},r)=>e.jsx(cgt,{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})}));hve.displayName=cgt.displayName;const Rps=({programId:s,opensLabel:t})=>{const{data:n,isLoading:r}=yps(s),a=vps(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(WS,{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(ts,{className:"mr-2 h-4 w-4 animate-spin"}):i?e.jsx(Ir,{className:"mr-2 h-4 w-4"}):e.jsx(WS,{className:"mr-2 h-4 w-4"}),i?"You're on the list":"Notify me"]})]})},Ops=()=>{const{slug:s}=bi(),{data:t,isLoading:n}=mIe(s),{data:r}=Wxt(t==null?void 0:t.id),{data:a}=pIe(t==null?void 0:t.id),i=AB(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||[],p=l.phases||[];if(n)return e.jsx(Ts,{children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-8",children:[e.jsx(Ws,{className:"h-64 w-full rounded-xl"}),e.jsx(Ws,{className:"h-40 w-full rounded-xl"})]})});if(!t)return e.jsx(Ts,{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(Ln,{to:"/programs",children:"Back to Programs"})})]})});const f=typeof r=="number"&&r<=0&&!i,{notOpenYet:g,closed:_,opensLabel:v}=ove(t),j=!i&&(f||_||g),b=i?"Open your program":g?`Enrollment opens ${ql(t.enrollment_open_at)}`:f?"Cohort is full":_?"Enrollment closed":t.payment_mode==="delayed"?"Reserve my seat":"Enroll now",S=i?`/programs/${t.slug}/workspace`:`/programs/${t.slug}/enroll`;return e.jsxs(Ts,{children:[e.jsxs(Go,{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(jps,{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(ze,{variant:"secondary",children:[t.duration_weeks,"-week program"]}),typeof r=="number"&&!i&&e.jsx(ze,{variant:r<=10?"destructive":"outline",children:r>0?`${r} of ${t.capacity} seats left`:"Full"}),i&&e.jsxs(ze,{children:[e.jsx(xr,{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":Eu(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 ",MB(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:ql(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(pf,{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:[n3e(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:ql(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:!j,size:"lg",disabled:j,children:j?e.jsx("span",{children:b}):e.jsxs(Ln,{to:S,children:[b,e.jsx(Oa,{className:"ml-2 h-4 w-4"})]})}),e.jsx(B,{asChild:!0,variant:"ghost",size:"lg",children:e.jsx(Ln,{to:"/programs",children:"All programs"})})]}),g&&!i&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Tl,{className:"h-3.5 w-3.5"}),"Enrollment opens ",v]}),e.jsx(Rps,{programId:t.id,opensLabel:v})]})]})]}),t.description&&e.jsxs("section",{className:"space-y-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What this program is"}),e.jsx("div",{className:"whitespace-pre-line text-muted-foreground",children:t.description})]}),o.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What you'll walk away with"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:o.map((A,T)=>e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(xr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("p",{className:"text-sm",children:A})]},T))})]}),p.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:p.map((A,T)=>e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ee,{className:"space-y-2 p-5",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-primary",children:["Phase ",T+1]}),e.jsx("h3",{className:"font-semibold",children:A.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:A.detail})]})},T))})]}),c.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What's included"}),e.jsx("ul",{className:"grid gap-2 sm:grid-cols-2",children:c.map((A,T)=>e.jsxs("li",{className:"flex items-start gap-2.5 text-sm",children:[e.jsx(un,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),A]},T))})]}),(d.length>0||u.length>0)&&e.jsxs("section",{className:"grid gap-6 md:grid-cols-2",children:[d.length>0&&e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ee,{className:"space-y-3 p-5",children:[e.jsx("h3",{className:"font-semibold",children:"This is for you if…"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:d.map((A,T)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(xr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),A]},T))})]})}),u.length>0&&e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ee,{className:"space-y-3 p-5",children:[e.jsx("h3",{className:"font-semibold",children:"This isn't for you if…"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:u.map((A,T)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(gr,{className:"mt-0.5 h-4 w-4 shrink-0"}),A]},T))})]})})]}),h.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Questions"}),e.jsx(vIe,{type:"single",collapsible:!0,className:"rounded-xl border border-border/60 px-4",children:h.map((A,T)=>e.jsxs(dve,{value:`faq-${T}`,children:[e.jsx(uve,{className:"text-left text-sm font-medium",children:A.q}),e.jsx(hve,{className:"text-sm text-muted-foreground",children:A.a})]},T))})]}),e.jsxs("section",{className:"rounded-2xl border border-border/60 bg-muted/40 p-6 text-center md:p-10",children:[e.jsx(br,{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:!j,size:"lg",disabled:j,children:j?e.jsx("span",{children:b}):e.jsxs(Ln,{to:S,children:[b,e.jsx(Oa,{className:"ml-2 h-4 w-4"})]})}),typeof r=="number"&&r>0&&!i&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Nn,{className:"h-4 w-4"}),r," seats remaining"]})]}),!i&&(g?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Tl,{className:"h-3.5 w-3.5"}),"Enrollment opens ",v]}):t.enrollment_close_at?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Tl,{className:"h-3.5 w-3.5"}),"Enrollment closes ",ql(t.enrollment_close_at)]}):null)]})]})]})},AH=["Your business","Your content","Your goals","Reserve your seat"],Fps=()=>{const{slug:s}=bi(),t=Mn(),[n,r]=gl(),{user:a}=ys(),{data:i,isLoading:l}=mIe(s),{data:o}=Wxt(i==null?void 0:i.id),{data:c,refetch:d}=pIe(i==null?void 0:i.id),{data:u}=Zms(i==null?void 0:i.id),h=Yms(),p=Qms(),f=ips(),g=ops(),[_,v]=N.useState(0),[j,b]=N.useState(!1),[S,A]=N.useState(!1),[T,L]=N.useState(!1),[D,M]=N.useState(!1),[F,z]=N.useState(""),[V,W]=N.useState(null),Y=N.useRef({}),[K,J]=N.useState({}),ne=N.useRef(!1),ie=(Be,Ye)=>{Y.current={...Y.current,[Be]:Ye},J(Y.current)};N.useEffect(()=>{ne.current||(u?(Y.current={...u},J(Y.current),ne.current=!0):a&&(Y.current={email:a.email,...Y.current},J(Y.current)))},[u,a]),N.useEffect(()=>{const Be=c;!i||!(Be!=null&&Be.discount_code)||V||W({code:Be.discount_code,discount_cents:Be.discount_cents||0,amount_cents:Be.amount_cents??i.price_cents,original_cents:i.price_cents})},[c,i,V]);const he=V?V.amount_cents:(i==null?void 0:i.price_cents)??0,ce=N.useMemo(()=>wxe(i),[i]),pe=Be=>Wms(ce,Be),le=Be=>LVe(ce,Be)?e.jsx("span",{className:"text-destructive",children:" *"}):null,ve=(Be,Ye)=>{const We={...Y.current.extra||{},[Be]:Ye};ie("extra",We)},ge=Be=>ce.custom.filter((Ye,We)=>We%3===Be),Te=Be=>{const Ye=ge(Be);if(!Ye.length)return null;const We=K.extra||{};return e.jsx("div",{className:"space-y-4",children:Ye.map(rt=>e.jsxs("div",{className:"space-y-2",children:[rt.type==="checkbox"?e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(ui,{id:rt.id,checked:!!We[rt.id],onCheckedChange:tt=>ve(rt.id,!!tt)}),e.jsxs(se,{htmlFor:rt.id,className:"text-sm font-normal leading-relaxed",children:[rt.label,rt.required&&e.jsx("span",{className:"text-destructive",children:" *"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(se,{htmlFor:rt.id,children:[rt.label,rt.required&&e.jsx("span",{className:"text-destructive",children:" *"})]}),rt.type==="long_text"?e.jsx(Es,{id:rt.id,rows:3,value:We[rt.id]||"",onChange:tt=>ve(rt.id,tt.target.value)}):rt.type==="select"?e.jsxs(ds,{value:We[rt.id]||"",onValueChange:tt=>ve(rt.id,tt),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select"})}),e.jsx(cs,{children:(rt.options||[]).map(tt=>e.jsx(Qe,{value:tt,children:tt},tt))})]}):e.jsx(ye,{id:rt.id,value:We[rt.id]||"",onChange:tt=>ve(rt.id,tt.target.value)})]}),rt.help&&e.jsx("p",{className:"text-xs text-muted-foreground",children:rt.help})]},rt.id))})},Me=Be=>{const Ye=Y.current,We=He=>He==null||He===""||He===!1,rt=Gxt.find(He=>He.step===Be&&LVe(ce,He.key)&&We(He.key==="timezone"?Ye.timezone||(i==null?void 0:i.timezone):Ye[He.key]));if(rt)return rt.label;const tt=Ye.extra||{},at=ge(Be).find(He=>He.required&&We(tt[He.id]));return at?at.label:null},Ce=()=>{if(_<=2){const Be=Me(_);if(Be)return ae.error(`Please answer: ${Be}`)}v(Be=>Be+1)},Ae=async()=>{if(!(!i||!F.trim()))try{let Be=c==null?void 0:c.id;(!Be||(c==null?void 0:c.status)==="canceled")&&(Be=await p.mutateAsync(i.id));const Ye=await f.mutateAsync({enrollmentId:Be,code:F});W(Ye),z(""),await d(),ae.success(`Code applied — you save ${Eu(Ye.discount_cents,i.currency)}`)}catch(Be){ae.error(Be.message||"That code could not be applied")}},De=async()=>{if(!(c!=null&&c.id))return W(null);try{await g.mutateAsync(c.id),W(null),await d()}catch(Be){ae.error(Be.message||"Could not remove the code")}},Ie=n.get("setup"),Fe=n.get("session_id"),qe=N.useRef(!1);N.useEffect(()=>{Ie!=="success"||!Fe||!(c!=null&&c.id)||qe.current||(qe.current=!0,A(!0),(async()=>{const{data:Be,error:Ye}=await q.functions.invoke("program-enroll",{body:{action:"verify",enrollment_id:c.id,session_id:Fe}});if(A(!1),Ye||Be!=null&&Be.error||(Be==null?void 0:Be.success)===!1){ae.error((Be==null?void 0:Be.error)||(Ye==null?void 0:Ye.message)||"We could not confirm your card");return}await d(),n.delete("setup"),n.delete("session_id"),r(n,{replace:!0}),ae.success("Your seat is confirmed")})())},[Ie,Fe,c==null?void 0:c.id]),N.useEffect(()=>{Ie==="cancelled"&&ae.info("Checkout cancelled — your seat is held for a short while.")},[Ie]);const be=N.useMemo(()=>c&&["reserved","scheduled_for_charge","paid","completed"].includes(c.status),[c]),Ze=async()=>{if(i){if(!T||i.payment_mode!=="free"&&!D){ae.error("Please confirm the checkboxes to continue");return}b(!0);try{let Be=c==null?void 0:c.id;(!Be||(c==null?void 0:c.status)==="canceled")&&(Be=await p.mutateAsync(i.id)),await h.mutateAsync({...Y.current,id:void 0,program_id:i.id,enrollment_id:Be,created_at:void 0,updated_at:void 0,user_id:void 0});const{data:Ye,error:We}=await q.functions.invoke("program-enroll",{body:{action:"setup",enrollment_id:Be}});if(We||Ye!=null&&Ye.error)throw new Error((Ye==null?void 0:Ye.error)||(We==null?void 0:We.message));if(Ye!=null&&Ye.free){await d(),ae.success("You're in"),t(`/programs/${i.slug}/workspace`);return}Ye!=null&&Ye.url&&(window.location.href=Ye.url)}catch(Be){ae.error(Be.message||"Could not start enrollment")}finally{b(!1)}}};if(l)return e.jsx(Ts,{children:e.jsxs("div",{className:"mx-auto max-w-2xl space-y-4 p-8",children:[e.jsx(Ws,{className:"h-10 w-1/2"}),e.jsx(Ws,{className:"h-64 w-full rounded-xl"})]})});if(!i)return e.jsx(Ts,{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(Ln,{to:"/programs",children:"Back to Programs"})})]})});if(AB(c)&&be&&Ie!=="success")return e.jsx(Ts,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx(xr,{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 ${ql(c==null?void 0:c.charge_scheduled_at)||"the program start date"}.`}),e.jsx(B,{asChild:!0,size:"lg",children:e.jsx(Ln,{to:`/programs/${i.slug}/workspace`,children:"Open your program workspace"})})]})});const Ne=typeof o=="number"&&o<=0,{notOpenYet:it,closed:je,opensLabel:Ge}=ove(i);return it||je?e.jsx(Ts,{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:it?"Enrollment is not open yet":"Enrollment is closed"}),e.jsx("p",{className:"text-muted-foreground",children:it?`Enrollment for ${i.name} opens ${Ge}. 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(Ln,{to:`/programs/${i.slug}`,children:"Back to program details"})})]})}):e.jsx(Ts,{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(Ln,{to:`/programs/${i.slug}`,children:[e.jsx(Hr,{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?`${n3e(i.price_cents,i.currency,i.duration_weeks)}. Your card is saved today and charged once on ${ql(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:AH[_]}),e.jsxs("span",{children:["Step ",_+1," of ",AH.length]})]}),e.jsx(pi,{value:(_+1)/AH.length*100})]}),S&&e.jsx(fe,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Ee,{className:"flex items-center gap-3 p-4 text-sm",children:[e.jsx(ts,{className:"h-4 w-4 animate-spin text-primary"}),"Confirming your card with Stripe…"]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-5 p-6",children:[_===0&&ce.intro&&e.jsx("p",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm text-muted-foreground",children:ce.intro}),_===0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[pe("full_name")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"full_name",children:["Full name",le("full_name")]}),e.jsx(ye,{id:"full_name",value:K.full_name||"",onChange:Be=>ie("full_name",Be.target.value)})]}),pe("phone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"phone",children:["Mobile number",le("phone")]}),e.jsx(ye,{id:"phone",value:K.phone||"",onChange:Be=>ie("phone",Be.target.value)})]}),pe("instagram_handle")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"instagram_handle",children:["Instagram handle",le("instagram_handle")]}),e.jsx(ye,{id:"instagram_handle",placeholder:"@yourhandle",value:K.instagram_handle||"",onChange:Be=>ie("instagram_handle",Be.target.value)})]}),pe("city")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"city",children:["Primary city / market",le("city")]}),e.jsx(ye,{id:"city",value:K.city||"",onChange:Be=>ie("city",Be.target.value)})]})]}),pe("service_areas")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"service_areas",children:["Neighborhoods or areas you serve",le("service_areas")]}),e.jsx(Es,{id:"service_areas",rows:2,value:K.service_areas||"",onChange:Be=>ie("service_areas",Be.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[pe("years_experience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["Years in real estate",le("years_experience")]}),e.jsxs(ds,{value:K.years_experience||"",onValueChange:Be=>ie("years_experience",Be),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select"})}),e.jsx(cs,{children:["Less than 1","1-3","4-7","8-15","15+"].map(Be=>e.jsx(Qe,{value:Be,children:Be},Be))})]})]}),pe("specialty")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"specialty",children:["Specialty or niche",le("specialty")]}),e.jsx(ye,{id:"specialty",value:K.specialty||"",onChange:Be=>ie("specialty",Be.target.value)})]})]}),Te(0)]}),_===1&&e.jsxs(e.Fragment,{children:[pe("target_audience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"target_audience",children:["Who are you trying to reach?",le("target_audience")]}),e.jsx(Es,{id:"target_audience",rows:2,placeholder:"First-time buyers, move-up sellers, investors…",value:K.target_audience||"",onChange:Be=>ie("target_audience",Be.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[pe("video_comfort")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["How comfortable are you on camera?",le("video_comfort")]}),e.jsxs(ds,{value:K.video_comfort||"",onValueChange:Be=>ie("video_comfort",Be),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select"})}),e.jsx(cs,{children:["Terrified","Nervous but willing","Getting comfortable","Very comfortable"].map(Be=>e.jsx(Qe,{value:Be,children:Be},Be))})]})]}),pe("posting_frequency")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["How often do you post today?",le("posting_frequency")]}),e.jsxs(ds,{value:K.posting_frequency||"",onValueChange:Be=>ie("posting_frequency",Be),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select"})}),e.jsx(cs,{children:["Never","Rarely","Weekly","A few times a week","Daily"].map(Be=>e.jsx(Qe,{value:Be,children:Be},Be))})]})]})]}),pe("content_style")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"content_style",children:["What content style feels like you?",le("content_style")]}),e.jsx(Es,{id:"content_style",rows:2,placeholder:"Educational, funny, behind-the-scenes, luxury-polished…",value:K.content_style||"",onChange:Be=>ie("content_style",Be.target.value)})]}),pe("personal_interests")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"personal_interests",children:["Interests or hobbies we can weave in",le("personal_interests")]}),e.jsx(Es,{id:"personal_interests",rows:2,value:K.personal_interests||"",onChange:Be=>ie("personal_interests",Be.target.value)})]}),Te(1)]}),_===2&&e.jsxs(e.Fragment,{children:[pe("primary_goal")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"primary_goal",children:["Your #1 goal for this program",le("primary_goal")]}),e.jsx(Es,{id:"primary_goal",rows:3,value:K.primary_goal||"",onChange:Be=>ie("primary_goal",Be.target.value)})]}),pe("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",le("topics_to_avoid")]}),e.jsx(Es,{id:"topics_to_avoid",rows:2,value:K.topics_to_avoid||"",onChange:Be=>ie("topics_to_avoid",Be.target.value)})]}),pe("timezone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["Your time zone",le("timezone")]}),e.jsxs(ds,{value:K.timezone||i.timezone,onValueChange:Be=>ie("timezone",Be),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select"})}),e.jsx(cs,{children:["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","Pacific/Honolulu"].map(Be=>e.jsx(Qe,{value:Be,children:Be.replace("America/","").replace("_"," ")},Be))})]})]}),Te(2),pe("consent_public_profile")&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(ui,{id:"consent_public_profile",checked:!!K.consent_public_profile,onCheckedChange:Be=>ie("consent_public_profile",!!Be)}),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."})]})]}),_===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":V?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-normal text-muted-foreground line-through",children:Eu(V.original_cents,i.currency)}),Eu(he,i.currency)]}):Eu(i.price_cents,i.currency)})]}),i.payment_mode!=="free"&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:n3e(he,i.currency,i.duration_weeks)}),i.payment_mode!=="free"&&e.jsx("div",{className:"mt-3 border-t border-border/60 pt-3",children:V?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(uh,{className:"h-3.5 w-3.5 text-primary"}),"Code ",e.jsx("span",{className:"font-mono font-semibold",children:V.code})," applied — you save ",Eu(V.discount_cents,i.currency)]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:De,disabled:g.isPending,children:[e.jsx(Bn,{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:F,onChange:Be=>z(Be.target.value.toUpperCase()),onKeyDown:Be=>{Be.key==="Enter"&&(Be.preventDefault(),Ae())}}),e.jsx(B,{variant:"outline",onClick:Ae,disabled:!F.trim()||f.isPending||p.isPending,children:f.isPending||p.isPending?e.jsx(ts,{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(pf,{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:ql(i.charge_at||i.kickoff_at)||"the program start date"}),". No recurring billing, installments, or renewal. Cancel any time before then at no cost."]})]}),typeof o=="number"&&e.jsx("p",{className:"mt-3 text-xs text-muted-foreground",children:o>0?`${o} of ${i.capacity} seats left`:"This cohort is full"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ui,{id:"terms",checked:T,onCheckedChange:Be=>L(!!Be)}),e.jsx(se,{htmlFor:"terms",className:"text-sm font-normal leading-relaxed",children:"I agree to the program terms, including the attendance and participation expectations, and understand seats are limited."})]}),i.payment_mode!=="free"&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ui,{id:"charge",checked:D,onCheckedChange:Be=>M(!!Be)}),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 — ${Eu(he,i.currency)} for the ${MB(i.duration_weeks)} — on ${ql(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 — ${Eu(he,i.currency)} for the ${MB(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(sg,{className:"h-3.5 w-3.5"}),"Card details are handled by Stripe — LevelUp never sees or stores them."]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border/60 pt-5",children:[e.jsxs(B,{variant:"ghost",onClick:()=>v(Be=>Math.max(0,Be-1)),disabled:_===0||j,children:[e.jsx(Hr,{className:"mr-1.5 h-4 w-4"})," Back"]}),_s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",zps=(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:${v2e(new Date)}`,`DTSTART:${v2e(n)}`,`DTEND:${v2e(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)},Bps={pdf:Nr,document:gw,checklist:uu,template_link:t4,video:Ah,external:El},$ps=()=>{var he;const{slug:s}=bi(),[t]=gl(),{isAdmin:n}=ys(),r=n&&t.get("preview")==="1",{data:a,isLoading:i}=mIe(s),{data:l}=pIe(a==null?void 0:a.id),{data:o,isLoading:c}=Xms(a==null?void 0:a.id),d=Jms(a==null?void 0:a.id),u=eps(a==null?void 0:a.id),h=tps(a==null?void 0:a.id),p=sps(a==null?void 0:a.id),[f,g]=N.useState(!1),[_,v]=N.useState({title:"",instagram_url:""}),[j,b]=N.useState({}),[S,A]=N.useState(null),T=N.useMemo(()=>{if(!(a!=null&&a.kickoff_at))return 1;const ce=Math.floor((Date.now()-new Date(a.kickoff_at).getTime())/864e5);return Math.min(Math.max(Math.floor(ce/7)+1,1),a.duration_weeks)},[a]),L=new Set(((o==null?void 0:o.completions)||[]).map(ce=>ce.lesson_id)),D=(o==null?void 0:o.lessons)||[],M=D.length?Math.round(L.size/D.length*100):0,F=((o==null?void 0:o.videoLogs)||[]).filter(ce=>ce.week_number===T).length,z=((o==null?void 0:o.videoLogs)||[]).length,V=(a==null?void 0:a.weekly_video_goal)||3,W=N.useMemo(()=>{const ce=new Map;((o==null?void 0:o.videoLogs)||[]).forEach(le=>ce.set(le.week_number,(ce.get(le.week_number)||0)+1));let pe=0;for(let le=T;le>=1;le--)if((ce.get(le)||0)>=V)pe++;else if(le!==T)break;return pe},[o==null?void 0:o.videoLogs,T,V]);if(i||c)return e.jsx(Ts,{children:e.jsxs("div",{className:"mx-auto max-w-6xl space-y-6 p-8",children:[e.jsx(Ws,{className:"h-28 w-full rounded-xl"}),e.jsx(Ws,{className:"h-64 w-full rounded-xl"})]})});if(!a)return e.jsx(Ts,{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(Ln,{to:"/programs",children:"Back to Programs"})})]})});if(!AB(l)&&!r)return e.jsx(Ts,{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 ",a.name," to unlock the roadmap, lessons and mastermind sessions."]}),e.jsx(B,{asChild:!0,size:"lg",children:e.jsx(Ln,{to:`/programs/${a.slug}`,children:"View the program"})})]})});const Y=((o==null?void 0:o.events)||[]).filter(ce=>new Date(ce.starts_at)>=new Date),K=((o==null?void 0:o.events)||[]).filter(ce=>new Date(ce.starts_at)ce.is_pinned),ne=((o==null?void 0:o.resources)||[]).reduce((ce,pe)=>{var le;return(ce[le=pe.category]||(ce[le]=[])).push(pe),ce},{}),ie=((o==null?void 0:o.progress)||[]).find(ce=>ce.week_number===T)||{};return e.jsx(Ts,{children:e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-8 p-4 md:p-8",children:[r&&!AB(l)&&e.jsx(fe,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Ee,{className:"flex flex-wrap items-center justify-between gap-3 p-4 text-sm",children:[e.jsxs("span",{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(Ln,{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(ze,{variant:"secondary",children:["Week ",T," of ",a.duration_weeks]}),(l==null?void 0:l.status)==="scheduled_for_charge"&&l.charge_scheduled_at&&e.jsxs(ze,{variant:"outline",children:["Billing ",ql(l.charge_scheduled_at)]}),(l==null?void 0:l.status)==="payment_failed"&&e.jsx(ze,{variant:"destructive",children:"Payment issue"})]}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:a.name}),a.subtitle&&e.jsx("p",{className:"text-muted-foreground",children:a.subtitle})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[e.jsx(Oc,{className:"h-3.5 w-3.5"})," This week"]}),e.jsxs("p",{className:"text-2xl font-bold",children:[F,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",V]})]}),e.jsx(pi,{value:Math.min(F/V*100,100),className:"h-1.5"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[e.jsx(Ah,{className:"h-3.5 w-3.5"})," Videos posted"]}),e.jsx("p",{className:"text-2xl font-bold",children:z}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"since kickoff"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[e.jsx(Dc,{className:"h-3.5 w-3.5"})," Streak"]}),e.jsxs("p",{className:"text-2xl font-bold",children:[W," wk"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"hitting your goal"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[e.jsx(mo,{className:"h-3.5 w-3.5"})," Curriculum"]}),e.jsxs("p",{className:"text-2xl font-bold",children:[M,"%"]}),e.jsx(pi,{value:M,className:"h-1.5"})]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(bs,{open:f,onOpenChange:g,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Is,{className:"mr-1.5 h-4 w-4"})," Log a video"]})}),e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Log a posted video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"v-title",children:"What was it about?"}),e.jsx(ye,{id:"v-title",value:_.title,onChange:ce=>v(pe=>({...pe,title:ce.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:_.instagram_url,onChange:ce=>v(pe=>({...pe,instagram_url:ce.target.value}))})]})]}),e.jsx(Xn,{children:e.jsx(B,{onClick:async()=>{await u.mutateAsync({week_number:T,..._}),v({title:"",instagram_url:""}),g(!1)},children:"Log video"})})]})]}),((he=Y[0])==null?void 0:he.meeting_link)&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:Y[0].meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(Au,{className:"mr-1.5 h-4 w-4"})," Join next session"]})})]}),J.length>0&&e.jsx(fe,{className:"border-primary/30 bg-primary/5",children:e.jsx(Ee,{className:"space-y-3 p-5",children:J.map(ce=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx($d,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ce.title}),ce.body&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ce.body})]})]},ce.id))})}),e.jsxs(Br,{defaultValue:"roadmap",children:[e.jsxs(Fr,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Kt,{value:"roadmap",children:"Roadmap"}),e.jsx(Kt,{value:"lessons",children:"Lessons"}),e.jsx(Kt,{value:"checkin",children:"Weekly check-in"}),e.jsx(Kt,{value:"events",children:"Sessions"}),e.jsx(Kt,{value:"resources",children:"Resources"}),e.jsx(Kt,{value:"profile",children:"Profile review"})]}),e.jsxs(is,{value:"roadmap",className:"mt-6 space-y-4",children:[((o==null?void 0:o.weeks)||[]).length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"The roadmap will appear here before kickoff."}),((o==null?void 0:o.weeks)||[]).map(ce=>{const pe=ce.release_at&&new Date(ce.release_at)>new Date;return e.jsx(fe,{className:pe?"opacity-60":ce.week_number===T?"border-primary/50":"",children:e.jsxs(Ee,{className:"space-y-2 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ze,{variant:"outline",children:["Week ",ce.week_number]}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:ce.phase}),ce.week_number===T&&e.jsx(ze,{children:"Current"}),pe&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(gr,{className:"h-3 w-3"})," Unlocks ",ql(ce.release_at)]})]}),e.jsx("h3",{className:"font-semibold",children:ce.title}),ce.learning_goal&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ce.learning_goal}),!pe&&Array.isArray(ce.tasks)&&ce.tasks.length>0&&e.jsx("ul",{className:"mt-2 space-y-1.5",children:ce.tasks.map((le,ve)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(xr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof le=="string"?le:le.label]},ve))})]})},ce.id)})]}),e.jsxs(is,{value:"lessons",className:"mt-6 space-y-3",children:[D.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Lessons unlock as the program progresses."}),D.map(ce=>{const pe=Yxt(ce.video_url),le=S===ce.id;return e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-4 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(ui,{checked:L.has(ce.id),onCheckedChange:ve=>d.mutate({lessonId:ce.id,done:!!ve}),"aria-label":`Mark ${ce.title} complete`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:ce.title}),ce.summary&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ce.summary}),ce.action_assignment&&e.jsxs("p",{className:"mt-1 text-xs text-primary",children:["Action: ",ce.action_assignment]})]}),ce.duration_minutes&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(gr,{className:"h-3 w-3"})," ",ce.duration_minutes," min"]}),e.jsxs("div",{className:"flex gap-2",children:[ce.video_url&&pe&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>A(le?null:ce.id),children:[e.jsx(Au,{className:"mr-1.5 h-3.5 w-3.5"})," ",le?"Close":"Watch"]}),ce.video_url&&!pe&&e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ce.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Au,{className:"mr-1.5 h-3.5 w-3.5"})," Watch"]})}),ce.worksheet_url&&e.jsx(B,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs("a",{href:ce.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Pa,{className:"mr-1.5 h-3.5 w-3.5"})," Worksheet"]})})]})]}),le&&pe&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:pe,title:ce.title,className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})})]})},ce.id)})]}),e.jsx(is,{value:"checkin",className:"mt-6",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-5 p-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold",children:["Week ",T," 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(([ce,pe])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:ce,children:pe}),e.jsx(ye,{id:ce,type:"number",min:0,defaultValue:ie[ce]??"",onChange:le=>b(ve=>({...ve,[ce]:Number(le.target.value)}))})]},ce))}),[["biggest_win","Biggest win"],["biggest_challenge","Biggest challenge"],["what_to_improve","What you’ll change next week"]].map(([ce,pe])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:ce,children:pe}),e.jsx(Es,{id:ce,rows:2,defaultValue:ie[ce]??"",onChange:le=>b(ve=>({...ve,[ce]:le.target.value}))})]},ce)),e.jsx(B,{onClick:()=>h.mutate({week_number:T,goal_videos:V,...j}),children:"Save check-in"})]})})}),e.jsxs(is,{value:"events",className:"mt-6 space-y-4",children:[Y.length===0&&K.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sessions will be scheduled before kickoff."}),Y.map(ce=>e.jsx(fe,{className:"border-primary/30",children:e.jsxs(Ee,{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(ze,{variant:"secondary",className:"capitalize",children:String(ce.event_kind).replace("_"," ")}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Tl,{className:"h-3 w-3"})," ",ql(ce.starts_at,!0)]})]}),e.jsx("p",{className:"mt-1.5 font-medium",children:ce.title}),ce.speaker&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["with ",ce.speaker]}),ce.description&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:ce.description})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>p.mutate({eventId:ce.id,optIn:!0}),children:"Remind me"}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>zps(ce,a.name),children:[e.jsx(Tl,{className:"mr-1.5 h-3.5 w-3.5"})," Add to calendar"]}),ce.meeting_link&&e.jsx(B,{size:"sm",asChild:!0,children:e.jsxs("a",{href:ce.meeting_link,target:"_blank",rel:"noreferrer",children:["Join ",e.jsx(tr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})},ce.id)),K.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"}),K.map(ce=>e.jsx(fe,{children:e.jsxs(Ee,{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:ce.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ql(ce.starts_at,!0)})]}),ce.replay_url?e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ce.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Au,{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"})]})},ce.id))]})]}),e.jsxs(is,{value:"resources",className:"mt-6 space-y-8",children:[Object.keys(ne).length===0&&e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center gap-2 p-12 text-center",children:[e.jsx(Nr,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"Your resource library is being built"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Worksheets, scripts and swipe files will appear here as the program unlocks."})]})}),Object.entries(ne).map(([ce,pe])=>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:ce}),e.jsx("span",{className:"h-px flex-1 bg-border"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[pe.length," item",pe.length===1?"":"s"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:pe.map(le=>{const ve=Zxt(le),ge=Bps[le.resource_kind]||Nr;return e.jsxs("a",{href:ve||"#",target:"_blank",rel:"noreferrer",onClick:Te=>{ve||Te.preventDefault()},className:"group relative flex 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(ge,{className:"h-5 w-5"})}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:String(le.resource_kind).replace("_"," ")})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-semibold leading-snug",children:le.title}),le.description&&e.jsx("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:le.description})]}),e.jsx("span",{className:"mt-auto inline-flex items-center gap-1.5 text-sm font-medium text-primary",children:le.file_path?e.jsxs(e.Fragment,{children:[e.jsx(Pa,{className:"h-3.5 w-3.5"})," Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(tr,{className:"h-3.5 w-3.5"})," Open"]})})]},le.id)})})]},ce))]}),e.jsx(is,{value:"profile",className:"mt-6",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-4 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(du,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"font-semibold",children:"Your profile review"})]}),!(o!=null&&o.analysis)||o.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."}):o.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:[o.analysis.scores&&Object.keys(o.analysis.scores).length>0&&e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:Object.entries(o.analysis.scores).map(([ce,pe])=>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:ce.replace(/_/g," ")}),e.jsxs("span",{className:"font-semibold",children:[pe,"/10"]})]}),e.jsx(pi,{value:Number(pe)*10,className:"h-1.5"})]},ce))}),Array.isArray(o.analysis.top_priorities)&&o.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:o.analysis.top_priorities.map((ce,pe)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(bc,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof ce=="string"?ce:ce.label]},pe))})]}),o.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:o.analysis.member_notes}),o.analysis.report_url&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:o.analysis.report_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Pa,{className:"mr-1.5 h-4 w-4"})," Download full report"]})})]})]})})})]})]})})},da=N.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})}));da.displayName="Table";const ua=N.forwardRef(({className:s,...t},n)=>e.jsx("thead",{ref:n,className:Et("[&_tr]:border-b",s),...t}));ua.displayName="TableHeader";const ha=N.forwardRef(({className:s,...t},n)=>e.jsx("tbody",{ref:n,className:Et("[&_tr:last-child]:border-0",s),...t}));ha.displayName="TableBody";const Ups=N.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}));Ups.displayName="TableFooter";const Hs=N.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}));Hs.displayName="TableRow";const Ct=N.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}));Ct.displayName="TableHead";const ut=N.forwardRef(({className:s,...t},n)=>e.jsx("td",{ref:n,className:Et("p-4 align-middle [&:has([role=checkbox])]:pr-0",s),...t}));ut.displayName="TableCell";const qps=N.forwardRef(({className:s,...t},n)=>e.jsx("caption",{ref:n,className:Et("mt-4 text-sm text-muted-foreground",s),...t}));qps.displayName="TableCaption";const MH=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())}`},IH=s=>s?new Date(s).toISOString():null,b2e=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:MH(s.enrollment_open_at),enrollment_close_at:MH(s.enrollment_close_at),kickoff_at:MH(s.kickoff_at),charge_at:MH(s.charge_at),status:s.status||"draft",is_public:!!s.is_public,is_featured:!!s.is_featured,sort_order:s.sort_order??0}),Vps=({program:s,onSaved:t})=>{const[n,r]=N.useState(()=>b2e(s)),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=N.useRef(null),h=N.useRef(null);N.useEffect(()=>{r(b2e(s)),i(!1)},[s.id,s.updated_at]);const p=(v,j)=>{r(b=>({...b,[v]:j})),i(!0)},f=async(v,j)=>{if(!v.type.startsWith("image/")){ae.error("Please choose an image file");return}if(v.size>8*1024*1024){ae.error("Image must be under 8MB");return}d(j);try{const b=v.name.split(".").pop()||"jpg",S=`programs/${s.id}/${j}-${Date.now()}.${b}`,{error:A}=await q.storage.from("event-images").upload(S,v,{cacheControl:"31536000",upsert:!0});if(A)throw A;const{data:T}=q.storage.from("event-images").getPublicUrl(S);p(j==="cover"?"cover_image_url":"hero_image_url",T.publicUrl),ae.success(`${j==="cover"?"Cover":"Hero"} image uploaded — remember to save`)}catch(b){ae.error(b.message||"Upload failed")}finally{d(null)}},g=async()=>{if(!n.name.trim())return ae.error("Program name is required");if(!n.slug.trim())return ae.error("Slug is required");o(!0);try{const v={name:n.name.trim(),slug:n.slug.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),subtitle:n.subtitle||null,tagline:n.tagline||null,short_description:n.short_description||null,description:n.description||null,price_cents:Math.max(0,Math.round(n.price_cents)),currency:n.currency||"usd",capacity:Math.max(0,Math.round(n.capacity)),duration_weeks:Math.max(1,Math.round(n.duration_weeks)),weekly_video_goal:Math.max(0,Math.round(n.weekly_video_goal)),payment_mode:n.payment_mode,payment_grace_days:Math.max(0,Math.round(n.payment_grace_days)),timezone:n.timezone||"America/New_York",accent_color:n.accent_color||null,cover_image_url:n.cover_image_url||null,hero_image_url:n.hero_image_url||null,promo_video_url:n.promo_video_url.trim()||null,promo_video_headline:n.promo_video_headline.trim()||null,enrollment_open_at:IH(n.enrollment_open_at),enrollment_close_at:IH(n.enrollment_close_at),kickoff_at:IH(n.kickoff_at),charge_at:IH(n.charge_at),status:n.status,is_public:n.is_public,is_featured:n.is_featured,sort_order:Math.round(n.sort_order)},{error:j}=await q.from("programs").update(v).eq("id",s.id);if(j)throw j;ae.success("Program saved"),i(!1),t()}catch(v){ae.error(v.message||"Could not save the program")}finally{o(!1)}},_=({kind:v,label:j,hint:b})=>{const S=v==="cover"?n.cover_image_url:n.hero_image_url,A=v==="cover"?u:h;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:j}),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:S?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:S,alt:`${j} preview`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>p(v==="cover"?"cover_image_url":"hero_image_url",""),className:"absolute right-1.5 top-1.5 rounded-full bg-background/90 p-1 text-foreground shadow","aria-label":`Remove ${j}`,children:e.jsx(Bn,{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(ry,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"No image"})]})}),e.jsxs("div",{className:"min-w-[220px] flex-1 space-y-2",children:[e.jsx("input",{ref:A,type:"file",accept:"image/*",className:"hidden",onChange:T=>{var D;const L=(D=T.target.files)==null?void 0:D[0];L&&f(L,v),T.target.value=""}}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var T;return(T=A.current)==null?void 0:T.click()},disabled:c===v,children:[c===v?e.jsx(ts,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Na,{className:"mr-1.5 h-4 w-4"}),"Upload image"]}),e.jsx(ye,{placeholder:"…or paste an image URL",value:S,onChange:T=>p(v==="cover"?"cover_image_url":"hero_image_url",T.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]})]})]})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"sticky top-0 z-10 -mx-1 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-background/95 px-4 py-3 backdrop-blur",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:a?"You have unsaved changes.":"All changes saved."}),e.jsxs("div",{className:"flex gap-2",children:[a&&e.jsx(B,{variant:"ghost",onClick:()=>{r(b2e(s)),i(!1)},children:"Discard"}),e.jsxs(B,{onClick:g,disabled:l||!a,children:[l?e.jsx(ts,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(qo,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})]})]}),e.jsx(fe,{children:e.jsxs(Ee,{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:v=>p("name",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Slug (public URL)"}),e.jsx(ye,{value:n.slug,onChange:v=>p("slug",v.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["/programs/",n.slug||"slug"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Subtitle"}),e.jsx(ye,{value:n.subtitle,onChange:v=>p("subtitle",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Tagline"}),e.jsx(ye,{value:n.tagline,onChange:v=>p("tagline",v.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Short description (cards & previews)"}),e.jsx(Es,{rows:2,value:n.short_description,onChange:v=>p("short_description",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Full program description (sales page)"}),e.jsx(Es,{rows:8,value:n.description,onChange:v=>p("description",v.target.value)})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{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(_,{kind:"cover",label:"Program cover image",hint:"Shown on the Programs list and enrollment cards. 1200×630 works great."}),e.jsx(_,{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:v=>p("promo_video_url",v.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:v=>p("promo_video_headline",v.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Plays in a cinematic player near the top of the program signup page."})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Accent color"}),e.jsx(ye,{placeholder:"#406E71",value:n.accent_color,onChange:v=>p("accent_color",v.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:v=>p("sort_order",Number(v.target.value))})]})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{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:v=>p("price_cents",Math.round(Number(v.target.value)*100))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Charged one time for the full program — never recurring."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Seats (capacity)"}),e.jsx(ye,{type:"number",min:0,value:n.capacity,onChange:v=>p("capacity",Number(v.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Billing mode"}),e.jsxs(ds,{value:n.payment_mode,onValueChange:v=>p("payment_mode",v),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"delayed",children:"Save card, charge once later"}),e.jsx(Qe,{value:"immediate",children:"Charge once at checkout"}),e.jsx(Qe,{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:v=>p("charge_at",v.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:v=>p("payment_grace_days",Number(v.target.value))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Days of access kept after a failed charge before access is paused."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Currency"}),e.jsx(ye,{value:n.currency,onChange:v=>p("currency",v.target.value)})]})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{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:v=>p("enrollment_open_at",v.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:v=>p("enrollment_close_at",v.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:v=>p("kickoff_at",v.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:v=>p("duration_weeks",Number(v.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:v=>p("weekly_video_goal",Number(v.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Timezone"}),e.jsx(ye,{value:n.timezone,onChange:v=>p("timezone",v.target.value)})]})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{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(ds,{value:n.status,onValueChange:v=>p("status",v),children:[e.jsx(ls,{className:"sm:max-w-xs",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"draft",children:"Draft (hidden)"}),e.jsx(Qe,{value:"published",children:"Published (members can enroll)"}),e.jsx(Qe,{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(bn,{checked:n.is_featured,onCheckedChange:v=>p("is_featured",v)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Visible to all members"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Turn off to keep it invite-only via a direct link."})]}),e.jsx(bn,{checked:n.is_public,onCheckedChange:v=>p("is_public",v)})]})]})}),e.jsx("div",{className:"flex justify-end pb-4",children:e.jsxs(B,{onClick:g,disabled:l||!a,size:"lg",children:[l?e.jsx(ts,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(qo,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})})]})},Hps=({program:s,enrollment:t,open:n,onOpenChange:r,onUpdated:a})=>{var J,ne,ie,he,ce,pe,le;const i=t==null?void 0:t.user_id,[l,o]=N.useState((t==null?void 0:t.admin_notes)||""),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState(!1),[g,_]=N.useState(!1),v=N.useRef(null),{data:j,isLoading:b,refetch:S}=ct({queryKey:["admin-program-agent",s.id,i],enabled:n&&!!i,queryFn:async()=>{const[ve,ge,Te,Me,Ce,Ae,De,Ie]=await Promise.all([q.from("program_weekly_progress").select("*").eq("program_id",s.id).eq("user_id",i).order("week_number"),q.from("program_video_logs").select("*").eq("program_id",s.id).eq("user_id",i).order("posted_at",{ascending:!1}),q.from("program_lesson_completions").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_badge_awards").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_intake_responses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle(),q.from("program_event_attendance").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_lessons").select("id").eq("program_id",s.id),q.from("program_profile_analyses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle()]);return{weekly:ve.data||[],videos:ge.data||[],completions:Te.data||[],badges:Me.data||[],intake:Ce.data,attendance:Ae.data||[],lessonCount:(De.data||[]).length,analysis:Ie.data}}});N.useEffect(()=>{var ve;h(((ve=j==null?void 0:j.analysis)==null?void 0:ve.member_notes)||"")},[(J=j==null?void 0:j.analysis)==null?void 0:J.id]);const A=N.useMemo(()=>{var Te;const ve=wxe(s),ge=((Te=j==null?void 0:j.intake)==null?void 0:Te.extra)||{};return ve.custom.map(Me=>({label:Me.label,value:typeof ge[Me.id]=="boolean"?ge[Me.id]?"Yes":"No":ge[Me.id]||""})).filter(Me=>!!Me.value)},[s,j==null?void 0:j.intake]),T=async ve=>i?q.from("program_profile_analyses").upsert({program_id:s.id,user_id:i,enrollment_id:(t==null?void 0:t.id)||null,...ve},{onConflict:"program_id,user_id"}):{error:{message:"Missing agent"}},L=async ve=>{if(ve.type!=="application/pdf")return ae.error("Please choose a PDF file");if(ve.size>25*1024*1024)return ae.error("PDF must be under 25MB");_(!0);try{const ge=`programs/${s.id}/reviews/${i}-${Date.now()}.pdf`,{error:Te}=await q.storage.from("event-images").upload(ge,ve,{contentType:"application/pdf",upsert:!0});if(Te)throw Te;const{data:Me}=q.storage.from("event-images").getPublicUrl(ge),{error:Ce}=await T({report_url:Me.publicUrl,status:"ready",reviewed_at:new Date().toISOString()});if(Ce)throw Ce;ae.success("Profile review uploaded"),await S()}catch(ge){ae.error(ge.message||"Upload failed")}finally{_(!1)}},D=async()=>{const{error:ve}=await T({report_url:null,status:"in_review"});if(ve)return ae.error(ve.message);ae.success("Review removed"),await S()},M=async()=>{f(!0);const{error:ve}=await T({member_notes:u});if(f(!1),ve)return ae.error(ve.message);ae.success("Review notes saved"),await S()},F=async()=>{if(!t)return;d(!0);const{error:ve}=await q.from("program_enrollments").update({admin_notes:l}).eq("id",t.id);if(d(!1),ve)return ae.error(ve.message);ae.success("Notes saved"),a()},z=((j==null?void 0:j.videos)||[]).filter(ve=>ve.posted).length,V=(s.weekly_video_goal||0)*(s.duration_weeks||0),W=j!=null&&j.lessonCount?Math.round(((j==null?void 0:j.completions.length)||0)/j.lessonCount*100):0,Y=V?Math.min(100,Math.round(z/V*100)):0,K=((j==null?void 0:j.attendance)||[]).filter(ve=>ve.attended).length;return e.jsx(cg,{open:n,onOpenChange:r,children:e.jsxs(ix,{className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(n0,{className:"mb-4",children:[e.jsxs(r0,{children:[((ne=t==null?void 0:t.profile)==null?void 0:ne.name)||"Agent"," · ",s.name]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(ie=t==null?void 0:t.profile)==null?void 0:ie.email})]}),t?b?e.jsx(Ws,{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(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsx(ze,{className:"mt-1 capitalize",children:String(t.status).replace(/_/g," ")}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[Eu(t.amount_cents,t.currency)," ·"," ",t.charged_at?`Charged ${ql(t.charged_at)}`:`Charge ${ql(t.charge_scheduled_at)||"not set"}`]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{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:ql(t.last_activity_at,!0)||"No activity yet"}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Enrolled ",ql(t.created_at)]})]})})]}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-4 p-5",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Videos posted"}),e.jsxs("span",{className:"text-muted-foreground",children:[z," / ",V||"—"]})]}),e.jsx(pi,{value:Y})]}),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:[(j==null?void 0:j.completions.length)||0," / ",(j==null?void 0:j.lessonCount)||0]})]}),e.jsx(pi,{value:W})]}),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: "}),K]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Badges: "}),(j==null?void 0:j.badges.length)||0]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Weeks reported: "}),(j==null?void 0:j.weekly.length)||0]})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Weekly progress"}),((j==null?void 0:j.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:j.weekly.map(ve=>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 ",ve.week_number]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[ve.videos_posted,"/",ve.goal_videos||s.weekly_video_goal," posted ·"," ",ve.stories_posted," stories"]})]}),ve.biggest_win&&e.jsxs("p",{className:"mt-1 text-muted-foreground",children:["Win: ",ve.biggest_win]}),ve.biggest_challenge&&e.jsxs("p",{className:"text-muted-foreground",children:["Challenge: ",ve.biggest_challenge]})]},ve.id))})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Video log"}),((j==null?void 0:j.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:j.videos.slice(0,25).map(ve=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(br,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:ve.title||"Untitled video"}),e.jsxs("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:["Wk ",ve.week_number," · ",ql(ve.posted_at)]}),ve.instagram_url&&e.jsx("a",{href:ve.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"})})]},ve.id))})]})}),(j==null?void 0:j.intake)&&e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-1 p-5 text-sm",children:[e.jsx("p",{className:"mb-2 text-sm font-semibold",children:"Intake answers"}),[["Full name",j.intake.full_name],["Email",j.intake.email],["Phone",j.intake.phone],["Instagram",j.intake.instagram_handle],["City / market",j.intake.city],["Areas served",j.intake.service_areas],["Years in real estate",j.intake.years_experience],["Specialty",j.intake.specialty],["Target audience",j.intake.target_audience],["On camera",j.intake.video_comfort],["Posts today",j.intake.posting_frequency],["Content style",j.intake.content_style],["Interests",j.intake.personal_interests],["#1 goal",j.intake.primary_goal],["Topics to avoid",j.intake.topics_to_avoid],["Time zone",j.intake.timezone]].filter(([,ve])=>!!ve).map(([ve,ge])=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[ve,": "]}),ge]},ve)),A.map(({label:ve,value:ge})=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[ve,": "]}),ge]},ve)),e.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Content-sharing consent: ",j.intake.consent_public_profile?"Yes":"No"]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{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."})]}),((he=j==null?void 0:j.analysis)==null?void 0:he.status)&&e.jsx(ze,{variant:"secondary",className:"capitalize",children:String(j.analysis.status).replace(/_/g," ")})]}),(ce=j==null?void 0:j.analysis)!=null&&ce.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(Nr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:"Review uploaded"}),e.jsxs("a",{href:j.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:v,type:"file",accept:"application/pdf",className:"hidden",onChange:ve=>{var Te;const ge=(Te=ve.target.files)==null?void 0:Te[0];ge&&L(ge),ve.target.value=""}}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{var ve;return(ve=v.current)==null?void 0:ve.click()},disabled:g,children:[e.jsx(Na,{className:"mr-1.5 h-3.5 w-3.5"}),g?"Uploading…":(pe=j==null?void 0:j.analysis)!=null&&pe.report_url?"Replace PDF":"Upload PDF"]}),((le=j==null?void 0:j.analysis)==null?void 0:le.report_url)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:D,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(Es,{rows:3,value:u,onChange:ve=>h(ve.target.value),placeholder:"Top 3 priorities, quick wins, what to fix first…"}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{size:"sm",variant:"outline",onClick:M,disabled:p,children:"Save review notes"})})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-3 p-5",children:[e.jsx(se,{children:"Coach notes (internal)"}),e.jsx(Es,{rows:4,value:l,onChange:ve=>o(ve.target.value)}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{size:"sm",onClick:F,disabled:c,children:"Save notes"})})]})})]}):null]})})},RVe={code:"",label:"",kind:"percent",percent_off:"20",amount_off:"",max_redemptions:"",starts_at:"",expires_at:"",is_active:!0},OVe=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},Gps=({program:s})=>{const{data:t=[],isLoading:n}=nps(s.id),r=rps(s.id),a=aps(),[i,l]=N.useState(!1),[o,c]=N.useState({...RVe}),d=()=>{c({...RVe}),l(!0)},u=g=>{c({id:g.id,code:g.code,label:g.label||"",kind:g.percent_off!=null?"percent":"amount",percent_off:g.percent_off!=null?String(g.percent_off):"",amount_off:g.amount_off_cents!=null?String(g.amount_off_cents/100):"",max_redemptions:g.max_redemptions!=null?String(g.max_redemptions):"",starts_at:OVe(g.starts_at),expires_at:OVe(g.expires_at),is_active:g.is_active}),l(!0)},h=N.useMemo(()=>{const g=o.kind==="percent"?Math.floor(s.price_cents*Number(o.percent_off||0)/100):Math.round(Number(o.amount_off||0)*100),_=Math.min(Math.max(g,0),s.price_cents);return{discount:_,final:s.price_cents-_}},[o,s.price_cents]),p=async()=>{if(!o.code.trim())return ae.error("Give the code a name, e.g. FOUNDER50");await r.mutateAsync({id:o.id,code:o.code,label:o.label||null,percent_off:o.kind==="percent"?Number(o.percent_off)||0:null,amount_off_cents:o.kind==="amount"?Math.round(Number(o.amount_off||0)*100):null,max_redemptions:o.max_redemptions?Number(o.max_redemptions):null,starts_at:o.starts_at?new Date(o.starts_at).toISOString():null,expires_at:o.expires_at?new Date(o.expires_at).toISOString():null,is_active:o.is_active}),l(!1)},f=g=>{const _=g.percent_off!=null?Math.floor(s.price_cents*Number(g.percent_off)/100):g.amount_off_cents||0,v=Math.max(s.price_cents-Math.min(_,s.price_cents),0);return{off:g.percent_off!=null?`${Number(g.percent_off)}% off`:`${Eu(g.amount_off_cents||0,s.currency)} off`,final:Eu(v,s.currency)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{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 ",Eu(s.price_cents,s.currency)," charge."]})]}),e.jsxs(bs,{open:i,onOpenChange:l,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{onClick:d,children:[e.jsx(Is,{className:"mr-1.5 h-4 w-4"})," New code"]})}),e.jsxs(vs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:o.id?"Edit discount code":"Create a discount code"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Code"}),e.jsx(ye,{placeholder:"FOUNDER50",value:o.code,onChange:g=>c({...o,code:g.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:g=>c({...o,label:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Discount type"}),e.jsxs(ds,{value:o.kind,onValueChange:g=>c({...o,kind:g}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"percent",children:"Percent off"}),e.jsx(Qe,{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:g=>c({...o,percent_off:g.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:g=>c({...o,amount_off:g.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:g=>c({...o,max_redemptions:g.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:g=>c({...o,starts_at:g.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:g=>c({...o,expires_at:g.target.value})})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Code is active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to stop new redemptions instantly."})]}),e.jsx(bn,{checked:o.is_active,onCheckedChange:g=>c({...o,is_active:g})})]}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 text-sm",children:[e.jsx("p",{className:"font-medium",children:"Enrollee sees"}),e.jsxs("p",{className:"mt-1 text-muted-foreground",children:[Eu(s.price_cents,s.currency)," →"," ",e.jsx("span",{className:"font-semibold text-foreground",children:Eu(h.final,s.currency)})," ","(",Eu(h.discount,s.currency)," off) — charged one time."]})]})]}),e.jsx(Xn,{children:e.jsxs(B,{onClick:p,disabled:r.isPending,children:[r.isPending&&e.jsx(ts,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save changes":"Create code"]})})]})]})]})}),n?e.jsx(Ws,{className:"h-40 w-full rounded-xl"}):t.length===0?e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(uh,{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(fe,{children:e.jsx(Ee,{className:"overflow-x-auto p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Code"}),e.jsx(Ct,{children:"Discount"}),e.jsx(Ct,{children:"Price after"}),e.jsx(Ct,{children:"Used"}),e.jsx(Ct,{children:"Window"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:t.map(g=>{const _=f(g);return e.jsxs(Hs,{children:[e.jsxs(ut,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono font-semibold",children:g.code}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{navigator.clipboard.writeText(g.code),ae.success("Code copied")},children:e.jsx(Xr,{className:"h-3.5 w-3.5"})})]}),g.label&&e.jsx("p",{className:"text-xs text-muted-foreground",children:g.label})]}),e.jsx(ut,{className:"whitespace-nowrap",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(a4,{className:"h-3.5 w-3.5 text-muted-foreground"}),_.off]})}),e.jsx(ut,{className:"font-medium",children:_.final}),e.jsxs(ut,{children:[g.times_redeemed,g.max_redemptions?` / ${g.max_redemptions}`:""]}),e.jsxs(ut,{className:"text-xs text-muted-foreground",children:[g.starts_at?`From ${ql(g.starts_at)}`:"Anytime",g.expires_at?` · until ${ql(g.expires_at)}`:""]}),e.jsx(ut,{children:e.jsx(ze,{variant:g.is_active?"default":"secondary",children:g.is_active?"Active":"Paused"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>u(g),children:"Edit"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm(`Delete ${g.code}?`)&&a.mutate(g.id)},children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},g.id)})})]})})})]})},T_=({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(xr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}):e.jsx($l,{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})]})]}),Wps=({program:s})=>{var c,d;const{data:t,isLoading:n}=ct({queryKey:["admin-program-content-counts",s.id],queryFn:async()=>{const[u,h,p,f,g]=await Promise.all([q.from("program_weeks").select("id, week_number, title").eq("program_id",s.id),q.from("program_lessons").select("id, title").eq("program_id",s.id),q.from("program_resources").select("id, title").eq("program_id",s.id),q.from("program_events").select("id, title, starts_at").eq("program_id",s.id),q.from("program_announcements").select("id, title").eq("program_id",s.id)]);return{weeks:u.data||[],lessons:h.data||[],resources:p.data||[],events:f.data||[],announcements:g.data||[]}}}),{notOpenYet:r,closed:a,opensLabel:i}=ove(s),l=`/programs/${s.slug}`,o=[{icon:un,title:"1 · Sales page",body:`${s.name} — hero image, ${s.subtitle?"subtitle":"no subtitle"}, description, price, dates, seats left and FAQ.`,href:l,cta:"Preview sales page"},{icon:j9,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:pf,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 ${Eu(s.price_cents,s.currency)} charge runs on ${ql(s.charge_at||s.kickoff_at)||"the charge date (not set)"}.`:`Stripe charges ${Eu(s.price_cents,s.currency)} once at checkout.`},{icon:Vs,title:"4 · Emails",body:"Confirmation right after enrollment, then payment receipt (or a payment-failed action email) when the one-time charge runs."},{icon:mL,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(fe,{children:e.jsxs(Ee,{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(fe,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(Ee,{className:"flex items-start gap-3 p-5 text-sm",children:[e.jsx($l,{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(fe,{children:e.jsxs(Ee,{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(fe,{children:e.jsxs(Ee,{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(Ws,{className:"mt-4 h-64 w-full rounded-lg"}):e.jsxs("div",{className:"mt-2",children:[e.jsx(T_,{ok:!!s.cover_image_url,label:"Cover image",detail:s.cover_image_url?"Set":"Missing — cards look empty on the Programs page"}),e.jsx(T_,{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(T_,{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(T_,{ok:s.payment_mode==="free"||s.price_cents>0,label:"One-time price",detail:s.payment_mode==="free"?"Free / included":Eu(s.price_cents,s.currency)}),e.jsx(T_,{ok:!!s.kickoff_at&&(s.payment_mode==="free"||!!s.charge_at),label:"Kickoff and charge dates",detail:`Kickoff ${ql(s.kickoff_at)||"not set"} · charge ${ql(s.charge_at)||"not set"}`}),e.jsx(T_,{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(T_,{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(T_,{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(T_,{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 ${ql(t.events[0].starts_at)}`:""}`}),e.jsx(T_,{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(fe,{children:e.jsx(Ee,{className:"grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-5",children:[{icon:Tl,label:"Weeks",value:t.weeks.length},{icon:Nr,label:"Lessons",value:t.lessons.length},{icon:Nr,label:"Resources",value:t.resources.length},{icon:Tl,label:"Events",value:t.events.length},{icon:$d,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(ze,{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."})]})},Kps=["Step 1 · Your business","Step 2 · Your content","Step 3 · Your goals"],Yps={short_text:"Short answer",long_text:"Paragraph",select:"Dropdown",checkbox:"Yes / no checkbox"},Zps=({program:s,onSaved:t})=>{const[n,r]=N.useState(()=>wxe(s)),[a,i]=N.useState(!1),[l,o]=N.useState(!1);N.useEffect(()=>{r(wxe(s)),i(!1)},[s.id,s.updated_at]);const c=v=>{r(j=>({...j,...v})),i(!0)},d=(v,j)=>{const b=j?n.hidden.filter(A=>A!==v):[...new Set([...n.hidden,v])],S=j?n.required:n.required.filter(A=>A!==v);c({hidden:b,required:S})},u=(v,j)=>{c({required:j?[...new Set([...n.required,v])]:n.required.filter(b=>b!==v)})},h=()=>{const v={id:`q_${Date.now().toString(36)}`,label:"",type:"short_text",required:!1,options:[]};c({custom:[...n.custom,v]})},p=(v,j)=>c({custom:n.custom.map(b=>b.id===v?{...b,...j}:b)}),f=v=>c({custom:n.custom.filter(j=>j.id!==v)}),g=(v,j)=>{const b=[...n.custom],S=v+j;S<0||S>=b.length||([b[v],b[S]]=[b[S],b[v]],c({custom:b}))},_=async()=>{if(n.custom.find(S=>!S.label.trim()))return ae.error("Every custom question needs a label");o(!0);const j={...s.sales_copy||{},intake:n},{error:b}=await q.from("programs").update({sales_copy:j}).eq("id",s.id);if(o(!1),b)return ae.error(b.message);i(!1),ae.success("Intake form saved"),t==null||t()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Intake form"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Controls the questions each agent answers during enrollment."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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:_,disabled:!a||l,children:[e.jsx(qo,{className:"mr-1.5 h-3.5 w-3.5"}),l?"Saving…":"Save intake form"]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsx(It,{className:"text-sm",children:"Intro message"})}),e.jsx(Ee,{children:e.jsx(Es,{rows:3,placeholder:"Shown at the top of the intake — e.g. “Answer a few questions so we can personalize your 90 days.”",value:n.intro||"",onChange:v=>c({intro:v.target.value})})})]}),[0,1,2].map(v=>e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsx(It,{className:"text-sm",children:Kps[v]})}),e.jsxs(Ee,{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"})]}),Gxt.filter(j=>j.step===v).map(j=>{const b=!n.hidden.includes(j.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:j.label}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(bn,{checked:b,onCheckedChange:S=>d(j.key,S),"aria-label":`Show ${j.label}`})}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(bn,{checked:n.required.includes(j.key),disabled:!b,onCheckedChange:S=>u(j.key,S),"aria-label":`Require ${j.label}`})})]},j.key)})]})]},v)),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(It,{className:"text-sm",children:["Custom questions"," ",e.jsx(ze,{variant:"secondary",className:"ml-1",children:n.custom.length})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:h,children:[e.jsx(Is,{className:"mr-1.5 h-3.5 w-3.5"})," Add question"]})]}),e.jsxs(Ee,{className:"space-y-3",children:[n.custom.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No custom questions yet. Add program-specific questions here — answers appear on each agent's dashboard."}),n.custom.map((v,j)=>e.jsxs("div",{className:"space-y-3 rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"flex flex-col pt-1.5",children:e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>g(j,-1),"aria-label":"Move up",children:e.jsx(Fu,{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:v.label,placeholder:"What is your biggest content roadblock?",onChange:b=>p(v.id,{label:b.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Answer type"}),e.jsxs(ds,{value:v.type,onValueChange:b=>p(v.id,{type:b}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:Object.entries(Yps).map(([b,S])=>e.jsx(Qe,{value:b,children:S},b))})]})]})]}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>f(v.id),"aria-label":"Delete question",children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]}),v.type==="select"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Options (one per line)"}),e.jsx(Es,{rows:3,value:(v.options||[]).join(` `),onChange:b=>p(v.id,{options:b.target.value.split(` `).map(S=>S.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:v.help||"",onChange:b=>p(v.id,{help:b.target.value})})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(bn,{checked:!!v.required,onCheckedChange:b=>p(v.id,{required:b}),"aria-label":"Required"}),e.jsx("span",{className:"text-sm",children:"Required"})]})]})]},v.id))]})]})]})},Qps=[{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"}],Xps=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},FVe={title:"",description:"",event_kind:"mastermind",starts_at:"",duration_minutes:60,speaker:"",meeting_link:"",replay_url:"",is_published:!0},Jps=({programId:s})=>{const{data:t=[],isLoading:n}=lps(s),r=cps(s),a=dps(),[i,l]=N.useState(!1),[o,c]=N.useState({...FVe}),d=()=>{c({...FVe}),l(!0)},u=v=>{c({id:v.id,title:v.title,description:v.description||"",event_kind:v.event_kind,starts_at:Xps(v.starts_at),duration_minutes:v.duration_minutes,speaker:v.speaker||"",meeting_link:v.meeting_link||"",replay_url:v.replay_url||"",is_published:v.is_published}),l(!0)},h=async()=>{if(!o.title.trim())return ae.error("Give the session a title");if(!o.starts_at)return ae.error("Pick a date and time");await r.mutateAsync({...o,starts_at:new Date(o.starts_at).toISOString(),duration_minutes:Number(o.duration_minutes)||60}),l(!1)},p=Date.now(),f=t.filter(v=>new Date(v.starts_at).getTime()>=p),g=t.filter(v=>new Date(v.starts_at).getTime()e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ee,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:v.title}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:v.event_kind.replace("_"," ")}),!v.is_published&&e.jsx(ze,{variant:"outline",children:"Hidden"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[ql(v.starts_at,!0)," · ",v.duration_minutes," min",v.speaker?` · ${v.speaker}`:""]}),v.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:v.description}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[v.meeting_link?e.jsxs(e.Fragment,{children:[e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:v.meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(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(v.meeting_link),ae.success("Join link copied")},children:[e.jsx(Xr,{className:"h-3 w-3"})," Copy"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"No meeting link yet"}),v.replay_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:v.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(br,{className:"h-3 w-3"})," Replay"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>u(v),children:e.jsx(_a,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{confirm(`Remove "${v.title}"?`)&&a.mutate(v.id)},children:e.jsx(_n,{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(Is,{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(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(om,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No live sessions scheduled"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Paste your recurring Zoom link once for each call — kickoff, weekly masterminds, workshops and office hours."})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Upcoming (",f.length,")"]}),f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing upcoming."}):f.map(v=>e.jsx(_,{e:v},v.id))]}),g.length>0&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Past (",g.length,") — add replay links so members can catch up"]}),g.map(v=>e.jsx(_,{e:v},v.id))]})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:o.id?"Edit session":"Add a live session"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{placeholder:"Week 1 Mastermind — Content that converts",value:o.title,onChange:v=>c({...o,title:v.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Type"}),e.jsxs(ds,{value:o.event_kind,onValueChange:v=>c({...o,event_kind:v}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:Qps.map(v=>e.jsx(Qe,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Host / speaker"}),e.jsx(ye,{value:o.speaker,onChange:v=>c({...o,speaker:v.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:v=>c({...o,starts_at:v.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:v=>c({...o,duration_minutes:v.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:v=>c({...o,meeting_link:v.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Members only see this after they're enrolled. A recurring Zoom link can be reused on every session."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Replay link (after the call)"}),e.jsx(ye,{placeholder:"YouTube, Vimeo, Loom or Zoom cloud recording URL",value:o.replay_url,onChange:v=>c({...o,replay_url:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"What we'll cover"}),e.jsx(Es,{rows:3,value:o.description,onChange:v=>c({...o,description:v.target.value})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Visible to members"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to draft a session privately."})]}),e.jsx(bn,{checked:o.is_published,onCheckedChange:v=>c({...o,is_published:v})})]})]}),e.jsx(Xn,{children:e.jsxs(B,{onClick:h,disabled:r.isPending,children:[r.isPending&&e.jsx(ts,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save session":"Add session"]})})]})})]})},zVe={title:"",summary:"",week_id:"none",duration_minutes:"",video_url:"",worksheet_url:"",action_assignment:"",status:"published",sort_order:0},efs=({programId:s})=>{const{data:t,isLoading:n}=ups(s),r=(t==null?void 0:t.lessons)||[],a=(t==null?void 0:t.weeks)||[],i=hps(s),l=mps(),[o,c]=N.useState(!1),[d,u]=N.useState({...zVe}),h=()=>{u({...zVe,sort_order:r.length}),c(!0)},p=v=>{u({id:v.id,title:v.title,summary:v.summary||"",week_id:v.week_id||"none",duration_minutes:v.duration_minutes??"",video_url:v.video_url||"",worksheet_url:v.worksheet_url||"",action_assignment:v.action_assignment||"",status:v.status,sort_order:v.sort_order}),c(!0)},f=async()=>{if(!d.title.trim())return ae.error("Give the video a title");await i.mutateAsync({...d,week_id:d.week_id==="none"?null:d.week_id,duration_minutes:d.duration_minutes===""?null:Number(d.duration_minutes),sort_order:Number(d.sort_order)||0}),c(!1)},g=v=>{const j=a.find(b=>b.id===v);return j?`Week ${j.week_number}`:"Unassigned"},_=Yxt(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(Is,{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(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Ah,{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(v=>e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ee,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:v.title}),e.jsx(ze,{variant:"secondary",children:g(v.week_id)}),v.status!=="published"&&e.jsx(ze,{variant:"outline",className:"capitalize",children:v.status}),v.duration_minutes?e.jsxs("span",{className:"text-xs text-muted-foreground",children:[v.duration_minutes," min"]}):null]}),v.summary&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:v.summary}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[v.video_url?e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:v.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"}),v.worksheet_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:v.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:()=>p(v),children:e.jsx(_a,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{confirm(`Remove "${v.title}"?`)&&l.mutate(v.id)},children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})},v.id))}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:d.id?"Edit video":"Add an on-demand video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{placeholder:"How to script a 30-second listing reel",value:d.title,onChange:v=>u({...d,title:v.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:v=>u({...d,video_url:v.target.value})}),d.video_url&&!_&&e.jsx("p",{className:"text-xs text-muted-foreground",children:`We can't embed this link — members will get an "Open video" button instead.`})]}),_&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:_,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(ds,{value:d.week_id,onValueChange:v=>u({...d,week_id:v}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"Unassigned (library)"}),a.map(v=>e.jsxs(Qe,{value:v.id,children:["Week ",v.week_number," — ",v.title]},v.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:v=>u({...d,duration_minutes:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Status"}),e.jsxs(ds,{value:d.status,onValueChange:v=>u({...d,status:v}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"published",children:"Published (visible)"}),e.jsx(Qe,{value:"draft",children:"Draft (hidden)"}),e.jsx(Qe,{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:v=>u({...d,sort_order:v.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Summary"}),e.jsx(Es,{rows:3,value:d.summary,onChange:v=>u({...d,summary:v.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:v=>u({...d,worksheet_url:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Action assignment"}),e.jsx(Es,{rows:2,placeholder:"Post one reel using this hook before your next mastermind.",value:d.action_assignment,onChange:v=>u({...d,action_assignment:v.target.value})})]})]}),e.jsx(Xn,{children:e.jsxs(B,{onClick:f,disabled:i.isPending,children:[i.isPending&&e.jsx(ts,{className:"mr-1.5 h-4 w-4 animate-spin"}),d.id?"Save video":"Add video"]})})]})})]})},BVe={title:"",description:"",category:"Resources",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},tfs=({programId:s})=>{const{data:t=[],isLoading:n}=fps(s),r=xps(s),a=gps(),[i,l]=N.useState(!1),[o,c]=N.useState({...BVe}),[d,u]=N.useState(!1),h=N.useRef(null),p=Array.from(new Set(t.map(j=>j.category))).filter(Boolean),f=()=>{c({...BVe,sort_order:t.length}),l(!0)},g=j=>{c({id:j.id,title:j.title,description:j.description||"",category:j.category||"Resources",resource_kind:j.resource_kind,url:j.url||"",file_path:j.file_path||"",status:j.status,sort_order:j.sort_order}),l(!0)},_=async j=>{if(!(!j||!s)){if(j.size>50*1024*1024)return ae.error("File must be under 50MB");u(!0);try{const b=j.name.split(".").pop()||"pdf",S=`programs/${s}/resources/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${b}`,{error:A}=await q.storage.from(fIe).upload(S,j,{contentType:j.type||"application/pdf",upsert:!1});if(A)throw A;c(T=>({...T,file_path:S,url:"",title:T.title||j.name.replace(/\.[^.]+$/,""),resource_kind:j.type==="application/pdf"?"pdf":T.resource_kind})),ae.success("File uploaded")}catch(b){ae.error(b.message||"Upload failed")}finally{u(!1),h.current&&(h.current.value="")}}},v=async()=>{if(!o.title.trim())return ae.error("Give the resource a title");if(!o.file_path&&!o.url.trim())return ae.error("Upload a file or paste a link");await r.mutateAsync({...o,sort_order:Number(o.sort_order)||0}),l(!1)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Resources"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload PDFs, worksheets and checklists — or link to Canva/Google templates. Enrollees see them grouped by category in their program dashboard."})]}),e.jsxs(B,{onClick:f,children:[e.jsx(Is,{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(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Nr,{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(j=>{const b=Zxt(j);return e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ee,{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:j.title}),e.jsx(ze,{variant:"secondary",children:j.category}),e.jsx(ze,{variant:"outline",className:"capitalize",children:j.resource_kind.replace("_"," ")}),j.status!=="published"&&e.jsx(ze,{variant:"outline",className:"capitalize",children:j.status})]}),j.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:j.description}),b&&e.jsxs("a",{href:b,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(tr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>g(j),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm(`Remove "${j.title}"?`)&&a.mutate(j)},children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})]})},j.id)})}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{children:e.jsx(_s,{children:o.id?"Edit resource":"Add resource"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:o.title,onChange:j=>c({...o,title:j.target.value}),placeholder:"90-Day Content Calendar"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description"}),e.jsx(Es,{rows:2,value:o.description,onChange:j=>c({...o,description:j.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:j=>c({...o,category:j.target.value}),placeholder:"Getting started",list:"program-resource-categories"}),e.jsx("datalist",{id:"program-resource-categories",children:p.map(j=>e.jsx("option",{value:j},j))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Type"}),e.jsxs(ds,{value:o.resource_kind,onValueChange:j=>c({...o,resource_kind:j}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:pps.map(j=>e.jsx(Qe,{value:j.value,children:j.label},j.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:j=>{var b;return _((b=j.target.files)==null?void 0:b[0])}}),o.file_path?e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsx("span",{className:"truncate",children:o.file_path.split("/").pop()}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c({...o,file_path:""}),children:"Remove"})]}):e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{var j;return(j=h.current)==null?void 0:j.click()},disabled:d,children:[d?e.jsx(ts,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Na,{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:j=>c({...o,url:j.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(ds,{value:o.status,onValueChange:j=>c({...o,status:j}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"published",children:"Published (visible)"}),e.jsx(Qe,{value:"draft",children:"Draft (hidden)"}),e.jsx(Qe,{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:j=>c({...o,sort_order:j.target.value})})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(B,{onClick:v,disabled:r.isPending||d,children:[r.isPending&&e.jsx(ts,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save resource"]})]})]})})]})},sfs=({programId:s})=>{const{data:t=[],isLoading:n}=bps(s),r=N.useMemo(()=>{const l=Date.now()-6048e5;return t.filter(o=>new Date(o.created_at).getTime()>=l).length},[t]),a=t.map(l=>l.email).filter(Boolean).join(", "),i=()=>{const l=`Name,Email,Phone,Brokerage,Joined `,o=t.map(u=>[u.full_name,u.email,u.phone,u.brokerage,u.created_at].map(h=>`"${(h??"").toString().replace(/"/g,'""')}"`).join(",")).join(` `),c=URL.createObjectURL(new Blob([l+o],{type:"text/csv"})),d=document.createElement("a");d.href=c,d.download="program-interest.csv",d.click(),URL.revokeObjectURL(c)};return n?e.jsx(Ws,{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(fe,{children:e.jsxs(Ee,{className:"flex items-center gap-3 p-4",children:[e.jsx(WS,{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(fe,{children:e.jsxs(Ee,{className:"flex items-center gap-3 p-4",children:[e.jsx(Nn,{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(fe,{children:e.jsx(Ee,{className:"flex items-center gap-3 p-4",children:e.jsxs(ze,{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),ae.success("Emails copied")},children:[e.jsx(Xr,{className:"mr-2 h-4 w-4"})," Copy emails"]}),e.jsxs(B,{variant:"outline",size:"sm",disabled:!t.length,onClick:i,children:[e.jsx(Pa,{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(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Member"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Phone"}),e.jsx(Ct,{children:"Brokerage"}),e.jsx(Ct,{children:"Joined"})]})}),e.jsx(ha,{children:t.map(l=>e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:l.full_name||"—"}),e.jsx(ut,{children:l.email||"—"}),e.jsx(ut,{children:l.phone||"—"}),e.jsx(ut,{children:l.brokerage||"—"}),e.jsx(ut,{className:"text-muted-foreground",children:ql(l.created_at)})]},l.id))})]})})]})},$Ve={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:""},nfs=()=>{const s=Ht(),[t,n]=N.useState(null),[r,a]=N.useState(!1),[i,l]=N.useState({...$Ve}),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState(null),{data:f=[],isLoading:g}=ct({queryKey:["admin-programs"],queryFn:async()=>{const{data:M,error:F}=await q.from("programs").select("*").order("created_at",{ascending:!1});if(F)throw F;return M||[]}}),_=f.find(M=>M.id===t)||f[0]||null,{data:v=[]}=ct({queryKey:["admin-program-enrollments",_==null?void 0:_.id],enabled:!!(_!=null&&_.id),queryFn:async()=>{const{data:M,error:F}=await q.from("program_enrollments").select("*").eq("program_id",_.id).order("created_at",{ascending:!1});if(F)throw F;const z=(M||[]).map(Y=>Y.user_id),{data:V}=z.length?await q.from("profiles").select("id, name, email").in("id",z):{data:[]},W=new Map((V||[]).map(Y=>[Y.id,Y]));return(M||[]).map(Y=>({...Y,profile:W.get(Y.user_id)}))}}),{data:j=[]}=ct({queryKey:["admin-program-intakes",_==null?void 0:_.id],enabled:!!(_!=null&&_.id),queryFn:async()=>{const{data:M,error:F}=await q.from("program_intake_responses").select("*").eq("program_id",_.id);if(F)throw F;return M||[]}}),{data:b=[]}=ct({queryKey:["admin-program-audit",_==null?void 0:_.id],enabled:!!(_!=null&&_.id),queryFn:async()=>{const{data:M,error:F}=await q.from("program_audit_logs").select("*").eq("program_id",_.id).order("created_at",{ascending:!1}).limit(100);if(F)throw F;return M||[]}}),S=async()=>{c(!0);try{const M={...i,slug:i.slug||i.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),kickoff_at:i.kickoff_at||null,charge_at:i.charge_at||null,enrollment_close_at:i.enrollment_close_at||null},{error:F}=await q.from("programs").insert(M);if(F)throw F;ae.success("Program created"),a(!1),l({...$Ve}),s.invalidateQueries({queryKey:["admin-programs"]})}catch(M){ae.error(M.message||"Could not create the program")}finally{c(!1)}},A=async M=>{if(!_)return;const{error:F}=await q.from("programs").update(M).eq("id",_.id);if(F)return ae.error(F.message);s.invalidateQueries({queryKey:["admin-programs"]})},T=async(M,F)=>{const{error:z}=await q.from("program_enrollments").update(F).eq("id",M);if(z)return ae.error(z.message);ae.success("Enrollment updated"),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},L=async M=>{u(!0);const{data:F,error:z}=await q.functions.invoke("program-charge-due",{body:M?{enrollment_id:M}:{}});if(u(!1),z||F!=null&&F.error)return ae.error((F==null?void 0:F.error)||(z==null?void 0:z.message));ae.success(`Processed ${(F==null?void 0:F.processed)??0} charge(s)`),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},D=M=>M==="paid"||M==="completed"?"default":M==="payment_failed"?"destructive":"secondary";return e.jsx(Ts,{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:()=>L(),disabled:d,children:[d?e.jsx(ts,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(pf,{className:"mr-1.5 h-4 w-4"}),"Run due charges"]}),e.jsxs(bs,{open:r,onOpenChange:a,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Is,{className:"mr-1.5 h-4 w-4"})," New program"]})}),e.jsxs(vs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Create a program"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Name"}),e.jsx(ye,{value:i.name,onChange:M=>l({...i,name:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Slug (URL)"}),e.jsx(ye,{placeholder:"reel-estate-90",value:i.slug,onChange:M=>l({...i,slug:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Subtitle"}),e.jsx(ye,{value:i.subtitle,onChange:M=>l({...i,subtitle:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Es,{rows:4,value:i.description,onChange:M=>l({...i,description:M.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"One-time price (USD)"}),e.jsx(ye,{type:"number",value:i.price_cents/100,onChange:M=>l({...i,price_cents:Math.round(Number(M.target.value)*100)})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Charged one time for the full program — never recurring."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Seats"}),e.jsx(ye,{type:"number",value:i.capacity,onChange:M=>l({...i,capacity:Number(M.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Weeks"}),e.jsx(ye,{type:"number",value:i.duration_weeks,onChange:M=>l({...i,duration_weeks:Number(M.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Videos per week"}),e.jsx(ye,{type:"number",value:i.weekly_video_goal,onChange:M=>l({...i,weekly_video_goal:Number(M.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Billing"}),e.jsxs(ds,{value:i.payment_mode,onValueChange:M=>l({...i,payment_mode:M}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"delayed",children:"Save card, charge later"}),e.jsx(Qe,{value:"immediate",children:"Charge at checkout"}),e.jsx(Qe,{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:M=>l({...i,kickoff_at:M.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:M=>l({...i,charge_at:M.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:M=>l({...i,enrollment_close_at:M.target.value})})]})]})]}),e.jsx(Xn,{children:e.jsxs(B,{onClick:S,disabled:o||!i.name,children:[o&&e.jsx(ts,{className:"mr-1.5 h-4 w-4 animate-spin"})," Create"]})})]})]})]})]}),g?e.jsx(Ws,{className:"h-40 w-full rounded-xl"}):f.length===0?e.jsx(fe,{className:"border-dashed",children:e.jsx(Ee,{className:"p-12 text-center text-sm text-muted-foreground",children:"No programs yet. Create your first cohort to get started."})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:f.map(M=>e.jsxs(B,{variant:(_==null?void 0:_.id)===M.id?"default":"outline",size:"sm",onClick:()=>n(M.id),children:[M.name,e.jsx(ze,{variant:"secondary",className:"ml-2 capitalize",children:M.status})]},M.id))}),_&&e.jsxs(Br,{defaultValue:"overview",children:[e.jsxs(Fr,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Kt,{value:"overview",children:"Overview"}),e.jsx(Kt,{value:"details",children:"Details & pricing"}),e.jsx(Kt,{value:"sessions",children:"Live sessions"}),e.jsx(Kt,{value:"videos",children:"On-demand videos"}),e.jsx(Kt,{value:"resources",children:"Resources"}),e.jsx(Kt,{value:"intake-form",children:"Intake form"}),e.jsx(Kt,{value:"discounts",children:"Discount codes"}),e.jsx(Kt,{value:"experience",children:"Enrollee experience"}),e.jsx(Kt,{value:"interest",children:"Interest list"}),e.jsxs(Kt,{value:"enrollments",children:["Enrollments (",v.length,")"]}),e.jsxs(Kt,{value:"intake",children:["Intake (",j.length,")"]}),e.jsx(Kt,{value:"audit",children:"Audit"})]}),e.jsxs(is,{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(fe,{children:e.jsxs(Ee,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Seats filled"}),e.jsxs("p",{className:"mt-1 text-2xl font-bold",children:[v.filter(M=>["reserved","scheduled_for_charge","paid","completed"].includes(M.status)).length,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",_.capacity]})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Paid"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:v.filter(M=>M.status==="paid").length})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Failed payments"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:v.filter(M=>M.status==="payment_failed").length})]})}),e.jsx(fe,{children:e.jsxs(Ee,{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:Eu(v.filter(M=>["scheduled_for_charge","paid","completed"].includes(M.status)).reduce((M,F)=>M+(F.amount_cents||0),0),_.currency)})]})})]}),e.jsx(fe,{children:e.jsxs(Ee,{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(bn,{checked:_.status==="published",onCheckedChange:M=>A({status:M?"published":"draft"})})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 border-t border-border/60 pt-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Feature it"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pins the program to the top."})]}),e.jsx(bn,{checked:_.is_featured,onCheckedChange:M=>A({is_featured:M})})]}),e.jsxs("div",{className:"grid gap-4 border-t border-border/60 pt-5 sm:grid-cols-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"One-time price"}),e.jsx("p",{className:"font-medium",children:Eu(_.price_cents,_.currency)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Kickoff"}),e.jsx("p",{className:"font-medium",children:ql(_.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:ql(_.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(is,{value:"details",className:"mt-6",children:e.jsx(Vps,{program:_,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(is,{value:"sessions",className:"mt-6",children:e.jsx(Jps,{programId:_.id})}),e.jsx(is,{value:"videos",className:"mt-6",children:e.jsx(efs,{programId:_.id})}),e.jsx(is,{value:"resources",className:"mt-6",children:e.jsx(tfs,{programId:_.id})}),e.jsx(is,{value:"discounts",className:"mt-6",children:e.jsx(Gps,{program:_})}),e.jsx(is,{value:"intake-form",className:"mt-6",children:e.jsx(Zps,{program:_,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(is,{value:"experience",className:"mt-6",children:e.jsx(Wps,{program:_})}),e.jsx(is,{value:"interest",className:"mt-6",children:e.jsx(sfs,{programId:_.id})}),e.jsx(is,{value:"enrollments",className:"mt-6",children:e.jsx(fe,{children:e.jsx(Ee,{className:"overflow-x-auto p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Member"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Charge date"}),e.jsx(Ct,{children:"Amount"}),e.jsx(Ct,{children:"Access"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsxs(ha,{children:[v.length===0&&e.jsx(Hs,{children:e.jsxs(ut,{colSpan:6,className:"py-10 text-center text-sm text-muted-foreground",children:[e.jsx(Nn,{className:"mx-auto mb-2 h-5 w-5"}),"No enrollments yet"]})}),v.map(M=>{var F,z;return e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsxs("button",{type:"button",className:"text-left hover:underline",onClick:()=>p(M),children:[e.jsx("p",{className:"font-medium",children:((F=M.profile)==null?void 0:F.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(z=M.profile)==null?void 0:z.email})]})}),e.jsxs(ut,{children:[e.jsx(ze,{variant:D(M.status),className:"capitalize",children:String(M.status).replace(/_/g," ")}),M.last_payment_error&&e.jsx("p",{className:"mt-1 max-w-[200px] truncate text-xs text-destructive",children:M.last_payment_error})]}),e.jsx(ut,{className:"text-sm",children:ql(M.charge_scheduled_at)||"—"}),e.jsx(ut,{className:"text-sm",children:Eu(M.amount_cents,M.currency)}),e.jsx(ut,{children:e.jsx(bn,{checked:M.access_override,onCheckedChange:V=>T(M.id,{access_override:V})})}),e.jsxs(ut,{className:"space-x-2 text-right",children:[["scheduled_for_charge","payment_failed"].includes(M.status)&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>L(M.id),disabled:d,children:[e.jsx(Ti,{className:"mr-1.5 h-3.5 w-3.5"})," Charge now"]}),!["canceled","refunded"].includes(M.status)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>T(M.id,{status:"canceled",canceled_at:new Date().toISOString()}),children:"Cancel"})]})]},M.id)})]})]})})})}),e.jsxs(is,{value:"intake",className:"mt-6 space-y-3",children:[j.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No intake responses yet."}),j.map(M=>e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-2 p-5 text-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-semibold",children:M.full_name||M.email||"Member"}),M.instagram_handle&&e.jsx(ze,{variant:"outline",children:M.instagram_handle}),M.city&&e.jsx("span",{className:"text-xs text-muted-foreground",children:M.city})]}),M.primary_goal&&e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Goal: "}),M.primary_goal]}),e.jsxs("div",{className:"flex flex-wrap gap-x-5 gap-y-1 text-xs text-muted-foreground",children:[M.years_experience&&e.jsxs("span",{children:["Experience: ",M.years_experience]}),M.video_comfort&&e.jsxs("span",{children:["On camera: ",M.video_comfort]}),M.posting_frequency&&e.jsxs("span",{children:["Posts: ",M.posting_frequency]})]})]})},M.id))]}),e.jsx(is,{value:"audit",className:"mt-6",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-2 p-5 text-sm",children:[b.length===0&&e.jsx("p",{className:"text-muted-foreground",children:"No activity yet."}),b.map(M=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 py-2 last:border-0",children:[e.jsx(ze,{variant:"outline",className:"capitalize",children:String(M.action).replace(/_/g," ")}),e.jsx("span",{className:"text-muted-foreground",children:M.actor_label||"system"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:ql(M.created_at,!0)})]},M.id))]})})})]}),_&&e.jsx(Hps,{program:_,enrollment:h,open:!!h,onOpenChange:M=>!M&&p(null),onUpdated:()=>s.invalidateQueries({queryKey:["admin-program-enrollments"]})})]})]})})},rfs=()=>{const{user:s}=ys(),[t,n]=N.useState(""),[r,a]=N.useState("all"),{data:i=[]}=ct({queryKey:["academy-categories"],queryFn:async()=>{const{data:p,error:f}=await q.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(f)throw f;return p}}),{data:l=[],isLoading:o}=ct({queryKey:["academy-videos"],queryFn:async()=>{const{data:p,error:f}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("is_published",!0).order("publish_date",{ascending:!1});if(f)throw f;const{data:g,error:_}=await q.from("academy_resources").select("*").order("sort_order");if(_)throw _;return p.map(j=>({...j,resources:(g==null?void 0:g.filter(b=>b.video_id===j.id))||[]}))}}),{data:c=[]}=ct({queryKey:["academy-video-likes"],queryFn:async()=>{const{data:p,error:f}=await q.from("academy_video_likes").select("video_id, user_id");if(f)throw f;return p}}),d=l.filter(p=>{var _;const f=t===""||p.title.toLowerCase().includes(t.toLowerCase())||((_=p.description)==null?void 0:_.toLowerCase().includes(t.toLowerCase())),g=r==="all"||p.category_id===r;return f&&g}),u=p=>c.filter(f=>f.video_id===p).length,h=p=>c.some(f=>f.video_id===p&&f.user_id===(s==null?void 0:s.id));return e.jsx(Ts,{title:"Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Academy"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"On-demand training videos and resources"})]}),e.jsx("div",{className:"flex flex-col sm:flex-row gap-4",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search videos...",value:t,onChange:p=>n(p.target.value),className:"pl-10"})]})}),e.jsx(Br,{value:r,onValueChange:a,children:e.jsxs(Fr,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[e.jsx(Kt,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),i.map(p=>e.jsx(Kt,{value:p.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:p.name},p.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(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(br,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",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(p=>e.jsx(Ln,{to:`/academy/${p.id}`,children:e.jsxs(fe,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow group h-full",children:[e.jsxs("div",{className:"relative aspect-video bg-muted",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 flex items-center justify-center",children:e.jsx(br,{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(Al,{className:"h-8 w-8 text-primary-foreground ml-1"})})}),p.duration&&e.jsxs("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-2 py-1 rounded flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),p.duration]})]}),e.jsxs(Mt,{className:"pb-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsx(It,{className:"text-lg line-clamp-2",children:p.title})}),p.category&&e.jsx(ze,{variant:"secondary",className:"w-fit",children:p.category.name})]}),e.jsxs(Ee,{className:"pt-0",children:[p.description&&e.jsx(Vn,{className:"line-clamp-2",children:p.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(Vm,{className:`h-4 w-4 ${h(p.id)?"fill-primary text-primary":""}`}),u(p.id)]}),p.resources&&p.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nr,{className:"h-4 w-4"}),p.resources.length]})]})]})]})},p.id))})]})})};function dgt({resourceType:s,resourceId:t}){const{data:n=[]}=ct({queryKey:["linked-templates",s,t],queryFn:async()=>{if(s==="academy_video"){const{data:r,error:a}=await q.from("academy_video_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("video_id",t);if(a)throw a;return(r||[]).map(i=>i.canva_templates).filter(Boolean)}else{const{data:r,error:a}=await q.from("resource_kit_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("kit_id",t);if(a)throw a;return(r||[]).map(i=>i.canva_templates).filter(Boolean)}},enabled:!!t});return n.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-sm",children:[e.jsx(fl,{className:"h-4 w-4"}),"Related Templates"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(r=>e.jsx(Ln,{to:`/templates/${r.id}`,children:e.jsxs(ze,{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(fl,{className:"h-3 w-3"}),r.name]})},r.id))})]})}const afs=(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},ifs=()=>{const{videoId:s}=bi();Mn();const{user:t,isAdmin:n}=ys(),{toast:r}=Ba(),a=Ht(),{trackEngagement:i}=KD(),[l,o]=N.useState(""),{data:c,isLoading:d}=ct({queryKey:["academy-video",s],queryFn:async()=>{const{data:S,error:A}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("id",s).eq("is_published",!0).single();if(A)throw A;const{data:T}=await q.from("academy_resources").select("*").eq("video_id",s).order("sort_order");return{...S,resources:T||[]}},enabled:!!s});N.useEffect(()=>{c&&i("academy_video",c.id,c.title,"view")},[c==null?void 0:c.id]);const{data:u=[]}=ct({queryKey:["academy-video-likes",s],queryFn:async()=>{const{data:S,error:A}=await q.from("academy_video_likes").select("*").eq("video_id",s);if(A)throw A;return S},enabled:!!s}),{data:h=[]}=ct({queryKey:["academy-video-comments",s],queryFn:async()=>{const{data:S,error:A}=await q.from("academy_video_comments").select("*").eq("video_id",s).order("created_at",{ascending:!1});if(A)throw A;const T=[...new Set(S.map(M=>M.user_id))],{data:L}=await q.from("profiles").select("id, name").in("id",T),D=new Map((L==null?void 0:L.map(M=>[M.id,M.name]))||[]);return S.map(M=>({...M,user_name:D.get(M.user_id)||"Unknown User"}))},enabled:!!s}),p=gt({mutationFn:async S=>{const{error:A}=await q.from("academy_video_comments").insert({video_id:s,user_id:t.id,content:S});if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),o(""),r({title:"Comment added!"})},onError:S=>{r({title:"Error adding comment",description:S.message,variant:"destructive"})}}),f=gt({mutationFn:async S=>{const{error:A}=await q.from("academy_video_comments").delete().eq("id",S);if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),r({title:"Comment deleted"})}}),g=gt({mutationFn:async()=>{const S=u.find(A=>A.user_id===(t==null?void 0:t.id));if(S){const{error:A}=await q.from("academy_video_likes").delete().eq("id",S.id);if(A)throw A}else{const{error:A}=await q.from("academy_video_likes").insert({video_id:s,user_id:t.id});if(A)throw A}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-likes",s]})}}),_=u.some(S=>S.user_id===(t==null?void 0:t.id)),v=S=>{switch(S==null?void 0:S.toLowerCase()){case"pdf":return"📄";case"pptx":case"ppt":return"📊";case"xlsx":case"xls":return"📈";case"docx":case"doc":return"📝";case"zip":return"📦";default:return"📁"}},j=S=>S.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),b=S=>{S.preventDefault(),!(!l.trim()||!t)&&p.mutate(l.trim())};return d?e.jsx(Ts,{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(Ts,{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(Ln,{to:"/academy",children:[e.jsx(Hr,{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:afs(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(br,{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(ze,{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(Ln,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(_a,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(XD,{resourceType:"academy_video",resourceId:c.id,resourceTitle:c.title}),e.jsxs(B,{variant:_?"default":"outline",className:"gap-2 w-fit",onClick:()=>g.mutate(),disabled:!t||g.isPending,children:[e.jsx(Vm,{className:`h-4 w-4 ${_?"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(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Nr,{className:"h-4 w-4"}),"Resources"]}),e.jsx("div",{className:"grid gap-2",children:c.resources.map(S=>e.jsxs("a",{href:S.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-3 p-3 rounded-lg border hover:bg-muted transition-colors",children:[e.jsx("span",{className:"text-2xl",children:v(S.file_type)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:S.title}),e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:S.file_type})]}),e.jsx(Pa,{className:"h-4 w-4 text-muted-foreground"})]},S.id))})]})}),e.jsx(dgt,{resourceType:"academy_video",resourceId:c.id}),e.jsx(ll,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ql,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:b,className:"flex gap-2",children:[e.jsx(Es,{placeholder:"Add a comment...",value:l,onChange:S=>o(S.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()||p.isPending,children:e.jsx(cr,{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(fe,{children:e.jsx(Ee,{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(S=>e.jsx(fe,{children:e.jsx(Ee,{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(aa,{className:"text-sm",children:j(S.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:S.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Vo(new Date(S.created_at),{addSuffix:!0})}),S.user_id===(t==null?void 0:t.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>f.mutate(S.id),children:e.jsx(_n,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:S.content})]})]})})},S.id))})]})]})}):e.jsx(Ts,{title:"Academy",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(br,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",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(Ln,{to:"/academy",children:"Back to Academy"})})]})})},CI="https://dashboard.relevelup.com",ofs=(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},lfs=[{icon:Au,title:"100+ Training Videos",desc:"On-demand LevelUp Academy content covering lead gen, listings, buyer conversion, marketing, and more."},{icon:hh,title:"Marketing Studio & Tools",desc:"AI-powered marketing tools, listing videos, landing pages, and social content — done for you."},{icon:Nn,title:"Coaching & Community",desc:"Live coaching sessions, private community, and a network of top-performing agents."},{icon:vo,title:"Business Scorecard",desc:"Track your deals, GCI, and pipeline in one dashboard built for real estate."}];function cfs(){var i;const{slug:s}=bi(),{data:t,isLoading:n,error:r}=ct({queryKey:["public-academy-video",s],queryFn:async()=>{if(!s)return null;const{data:l,error:o}=await q.from("academy_videos").select("id, title, description, video_url, video_type, thumbnail_url, duration, category:academy_categories(name)").eq("public_slug",s).eq("is_public",!0).maybeSingle();if(o)throw o;return l},enabled:!!s});N.useEffect(()=>{if(t&&s){q.rpc("increment_academy_public_view",{_slug:s}),document.title=`${t.title} | LevelUp Academy`;const l=(t.description||"").replace(/<[^>]+>/g,"").slice(0,155),o=document.querySelector('meta[name="description"]');if(o&&o.setAttribute("content",l||"Free training preview from LevelUp Academy."),t.thumbnail_url){let c=document.querySelector('meta[property="og:image"]');c||(c=document.createElement("meta"),c.setAttribute("property","og:image"),document.head.appendChild(c)),c.setAttribute("content",t.thumbnail_url)}}},[t,s]);const a=N.useMemo(()=>t?ofs(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:CI,children:e.jsx(B,{className:"bg-[#406E71] hover:bg-[#4d8285] text-white",children:"Go to LevelUp"})})]}):e.jsxs("div",{className:"min-h-screen bg-[#0a1520] text-[#e8ecf1] overflow-x-hidden",children:[e.jsxs("div",{className:"pointer-events-none fixed inset-0 z-0",children:[e.jsx("div",{className:"absolute -top-40 -left-40 w-[600px] h-[600px] rounded-full bg-[#406E71]/20 blur-3xl"}),e.jsx("div",{className:"absolute top-1/2 -right-40 w-[500px] h-[500px] rounded-full bg-[#2a4c64]/30 blur-3xl"}),e.jsx("div",{className:"absolute bottom-0 left-1/3 w-[400px] h-[400px] rounded-full bg-[#406E71]/10 blur-3xl"})]}),e.jsx("header",{className:"relative z-10 border-b border-white/5 backdrop-blur-sm bg-[#0a1520]/70",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-5 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-gradient-to-br from-[#406E71] to-[#2a4c64] flex items-center justify-center",children:e.jsx(un,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-lg tracking-tight",children:"LevelUp"}),e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-[#5a9ea1] -mt-1",children:"Academy"})]})]}),e.jsx("a",{href:CI,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(ze,{className:"bg-[#406E71]/20 text-[#7ec0c3] border-[#406E71]/40 hover:bg-[#406E71]/30",children:[e.jsx(Au,{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(sx,{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:CI,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(Oa,{className:"w-4 h-4 ml-2"})]})}),e.jsx("a",{href:CI,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:lfs.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(xr,{className:"w-4 h-4 text-[#7ec0c3]"})," Trusted by top producers"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(xr,{className:"w-4 h-4 text-[#7ec0c3]"})," New training weekly"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(xr,{className:"w-4 h-4 text-[#7ec0c3]"})," Cancel anytime"]})]}),e.jsx("div",{className:"text-center",children:e.jsx("a",{href:CI,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(Oa,{className:"w-4 h-4 ml-2"})]})})})]})}),e.jsxs("footer",{className:"relative z-10 border-t border-white/5 py-6 text-center text-xs text-[#5a6a7a]",children:["© ",new Date().getFullYear()," LevelUp · ",e.jsx("a",{href:CI,className:"hover:text-[#7ec0c3]",children:"dashboard.relevelup.com"})]})]})}function dfs(){const s=Mn(),[t,n]=N.useState(""),{data:r,isLoading:a}=ct({queryKey:["resource-kits-published"],queryFn:async()=>{const{data:f,error:g}=await q.from("resource_kits").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(g)throw g;return f}}),{data:i}=ct({queryKey:["resource-kit-files-all"],queryFn:async()=>{const{data:f,error:g}=await q.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(g)throw g;return f}}),{data:l}=ct({queryKey:["resource-kit-likes-all"],queryFn:async()=>{const{data:f,error:g}=await q.from("resource_kit_likes").select("kit_id");if(g)throw g;return f}}),{data:o}=ct({queryKey:["resource-kit-comments-all"],queryFn:async()=>{const{data:f,error:g}=await q.from("resource_kit_comments").select("kit_id");if(g)throw g;return f}}),c=r==null?void 0:r.filter(f=>{var g;return f.name.toLowerCase().includes(t.toLowerCase())||((g=f.description)==null?void 0:g.toLowerCase().includes(t.toLowerCase()))}),d=f=>(i==null?void 0:i.filter(g=>g.kit_id===f))||[],u=f=>(l==null?void 0:l.filter(g=>g.kit_id===f).length)||0,h=f=>(o==null?void 0:o.filter(g=>g.kit_id===f).length)||0,p=f=>{s(`/toolbox/${f}`)};return e.jsx(Ts,{title:"Toolbox",description:"Download resource kits and tools to help grow your business",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Toolbox"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Download resource kits and tools to help grow your business"})]}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search resource kits...",value:t,onChange:f=>n(f.target.value),className:"pl-10"})]}),!a&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(c==null?void 0:c.length)||0," resource kit",(c==null?void 0:c.length)!==1?"s":""," available"]}),a?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(8)].map((f,g)=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx(Ws,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Ws,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ws,{className:"h-4 w-full mb-4"}),e.jsx(Ws,{className:"h-4 w-2/3"})]})},g))}):(c==null?void 0:c.length)===0?e.jsxs(fe,{className:"p-12 text-center",children:[e.jsx(Rc,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No resource kits found"}),e.jsx("p",{className:"text-muted-foreground",children:t?"Try adjusting your search terms":"Check back later for new resources"})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:c==null?void 0:c.map(f=>{const g=d(f.id).length,_=u(f.id),v=h(f.id);return e.jsxs(fe,{className:"group overflow-hidden cursor-pointer hover:shadow-lg transition-all duration-200",onClick:()=>p(f.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:f.featured_image_url?e.jsx("img",{src:f.featured_image_url,alt:f.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Rc,{className:"h-16 w-16 text-muted-foreground"})})}),e.jsxs(Ee,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:f.name}),f.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:Xz(f.description)}),e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nr,{className:"h-4 w-4"}),g," file",g!==1?"s":""]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vm,{className:"h-3.5 w-3.5"}),_]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"}),v]})]})]})]})]},f.id)})})]})})}const ufs=()=>{const{kitId:s}=bi(),{user:t,isAdmin:n}=ys(),{toast:r}=Ba(),a=Ht(),{trackEngagement:i}=KD(),[l,o]=N.useState(""),{data:c,isLoading:d}=ct({queryKey:["resource-kit-detail",s],queryFn:async()=>{const{data:S,error:A}=await q.from("resource_kits").select("*").eq("id",s).eq("is_published",!0).single();if(A)throw A;const{data:T}=await q.from("resource_kit_files").select("*").eq("kit_id",s).order("sort_order"),{data:L}=await q.from("resource_kit_links").select("*").eq("kit_id",s).order("sort_order");return{...S,files:T||[],links:L||[]}},enabled:!!s});N.useEffect(()=>{c&&i("toolbox",c.id,c.name,"view")},[c==null?void 0:c.id]);const{data:u=[]}=ct({queryKey:["resource-kit-likes",s],queryFn:async()=>{const{data:S,error:A}=await q.from("resource_kit_likes").select("*").eq("kit_id",s);if(A)throw A;return S},enabled:!!s}),{data:h=[]}=ct({queryKey:["resource-kit-comments",s],queryFn:async()=>{const{data:S,error:A}=await q.from("resource_kit_comments").select("*").eq("kit_id",s).order("created_at",{ascending:!1});if(A)throw A;const T=[...new Set(S.map(M=>M.user_id))],{data:L}=await q.from("profiles").select("id, name").in("id",T),D=new Map((L==null?void 0:L.map(M=>[M.id,M.name]))||[]);return S.map(M=>({...M,user_name:D.get(M.user_id)||"Unknown User"}))},enabled:!!s}),p=gt({mutationFn:async S=>{const{error:A}=await q.from("resource_kit_comments").insert({kit_id:s,user_id:t.id,content:S});if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),o(""),r({title:"Comment added!"})},onError:S=>{r({title:"Error adding comment",description:S.message,variant:"destructive"})}}),f=gt({mutationFn:async S=>{const{error:A}=await q.from("resource_kit_comments").delete().eq("id",S);if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),r({title:"Comment deleted"})}}),g=gt({mutationFn:async()=>{const S=u.find(A=>A.user_id===(t==null?void 0:t.id));if(S){const{error:A}=await q.from("resource_kit_likes").delete().eq("id",S.id);if(A)throw A}else{const{error:A}=await q.from("resource_kit_likes").insert({kit_id:s,user_id:t.id});if(A)throw A}},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-likes",s]})}}),_=u.some(S=>S.user_id===(t==null?void 0:t.id)),v=S=>S.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),j=S=>S?S<1024?S+" B":S<1024*1024?(S/1024).toFixed(1)+" KB":(S/(1024*1024)).toFixed(1)+" MB":"",b=S=>{S.preventDefault(),!(!l.trim()||!t)&&p.mutate(l.trim())};return d?e.jsx(Ts,{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(Ts,{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(Ln,{to:"/toolbox",children:[e.jsx(Hr,{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(Ln,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(_a,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(XD,{resourceType:"resource_kit",resourceId:c.id,resourceTitle:c.name,size:"default",className:"rounded-full"}),e.jsxs(B,{variant:_?"default":"outline",className:"gap-2 rounded-full",onClick:()=>g.mutate(),disabled:!t||g.isPending,children:[e.jsx(Vm,{className:`h-4 w-4 ${_?"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(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Nr,{className:"h-4 w-4"}),"Included Resources (",c.files.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.files.map(S=>e.jsxs("a",{href:S.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(Nr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:S.name}),S.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:j(S.file_size)})]})]}),e.jsx(Pa,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},S.id))})]})}),c.links&&c.links.length>0&&e.jsx(fe,{children:e.jsxs(Ee,{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(S=>e.jsxs("a",{href:S.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:S.title})]}),e.jsx("span",{className:"text-xs text-muted-foreground group-hover:text-primary transition-colors",children:"Open in Canva"})]},S.id))})]})}),e.jsx(dgt,{resourceType:"resource_kit",resourceId:c.id}),e.jsx(ll,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ql,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:b,className:"flex gap-2",children:[e.jsx(Es,{placeholder:"Add a comment...",value:l,onChange:S=>o(S.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()||p.isPending,children:e.jsx(cr,{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(fe,{children:e.jsx(Ee,{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(S=>e.jsx(fe,{children:e.jsx(Ee,{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(aa,{className:"text-sm",children:v(S.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:S.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Vo(new Date(S.created_at),{addSuffix:!0})}),S.user_id===(t==null?void 0:t.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>f.mutate(S.id),children:e.jsx(_n,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:S.content})]})]})})},S.id))})]})]})}):e.jsx(Ts,{title:"Toolbox",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Rc,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"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(Ln,{to:"/toolbox",children:"Back to Toolbox"})})]})})},hfs=()=>{const s=Mn(),[t,n]=N.useState(""),[r,a]=N.useState("grid"),{data:i=[],isLoading:l}=ct({queryKey:["social-swag"],queryFn:async()=>{const{data:d,error:u}=await q.from("social_swag").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(u)throw u;const{data:h,error:p}=await q.from("social_swag_links").select("*").order("sort_order");if(p)throw p;const{data:f}=await q.from("social_swag_likes").select("swag_id"),{data:g}=await q.from("social_swag_comments").select("swag_id"),_=new Map;f==null||f.forEach(b=>{_.set(b.swag_id,(_.get(b.swag_id)||0)+1)});const v=new Map;return g==null||g.forEach(b=>{v.set(b.swag_id,(v.get(b.swag_id)||0)+1)}),(d||[]).map(b=>({...b,links:(h||[]).filter(S=>S.swag_id===b.id)||[],likesCount:_.get(b.id)||0,commentsCount:v.get(b.id)||0}))}}),o=i.filter(d=>{var h;return d.title.toLowerCase().includes(t.toLowerCase())||((h=d.description)==null?void 0:h.toLowerCase().includes(t.toLowerCase()))}),c=d=>{s(`/social-swag/${d}`)};return e.jsx(Ts,{title:"Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Social Swag"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse our collection of social media content and graphics"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(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(yf,{className:"h-4 w-4"})}),e.jsx(B,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(Tp,{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(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx(Ws,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Ws,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ws,{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(fe,{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(ze,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[e.jsx(Jo,{className:"h-3 w-3"}),d.links.length]})})]}),e.jsxs(Ee,{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(Vm,{className:"h-3.5 w-3.5"}),d.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ql,{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 ao=function(){return ao=Object.assign||function(t){for(var n,r=1,a=arguments.length;r1&&(c||!d),h=t>1&&(d||!c),p=function(){r&&i(r)},f=function(){a&&i(a)};return e.jsx(Hfs,{displayMonth:s.displayMonth,hideNext:u,hidePrevious:h,nextMonth:a,previousMonth:r,onPreviousClick:p,onNextClick:f})}function Gfs(s){var t,n=kd(),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:mgt,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(UVe,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(UVe,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(qVe,{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(qVe,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function Wfs(s){var t=kd(),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 Kfs(s,t,n){for(var r=n?pN(new Date):Wm(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=Bl(r,i);a.push(l)}return a}function Yfs(){var s=kd(),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=Kfs(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 Zfs(){var s,t=kd(),n=t.classNames,r=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:Yfs;return e.jsx("thead",{style:r.head,className:n.head,children:e.jsx(i,{})})}function Qfs(s){var t=kd(),n=t.locale,r=t.formatters.formatDay;return e.jsx(e.Fragment,{children:r(s.date,{locale:n})})}var bIe=N.createContext(void 0);function Xfs(s){if(!vU(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx(bIe.Provider,{value:t,children:s.children})}return e.jsx(Jfs,{initialProps:s.initialProps,children:s.children})}function Jfs(s){var t=s.initialProps,n=s.children,r=t.selected,a=t.min,i=t.max,l=function(d,u,h){var p,f;(p=t.onDayClick)===null||p===void 0||p.call(t,d,u,h);var g=!!(u.selected&&a&&(r==null?void 0:r.length)===a);if(!g){var _=!!(!u.selected&&i&&(r==null?void 0:r.length)===i);if(!_){var v=r?ugt([],r):[];if(u.selected){var j=v.findIndex(function(b){return Vl(d,b)});v.splice(j,1)}else v.push(d);(f=t.onSelect)===null||f===void 0||f.call(t,v,d,u,h)}}},o={disabled:[]};r&&o.disabled.push(function(d){var u=i&&r.length>i-1,h=r.some(function(p){return Vl(p,d)});return!!(u&&!h)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(bIe.Provider,{value:c,children:n})}function _Ie(){var s=N.useContext(bIe);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function exs(s,t){var n=t||{},r=n.from,a=n.to;return r&&a?Vl(a,s)&&Vl(r,s)?void 0:Vl(a,s)?{from:a,to:void 0}:Vl(r,s)?void 0:Bv(r,s)?{from:s,to:a}:{from:r,to:s}:a?Bv(s,a)?{from:a,to:s}:{from:s,to:a}:r?wb(s,r)?{from:s,to:r}:{from:r,to:s}:{from:s,to:void 0}}var wIe=N.createContext(void 0);function txs(s){if(!bU(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(wIe.Provider,{value:t,children:s.children})}return e.jsx(sxs,{initialProps:s.initialProps,children:s.children})}function sxs(s){var t=s.initialProps,n=s.children,r=t.selected,a=r||{},i=a.from,l=a.to,o=t.min,c=t.max,d=function(f,g,_){var v,j;(v=t.onDayClick)===null||v===void 0||v.call(t,f,g,_);var b=exs(f,r);(j=t.onSelect)===null||j===void 0||j.call(t,b,f,g,_)},u={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(u.range_start=[i],l?(u.range_end=[l],Vl(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:G9(i,o-1),before:Bl(i,o-1)}),i&&l&&u.disabled.push({after:i,before:Bl(i,o-1)}),!i&&l&&u.disabled.push({after:G9(l,o-1),before:Bl(l,o-1)})),c){if(i&&!l&&(u.disabled.push({before:Bl(i,-c+1)}),u.disabled.push({after:Bl(i,c-1)})),i&&l){var h=Gx(l,i)+1,p=c-h;u.disabled.push({before:G9(i,p)}),u.disabled.push({after:Bl(l,p)})}!i&&l&&(u.disabled.push({before:Bl(l,-c+1)}),u.disabled.push({after:Bl(l,c-1)}))}return e.jsx(wIe.Provider,{value:{selected:r,onDayClick:d,modifiers:u},children:n})}function jIe(){var s=N.useContext(wIe);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function Jme(s){return Array.isArray(s)?ugt([],s):s!==void 0?[s]:[]}function nxs(s){var t={};return Object.entries(s).forEach(function(n){var r=n[0],a=n[1];t[r]=Jme(a)}),t}var Ab;(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"})(Ab||(Ab={}));var rxs=Ab.Selected,o2=Ab.Disabled,axs=Ab.Hidden,ixs=Ab.Today,_2e=Ab.RangeEnd,w2e=Ab.RangeMiddle,j2e=Ab.RangeStart,oxs=Ab.Outside;function lxs(s,t,n){var r,a=(r={},r[rxs]=Jme(s.selected),r[o2]=Jme(s.disabled),r[axs]=Jme(s.hidden),r[ixs]=[s.today],r[_2e]=[],r[w2e]=[],r[j2e]=[],r[oxs]=[],r);return s.fromDate&&a[o2].push({before:s.fromDate}),s.toDate&&a[o2].push({after:s.toDate}),vU(s)?a[o2]=a[o2].concat(t.modifiers[o2]):bU(s)&&(a[o2]=a[o2].concat(n.modifiers[o2]),a[j2e]=n.modifiers[j2e],a[w2e]=n.modifiers[w2e],a[_2e]=n.modifiers[_2e]),a}var xgt=N.createContext(void 0);function cxs(s){var t=kd(),n=_Ie(),r=jIe(),a=lxs(t,n,r),i=nxs(t.modifiers),l=ao(ao({},a),i);return e.jsx(xgt.Provider,{value:l,children:s.children})}function ggt(){var s=N.useContext(xgt);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function dxs(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function uxs(s){return!!(s&&typeof s=="object"&&"from"in s)}function hxs(s){return!!(s&&typeof s=="object"&&"after"in s)}function mxs(s){return!!(s&&typeof s=="object"&&"before"in s)}function pxs(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function fxs(s,t){var n,r=t.from,a=t.to;if(r&&a){var i=Gx(a,r)<0;i&&(n=[a,r],r=n[0],a=n[1]);var l=Gx(s,r)>=0&&Gx(a,s)>=0;return l}return a?Vl(a,s):r?Vl(r,s):!1}function xxs(s){return nMe(s)}function gxs(s){return Array.isArray(s)&&s.every(nMe)}function yxs(s,t){return t.some(function(n){if(typeof n=="boolean")return n;if(xxs(n))return Vl(s,n);if(gxs(n))return n.includes(s);if(uxs(n))return fxs(s,n);if(pxs(n))return n.dayOfWeek.includes(s.getDay());if(dxs(n)){var r=Gx(n.before,s),a=Gx(n.after,s),i=r>0,l=a<0,o=Bv(n.before,n.after);return o?l&&i:i||l}return hxs(n)?Gx(s,n.after)>0:mxs(n)?Gx(n.before,s)>0:typeof n=="function"?n(s):!1})}function NIe(s,t,n){var r=Object.keys(t).reduce(function(i,l){var o=t[l];return yxs(s,o)&&i.push(l),i},[]),a={};return r.forEach(function(i){return a[i]=!0}),n&&!sU(s,n)&&(a.outside=!0),a}function vxs(s,t){for(var n=Fd(s[0]),r=V0(s[s.length-1]),a,i,l=n;l<=r;){var o=NIe(l,t),c=!o.disabled&&!o.hidden;if(!c){l=Bl(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),a||(a=l),l=Bl(l,1)}return i||a}var bxs=365;function ygt(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,p={day:Bl,week:O2,month:Nf,year:LBt,startOfWeek:function(v){return a.ISOWeek?pN(v):Wm(v,{locale:h,weekStartsOn:c})},endOfWeek:function(v){return a.ISOWeek?Pct(v):w8(v,{locale:h,weekStartsOn:c})}},f=p[n](s,r==="after"?1:-1);r==="before"&&d?f=DBt([d,f]):r==="after"&&u&&(f=RBt([u,f]));var g=!0;if(i){var _=NIe(f,i);g=!_.disabled&&!_.hidden}return g?f:o.count>bxs?o.lastFocused:ygt(f,{moveBy:n,direction:r,context:a,modifiers:i,retry:ao(ao({},o),{count:o.count+1})})}var vgt=N.createContext(void 0);function _xs(s){var t=_U(),n=ggt(),r=N.useState(),a=r[0],i=r[1],l=N.useState(),o=l[0],c=l[1],d=vxs(t.displayMonths,n),u=a??(o&&t.isDateDisplayed(o))?o:d,h=function(){c(a),i(void 0)},p=function(v){i(v)},f=kd(),g=function(v,j){if(a){var b=ygt(a,{moveBy:v,direction:j,context:f,modifiers:n});Vl(a,b)||(t.goToDate(b,a),p(b))}},_={focusedDay:a,focusTarget:u,blur:h,focus:p,focusDayAfter:function(){return g("day","after")},focusDayBefore:function(){return g("day","before")},focusWeekAfter:function(){return g("week","after")},focusWeekBefore:function(){return g("week","before")},focusMonthBefore:function(){return g("month","before")},focusMonthAfter:function(){return g("month","after")},focusYearBefore:function(){return g("year","before")},focusYearAfter:function(){return g("year","after")},focusStartOfWeek:function(){return g("startOfWeek","before")},focusEndOfWeek:function(){return g("endOfWeek","after")}};return e.jsx(vgt.Provider,{value:_,children:s.children})}function kIe(){var s=N.useContext(vgt);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function wxs(s,t){var n=ggt(),r=NIe(s,n,t);return r}var SIe=N.createContext(void 0);function jxs(s){if(!mve(s.initialProps)){var t={selected:void 0};return e.jsx(SIe.Provider,{value:t,children:s.children})}return e.jsx(Nxs,{initialProps:s.initialProps,children:s.children})}function Nxs(s){var t=s.initialProps,n=s.children,r=function(i,l,o){var c,d,u;if((c=t.onDayClick)===null||c===void 0||c.call(t,i,l,o),l.selected&&!t.required){(d=t.onSelect)===null||d===void 0||d.call(t,void 0,i,l,o);return}(u=t.onSelect)===null||u===void 0||u.call(t,i,i,l,o)},a={selected:t.selected,onDayClick:r};return e.jsx(SIe.Provider,{value:a,children:n})}function bgt(){var s=N.useContext(SIe);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function kxs(s,t){var n=kd(),r=bgt(),a=_Ie(),i=jIe(),l=kIe(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,u=l.focusWeekBefore,h=l.blur,p=l.focus,f=l.focusMonthBefore,g=l.focusMonthAfter,_=l.focusYearBefore,v=l.focusYearAfter,j=l.focusStartOfWeek,b=l.focusEndOfWeek,S=function(ie){var he,ce,pe,le;mve(n)?(he=r.onDayClick)===null||he===void 0||he.call(r,s,t,ie):vU(n)?(ce=a.onDayClick)===null||ce===void 0||ce.call(a,s,t,ie):bU(n)?(pe=i.onDayClick)===null||pe===void 0||pe.call(i,s,t,ie):(le=n.onDayClick)===null||le===void 0||le.call(n,s,t,ie)},A=function(ie){var he;p(s),(he=n.onDayFocus)===null||he===void 0||he.call(n,s,t,ie)},T=function(ie){var he;h(),(he=n.onDayBlur)===null||he===void 0||he.call(n,s,t,ie)},L=function(ie){var he;(he=n.onDayMouseEnter)===null||he===void 0||he.call(n,s,t,ie)},D=function(ie){var he;(he=n.onDayMouseLeave)===null||he===void 0||he.call(n,s,t,ie)},M=function(ie){var he;(he=n.onDayPointerEnter)===null||he===void 0||he.call(n,s,t,ie)},F=function(ie){var he;(he=n.onDayPointerLeave)===null||he===void 0||he.call(n,s,t,ie)},z=function(ie){var he;(he=n.onDayTouchCancel)===null||he===void 0||he.call(n,s,t,ie)},V=function(ie){var he;(he=n.onDayTouchEnd)===null||he===void 0||he.call(n,s,t,ie)},W=function(ie){var he;(he=n.onDayTouchMove)===null||he===void 0||he.call(n,s,t,ie)},Y=function(ie){var he;(he=n.onDayTouchStart)===null||he===void 0||he.call(n,s,t,ie)},K=function(ie){var he;(he=n.onDayKeyUp)===null||he===void 0||he.call(n,s,t,ie)},J=function(ie){var he;switch(ie.key){case"ArrowLeft":ie.preventDefault(),ie.stopPropagation(),n.dir==="rtl"?o():c();break;case"ArrowRight":ie.preventDefault(),ie.stopPropagation(),n.dir==="rtl"?c():o();break;case"ArrowDown":ie.preventDefault(),ie.stopPropagation(),d();break;case"ArrowUp":ie.preventDefault(),ie.stopPropagation(),u();break;case"PageUp":ie.preventDefault(),ie.stopPropagation(),ie.shiftKey?_():f();break;case"PageDown":ie.preventDefault(),ie.stopPropagation(),ie.shiftKey?v():g();break;case"Home":ie.preventDefault(),ie.stopPropagation(),j();break;case"End":ie.preventDefault(),ie.stopPropagation(),b();break}(he=n.onDayKeyDown)===null||he===void 0||he.call(n,s,t,ie)},ne={onClick:S,onFocus:A,onBlur:T,onKeyDown:J,onKeyUp:K,onMouseEnter:L,onMouseLeave:D,onPointerEnter:M,onPointerLeave:F,onTouchCancel:z,onTouchEnd:V,onTouchMove:W,onTouchStart:Y};return ne}function Sxs(){var s=kd(),t=bgt(),n=_Ie(),r=jIe(),a=mve(s)?t.selected:vU(s)?n.selected:bU(s)?r.selected:void 0;return a}function Cxs(s){return Object.values(Ab).includes(s)}function Txs(s,t){var n=[s.classNames.day];return Object.keys(t).forEach(function(r){var a=s.modifiersClassNames[r];if(a)n.push(a);else if(Cxs(r)){var i=s.classNames["day_".concat(r)];i&&n.push(i)}}),n}function Exs(s,t){var n=ao({},s.styles.day);return Object.keys(t).forEach(function(r){var a;n=ao(ao({},n),(a=s.modifiersStyles)===null||a===void 0?void 0:a[r])}),n}function Axs(s,t,n){var r,a,i,l=kd(),o=kIe(),c=wxs(s,t),d=kxs(s,c),u=Sxs(),h=!!(l.onDayClick||l.mode!=="default");N.useEffect(function(){var L;c.outside||o.focusedDay&&h&&Vl(o.focusedDay,s)&&((L=n.current)===null||L===void 0||L.focus())},[o.focusedDay,s,n,h,c.outside]);var p=Txs(l,c).join(" "),f=Exs(l,c),g=!!(c.outside&&!l.showOutsideDays||c.hidden),_=(i=(a=l.components)===null||a===void 0?void 0:a.DayContent)!==null&&i!==void 0?i:Qfs,v=e.jsx(_,{date:s,displayMonth:t,activeModifiers:c}),j={style:f,className:p,children:v,role:"gridcell"},b=o.focusTarget&&Vl(o.focusTarget,s)&&!c.outside,S=o.focusedDay&&Vl(o.focusedDay,s),A=ao(ao(ao({},j),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=S||b?0:-1,r)),d),T={isButton:h,isHidden:g,activeModifiers:c,selectedDays:u,buttonProps:A,divProps:j};return T}function Mxs(s){var t=N.useRef(null),n=Axs(s.date,s.displayMonth,t);return n.isHidden?e.jsx("div",{role:"gridcell"}):n.isButton?e.jsx(Nxe,ao({name:"day",ref:t},n.buttonProps)):e.jsx("div",ao({},n.divProps))}function Ixs(s){var t=s.number,n=s.dates,r=kd(),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}),p=function(f){a(t,n,f)};return e.jsx(Nxe,{name:"week-number","aria-label":h,className:l.weeknumber,style:i.weeknumber,onClick:p,children:u})}function Pxs(s){var t,n,r=kd(),a=r.styles,i=r.classNames,l=r.showWeekNumber,o=r.components,c=(t=o==null?void 0:o.Day)!==null&&t!==void 0?t:Mxs,d=(n=o==null?void 0:o.WeekNumber)!==null&&n!==void 0?n:Ixs,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})},z$t(h))})]})}function VVe(s,t,n){for(var r=n!=null&&n.ISOWeek?Pct(t):w8(t,n),a=n!=null&&n.ISOWeek?pN(s):Wm(s,n),i=Gx(r,a),l=[],o=0;o<=i;o++)l.push(Bl(a,o));var c=l.reduce(function(d,u){var h=n!=null&&n.ISOWeek?rMe(u):iMe(u,n),p=d.find(function(f){return f.weekNumber===h});return p?(p.dates.push(u),d):(d.push({weekNumber:h,dates:[u]}),d)},[]);return c}function Lxs(s,t){var n=VVe(Fd(s),V0(s),t);if(t!=null&&t.useFixedWeeks){var r=$$t(s,t);if(r<6){var a=n[n.length-1],i=a.dates[a.dates.length-1],l=O2(i,6-r),o=VVe(O2(i,1),l,t);n.push.apply(n,o)}}return n}function Dxs(s){var t,n,r,a=kd(),i=a.locale,l=a.classNames,o=a.styles,c=a.hideHead,d=a.fixedWeeks,u=a.components,h=a.weekStartsOn,p=a.firstWeekContainsDate,f=a.ISOWeek,g=Lxs(s.displayMonth,{useFixedWeeks:!!d,ISOWeek:f,locale:i,weekStartsOn:h,firstWeekContainsDate:p}),_=(t=u==null?void 0:u.Head)!==null&&t!==void 0?t:Zfs,v=(n=u==null?void 0:u.Row)!==null&&n!==void 0?n:Pxs,j=(r=u==null?void 0:u.Footer)!==null&&r!==void 0?r:Wfs;return e.jsxs("table",{id:s.id,className:l.table,style:o.table,role:"grid","aria-labelledby":s["aria-labelledby"],children:[!c&&e.jsx(_,{}),e.jsx("tbody",{className:l.tbody,style:o.tbody,children:g.map(function(b){return e.jsx(v,{displayMonth:s.displayMonth,dates:b.dates,weekNumber:b.weekNumber},b.weekNumber)})}),e.jsx(j,{displayMonth:s.displayMonth})]})}function Rxs(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var Oxs=Rxs()?N.useLayoutEffect:N.useEffect,N2e=!1,Fxs=0;function HVe(){return"react-day-picker-".concat(++Fxs)}function zxs(s){var t,n=s??(N2e?HVe():null),r=N.useState(n),a=r[0],i=r[1];return Oxs(function(){a===null&&i(HVe())},[]),N.useEffect(function(){N2e===!1&&(N2e=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function Bxs(s){var t,n,r=kd(),a=r.dir,i=r.classNames,l=r.styles,o=r.components,c=_U().displayMonths,d=zxs(r.id?"".concat(r.id,"-").concat(s.displayIndex):void 0),u=r.id?"".concat(r.id,"-grid-").concat(s.displayIndex):void 0,h=[i.month],p=l.month,f=s.displayIndex===0,g=s.displayIndex===c.length-1,_=!f&&!g;a==="rtl"&&(t=[f,g],g=t[0],f=t[1]),f&&(h.push(i.caption_start),p=ao(ao({},p),l.caption_start)),g&&(h.push(i.caption_end),p=ao(ao({},p),l.caption_end)),_&&(h.push(i.caption_between),p=ao(ao({},p),l.caption_between));var v=(n=o==null?void 0:o.Caption)!==null&&n!==void 0?n:Gfs;return e.jsxs("div",{className:h.join(" "),style:p,children:[e.jsx(v,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(Dxs,{id:u,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function $xs(s){var t=kd(),n=t.classNames,r=t.styles;return e.jsx("div",{className:n.months,style:r.months,children:s.children})}function Uxs(s){var t,n,r=s.initialProps,a=kd(),i=kIe(),l=_U(),o=N.useState(!1),c=o[0],d=o[1];N.useEffect(function(){a.initialFocus&&i.focusTarget&&(c||(i.focus(i.focusTarget),d(!0)))},[a.initialFocus,c,i.focus,i.focusTarget,i]);var u=[a.classNames.root,a.className];a.numberOfMonths>1&&u.push(a.classNames.multiple_months),a.showWeekNumber&&u.push(a.classNames.with_weeknumber);var h=ao(ao({},a.styles.root),a.style),p=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,_){var v;return ao(ao({},g),(v={},v[_]=r[_],v))},{}),f=(n=(t=r.components)===null||t===void 0?void 0:t.Months)!==null&&n!==void 0?n:$xs;return e.jsx("div",ao({className:u.join(" "),style:h,dir:a.dir,id:a.id,nonce:r.nonce,title:r.title,lang:r.lang},p,{children:e.jsx(f,{children:l.displayMonths.map(function(g,_){return e.jsx(Bxs,{displayIndex:_,displayMonth:g},_)})})}))}function qxs(s){var t=s.children,n=mfs(s,["children"]);return e.jsx(Ifs,{initialProps:n,children:e.jsx(Ufs,{children:e.jsx(jxs,{initialProps:n,children:e.jsx(Xfs,{initialProps:n,children:e.jsx(txs,{initialProps:n,children:e.jsx(cxs,{children:e.jsx(_xs,{children:t})})})})})})})}function Vxs(s){return e.jsx(qxs,ao({},s,{children:e.jsx(Uxs,{initialProps:s})}))}function Kg({className:s,classNames:t,showOutsideDays:n=!0,...r}){return e.jsx(Vxs,{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(v8({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(v8({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(pl,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(xa,{className:"h-4 w-4"})},...r})}Kg.displayName="Calendar";var pve="Popover",[_gt,Hxn]=pu(pve,[Gw]),wU=Gw(),[Hxs,nC]=_gt(pve),wgt=s=>{const{__scopePopover:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=wU(t),c=N.useRef(null),[d,u]=N.useState(!1),[h,p]=hm({prop:r,defaultProp:a??!1,onChange:i,caller:pve});return e.jsx($$,{...o,children:e.jsx(Hxs,{scope:t,contentId:dm(),triggerRef:c,open:h,onOpenChange:p,onOpenToggle:N.useCallback(()=>p(f=>!f),[p]),hasCustomAnchor:d,onCustomAnchorAdd:N.useCallback(()=>u(!0),[]),onCustomAnchorRemove:N.useCallback(()=>u(!1),[]),modal:l,children:n})})};wgt.displayName=pve;var jgt="PopoverAnchor",Gxs=N.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=nC(jgt,n),i=wU(n),{onCustomAnchorAdd:l,onCustomAnchorRemove:o}=a;return N.useEffect(()=>(l(),()=>o()),[l,o]),e.jsx(PD,{...i,...r,ref:t})});Gxs.displayName=jgt;var Ngt="PopoverTrigger",kgt=N.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=nC(Ngt,n),i=wU(n),l=Si(t,a.triggerRef),o=e.jsx(Jr.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":Agt(a.open),...r,ref:l,onClick:_r(s.onClick,a.onOpenToggle)});return a.hasCustomAnchor?o:e.jsx(PD,{asChild:!0,...i,children:o})});kgt.displayName=Ngt;var CIe="PopoverPortal",[Wxs,Kxs]=_gt(CIe,{forceMount:void 0}),Sgt=s=>{const{__scopePopover:t,forceMount:n,children:r,container:a}=s,i=nC(CIe,t);return e.jsx(Wxs,{scope:t,forceMount:n,children:e.jsx(Rh,{present:n||i.open,children:e.jsx(ED,{asChild:!0,container:a,children:r})})})};Sgt.displayName=CIe;var P8="PopoverContent",Cgt=N.forwardRef((s,t)=>{const n=Kxs(P8,s.__scopePopover),{forceMount:r=n.forceMount,...a}=s,i=nC(P8,s.__scopePopover);return e.jsx(Rh,{present:r||i.open,children:i.modal?e.jsx(Zxs,{...a,ref:t}):e.jsx(Qxs,{...a,ref:t})})});Cgt.displayName=P8;var Yxs=S4("PopoverContent.RemoveScroll"),Zxs=N.forwardRef((s,t)=>{const n=nC(P8,s.__scopePopover),r=N.useRef(null),a=Si(t,r),i=N.useRef(!1);return N.useEffect(()=>{const l=r.current;if(l)return Y0e(l)},[]),e.jsx(K$,{as:Yxs,allowPinchZoom:!0,children:e.jsx(Tgt,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:_r(s.onCloseAutoFocus,l=>{var o;l.preventDefault(),i.current||(o=n.triggerRef.current)==null||o.focus()}),onPointerDownOutside:_r(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:_r(s.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})}),Qxs=N.forwardRef((s,t)=>{const n=nC(P8,s.__scopePopover),r=N.useRef(!1),a=N.useRef(!1);return e.jsx(Tgt,{...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()}})}),Tgt=N.forwardRef((s,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,disableOutsidePointerEvents:l,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onInteractOutside:u,...h}=s,p=nC(P8,n),f=wU(n);return G0e(),e.jsx(G$,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(H4,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:u,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>p.onOpenChange(!1),children:e.jsx(U$,{"data-state":Agt(p.open),role:"dialog",id:p.contentId,...f,...h,ref:t,style:{...h.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),Egt="PopoverClose",Xxs=N.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=nC(Egt,n);return e.jsx(Jr.button,{type:"button",...r,ref:t,onClick:_r(s.onClick,()=>a.onOpenChange(!1))})});Xxs.displayName=Egt;var Jxs="PopoverArrow",egs=N.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=wU(n);return e.jsx(q$,{...a,...r,ref:t})});egs.displayName=Jxs;function Agt(s){return s?"open":"closed"}var tgs=wgt,sgs=kgt,ngs=Sgt,Mgt=Cgt;const el=tgs,tl=sgs,Ho=N.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(ngs,{children:e.jsx(Mgt,{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})}));Ho.displayName=Mgt.displayName;const rgs=UM("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"}}),TIe=N.forwardRef(({className:s,variant:t,...n},r)=>e.jsx("div",{ref:r,role:"alert",className:Et(rgs({variant:t}),s),...n}));TIe.displayName="Alert";const ags=N.forwardRef(({className:s,...t},n)=>e.jsx("h5",{ref:n,className:Et("mb-1 font-medium leading-none tracking-tight",s),...t}));ags.displayName="AlertTitle";const EIe=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Et("text-sm [&_p]:leading-relaxed",s),...t}));EIe.displayName="AlertDescription";function igs({open:s,onOpenChange:t,imageUrl:n,imageId:r,defaultCaption:a="",swagItemId:i,reelId:l}){const o=Ht(),[c,d]=N.useState(a),[u,h]=N.useState([]),[p,f]=N.useState(null),[g,_]=N.useState("now"),[v,j]=N.useState(uBe(gBe(new Date),1)),[b,S]=N.useState("12"),[A,T]=N.useState("00"),[L,D]=N.useState("PM");N.useEffect(()=>{if(s){d(a),_("now"),h([]);const ge=uBe(gBe(new Date),1);j(ge);const Te=ge.getHours();S(String(Te>12?Te-12:Te===0?12:Te)),T("00"),D(Te>=12?"PM":"AM")}},[s,a]);const M=()=>{if(!v)return null;let ge=parseInt(b);const Te=parseInt(A);return L==="PM"&&ge!==12&&(ge+=12),L==="AM"&&ge===12&&(ge=0),K9(W9(v,ge),Te)},{data:F,isLoading:z}=ct({queryKey:["social-accounts-for-post"],queryFn:async()=>{const{data:{user:ge}}=await q.auth.getUser();if(!ge)return[];const{data:Te,error:Me}=await q.from("social_accounts").select("*").eq("user_id",ge.id).eq("is_active",!0).order("platform",{ascending:!0});if(Me)throw Me;return console.log("Fetched social accounts for posting:",Te),Te},enabled:s,staleTime:0}),V=gt({mutationFn:async({accountId:ge,platform:Te})=>{f(ge);const{data:Me,error:Ce}=await q.functions.invoke("social-post",{body:{platform:Te,accountId:ge,imageUrl:n,caption:c}});if(Ce)throw Ce;if(Me!=null&&Me.error)throw new Error(Me.error);return Me},onSuccess:ge=>{const Te=ge.platform==="facebook"?"Facebook":ge.platform==="instagram"?"Instagram":ge.platform==="linkedin"?"LinkedIn":"Google Business";ae.success(`Posted to ${Te}!`)},onError:ge=>{ae.error(`Failed to post: ${ge.message}`)},onSettled:()=>{f(null)}}),W=gt({mutationFn:async({accountId:ge,platform:Te,scheduledFor:Me})=>{const{data:{user:Ce}}=await q.auth.getUser();if(!Ce)throw new Error("Not authenticated");const{error:Ae}=await q.from("scheduled_posts").insert({user_id:Ce.id,social_account_id:ge,platform:Te,image_url:n,caption:c,swag_item_id:i||null,reel_id:l||null,scheduled_for:Me.toISOString(),status:"scheduled"});if(Ae)throw Ae;return{platform:Te}},onSuccess:ge=>{const Te=ge.platform==="facebook"?"Facebook":ge.platform==="instagram"?"Instagram":"LinkedIn";ae.success(`Post scheduled for ${Te}!`)},onError:ge=>{ae.error(`Failed to schedule: ${ge.message}`)}}),Y=async()=>{if(u.length===0){ae.error("Please select at least one account");return}if(g==="schedule"){const ge=M();if(!ge||ge<=new Date){ae.error("Please select a future date and time");return}for(const Te of u){const Me=F==null?void 0:F.find(Ce=>Ce.id===Te);Me&&await W.mutateAsync({accountId:Te,platform:Me.platform,scheduledFor:ge})}o.invalidateQueries({queryKey:["scheduled-posts"]}),ae.success(`${u.length} post(s) scheduled for ${Ss(ge,"PPp")}`)}else for(const ge of u){const Te=F==null?void 0:F.find(Me=>Me.id===ge);Te&&await V.mutateAsync({accountId:ge,platform:Te.platform})}o.invalidateQueries({queryKey:["scheduled-posts"]}),d(""),h([]),t(!1)},K=ge=>{h(Te=>Te.includes(ge)?Te.filter(Me=>Me!==ge):[...Te,ge])},J=(F==null?void 0:F.filter(ge=>ge.platform==="facebook"))||[],ne=(F==null?void 0:F.filter(ge=>ge.platform==="instagram"))||[],ie=(F==null?void 0:F.filter(ge=>ge.platform==="linkedin"))||[],he=(F==null?void 0:F.filter(ge=>ge.platform==="google_business"))||[],ce=((F==null?void 0:F.length)||0)>0,pe=V.isPending||W.isPending,le=Array.from({length:12},(ge,Te)=>String(Te+1)),ve=["00","15","30","45"];return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create Social Post"}),e.jsx(Qn,{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(Es,{id:"caption",placeholder:"Write a caption for your post...",value:c,onChange:ge=>d(ge.target.value),rows:3}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.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:()=>_("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:()=>_("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(gr,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(el,{children:[e.jsx(tl,{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(yr,{className:"mr-2 h-4 w-4"}),v?Ss(v,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Ho,{className:"w-auto p-0",align:"start",children:e.jsx(Kg,{mode:"single",selected:v,onSelect:j,disabled:ge=>gee.jsx(Qe,{value:ge,children:ge},ge))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(ds,{value:A,onValueChange:T,children:[e.jsx(ls,{className:"w-[70px]",children:e.jsx(us,{})}),e.jsx(cs,{children:ve.map(ge=>e.jsx(Qe,{value:ge,children:ge},ge))})]}),e.jsxs(ds,{value:L,onValueChange:ge=>D(ge),children:[e.jsx(ls,{className:"w-[70px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"AM",children:"AM"}),e.jsx(Qe,{value:"PM",children:"PM"})]})]})]})]}),v&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Post will be published on ",Ss(M()||new Date,"PPP 'at' p")]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Post to"}),z&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ts,{className:"h-6 w-6 animate-spin"})}),!z&&!ce&&e.jsxs(TIe,{children:[e.jsx(Gi,{className:"h-4 w-4"}),e.jsxs(EIe,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(Ln,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(Xo,{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(Lh,{className:"h-4 w-4 text-blue-600"})," Facebook"]}),J.map(ge=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(ui,{checked:u.includes(ge.id),onCheckedChange:()=>K(ge.id),disabled:p===ge.id}),e.jsxs(ra,{className:"h-8 w-8",children:[e.jsx(ni,{src:ge.profile_picture_url||""}),e.jsx(aa,{children:e.jsx(Lh,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ge.page_name||ge.platform_username}),p===ge.id&&e.jsx(ts,{className:"h-4 w-4 animate-spin"})]},ge.id))]}),ne.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(du,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),ne.map(ge=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(ui,{checked:u.includes(ge.id),onCheckedChange:()=>K(ge.id),disabled:p===ge.id}),e.jsxs(ra,{className:"h-8 w-8",children:[e.jsx(ni,{src:ge.profile_picture_url||""}),e.jsx(aa,{children:e.jsx(du,{className:"h-4 w-4"})})]}),e.jsxs("span",{className:"flex-1 text-sm font-medium",children:["@",ge.platform_username]}),p===ge.id&&e.jsx(ts,{className:"h-4 w-4 animate-spin"})]},ge.id))]}),ie.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(vf,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),ie.map(ge=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(ui,{checked:u.includes(ge.id),onCheckedChange:()=>K(ge.id),disabled:p===ge.id}),e.jsxs(ra,{className:"h-8 w-8",children:[e.jsx(ni,{src:ge.profile_picture_url||""}),e.jsx(aa,{children:e.jsx(vf,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ge.platform_username}),p===ge.id&&e.jsx(ts,{className:"h-4 w-4 animate-spin"})]},ge.id))]}),he.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(ka,{className:"h-4 w-4 text-red-600"})," Google Business"]}),he.map(ge=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(ui,{checked:u.includes(ge.id),onCheckedChange:()=>K(ge.id),disabled:p===ge.id}),e.jsxs(ra,{className:"h-8 w-8",children:[e.jsx(ni,{src:ge.profile_picture_url||""}),e.jsx(aa,{children:e.jsx(ka,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ge.page_name||ge.platform_username}),p===ge.id&&e.jsx(ts,{className:"h-4 w-4 animate-spin"})]},ge.id))]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:Y,disabled:u.length===0||pe,className:"gap-2",children:[pe?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):g==="schedule"?e.jsx(yr,{className:"h-4 w-4"}):e.jsx(cr,{className:"h-4 w-4"}),g==="schedule"?`Schedule ${u.length} post${u.length!==1?"s":""}`:`Post to ${u.length} account${u.length!==1?"s":""}`]})]})]})})}function ogs(){const s=Ht(),[t,n]=N.useState(void 0),[r,a]=N.useState("all"),[i,l]=N.useState(null),[o,c]=N.useState(""),[d,u]=N.useState(void 0),[h,p]=N.useState("12"),[f,g]=N.useState("00"),[_,v]=N.useState("PM"),{data:j=[],isLoading:b}=ct({queryKey:["scheduled-posts"],queryFn:async()=>{const{data:he,error:ce}=await q.from("scheduled_posts").select(` *, social_accounts ( page_name, platform_username, profile_picture_url ) `).order("scheduled_for",{ascending:!1});if(ce)throw ce;return he}}),S=j.filter(he=>{if(r!=="all"&&he.status!==r)return!1;if(t&&he.scheduled_for){const ce=new Date(he.scheduled_for);if(!Vl(ce,t))return!1}return!0}),A=j.filter(he=>he.scheduled_for).map(he=>kf(new Date(he.scheduled_for))),T=gt({mutationFn:async he=>{const{error:ce}=await q.from("scheduled_posts").update({caption:he.caption,scheduled_for:he.scheduled_for}).eq("id",he.id);if(ce)throw ce},onSuccess:()=>{ae.success("Post updated!"),s.invalidateQueries({queryKey:["scheduled-posts"]}),l(null)},onError:he=>{ae.error(`Failed to update: ${he.message}`)}}),L=gt({mutationFn:async he=>{const{error:ce}=await q.from("scheduled_posts").update({status:"cancelled"}).eq("id",he);if(ce)throw ce},onSuccess:()=>{ae.success("Post cancelled"),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:he=>{ae.error(`Failed to cancel: ${he.message}`)}}),D=gt({mutationFn:async he=>{const{error:ce}=await q.from("scheduled_posts").delete().eq("id",he);if(ce)throw ce},onSuccess:()=>{ae.success("Post deleted"),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:he=>{ae.error(`Failed to delete: ${he.message}`)}}),M=gt({mutationFn:async he=>{const{data:ce,error:pe}=await q.functions.invoke("social-post",{body:{platform:he.platform,accountId:he.social_account_id,imageUrl:he.image_url,caption:he.caption}});if(pe)throw pe;if(ce!=null&&ce.error)throw new Error(ce.error);return await q.from("scheduled_posts").update({status:"posted",posted_at:new Date().toISOString(),post_id:ce.postId}).eq("id",he.id),ce},onSuccess:he=>{const ce=he.platform==="facebook"?"Facebook":he.platform==="instagram"?"Instagram":"LinkedIn";ae.success(`Posted to ${ce}!`),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:he=>{ae.error(`Failed to post: ${he.message}`)}}),F=he=>{if(l(he),c(he.caption||""),he.scheduled_for){const ce=new Date(he.scheduled_for);u(ce);const pe=ce.getHours();p(String(pe>12?pe-12:pe===0?12:pe)),g(String(ce.getMinutes()).padStart(2,"0")),v(pe>=12?"PM":"AM")}},z=()=>{if(!i||!d)return;let he=parseInt(h);const ce=parseInt(f);_==="PM"&&he!==12&&(he+=12),_==="AM"&&he===12&&(he=0);const pe=K9(W9(d,he),ce);T.mutate({id:i.id,caption:o,scheduled_for:pe.toISOString()})},V=he=>{switch(he){case"facebook":return e.jsx(Lh,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(du,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(vf,{className:"h-4 w-4 text-blue-700"});default:return null}},W=he=>{switch(he){case"scheduled":return e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),"Scheduled"]});case"posted":return e.jsxs(ze,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(Ri,{className:"h-3 w-3"}),"Posted"]});case"failed":return e.jsxs(ze,{variant:"destructive",className:"gap-1",children:[e.jsx(Hc,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs(ze,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Gi,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx(ze,{variant:"outline",children:he})}},Y=Array.from({length:12},(he,ce)=>String(ce+1)),K=["00","15","30","45"],J=j.filter(he=>he.status==="scheduled").length,ne=j.filter(he=>he.status==="posted").length,ie=j.filter(he=>he.status==="scheduled"&&he.scheduled_for&&U$t(new Date(he.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(fe,{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(fe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ie}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Upcoming"})]}),e.jsxs(fe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ne}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Posted"})]}),e.jsxs(fe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:j.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total"})]})]}),e.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[e.jsxs(fe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Tl,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold",children:"Calendar"})]}),e.jsx(Kg,{mode:"single",selected:t,onSelect:n,className:Et("pointer-events-auto"),modifiers:{hasPost:A},modifiersStyles:{hasPost:{fontWeight:"bold",backgroundColor:"hsl(var(--primary) / 0.1)",borderRadius:"50%"}}}),t&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>n(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(Rv,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["all","scheduled","posted","failed","cancelled"].map(he=>e.jsx(B,{variant:r===he?"default":"outline",size:"sm",onClick:()=>a(he),className:"capitalize",children:he},he))})]}),b&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ts,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),!b&&S.length===0&&e.jsxs(fe,{className:"p-8 text-center",children:[e.jsx(yr,{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:t?`No posts scheduled for ${Ss(t,"PPP")}`:"Schedule a post from Social Swag to get started!"})]}),e.jsx("div",{className:"space-y-4",children:S.map(he=>{var ce,pe;return e.jsx(fe,{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:he.image_url,alt:"Post preview",className:"w-full h-full object-cover"})}),e.jsxs(Ee,{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:[V(he.platform),e.jsx("span",{className:"font-medium",children:((ce=he.social_accounts)==null?void 0:ce.page_name)||((pe=he.social_accounts)==null?void 0:pe.platform_username)||"Unknown"}),W(he.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[he.status==="scheduled"&&e.jsxs(Ww,{children:[e.jsxs(Ec,{children:[e.jsx(Ac,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>F(he),children:e.jsx(_a,{className:"h-4 w-4"})})}),e.jsx(vc,{children:"Edit post"})]}),e.jsxs(Ec,{children:[e.jsx(Ac,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>M.mutate(he),disabled:M.isPending,children:M.isPending?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"})})}),e.jsx(vc,{children:"Post now"})]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Cancel this scheduled post?"}),e.jsx(Mo,{children:"This will cancel the post. You can delete it entirely or keep it in your history."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Keep"}),e.jsx(jo,{onClick:()=>L.mutate(he.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(jo,{onClick:()=>D.mutate(he.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]}),(he.status==="posted"||he.status==="cancelled"||he.status==="failed")&&e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete this post?"}),e.jsx(Mo,{children:"This will permanently remove this post from your history."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>D.mutate(he.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),he.caption&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-2",children:he.caption}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),he.status==="posted"&&he.posted_at?`Posted ${Ss(new Date(he.posted_at),"PPp")}`:he.scheduled_for?`Scheduled for ${Ss(new Date(he.scheduled_for),"PPp")}`:"Not scheduled"]}),he.status==="failed"&&he.error_message&&e.jsxs("p",{className:"text-xs text-destructive mt-2",children:["Error: ",he.error_message]})]})]})},he.id)})})]})]}),e.jsx(bs,{open:!!i,onOpenChange:he=>!he&&l(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Edit Scheduled Post"}),e.jsx(Qn,{children:"Update the caption or reschedule this post"})]}),i&&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:i.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(Es,{value:o,onChange:he=>c(he.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(el,{children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("justify-start text-left font-normal flex-1",!d&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),d?Ss(d,"PPP"):"Pick a date"]})}),e.jsx(Ho,{className:"w-auto p-0",align:"start",children:e.jsx(Kg,{mode:"single",selected:d,onSelect:u,disabled:he=>hee.jsx(Qe,{value:he,children:he},he))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(ds,{value:f,onValueChange:g,children:[e.jsx(ls,{className:"w-[70px]",children:e.jsx(us,{})}),e.jsx(cs,{children:K.map(he=>e.jsx(Qe,{value:he,children:he},he))})]}),e.jsxs(ds,{value:_,onValueChange:he=>v(he),children:[e.jsx(ls,{className:"w-[70px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"AM",children:"AM"}),e.jsx(Qe,{value:"PM",children:"PM"})]})]})]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(null),children:"Cancel"}),e.jsxs(B,{onClick:z,disabled:T.isPending,children:[T.isPending?e.jsx(ts,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})})]})}function PH(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 Igt={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 PH=="function"&&PH;if(!u&&h)return h(d,!0);if(o)return o(d,!0);var p=new Error("Cannot find module '"+d+"'");throw p.code="MODULE_NOT_FOUND",p}var f=a[d]={exports:{}};r[d][0].call(f.exports,function(g){var _=r[d][1][g];return l(_||g)},f,f.exports,n,r,a,i)}return a[d].exports}for(var o=typeof PH=="function"&&PH,c=0;c>2,f=(3&d)<<4|u>>4,g=1>6:64,_=2>4,u=(15&p)<<4|(f=o.indexOf(c.charAt(_++)))>>2,h=(3&f)<<6|(g=o.indexOf(c.charAt(_++))),b[v++]=d,f!==64&&(b[v++]=u),g!==64&&(b[v++]=h);return b}},{"./support":30,"./utils":32}],2:[function(n,r,a){var i=n("./external"),l=n("./stream/DataWorker"),o=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function d(u,h,p,f,g){this.compressedSize=u,this.uncompressedSize=h,this.crc32=p,this.compression=f,this.compressedContent=g}d.prototype={getContentWorker:function(){var u=new l(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),h=this;return u.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},getCompressedWorker:function(){return new l(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},d.createWorkerFrom=function(u,h,p){return u.pipe(new o).pipe(new c("uncompressedSize")).pipe(h.compressWorker(p)).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,p){var f=l,g=p+h;d^=-1;for(var _=p;_>>8^f[255&(d^u[_])];return-1^d}(0|c,o,o.length,0):function(d,u,h,p){var f=l,g=p+h;d^=-1;for(var _=p;_>>8^f[255&(d^u.charCodeAt(_))];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,p){c.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=p,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(p){h.push({data:p,meta:h.meta})}},a.compressWorker=function(h){return new u("Deflate",h)},a.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,a){function i(f,g){var _,v="";for(_=0;_>>=8;return v}function l(f,g,_,v,j,b){var S,A,T=f.file,L=f.compression,D=b!==d.utf8encode,M=o.transformTo("string",b(T.name)),F=o.transformTo("string",d.utf8encode(T.name)),z=T.comment,V=o.transformTo("string",b(z)),W=o.transformTo("string",d.utf8encode(z)),Y=F.length!==T.name.length,K=W.length!==z.length,J="",ne="",ie="",he=T.dir,ce=T.date,pe={crc32:0,compressedSize:0,uncompressedSize:0};g&&!_||(pe.crc32=f.crc32,pe.compressedSize=f.compressedSize,pe.uncompressedSize=f.uncompressedSize);var le=0;g&&(le|=8),D||!Y&&!K||(le|=2048);var ve=0,ge=0;he&&(ve|=16),j==="UNIX"?(ge=798,ve|=function(Me,Ce){var Ae=Me;return Me||(Ae=Ce?16893:33204),(65535&Ae)<<16}(T.unixPermissions,he)):(ge=20,ve|=function(Me){return 63&(Me||0)}(T.dosPermissions)),S=ce.getUTCHours(),S<<=6,S|=ce.getUTCMinutes(),S<<=5,S|=ce.getUTCSeconds()/2,A=ce.getUTCFullYear()-1980,A<<=4,A|=ce.getUTCMonth()+1,A<<=5,A|=ce.getUTCDate(),Y&&(ne=i(1,1)+i(u(M),4)+F,J+="up"+i(ne.length,2)+ne),K&&(ie=i(1,1)+i(u(V),4)+W,J+="uc"+i(ie.length,2)+ie);var Te="";return Te+=` \0`,Te+=i(le,2),Te+=L.magic,Te+=i(S,2),Te+=i(A,2),Te+=i(pe.crc32,4),Te+=i(pe.compressedSize,4),Te+=i(pe.uncompressedSize,4),Te+=i(M.length,2),Te+=i(J.length,2),{fileRecord:h.LOCAL_FILE_HEADER+Te+M+J,dirRecord:h.CENTRAL_FILE_HEADER+i(ge,2)+Te+i(V.length,2)+"\0\0\0\0"+i(ve,4)+i(v,4)+M+J+V}}var o=n("../utils"),c=n("../stream/GenericWorker"),d=n("../utf8"),u=n("../crc32"),h=n("../signature");function p(f,g,_,v){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=_,this.encodeFileName=v,this.streamFiles=f,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(p,c),p.prototype.push=function(f){var g=f.meta.percent||0,_=this.entriesCount,v=this._sources.length;this.accumulate?this.contentBuffer.push(f):(this.bytesWritten+=f.data.length,c.prototype.push.call(this,{data:f.data,meta:{currentFile:this.currentFile,percent:_?(g+100*(_-v-1))/_:100}}))},p.prototype.openedSource=function(f){this.currentSourceOffset=this.bytesWritten,this.currentFile=f.file.name;var g=this.streamFiles&&!f.file.dir;if(g){var _=l(f,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:_.fileRecord,meta:{percent:0}})}else this.accumulate=!0},p.prototype.closedSource=function(f){this.accumulate=!1;var g=this.streamFiles&&!f.file.dir,_=l(f,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(_.dirRecord),g)this.push({data:function(v){return h.DATA_DESCRIPTOR+i(v.crc32,4)+i(v.compressedSize,4)+i(v.uncompressedSize,4)}(f),meta:{percent:100}});else for(this.push({data:_.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},p.prototype.flush=function(){for(var f=this.bytesWritten,g=0;g=this.index;c--)d=(d<<8)+this.byteAt(c);return this.index+=o,d},readString:function(o){return i.transformTo("string",this.readData(o))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var o=this.readInt(4);return new Date(Date.UTC(1980+(o>>25&127),(o>>21&15)-1,o>>16&31,o>>11&31,o>>5&63,(31&o)<<1))}},r.exports=l},{"../utils":32}],19:[function(n,r,a){var i=n("./Uint8ArrayReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,a){var i=n("./DataReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.byteAt=function(o){return this.data.charCodeAt(this.zero+o)},l.prototype.lastIndexOfSignature=function(o){return this.data.lastIndexOf(o)-this.zero},l.prototype.readAndCheckSignature=function(o){return o===this.readData(4)},l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./DataReader":18}],21:[function(n,r,a){var i=n("./ArrayReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.readData=function(o){if(this.checkOffset(o),o===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,a){var i=n("../utils"),l=n("../support"),o=n("./ArrayReader"),c=n("./StringReader"),d=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(h){var p=i.getTypeOf(h);return i.checkSupport(p),p!=="string"||l.uint8array?p==="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 p(g,_){return new u.Promise(function(v,j){var b=[],S=g._internalType,A=g._outputType,T=g._mimeType;g.on("data",function(L,D){b.push(L),_&&_(D)}).on("error",function(L){b=[],j(L)}).on("end",function(){try{var L=function(D,M,F){switch(D){case"blob":return i.newBlob(i.transformTo("arraybuffer",M),F);case"base64":return c.encode(M);default:return i.transformTo(D,M)}}(A,function(D,M){var F,z=0,V=null,W=0;for(F=0;F"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 p(){c.call(this,"utf-8 encode")}a.utf8encode=function(f){return l.nodebuffer?o.newBufferFrom(f,"utf-8"):function(g){var _,v,j,b,S,A=g.length,T=0;for(b=0;b>>6:(v<65536?_[S++]=224|v>>>12:(_[S++]=240|v>>>18,_[S++]=128|v>>>12&63),_[S++]=128|v>>>6&63),_[S++]=128|63&v);return _}(f)},a.utf8decode=function(f){return l.nodebuffer?i.transformTo("nodebuffer",f).toString("utf-8"):function(g){var _,v,j,b,S=g.length,A=new Array(2*S);for(_=v=0;_>10&1023,A[v++]=56320|1023&j)}return A.length!==v&&(A.subarray?A=A.subarray(0,v):A.length=v),i.applyFromCharCode(A)}(f=i.transformTo(l.uint8array?"uint8array":"array",f))},i.inherits(h,c),h.prototype.processChunk=function(f){var g=i.transformTo(l.uint8array?"uint8array":"array",f.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var _=g;(g=new Uint8Array(_.length+this.leftOver.length)).set(this.leftOver,0),g.set(_,this.leftOver.length)}else g=this.leftOver.concat(g);this.leftOver=null}var v=function(b,S){var A;for((S=S||b.length)>b.length&&(S=b.length),A=S-1;0<=A&&(192&b[A])==128;)A--;return A<0||A===0?S:A+d[b[A]]>S?A:S}(g),j=g;v!==g.length&&(l.uint8array?(j=g.subarray(0,v),this.leftOver=g.subarray(v,g.length)):(j=g.slice(0,v),this.leftOver=g.slice(v,g.length))),this.push({data:a.utf8decode(j),meta:f.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=h,i.inherits(p,c),p.prototype.processChunk=function(f){this.push({data:a.utf8encode(f.data),meta:f.meta})},a.Utf8EncodeWorker=p},{"./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(_){return _}function u(_,v){for(var j=0;j<_.length;++j)v[j]=255&_.charCodeAt(j);return v}n("setimmediate"),a.newBlob=function(_,v){a.checkSupport("blob");try{return new Blob([_],{type:v})}catch{try{var j=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return j.append(_),j.getBlob(v)}catch{throw new Error("Bug : can't construct the Blob.")}}};var h={stringifyByChunk:function(_,v,j){var b=[],S=0,A=_.length;if(A<=j)return String.fromCharCode.apply(null,_);for(;S>8;this.dir=!!(16&this.externalFileAttributes),f==0&&(this.dosPermissions=63&this.externalFileAttributes),f==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var f=i(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=f.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=f.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=f.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=f.readInt(4))}},readExtraFields:function(f){var g,_,v,j=f.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});f.index+4>>6:(f<65536?p[v++]=224|f>>>12:(p[v++]=240|f>>>18,p[v++]=128|f>>>12&63),p[v++]=128|f>>>6&63),p[v++]=128|63&f);return p},a.buf2binstring=function(h){return u(h,h.length)},a.binstring2buf=function(h){for(var p=new i.Buf8(h.length),f=0,g=p.length;f>10&1023,b[g++]=56320|1023&_)}return u(b,g)},a.utf8border=function(h,p){var f;for((p=p||h.length)>h.length&&(p=h.length),f=p-1;0<=f&&(192&h[f])==128;)f--;return f<0||f===0?p:f+c[h[f]]>p?f:p}},{"./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 p=d;p>>8^u[255&(l^o[p])];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,p=4,f=0,g=-2,_=-1,v=4,j=2,b=8,S=9,A=286,T=30,L=19,D=2*A+1,M=15,F=3,z=258,V=z+F+1,W=42,Y=113,K=1,J=2,ne=3,ie=4;function he(Ne,it){return Ne.msg=u[it],it}function ce(Ne){return(Ne<<1)-(4Ne.avail_out&&(je=Ne.avail_out),je!==0&&(l.arraySet(Ne.output,it.pending_buf,it.pending_out,je,Ne.next_out),Ne.next_out+=je,it.pending_out+=je,Ne.total_out+=je,Ne.avail_out-=je,it.pending-=je,it.pending===0&&(it.pending_out=0))}function ve(Ne,it){o._tr_flush_block(Ne,0<=Ne.block_start?Ne.block_start:-1,Ne.strstart-Ne.block_start,it),Ne.block_start=Ne.strstart,le(Ne.strm)}function ge(Ne,it){Ne.pending_buf[Ne.pending++]=it}function Te(Ne,it){Ne.pending_buf[Ne.pending++]=it>>>8&255,Ne.pending_buf[Ne.pending++]=255&it}function Me(Ne,it){var je,Ge,Be=Ne.max_chain_length,Ye=Ne.strstart,We=Ne.prev_length,rt=Ne.nice_match,tt=Ne.strstart>Ne.w_size-V?Ne.strstart-(Ne.w_size-V):0,at=Ne.window,He=Ne.w_mask,dt=Ne.prev,bt=Ne.strstart+z,vt=at[Ye+We-1],Bt=at[Ye+We];Ne.prev_length>=Ne.good_match&&(Be>>=2),rt>Ne.lookahead&&(rt=Ne.lookahead);do if(at[(je=it)+We]===Bt&&at[je+We-1]===vt&&at[je]===at[Ye]&&at[++je]===at[Ye+1]){Ye+=2,je++;do;while(at[++Ye]===at[++je]&&at[++Ye]===at[++je]&&at[++Ye]===at[++je]&&at[++Ye]===at[++je]&&at[++Ye]===at[++je]&&at[++Ye]===at[++je]&&at[++Ye]===at[++je]&&at[++Ye]===at[++je]&&Yett&&--Be!=0);return We<=Ne.lookahead?We:Ne.lookahead}function Ce(Ne){var it,je,Ge,Be,Ye,We,rt,tt,at,He,dt=Ne.w_size;do{if(Be=Ne.window_size-Ne.lookahead-Ne.strstart,Ne.strstart>=dt+(dt-V)){for(l.arraySet(Ne.window,Ne.window,dt,dt,0),Ne.match_start-=dt,Ne.strstart-=dt,Ne.block_start-=dt,it=je=Ne.hash_size;Ge=Ne.head[--it],Ne.head[it]=dt<=Ge?Ge-dt:0,--je;);for(it=je=dt;Ge=Ne.prev[--it],Ne.prev[it]=dt<=Ge?Ge-dt:0,--je;);Be+=dt}if(Ne.strm.avail_in===0)break;if(We=Ne.strm,rt=Ne.window,tt=Ne.strstart+Ne.lookahead,at=Be,He=void 0,He=We.avail_in,at=F)for(Ye=Ne.strstart-Ne.insert,Ne.ins_h=Ne.window[Ye],Ne.ins_h=(Ne.ins_h<=F&&(Ne.ins_h=(Ne.ins_h<=F)if(Ge=o._tr_tally(Ne,Ne.strstart-Ne.match_start,Ne.match_length-F),Ne.lookahead-=Ne.match_length,Ne.match_length<=Ne.max_lazy_match&&Ne.lookahead>=F){for(Ne.match_length--;Ne.strstart++,Ne.ins_h=(Ne.ins_h<=F&&(Ne.ins_h=(Ne.ins_h<=F&&Ne.match_length<=Ne.prev_length){for(Be=Ne.strstart+Ne.lookahead-F,Ge=o._tr_tally(Ne,Ne.strstart-1-Ne.prev_match,Ne.prev_length-F),Ne.lookahead-=Ne.prev_length-1,Ne.prev_length-=2;++Ne.strstart<=Be&&(Ne.ins_h=(Ne.ins_h<Ne.pending_buf_size-5&&(je=Ne.pending_buf_size-5);;){if(Ne.lookahead<=1){if(Ce(Ne),Ne.lookahead===0&&it===h)return K;if(Ne.lookahead===0)break}Ne.strstart+=Ne.lookahead,Ne.lookahead=0;var Ge=Ne.block_start+je;if((Ne.strstart===0||Ne.strstart>=Ge)&&(Ne.lookahead=Ne.strstart-Ge,Ne.strstart=Ge,ve(Ne,!1),Ne.strm.avail_out===0)||Ne.strstart-Ne.block_start>=Ne.w_size-V&&(ve(Ne,!1),Ne.strm.avail_out===0))return K}return Ne.insert=0,it===p?(ve(Ne,!0),Ne.strm.avail_out===0?ne:ie):(Ne.strstart>Ne.block_start&&(ve(Ne,!1),Ne.strm.avail_out),K)}),new Ie(4,4,8,4,Ae),new Ie(4,5,16,8,Ae),new Ie(4,6,32,32,Ae),new Ie(4,4,16,16,De),new Ie(8,16,32,32,De),new Ie(8,16,128,128,De),new Ie(8,32,128,256,De),new Ie(32,128,258,1024,De),new Ie(32,258,258,4096,De)],a.deflateInit=function(Ne,it){return Ze(Ne,it,b,15,8,0)},a.deflateInit2=Ze,a.deflateReset=be,a.deflateResetKeep=qe,a.deflateSetHeader=function(Ne,it){return Ne&&Ne.state?Ne.state.wrap!==2?g:(Ne.state.gzhead=it,f):g},a.deflate=function(Ne,it){var je,Ge,Be,Ye;if(!Ne||!Ne.state||5>8&255),ge(Ge,Ge.gzhead.time>>16&255),ge(Ge,Ge.gzhead.time>>24&255),ge(Ge,Ge.level===9?2:2<=Ge.strategy||Ge.level<2?4:0),ge(Ge,255&Ge.gzhead.os),Ge.gzhead.extra&&Ge.gzhead.extra.length&&(ge(Ge,255&Ge.gzhead.extra.length),ge(Ge,Ge.gzhead.extra.length>>8&255)),Ge.gzhead.hcrc&&(Ne.adler=d(Ne.adler,Ge.pending_buf,Ge.pending,0)),Ge.gzindex=0,Ge.status=69):(ge(Ge,0),ge(Ge,0),ge(Ge,0),ge(Ge,0),ge(Ge,0),ge(Ge,Ge.level===9?2:2<=Ge.strategy||Ge.level<2?4:0),ge(Ge,3),Ge.status=Y);else{var We=b+(Ge.w_bits-8<<4)<<8;We|=(2<=Ge.strategy||Ge.level<2?0:Ge.level<6?1:Ge.level===6?2:3)<<6,Ge.strstart!==0&&(We|=32),We+=31-We%31,Ge.status=Y,Te(Ge,We),Ge.strstart!==0&&(Te(Ge,Ne.adler>>>16),Te(Ge,65535&Ne.adler)),Ne.adler=1}if(Ge.status===69)if(Ge.gzhead.extra){for(Be=Ge.pending;Ge.gzindex<(65535&Ge.gzhead.extra.length)&&(Ge.pending!==Ge.pending_buf_size||(Ge.gzhead.hcrc&&Ge.pending>Be&&(Ne.adler=d(Ne.adler,Ge.pending_buf,Ge.pending-Be,Be)),le(Ne),Be=Ge.pending,Ge.pending!==Ge.pending_buf_size));)ge(Ge,255&Ge.gzhead.extra[Ge.gzindex]),Ge.gzindex++;Ge.gzhead.hcrc&&Ge.pending>Be&&(Ne.adler=d(Ne.adler,Ge.pending_buf,Ge.pending-Be,Be)),Ge.gzindex===Ge.gzhead.extra.length&&(Ge.gzindex=0,Ge.status=73)}else Ge.status=73;if(Ge.status===73)if(Ge.gzhead.name){Be=Ge.pending;do{if(Ge.pending===Ge.pending_buf_size&&(Ge.gzhead.hcrc&&Ge.pending>Be&&(Ne.adler=d(Ne.adler,Ge.pending_buf,Ge.pending-Be,Be)),le(Ne),Be=Ge.pending,Ge.pending===Ge.pending_buf_size)){Ye=1;break}Ye=Ge.gzindexBe&&(Ne.adler=d(Ne.adler,Ge.pending_buf,Ge.pending-Be,Be)),Ye===0&&(Ge.gzindex=0,Ge.status=91)}else Ge.status=91;if(Ge.status===91)if(Ge.gzhead.comment){Be=Ge.pending;do{if(Ge.pending===Ge.pending_buf_size&&(Ge.gzhead.hcrc&&Ge.pending>Be&&(Ne.adler=d(Ne.adler,Ge.pending_buf,Ge.pending-Be,Be)),le(Ne),Be=Ge.pending,Ge.pending===Ge.pending_buf_size)){Ye=1;break}Ye=Ge.gzindexBe&&(Ne.adler=d(Ne.adler,Ge.pending_buf,Ge.pending-Be,Be)),Ye===0&&(Ge.status=103)}else Ge.status=103;if(Ge.status===103&&(Ge.gzhead.hcrc?(Ge.pending+2>Ge.pending_buf_size&&le(Ne),Ge.pending+2<=Ge.pending_buf_size&&(ge(Ge,255&Ne.adler),ge(Ge,Ne.adler>>8&255),Ne.adler=0,Ge.status=Y)):Ge.status=Y),Ge.pending!==0){if(le(Ne),Ne.avail_out===0)return Ge.last_flush=-1,f}else if(Ne.avail_in===0&&ce(it)<=ce(je)&&it!==p)return he(Ne,-5);if(Ge.status===666&&Ne.avail_in!==0)return he(Ne,-5);if(Ne.avail_in!==0||Ge.lookahead!==0||it!==h&&Ge.status!==666){var rt=Ge.strategy===2?function(tt,at){for(var He;;){if(tt.lookahead===0&&(Ce(tt),tt.lookahead===0)){if(at===h)return K;break}if(tt.match_length=0,He=o._tr_tally(tt,0,tt.window[tt.strstart]),tt.lookahead--,tt.strstart++,He&&(ve(tt,!1),tt.strm.avail_out===0))return K}return tt.insert=0,at===p?(ve(tt,!0),tt.strm.avail_out===0?ne:ie):tt.last_lit&&(ve(tt,!1),tt.strm.avail_out===0)?K:J}(Ge,it):Ge.strategy===3?function(tt,at){for(var He,dt,bt,vt,Bt=tt.window;;){if(tt.lookahead<=z){if(Ce(tt),tt.lookahead<=z&&at===h)return K;if(tt.lookahead===0)break}if(tt.match_length=0,tt.lookahead>=F&&0tt.lookahead&&(tt.match_length=tt.lookahead)}if(tt.match_length>=F?(He=o._tr_tally(tt,1,tt.match_length-F),tt.lookahead-=tt.match_length,tt.strstart+=tt.match_length,tt.match_length=0):(He=o._tr_tally(tt,0,tt.window[tt.strstart]),tt.lookahead--,tt.strstart++),He&&(ve(tt,!1),tt.strm.avail_out===0))return K}return tt.insert=0,at===p?(ve(tt,!0),tt.strm.avail_out===0?ne:ie):tt.last_lit&&(ve(tt,!1),tt.strm.avail_out===0)?K:J}(Ge,it):i[Ge.level].func(Ge,it);if(rt!==ne&&rt!==ie||(Ge.status=666),rt===K||rt===ne)return Ne.avail_out===0&&(Ge.last_flush=-1),f;if(rt===J&&(it===1?o._tr_align(Ge):it!==5&&(o._tr_stored_block(Ge,0,0,!1),it===3&&(pe(Ge.head),Ge.lookahead===0&&(Ge.strstart=0,Ge.block_start=0,Ge.insert=0))),le(Ne),Ne.avail_out===0))return Ge.last_flush=-1,f}return it!==p?f:Ge.wrap<=0?1:(Ge.wrap===2?(ge(Ge,255&Ne.adler),ge(Ge,Ne.adler>>8&255),ge(Ge,Ne.adler>>16&255),ge(Ge,Ne.adler>>24&255),ge(Ge,255&Ne.total_in),ge(Ge,Ne.total_in>>8&255),ge(Ge,Ne.total_in>>16&255),ge(Ge,Ne.total_in>>24&255)):(Te(Ge,Ne.adler>>>16),Te(Ge,65535&Ne.adler)),le(Ne),0=je.w_size&&(Ye===0&&(pe(je.head),je.strstart=0,je.block_start=0,je.insert=0),at=new l.Buf8(je.w_size),l.arraySet(at,it,He-je.w_size,je.w_size,0),it=at,He=je.w_size),We=Ne.avail_in,rt=Ne.next_in,tt=Ne.input,Ne.avail_in=He,Ne.next_in=0,Ne.input=it,Ce(je);je.lookahead>=F;){for(Ge=je.strstart,Be=je.lookahead-(F-1);je.ins_h=(je.ins_h<>>=F=M>>>24,S-=F,(F=M>>>16&255)===0)J[u++]=65535&M;else{if(!(16&F)){if(!(64&F)){M=A[(65535&M)+(b&(1<>>=F,S-=F),S<15&&(b+=K[c++]<>>=F=M>>>24,S-=F,!(16&(F=M>>>16&255))){if(!(64&F)){M=T[(65535&M)+(b&(1<>>=F,S-=F,(F=u-h)>3,b&=(1<<(S-=z<<3))-1,i.next_in=c,i.next_out=u,i.avail_in=c>>24&255)+(W>>>8&65280)+((65280&W)<<8)+((255&W)<<24)}function b(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new i.Buf16(320),this.work=new i.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function S(W){var Y;return W&&W.state?(Y=W.state,W.total_in=W.total_out=Y.total=0,W.msg="",Y.wrap&&(W.adler=1&Y.wrap),Y.mode=g,Y.last=0,Y.havedict=0,Y.dmax=32768,Y.head=null,Y.hold=0,Y.bits=0,Y.lencode=Y.lendyn=new i.Buf32(_),Y.distcode=Y.distdyn=new i.Buf32(v),Y.sane=1,Y.back=-1,p):f}function A(W){var Y;return W&&W.state?((Y=W.state).wsize=0,Y.whave=0,Y.wnext=0,S(W)):f}function T(W,Y){var K,J;return W&&W.state?(J=W.state,Y<0?(K=0,Y=-Y):(K=1+(Y>>4),Y<48&&(Y&=15)),Y&&(Y<8||15=ie.wsize?(i.arraySet(ie.window,Y,K-ie.wsize,ie.wsize,0),ie.wnext=0,ie.whave=ie.wsize):(J<(ne=ie.wsize-ie.wnext)&&(ne=J),i.arraySet(ie.window,Y,K-J,ne,ie.wnext),(J-=ne)?(i.arraySet(ie.window,Y,K-J,J,0),ie.wnext=J,ie.whave=ie.wsize):(ie.wnext+=ne,ie.wnext===ie.wsize&&(ie.wnext=0),ie.whave>>8&255,K.check=o(K.check,Ye,2,0),ve=le=0,K.mode=2;break}if(K.flags=0,K.head&&(K.head.done=!1),!(1&K.wrap)||(((255&le)<<8)+(le>>8))%31){W.msg="incorrect header check",K.mode=30;break}if((15&le)!=8){W.msg="unknown compression method",K.mode=30;break}if(ve-=4,Ne=8+(15&(le>>>=4)),K.wbits===0)K.wbits=Ne;else if(Ne>K.wbits){W.msg="invalid window size",K.mode=30;break}K.dmax=1<>8&1),512&K.flags&&(Ye[0]=255&le,Ye[1]=le>>>8&255,K.check=o(K.check,Ye,2,0)),ve=le=0,K.mode=3;case 3:for(;ve<32;){if(ce===0)break e;ce--,le+=J[ie++]<>>8&255,Ye[2]=le>>>16&255,Ye[3]=le>>>24&255,K.check=o(K.check,Ye,4,0)),ve=le=0,K.mode=4;case 4:for(;ve<16;){if(ce===0)break e;ce--,le+=J[ie++]<>8),512&K.flags&&(Ye[0]=255&le,Ye[1]=le>>>8&255,K.check=o(K.check,Ye,2,0)),ve=le=0,K.mode=5;case 5:if(1024&K.flags){for(;ve<16;){if(ce===0)break e;ce--,le+=J[ie++]<>>8&255,K.check=o(K.check,Ye,2,0)),ve=le=0}else K.head&&(K.head.extra=null);K.mode=6;case 6:if(1024&K.flags&&(ce<(Me=K.length)&&(Me=ce),Me&&(K.head&&(Ne=K.head.extra_len-K.length,K.head.extra||(K.head.extra=new Array(K.head.extra_len)),i.arraySet(K.head.extra,J,ie,Me,Ne)),512&K.flags&&(K.check=o(K.check,J,Me,ie)),ce-=Me,ie+=Me,K.length-=Me),K.length))break e;K.length=0,K.mode=7;case 7:if(2048&K.flags){if(ce===0)break e;for(Me=0;Ne=J[ie+Me++],K.head&&Ne&&K.length<65536&&(K.head.name+=String.fromCharCode(Ne)),Ne&&Me>9&1,K.head.done=!0),W.adler=K.check=0,K.mode=12;break;case 10:for(;ve<32;){if(ce===0)break e;ce--,le+=J[ie++]<>>=7&ve,ve-=7&ve,K.mode=27;break}for(;ve<3;){if(ce===0)break e;ce--,le+=J[ie++]<>>=1)){case 0:K.mode=14;break;case 1:if(z(K),K.mode=20,Y!==6)break;le>>>=2,ve-=2;break e;case 2:K.mode=17;break;case 3:W.msg="invalid block type",K.mode=30}le>>>=2,ve-=2;break;case 14:for(le>>>=7&ve,ve-=7&ve;ve<32;){if(ce===0)break e;ce--,le+=J[ie++]<>>16^65535)){W.msg="invalid stored block lengths",K.mode=30;break}if(K.length=65535&le,ve=le=0,K.mode=15,Y===6)break e;case 15:K.mode=16;case 16:if(Me=K.length){if(ce>>=5,ve-=5,K.ndist=1+(31&le),le>>>=5,ve-=5,K.ncode=4+(15&le),le>>>=4,ve-=4,286>>=3,ve-=3}for(;K.have<19;)K.lens[We[K.have++]]=0;if(K.lencode=K.lendyn,K.lenbits=7,je={bits:K.lenbits},it=d(0,K.lens,0,19,K.lencode,0,K.work,je),K.lenbits=je.bits,it){W.msg="invalid code lengths set",K.mode=30;break}K.have=0,K.mode=19;case 19:for(;K.have>>16&255,Fe=65535&Be,!((De=Be>>>24)<=ve);){if(ce===0)break e;ce--,le+=J[ie++]<>>=De,ve-=De,K.lens[K.have++]=Fe;else{if(Fe===16){for(Ge=De+2;ve>>=De,ve-=De,K.have===0){W.msg="invalid bit length repeat",K.mode=30;break}Ne=K.lens[K.have-1],Me=3+(3&le),le>>>=2,ve-=2}else if(Fe===17){for(Ge=De+3;ve>>=De)),le>>>=3,ve-=3}else{for(Ge=De+7;ve>>=De)),le>>>=7,ve-=7}if(K.have+Me>K.nlen+K.ndist){W.msg="invalid bit length repeat",K.mode=30;break}for(;Me--;)K.lens[K.have++]=Ne}}if(K.mode===30)break;if(K.lens[256]===0){W.msg="invalid code -- missing end-of-block",K.mode=30;break}if(K.lenbits=9,je={bits:K.lenbits},it=d(u,K.lens,0,K.nlen,K.lencode,0,K.work,je),K.lenbits=je.bits,it){W.msg="invalid literal/lengths set",K.mode=30;break}if(K.distbits=6,K.distcode=K.distdyn,je={bits:K.distbits},it=d(h,K.lens,K.nlen,K.ndist,K.distcode,0,K.work,je),K.distbits=je.bits,it){W.msg="invalid distances set",K.mode=30;break}if(K.mode=20,Y===6)break e;case 20:K.mode=21;case 21:if(6<=ce&&258<=pe){W.next_out=he,W.avail_out=pe,W.next_in=ie,W.avail_in=ce,K.hold=le,K.bits=ve,c(W,Te),he=W.next_out,ne=W.output,pe=W.avail_out,ie=W.next_in,J=W.input,ce=W.avail_in,le=K.hold,ve=K.bits,K.mode===12&&(K.back=-1);break}for(K.back=0;Ie=(Be=K.lencode[le&(1<>>16&255,Fe=65535&Be,!((De=Be>>>24)<=ve);){if(ce===0)break e;ce--,le+=J[ie++]<>qe)])>>>16&255,Fe=65535&Be,!(qe+(De=Be>>>24)<=ve);){if(ce===0)break e;ce--,le+=J[ie++]<>>=qe,ve-=qe,K.back+=qe}if(le>>>=De,ve-=De,K.back+=De,K.length=Fe,Ie===0){K.mode=26;break}if(32&Ie){K.back=-1,K.mode=12;break}if(64&Ie){W.msg="invalid literal/length code",K.mode=30;break}K.extra=15&Ie,K.mode=22;case 22:if(K.extra){for(Ge=K.extra;ve>>=K.extra,ve-=K.extra,K.back+=K.extra}K.was=K.length,K.mode=23;case 23:for(;Ie=(Be=K.distcode[le&(1<>>16&255,Fe=65535&Be,!((De=Be>>>24)<=ve);){if(ce===0)break e;ce--,le+=J[ie++]<>qe)])>>>16&255,Fe=65535&Be,!(qe+(De=Be>>>24)<=ve);){if(ce===0)break e;ce--,le+=J[ie++]<>>=qe,ve-=qe,K.back+=qe}if(le>>>=De,ve-=De,K.back+=De,64&Ie){W.msg="invalid distance code",K.mode=30;break}K.offset=Fe,K.extra=15&Ie,K.mode=24;case 24:if(K.extra){for(Ge=K.extra;ve>>=K.extra,ve-=K.extra,K.back+=K.extra}if(K.offset>K.dmax){W.msg="invalid distance too far back",K.mode=30;break}K.mode=25;case 25:if(pe===0)break e;if(Me=Te-pe,K.offset>Me){if((Me=K.offset-Me)>K.whave&&K.sane){W.msg="invalid distance too far back",K.mode=30;break}Ce=Me>K.wnext?(Me-=K.wnext,K.wsize-Me):K.wnext-Me,Me>K.length&&(Me=K.length),Ae=K.window}else Ae=ne,Ce=he-K.offset,Me=K.length;for(peD?(F=Ce[Ae+v[Y]],ve[ge+v[Y]]):(F=96,0),b=1<>he)+(S-=b)]=M<<24|F<<16|z|0,S!==0;);for(b=1<>=1;if(b!==0?(le&=b-1,le+=b):le=0,Y++,--Te[W]==0){if(W===J)break;W=h[p+v[Y]]}if(ne>>7)]}function ge(Be,Ye){Be.pending_buf[Be.pending++]=255&Ye,Be.pending_buf[Be.pending++]=Ye>>>8&255}function Te(Be,Ye,We){Be.bi_valid>j-We?(Be.bi_buf|=Ye<>j-Be.bi_valid,Be.bi_valid+=We-j):(Be.bi_buf|=Ye<>>=1,We<<=1,0<--Ye;);return We>>>1}function Ae(Be,Ye,We){var rt,tt,at=new Array(v+1),He=0;for(rt=1;rt<=v;rt++)at[rt]=He=He+We[rt-1]<<1;for(tt=0;tt<=Ye;tt++){var dt=Be[2*tt+1];dt!==0&&(Be[2*tt]=Ce(at[dt]++,dt))}}function De(Be){var Ye;for(Ye=0;Ye>1;1<=We;We--)qe(Be,at,We);for(tt=bt;We=Be.heap[1],Be.heap[1]=Be.heap[Be.heap_len--],qe(Be,at,1),rt=Be.heap[1],Be.heap[--Be.heap_max]=We,Be.heap[--Be.heap_max]=rt,at[2*tt]=at[2*We]+at[2*rt],Be.depth[tt]=(Be.depth[We]>=Be.depth[rt]?Be.depth[We]:Be.depth[rt])+1,at[2*We+1]=at[2*rt+1]=tt,Be.heap[1]=tt++,qe(Be,at,1),2<=Be.heap_len;);Be.heap[--Be.heap_max]=Be.heap[1],function(Bt,Zt){var Fs,Rs,ms,Pt,Jt,ft,Vt=Zt.dyn_tree,Ms=Zt.max_code,Xt=Zt.stat_desc.static_tree,Js=Zt.stat_desc.has_stree,Cs=Zt.stat_desc.extra_bits,As=Zt.stat_desc.extra_base,rn=Zt.stat_desc.max_length,tn=0;for(Pt=0;Pt<=v;Pt++)Bt.bl_count[Pt]=0;for(Vt[2*Bt.heap[Bt.heap_max]+1]=0,Fs=Bt.heap_max+1;Fs<_;Fs++)rn<(Pt=Vt[2*Vt[2*(Rs=Bt.heap[Fs])+1]+1]+1)&&(Pt=rn,tn++),Vt[2*Rs+1]=Pt,Ms>=7;tt>>=1)if(1&vt&&dt.dyn_ltree[2*bt]!==0)return l;if(dt.dyn_ltree[18]!==0||dt.dyn_ltree[20]!==0||dt.dyn_ltree[26]!==0)return o;for(bt=32;bt>>3,(at=Be.static_len+3+7>>>3)<=tt&&(tt=at)):tt=at=We+5,We+4<=tt&&Ye!==-1?Ge(Be,Ye,We,rt):Be.strategy===4||at===tt?(Te(Be,2+(rt?1:0),3),be(Be,V,W)):(Te(Be,4+(rt?1:0),3),function(dt,bt,vt,Bt){var Zt;for(Te(dt,bt-257,5),Te(dt,vt-1,5),Te(dt,Bt-4,4),Zt=0;Zt>>8&255,Be.pending_buf[Be.d_buf+2*Be.last_lit+1]=255&Ye,Be.pending_buf[Be.l_buf+Be.last_lit]=255&We,Be.last_lit++,Ye===0?Be.dyn_ltree[2*We]++:(Be.matches++,Ye--,Be.dyn_ltree[2*(K[We]+h+1)]++,Be.dyn_dtree[2*ve(Ye)]++),Be.last_lit===Be.lit_bufsize-1},a._tr_align=function(Be){Te(Be,2,3),Me(Be,S,V),function(Ye){Ye.bi_valid===16?(ge(Ye,Ye.bi_buf),Ye.bi_buf=0,Ye.bi_valid=0):8<=Ye.bi_valid&&(Ye.pending_buf[Ye.pending++]=255&Ye.bi_buf,Ye.bi_buf>>=8,Ye.bi_valid-=8)}(Be)}},{"../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,p=1,f={},g=!1,_=l.document,v=Object.getPrototypeOf&&Object.getPrototypeOf(l);v=v&&v.setTimeout?v:l,c={}.toString.call(l.process)==="[object process]"?function(A){process.nextTick(function(){b(A)})}:function(){if(l.postMessage&&!l.importScripts){var A=!0,T=l.onmessage;return l.onmessage=function(){A=!1},l.postMessage("","*"),l.onmessage=T,A}}()?(h="setImmediate$"+Math.random()+"$",l.addEventListener?l.addEventListener("message",S,!1):l.attachEvent("onmessage",S),function(A){l.postMessage(h+A,"*")}):l.MessageChannel?((u=new MessageChannel).port1.onmessage=function(A){b(A.data)},function(A){u.port2.postMessage(A)}):_&&"onreadystatechange"in _.createElement("script")?(d=_.documentElement,function(A){var T=_.createElement("script");T.onreadystatechange=function(){b(A),T.onreadystatechange=null,d.removeChild(T),T=null},d.appendChild(T)}):function(A){setTimeout(b,0,A)},v.setImmediate=function(A){typeof A!="function"&&(A=new Function(""+A));for(var T=new Array(arguments.length-1),L=0;L"u"?i===void 0?this:i:self)}).call(this,typeof Eh<"u"?Eh:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(Igt);var lgs=Igt.exports;const Pgt=wl(lgs);function k2e(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 cgs=()=>{ys();const[s,t]=N.useState(null),[n,r]=N.useState(null),[a,i]=N.useState("all"),[l,o]=N.useState(new Set),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[p,f]=N.useState("images"),[g,_]=N.useState(null),{data:v=[],isLoading:j}=ct({queryKey:["social-swag-2"],queryFn:async()=>{const{data:he,error:ce}=await q.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(ce)throw ce;return he}}),{data:b=[]}=ct({queryKey:["social-swag-2-months"],queryFn:async()=>{const{data:he,error:ce}=await q.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(ce)throw ce;return he}}),{data:S=[]}=ct({queryKey:["social-swag-2-reels"],queryFn:async()=>{const{data:he,error:ce}=await q.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(ce)throw ce;return he}}),{data:A=[]}=ct({queryKey:["my-social-accounts-count"],queryFn:async()=>{const{data:he,error:ce}=await q.from("social_accounts").select("id, platform").eq("is_active",!0);if(ce)throw ce;return he||[]}}),T=A.length>0,L=N.useMemo(()=>a==="all"?null:S.find(he=>he.month===a)||null,[a,S]),D=N.useMemo(()=>[...new Set(v.map(ce=>ce.month))].sort((ce,pe)=>pe.localeCompare(ce)),[v]);N.useEffect(()=>{D.length>0&&a==="all"&&i(D[0])},[D,a]);const M=he=>{try{const ce=cMe(he,"yyyy-MM",new Date);return Ss(ce,"MMMM yyyy")}catch{return he}},F=N.useMemo(()=>a==="all"?v:v.filter(he=>he.month===a),[a,v]),z=N.useMemo(()=>{var he;return a==="all"?null:((he=b.find(ce=>ce.month===a))==null?void 0:he.canva_link)||null},[a,b]),V=async he=>{try{await navigator.clipboard.writeText(he),ae.success("Caption copied to clipboard!")}catch{ae.error("Failed to copy caption")}},W=async(he,ce)=>{try{const le=await(await fetch(he)).blob(),ve=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),ge=navigator.canShare&&navigator.canShare({files:[new File([le],"test.jpg",{type:"image/jpeg"})]});if(ve&&ge){const Te=new File([le],`social-swag-${ce}.jpg`,{type:"image/jpeg"});await navigator.share({files:[Te],title:"Social Swag Image"}),ae.success("Image ready to save!")}else{const Te=window.URL.createObjectURL(le),Me=document.createElement("a");Me.href=Te,Me.download=`social-swag-${ce}.jpg`,document.body.appendChild(Me),Me.click(),document.body.removeChild(Me),window.URL.revokeObjectURL(Te),ae.success("Image downloaded!")}}catch(pe){pe.name!=="AbortError"&&ae.error("Failed to download image")}},Y=he=>{o(ce=>{const pe=new Set(ce);return pe.has(he)?pe.delete(he):pe.add(he),pe})},K=()=>{o(new Set(F.map(he=>he.id)))},J=()=>{o(new Set),d(!1)},ne=async()=>{const he=F.filter(ce=>l.has(ce.id));if(he.length===0){ae.error("No images selected");return}h(!0),ae.info(`Preparing ${he.length} images for download...`);try{const ce=new Pgt,pe=[...he].sort((Me,Ce)=>Me.sort_order-Ce.sort_order);for(let Me=0;Me{c?Y(he.id):t(he)};return e.jsx(Ts,{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(ze,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"New content monthly"]}),e.jsxs(ze,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(nl,{className:"h-3 w-3 mr-1"}),v.length," images"]})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3",children:"Social Swag 📸"}),e.jsx("p",{className:"text-lg text-primary-foreground/90 max-w-2xl",children:"Ready-to-post social media images delivered to you monthly. Just download, copy the caption, and share with your audience!"})]})]}),e.jsxs(Br,{defaultValue:"gallery",className:"space-y-6",children:[e.jsxs(Fr,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(Kt,{value:"gallery",className:"gap-2",children:[e.jsx(nl,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Kt,{value:"scheduled",className:"gap-2",children:[e.jsx(Tl,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(is,{value:"gallery",className:"space-y-6",children:[T?e.jsx(fe,{className:"border rounded-xl",children:e.jsx(Ee,{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(Ln,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(fe,{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(Ee,{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(Lh,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(du,{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(Ln,{to:"/social-connections",children:[e.jsx(El,{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:D.map(he=>e.jsx("button",{onClick:()=>i(he),className:Et("px-4 py-2 rounded-full text-sm font-medium transition-all",a===he?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground hover:text-foreground"),children:M(he)},he))}),a!=="all"&&(z?e.jsxs("a",{href:z,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("span",{className:"text-base",children:"🎨"}),"Edit ",M(a)," Images in Canva"]}):e.jsxs("span",{className:"inline-flex items-center gap-2 text-sm text-muted-foreground/50",children:[e.jsx("span",{className:"text-base",children:"🎨"}),"Edit ",M(a)," Images in Canva"]}))]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1 p-1 bg-muted rounded-full",children:[e.jsxs("button",{onClick:()=>{f("images"),J()},className:Et("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",p==="images"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(nl,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{f("reels"),J()},className:Et("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",p==="reels"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(Ah,{className:"h-4 w-4"}),"Reels"]})]}),p==="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:K,className:"gap-2",children:["Select All (",F.length,")"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:J,className:"gap-2",children:[e.jsx(Bn,{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:ne,disabled:u,className:"gap-2",children:[e.jsx(Pa,{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(Ir,{className:"h-4 w-4"}),"Select Images"]})})]}),j&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}),!j&&p==="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:F.map(he=>{const ce=l.has(he.id);return e.jsx(fe,{className:Et("group cursor-pointer overflow-hidden border-0 shadow-md hover:shadow-xl transition-all duration-300 rounded-2xl",c&&ce&&"ring-2 ring-primary ring-offset-2"),onClick:()=>ie(he),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:k2e(he.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"}),he.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:Ss(new Date(he.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",ce?"bg-primary border-primary text-primary-foreground":"bg-white/80 border-muted-foreground/50"),children:ce&&e.jsx(Ir,{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"})})]})},he.id)})}),F.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(nl,{className:"h-12 w-12 text-muted-foreground/50 mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No images available for this month yet."})]})]}),!j&&p==="reels"&&e.jsx(e.Fragment,{children:L?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(fe,{className:"group overflow-hidden rounded-2xl cursor-pointer transition-all duration-300 hover:shadow-xl hover:scale-[1.02]",onClick:()=>r(L),children:e.jsxs("div",{className:"relative aspect-[9/16] overflow-hidden",children:[e.jsx("img",{src:k2e(L.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(ze,{variant:"secondary",className:"bg-black/50 text-white border-0 backdrop-blur-sm text-xs",children:[e.jsx(Ah,{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(Ah,{className:"h-12 w-12 text-muted-foreground/50 mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No reel available for this month yet."})]})})]}),e.jsx(bs,{open:!!s,onOpenChange:()=>t(null),children:e.jsx(vs,{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:k2e(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(yr,{className:"h-4 w-4"}),Ss(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(yr,{className:"h-3.5 w-3.5"}),"Post on ",Ss(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:()=>{_({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(cr,{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:()=>V(s.caption),className:"flex-1 gap-2",children:[e.jsx(Xr,{className:"h-4 w-4"}),"Copy Caption"]}),e.jsxs(B,{variant:"outline",onClick:()=>W(s.image_url,s.id),className:"flex-1 gap-2",children:[e.jsx(Pa,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(bs,{open:!!n,onOpenChange:()=>r(null),children:e.jsx(vs,{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(Ah,{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:()=>V(n.caption||""),className:"flex-1 gap-2",children:[e.jsx(Xr,{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(igs,{open:!!g,onOpenChange:he=>!he&&_(null),imageUrl:(g==null?void 0:g.imageUrl)||"",imageId:(g==null?void 0:g.imageId)||"",defaultCaption:(g==null?void 0:g.caption)||"",swagItemId:g==null?void 0:g.imageId})]}),e.jsx(is,{value:"scheduled",children:e.jsx(ogs,{})})]})]})})},dgs=[{id:"branding-bar",title:"Branding Bar Studio",description:"Drop in any image — get a branded version with your headshot, logo, and contact info.",icon:nl,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:Or,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:Xi,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:yo,comingSoon:!0,color:"from-orange-500 to-red-500"},{id:"milestones",title:"Client Milestones",description:"Closing day, home anniversaries, birthdays, referral thank-yous.",icon:cu,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:Ev,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:bw,comingSoon:!0,color:"from-amber-500 to-yellow-500"}];function ugs(){return e.jsx(Ts,{title:"Marketing Studio",children:e.jsxs("div",{className:"container max-w-6xl py-8 space-y-6",children:[e.jsxs(Go,{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(ze,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(un,{className:"h-3 w-3"})," New"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"Marketing Studio"}),e.jsx("p",{className:"text-muted-foreground max-w-2xl mt-1",children:"Your one-stop creative hub. Drop in any photo or video, and walk away with a fully branded export — no design skills, no AI credits."})]}),e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs(Ln,{to:"/marketing-studio/brand-kit",children:[e.jsx(fl,{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:dgs.map(s=>{const t=s.icon,n=e.jsxs(fe,{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(Ee,{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(ze,{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(Ln,{to:s.to,className:"block",children:n},s.id):e.jsx("div",{children:n},s.id)})})]})})}function jU(){const s=ma();return ct({queryKey:["marketing-brand-presets",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("marketing_brand_presets").select("*").eq("user_id",s).order("is_default",{ascending:!1}).order("created_at",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function hgs(){const{data:s,...t}=jU();return{data:(s==null?void 0:s.find(n=>n.is_default))??(s==null?void 0:s[0])??null,...t}}function mgs(){const s=ma(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not signed in");if(n.is_default&&await q.from("marketing_brand_presets").update({is_default:!1}).eq("user_id",s),n.id){const{id:r,...a}=n,{data:i,error:l}=await q.from("marketing_brand_presets").update(a).eq("id",r).eq("user_id",s).select().single();if(l)throw l;return i}else{const{data:r,error:a}=await q.from("marketing_brand_presets").insert({...n,user_id:s}).select().single();if(a)throw a;return r}},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}function pgs(){const s=ma(),t=Ht();return gt({mutationFn:async n=>{const{error:r}=await q.from("marketing_brand_presets").delete().eq("id",n);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}async function fgs(s,t,n){var o;const r=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${n}-${Date.now()}.${r}`,{error:i}=await q.storage.from("marketing-studio-uploads").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=await q.storage.from("marketing-studio-uploads").createSignedUrl(a,60*60*24*365*5);return(l==null?void 0:l.signedUrl)??""}function xgs({preset:s,onSaved:t,onCancel:n}){var _;const r=ma(),a=mgs(),i=pgs(),l=N.useRef(null),o=N.useRef(null),[c,d]=N.useState(null),[u,h]=N.useState({name:(s==null?void 0:s.name)??"My Brand",is_default:(s==null?void 0:s.is_default)??!0,display_name:(s==null?void 0:s.display_name)??"",phone:(s==null?void 0:s.phone)??"",email:(s==null?void 0:s.email)??"",license_number:(s==null?void 0:s.license_number)??"",tagline:(s==null?void 0:s.tagline)??"",website_url:(s==null?void 0:s.website_url)??"",headshot_url:(s==null?void 0:s.headshot_url)??"",brokerage_logo_url:(s==null?void 0:s.brokerage_logo_url)??"",brand_color:(s==null?void 0:s.brand_color)??"#0f172a",accent_color:(s==null?void 0:s.accent_color)??"#3b82f6"});N.useEffect(()=>{s||(async()=>{if(!r)return;const{supabase:v}=await yi(async()=>{const{supabase:b}=await Promise.resolve().then(()=>sOt);return{supabase:b}},void 0),{data:j}=await v.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_id").eq("id",r).maybeSingle();j&&h(b=>({...b,display_name:b.display_name||(j.name??""),email:b.email||(j.email??""),phone:b.phone||(j.phone??""),headshot_url:b.headshot_url||(j.avatar_url??""),website_url:b.website_url||(j.website_url??""),tagline:b.tagline||(j.title??"")}))})()},[r]);const p=async(v,j)=>{if(r){d(v);try{const b=await fgs(r,j,v);h(S=>({...S,[v==="headshot"?"headshot_url":"brokerage_logo_url"]:b}))}catch(b){ae.error(b.message||"Upload failed")}finally{d(null)}}},f=async()=>{try{const v=await a.mutateAsync({id:s==null?void 0:s.id,...u});ae.success("Brand preset saved"),t==null||t(v)}catch(v){ae.error(v.message||"Save failed")}},g=async()=>{s!=null&&s.id&&confirm("Delete this brand preset?")&&(await i.mutateAsync(s.id),ae.success("Preset deleted"),n==null||n())};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Preset name"}),e.jsx(ye,{value:u.name,onChange:v=>h({...u,name:v.target.value}),placeholder:"Personal, Team, Luxury..."})]}),e.jsxs("div",{className:"flex items-end gap-3 pb-1",children:[e.jsx(bn,{checked:u.is_default,onCheckedChange:v=>h({...u,is_default:v})}),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:v=>h({...u,display_name:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:u.phone,onChange:v=>h({...u,phone:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ye,{value:u.email,onChange:v=>h({...u,email:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"License #"}),e.jsx(ye,{value:u.license_number,onChange:v=>h({...u,license_number:v.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Tagline"}),e.jsx(ye,{value:u.tagline,onChange:v=>h({...u,tagline:v.target.value}),placeholder:"Helping families find home"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Website"}),e.jsx(ye,{value:u.website_url,onChange:v=>h({...u,website_url:v.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ra,{className:"h-16 w-16",children:[e.jsx(ni,{src:u.headshot_url||void 0}),e.jsx(aa,{children:((_=u.display_name)==null?void 0:_[0])??"A"})]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var v;return(v=l.current)==null?void 0:v.click()},disabled:c==="headshot",children:[c==="headshot"?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(Na,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",hidden:!0,onChange:v=>{var j;return((j=v.target.files)==null?void 0:j[0])&&p("headshot",v.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 v;return(v=o.current)==null?void 0:v.click()},disabled:c==="logo",children:[c==="logo"?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(Na,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:o,type:"file",accept:"image/*",hidden:!0,onChange:v=>{var j;return((j=v.target.files)==null?void 0:j[0])&&p("logo",v.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:v=>h({...u,brand_color:v.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(ye,{value:u.brand_color,onChange:v=>h({...u,brand_color:v.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:v=>h({...u,accent_color:v.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(ye,{value:u.accent_color,onChange:v=>h({...u,accent_color:v.target.value})})]})]})]}),e.jsxs("div",{className:"flex justify-between pt-2",children:[e.jsx("div",{children:(s==null?void 0:s.id)&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:g,className:"text-destructive",children:[e.jsx(_n,{className:"h-4 w-4 mr-1"})," Delete"]})}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx(B,{variant:"outline",onClick:n,children:"Cancel"}),e.jsxs(B,{onClick:f,disabled:a.isPending,children:[a.isPending&&e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}),"Save preset"]})]})]})]})}function ggs(){const{data:s,isLoading:t}=jU(),[n,r]=N.useState(null);return e.jsx(Ts,{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(Go,{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(Ln,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Hr,{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(Is,{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(fe,{className:"border-dashed",children:e.jsxs(Ee,{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(Is,{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(fe,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-3",style:{background:`linear-gradient(90deg, ${a.brand_color}, ${a.accent_color})`}}),e.jsxs(Mt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:[a.name,a.is_default&&e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(ca,{className:"h-3 w-3"})," Default"]})]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>r(a),children:e.jsx(_a,{className:"h-4 w-4"})})]}),e.jsx(Vn,{children:a.display_name})]}),e.jsxs(Ee,{className:"text-sm text-muted-foreground space-y-1",children:[a.tagline&&e.jsxs("div",{className:"italic",children:['"',a.tagline,'"']}),a.phone&&e.jsx("div",{children:a.phone}),a.email&&e.jsx("div",{children:a.email})]})]},a.id))}),e.jsx(bs,{open:n!==null,onOpenChange:a=>!a&&r(null),children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto w-[calc(100vw-2rem)] sm:w-full",children:[e.jsx(ws,{children:e.jsx(_s,{children:n==="new"?"New brand preset":"Edit brand preset"})}),e.jsx(xgs,{preset:n==="new"?null:n,onSaved:()=>r(null),onCancel:()=>r(null)})]})})]})})}const a3e=[{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"}],ygs=s=>a3e.find(t=>t.id===s)??a3e[0];function vgs(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 bgs({value:s,onChange:t,mediaType:n}){const r=a3e.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(_gs,{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 _gs({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 wgs=Math.PI/180;function jgs(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const eA=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},pa={_global:eA,version:"10.2.5",isBrowser:jgs(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return pa.angleDeg?s*wgs: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 pa.DD.isDragging},isTransforming(){var s,t;return(t=(s=pa.Transformer)===null||s===void 0?void 0:s.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!pa.DD.node},releaseCanvasOnDestroy:!0,document:eA.document,_injectGlobal(s){typeof eA.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),eA.Konva=s}},qu=s=>{pa[s.prototype.getClassName()]=s};pa._injectGlobal(pa);const Ngs=`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"; `,GVe=()=>{if(typeof document>"u")throw new Error(Ngs)};class X0{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 X0(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=vn._getRotation(c.rotation),c}}const kgs="[object Array]",Sgs="[object Number]",Cgs="[object String]",Tgs="[object Boolean]",Egs=Math.PI/180,Ags=180/Math.PI,gF="#",Mgs="",Igs="0",Pgs="Konva warning: ",WVe="Konva error: ",Lgs="rgb(",S2e={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]},Dgs=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let LH=[],yF=null;const Rgs=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(s){setTimeout(s,16)},vn={_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)===kgs},_isNumber(s){return Object.prototype.toString.call(s)===Sgs&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===Cgs},_isBoolean(s){return Object.prototype.toString.call(s)===Tgs},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){LH.push(s),LH.length===1&&Rgs(function(){const t=LH;LH=[],t.forEach(function(n){n()})})},createCanvasElement(){GVe();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return GVe(),document.createElement("img")},_isInDocument(s){for(;s=s.parentNode;)if(s==document)return!0;return!1},_urlToImage(s,t){const n=vn.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(gF,Mgs);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=Igs+s;return gF+s},isCanvasFarblingActive(){if(yF!==null)return yF;if(typeof document>"u")return yF=!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 yF=r,this.releaseCanvas(s),yF},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),gF+this._rgbToHex(s,t,n)},getSnappedHexColor(s){const t=this._hexToRgb(s);return gF+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 S2e?(t=S2e[s],{r:t[0],g:t[1],b:t[2]}):s[0]===gF?this._hexToRgb(s.substring(1)):s.substr(0,4)===Lgs?(t=Dgs.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",vn._namedColorToRBA(s)||vn._hex3ColorToRGBA(s)||vn._hex4ColorToRGBA(s)||vn._hex6ColorToRGBA(s)||vn._hex8ColorToRGBA(s)||vn._rgbColorToRGBA(s)||vn._rgbaColorToRGBA(s)||vn._hslColorToRGBA(s)},_namedColorToRBA(s){const t=S2e[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=vn.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=vn._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+=Fgs+d.join(KVe)+zgs)):(i+=o.property,t||(i+=Vgs+o.val)),i+=Ugs;return i}clearTrace(){this.traceArr=[]}_trace(t){let n=this.traceArr,r;n.push(t),r=n.length,r>=Ggs&&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=YVe.length,r=this.setAttr,a,i;const l=function(o){let c=t[o],d;t[o]=function(){return i=Ogs(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 zl._dragElements.forEach(t=>{s=t.node}),s},_dragElements:new Map,_drag(s){const t=[];zl._dragElements.forEach((n,r)=>{const{node:a}=n,i=a.getStage();i.setPointersPositions(s),n.pointerId===void 0&&(n.pointerId=vn._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=[];zl._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")&&(zl.justDragged=!0,pa._mouseListenClick=!1,pa._touchListenClick=!1,pa._pointerListenClick=!1,n.dragStatus="stopped");const l=n.node.getLayer()||n.node instanceof pa.Stage&&n.node;l&&t.indexOf(l)===-1&&t.push(l)}),t.forEach(n=>{n.draw()})},_endDragAfter(s){zl._dragElements.forEach((t,n)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:s},!0),t.dragStatus!=="dragging"&&zl._dragElements.delete(n)})}};pa.isBrowser&&(window.addEventListener("mouseup",zl._endDragBefore,!0),window.addEventListener("touchend",zl._endDragBefore,!0),window.addEventListener("touchcancel",zl._endDragBefore,!0),window.addEventListener("mousemove",zl._drag),window.addEventListener("touchmove",zl._drag),window.addEventListener("mouseup",zl._endDragAfter,!1),window.addEventListener("touchend",zl._endDragAfter,!1),window.addEventListener("touchcancel",zl._endDragAfter,!1));function rC(s){return vn._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||vn._isBoolean(s)?s:Object.prototype.toString.call(s)}function Lgt(s){return s>255?255:s<0?0:Math.round(s)}function ia(){if(pa.isUnminified)return function(s,t){return vn._isNumber(s)||vn.warn(rC(s)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),s}}function xve(s){if(pa.isUnminified)return function(t,n){let r=vn._isNumber(t),a=vn._isArray(t)&&t.length==s;return!r&&!a&&vn.warn(rC(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array('+s+")"),t}}function IIe(){if(pa.isUnminified)return function(s,t){return vn._isNumber(s)||s==="auto"||vn.warn(rC(s)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),s}}function KM(){if(pa.isUnminified)return function(s,t){return vn._isString(s)||vn.warn(rC(s)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),s}}function Dgt(){if(pa.isUnminified)return function(s,t){const n=vn._isString(s),r=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return n||r||vn.warn(rC(s)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),s}}function Zgs(){if(pa.isUnminified)return function(s,t){const n=Int8Array?Object.getPrototypeOf(Int8Array):null;return n&&s instanceof n||(vn._isArray(s)?s.forEach(function(r){vn._isNumber(r)||vn.warn('"'+t+'" attribute has non numeric element '+r+". Make sure that all elements are numbers.")}):vn.warn(rC(s)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),s}}function Rb(){if(pa.isUnminified)return function(s,t){return s===!0||s===!1||vn.warn(rC(s)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),s}}function Qgs(s){if(pa.isUnminified)return function(t,n){return t==null||vn.isObject(t)||vn.warn(rC(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+s),t}}const vF="get",bF="set",Ds={addGetterSetter(s,t,n,r,a){Ds.addGetter(s,t,n),Ds.addSetter(s,t,r,a),Ds.addOverloadedGetterSetter(s,t)},addGetter(s,t,n){const r=vF+vn._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=bF+vn._capitalize(t);s.prototype[a]||Ds.overWriteSetter(s,t,n,r)},overWriteSetter(s,t,n,r){const a=bF+vn._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=vn._capitalize,o=vF+l(t),c=bF+l(t);s.prototype[o]=function(){const u={};for(let h=0;h{this._setAttr(t+l(p),void 0)}),this._fireChangeEvent(t,h,u),a&&a.call(this),this},Ds.addOverloadedGetterSetter(s,t)},addOverloadedGetterSetter(s,t){const n=vn._capitalize(t),r=bF+n,a=vF+n;s.prototype[t]=function(){return arguments.length?(this[r](arguments[0]),this):this[a]()}},addDeprecatedGetterSetter(s,t,n,r){vn.error("Adding deprecated "+t);const a=vF+vn._capitalize(t),i=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";s.prototype[a]=function(){vn.error(i);const l=this.attrs[t];return l===void 0?n:l},Ds.addSetter(s,t,r,function(){vn.error(i)}),Ds.addOverloadedGetterSetter(s,t)},backCompat(s,t){vn.each(t,function(n,r){const a=s.prototype[r],i=vF+vn._capitalize(n),l=bF+vn._capitalize(n);function o(){a.apply(this,arguments),vn.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 Xgs(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=pa.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=pa.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=pa.Filters;c&&c.Contrast&&c.Contrast.call(this,l)}}case"grayscale":return function(i){const l=pa.Filters;l&&l.Grayscale&&l.Grayscale.call(this,i)};case"sepia":return function(i){const l=pa.Filters;l&&l.Sepia&&l.Sepia.call(this,i)};case"invert":return function(i){const l=pa.Filters;l&&l.Invert&&l.Invert.call(this,i)};default:vn.warn(`CSS filter "${r}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const epe="absoluteOpacity",QVe="allEventListeners",y2="absoluteTransform",XVe="absoluteScale",h3="canvas",Jgs="Change",e0s="children",t0s="konva",i3e="listening",s0s="mouseenter",n0s="mouseleave",r0s="pointerenter",a0s="pointerleave",i0s="touchenter",o0s="touchleave",JVe="set",eHe="Shape",tpe=" ",tHe="stage",Vk="transform",l0s="Stage",o3e="visible",c0s=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(tpe);let d0s=1,ba=class y7{constructor(t){this._id=d0s++,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===Vk||t===y2)&&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===Vk||t===y2)&&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(tpe);this.on(a,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,r)}_getCanvasCache(){return this._cache.get(h3)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===y2&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(h3)){const{scene:t,filter:n,hit:r}=this._cache.get(h3);vn.releaseCanvas(t._canvas,n._canvas,r._canvas),this._cache.delete(h3)}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){vn.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const p=Math.abs(Math.round(r.x)-o)>.5?1:0,f=Math.abs(Math.round(r.y)-c)>.5?1:0;a+=d*2+p,i+=d*2+f,o-=d,c-=d;const g=new fS({pixelRatio:l,width:a,height:i}),_=new fS({pixelRatio:l,width:0,height:0,willReadFrequently:!0}),v=new MIe({pixelRatio:h,width:a,height:i}),j=g.getContext(),b=v.getContext(),S=new fS({width:g.width/g.pixelRatio+Math.abs(o),height:g.height/g.pixelRatio+Math.abs(c),pixelRatio:g.pixelRatio}),A=S.getContext();return v.isCache=!0,g.isCache=!0,this._cache.delete(h3),this._filterUpToDate=!1,n.imageSmoothingEnabled===!1&&(g.getContext()._context.imageSmoothingEnabled=!1,_.getContext()._context.imageSmoothingEnabled=!1),j.save(),b.save(),A.save(),j.translate(-o,-c),b.translate(-o,-c),A.translate(-o,-c),S.x=o,S.y=c,this._isUnderCache=!0,this._clearSelfAndDescendantCache(epe),this._clearSelfAndDescendantCache(XVe),this.drawScene(g,this,S),this.drawHit(v,this),this._isUnderCache=!1,j.restore(),b.restore(),u&&(j.save(),j.beginPath(),j.rect(0,0,a,i),j.closePath(),j.setAttr("strokeStyle","red"),j.setAttr("lineWidth",5),j.stroke(),j.restore()),vn.releaseCanvas(S._canvas),this._cache.set(h3,{scene:g,filter:_,hit:v,x:o,y:c}),this._requestDraw(),this}isCached(){return this._cache.has(h3)}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 p=0;p{this.isAncestorOf(t.node)&&zl._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(y2),this._clearSelfAndDescendantCache(epe),this._clearSelfAndDescendantCache(XVe),this._clearSelfAndDescendantCache(tHe),this._clearSelfAndDescendantCache(o3e),this._clearSelfAndDescendantCache(i3e)}_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"+vn._capitalize(t);return vn._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!==e0s&&(r=JVe+vn._capitalize(n),vn._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(i3e,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(o3e,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;zl._dragElements.forEach(l=>{l.dragStatus==="dragging"&&(l.node.nodeType==="Stage"||l.node.getLayer()===r)&&(a=!0)});const i=!n&&!pa.hitOnDragEnabled&&(a||pa.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!==l0s&&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(Vk),this._clearSelfAndDescendantCache(y2)),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 X0,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(Vk);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(Vk),this._clearSelfAndDescendantCache(y2),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 vn.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 vn.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&vn.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(epe,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=vn.isObject(r)&&!vn._isPlainObject(r)&&!vn._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 vn._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,vn._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():pa.dragDistance}_off(t,n,r){let a=this.eventListeners[t],i,l,o;for(i=0;i=0)||this.isDragging())return;let a=!1;zl._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=zl._dragElements.get(this._id),r=n&&n.dragStatus==="dragging",a=n&&n.dragStatus==="ready";r?this.stopDrag():a&&zl._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 vn.haveIntersection(r,this.getClientRect())}static create(t,n){return vn._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=y7.prototype.getClassName.call(t),a=t.children,i,l,o;n&&(t.attrs.container=n),pa[r]||(vn.warn('Can not find a node with class name "'+r+'". Fallback to "Shape".'),r="Shape");const c=pa[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=ba.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=ba.prototype.clone.call(this,t);return this.getChildren().forEach(function(r){n.add(r.clone())}),n}getAllIntersections(t){const n=[];return this.find("Shape").forEach(r=>{r.isVisible()&&r.intersects(t)&&n.push(r)}),n}_clearSelfAndDescendantCache(t){var n;super._clearSelfAndDescendantCache(t),!this.isCached()&&((n=this.children)===null||n===void 0||n.forEach(function(r){r._clearSelfAndDescendantCache(t)}))}_setChildrenIndices(){var t;(t=this.children)===null||t===void 0||t.forEach(function(n,r){n.index=r}),this._requestDraw()}drawScene(t,n,r){const a=this.getLayer(),i=t||a&&a.getCanvas(),l=i&&i.getContext(),o=this._getCanvasCache(),c=o&&o.scene,d=i&&i.isCache;if(!this.isVisible()&&!d)return this;if(c){l.save();const u=this.getAbsoluteTransform(n).getMatrix();l.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(l),l.restore()}else this._drawChildren("drawScene",i,n,r);return this}drawHit(t,n){if(!this.shouldDrawHit(n))return this;const r=this.getLayer(),a=t||r&&r.hitCanvas,i=a&&a.getContext(),l=this._getCanvasCache();if(l&&l.hit){i.save();const c=this.getAbsoluteTransform(n).getMatrix();i.transform(c[0],c[1],c[2],c[3],c[4],c[5]),this._drawCachedHitCanvas(i),i.restore()}else this._drawChildren("drawHit",a,n);return this}_drawChildren(t,n,r,a){var i;const l=n&&n.getContext(),o=this.clipWidth(),c=this.clipHeight(),d=this.clipFunc(),u=typeof o=="number"&&typeof c=="number"||d,h=r===this;if(u){l.save();const f=this.getAbsoluteTransform(r);let g=f.getMatrix();l.transform(g[0],g[1],g[2],g[3],g[4],g[5]),l.beginPath();let _;if(d)_=d.call(this,l,this);else{const v=this.clipX(),j=this.clipY();l.rect(v||0,j||0,o,c)}l.clip.apply(l,_),g=f.copy().invert().getMatrix(),l.transform(g[0],g[1],g[2],g[3],g[4],g[5])}const p=!h&&this.globalCompositeOperation()!=="source-over"&&t==="drawScene";p&&(l.save(),l._applyGlobalCompositeOperation(this)),(i=this.children)===null||i===void 0||i.forEach(function(f){f[t](n,r,a)}),p&&l.restore(),u&&l.restore()}getClientRect(t={}){var n;const r=t.skipTransform,a=t.relativeTo;let i,l,o,c,d={x:1/0,y:1/0,width:0,height:0};const u=this;(n=this.children)===null||n===void 0||n.forEach(function(f){if(!f.visible())return;const g=f.getClientRect({relativeTo:u,skipShadow:t.skipShadow,skipStroke:t.skipStroke});g.width===0&&g.height===0||(i===void 0?(i=g.x,l=g.y,o=g.x+g.width,c=g.y+g.height):(i=Math.min(i,g.x),l=Math.min(l,g.y),o=Math.max(o,g.x+g.width),c=Math.max(c,g.y+g.height)))});const h=this.find("Shape");let p=!1;for(let f=0;fs.indexOf("pointer")>=0?"pointer":s.indexOf("touch")>=0?"touch":"mouse",TI=s=>{const t=j7(s);if(t==="pointer")return pa.pointerEventsEnabled&&T2e.pointer;if(t==="touch")return T2e.touch;if(t==="mouse")return T2e.mouse};function nHe(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&vn.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const g0s="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);",fz=[];let gve=class extends my{constructor(t){super(nHe(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),fz.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{nHe(this.attrs)}),this._checkVisibility()}_validateAdd(t){const n=t.getType()==="Layer",r=t.getType()==="FastLayer";n||r||vn.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===h0s){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&&fz.splice(n,1),vn.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}:(vn.warn(g0s),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 fS({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+sHe,this.content.style.height=n+sHe),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;af0s&&vn.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(),pa.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return Ogt(t,this)}setPointerCapture(t){Fgt(t,this)}releaseCapture(t){pz(t)}getLayers(){return this.children}_bindContentEvents(){pa.isBrowser&&x0s.forEach(([t,n])=>{this.content.addEventListener(t,r=>{this[n](r)},{passive:!1})})}_pointerenter(t){this.setPointersPositions(t);const n=TI(t.type);n&&this._fire(n.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const n=TI(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=TI(t.type),r=j7(t.type);if(!n)return;this.setPointersPositions(t);const a=this._getTargetShape(r),i=!(pa.isDragging()||pa.isTransforming())||pa.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=TI(t.type),r=j7(t.type);if(!n)return;this.setPointersPositions(t);let a=!1;this._changedPointerPositions.forEach(i=>{const l=this.getIntersection(i);if(zl.justDragged=!1,pa["_"+r+"ListenClick"]=!0,!l||!l.isListening()){this[r+"ClickStartShape"]=void 0;return}pa.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=TI(t.type),r=j7(t.type);if(!n)return;const a=t.type.indexOf("touch")>=0||t.pointerType==="touch";if(pa.isDragging()&&zl.node.preventDefault()&&t.cancelable&&a&&t.preventDefault(),this.setPointersPositions(t),!(!(pa.isDragging()||pa.isTransforming())||pa.hitOnDragEnabled))return;const l={};let o=!1;const c=this._getTargetShape(r);this._changedPointerPositions.forEach(d=>{const u=C2e(d.id)||this.getIntersection(d),h=d.id,p={evt:t,pointerId:h},f=c!==u;if(f&&c&&(c._fireAndBubble(n.pointerout,{...p},u),c._fireAndBubble(n.pointerleave,{...p},u)),u){if(l[u._id])return;l[u._id]=!0}u&&u.isListening()?(o=!0,f&&(u._fireAndBubble(n.pointerover,{...p},c),u._fireAndBubble(n.pointerenter,{...p},c),this[r+"targetShape"]=u),u._fireAndBubble(n.pointermove,{...p})):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=TI(t.type),r=j7(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=C2e(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 p=!1;pa["_"+r+"InDblClickWindow"]?(p=!0,clearTimeout(this[r+"DblTimeout"])):zl.justDragged||(pa["_"+r+"InDblClickWindow"]=!0,clearTimeout(this[r+"DblTimeout"])),this[r+"DblTimeout"]=setTimeout(function(){pa["_"+r+"InDblClickWindow"]=!1},pa.dblClickWindow),d&&d.isListening()?(o=!0,this[r+"ClickEndShape"]=d,d._fireAndBubble(n.pointerup,{...h}),pa["_"+r+"ListenClick"]&&a&&a===d&&(d._fireAndBubble(n.pointerclick,{...h}),p&&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),pa["_"+r+"ListenClick"]&&this._fire(n.pointerclick,{evt:t,target:this,currentTarget:this,pointerId:u}),p&&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}),pa["_"+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(l3e,{evt:t}):this._fire(l3e,{evt:t,target:this,currentTarget:this})}_wheel(t){this.setPointersPositions(t);const n=this.getIntersection(this.getPointerPosition());n&&n.isListening()?n._fireAndBubble(c3e,{evt:t}):this._fire(c3e,{evt:t,target:this,currentTarget:this})}_pointercancel(t){this.setPointersPositions(t);const n=C2e(t.pointerId)||this.getIntersection(this.getPointerPosition());n&&n._fireAndBubble(IP,PIe(t)),pz(t.pointerId)}_lostpointercapture(t){pz(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:vn._getFirstPointerId(t)}],this._changedPointerPositions=[{x:r,y:a,id:vn._getFirstPointerId(t)}])}_setPointerPosition(t){vn.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 fS({width:this.width(),height:this.height()}),this.bufferHitCanvas=new MIe({pixelRatio:1,width:this.width(),height:this.height()}),!pa.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 vn.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}};gve.prototype.nodeType=u0s;qu(gve);Ds.addGetterSetter(gve,"container");pa.isBrowser&&document.addEventListener("visibilitychange",()=>{fz.forEach(s=>{s.batchDraw()})});const Ygt="hasShadow",Zgt="shadowRGBA",Qgt="patternImage",Xgt="linearGradient",Jgt="radialGradient";let BH;function E2e(){return BH||(BH=vn.createCanvasElement().getContext("2d"),BH)}const xz={};function y0s(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function v0s(s){s.stroke()}function b0s(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function _0s(s){s.stroke()}function w0s(){this._clearCache(Ygt)}function j0s(){this._clearCache(Zgt)}function N0s(){this._clearCache(Qgt)}function k0s(){this._clearCache(Xgt)}function S0s(){this._clearCache(Jgt)}let Yr=class extends ba{constructor(t){super(t);let n,r=0;for(;n=vn.getHitColor(),!(n&&!(n in xz));)if(r++,r>=1e4){vn.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=vn.getRandomColor();break}this.colorKey=n,xz[n]=this}getContext(){return vn.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return vn.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(Ygt,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(Qgt,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const n=E2e().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(n&&n.setTransform){const r=new X0;r.translate(this.fillPatternX(),this.fillPatternY()),r.rotate(pa.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(Xgt,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const n=E2e(),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 ba.prototype.destroy.call(this),delete xz[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){vn.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(),p=h?this.shadowOffsetX():0,f=h?this.shadowOffsetY():0,g=d+Math.abs(p),_=u+Math.abs(f),v=h&&this.shadowBlur()||0,j=g+v*2,b=_+v*2,S={width:j,height:b,x:-(c/2+v)+Math.min(p,0)+l.x,y:-(c/2+v)+Math.min(f,0)+l.y};return a?S:this._transformedRect(S,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,p=n===this;if(!this.isVisible()&&!p)return this;if(o){l.save();const f=this.getAbsoluteTransform(n).getMatrix();return l.transform(f[0],f[1],f[2],f[3],f[4],f[5]),this._drawCachedSceneCanvas(l),l.restore(),this}if(!c)return this;if(l.save(),this._useBufferCanvas()&&!h){u=this.getStage();const f=r||u.bufferCanvas,g=f.getContext();r?(g.save(),g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,f.width,f.height),g.restore()):g.clear(),g.save(),g._applyLineJoin(this),g._applyMiterLimit(this);const _=this.getAbsoluteTransform(n).getMatrix();g.transform(_[0],_[1],_[2],_[3],_[4],_[5]),c.call(this,g,this),g.restore();const v=f.pixelRatio;d&&l._applyShadow(this),p||(l._applyOpacity(this),l._applyGlobalCompositeOperation(this)),l.drawImage(f._canvas,f.x||0,f.y||0,f.width/v,f.height/v)}else{if(l._applyLineJoin(this),l._applyMiterLimit(this),!p){const f=this.getAbsoluteTransform(n).getMatrix();l.transform(f[0],f[1],f[2],f[3],f[4],f[5]),l._applyOpacity(this),l._applyGlobalCompositeOperation(this)}d&&l._applyShadow(this),c.call(this,l,this)}return l.restore(),this}drawHit(t,n,r=!1){if(!this.shouldDrawHit(n,r))return this;const a=this.getLayer(),i=t||a.hitCanvas,l=i&&i.getContext(),o=this.hitFunc()||this.sceneFunc(),c=this._getCanvasCache(),d=c&&c.hit;if(this.colorKey||vn.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=vn._hexToRgb(this.colorKey);for(let p=0;pt?(d[p]=h.r,d[p+1]=h.g,d[p+2]=h.b,d[p+3]=255):d[p+3]=0;i.putImageData(c,0,0)}catch(c){vn.error("Unable to draw hit graph from cached scene canvas. "+c.message)}return this}hasPointerCapture(t){return Ogt(t,this)}setPointerCapture(t){Fgt(t,this)}releaseCapture(t){pz(t)}};Yr.prototype._fillFunc=y0s;Yr.prototype._strokeFunc=v0s;Yr.prototype._fillFuncHit=b0s;Yr.prototype._strokeFuncHit=_0s;Yr.prototype._centroid=!1;Yr.prototype.nodeType="Shape";qu(Yr);Yr.prototype.eventListeners={};Yr.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",w0s);Yr.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",j0s);Yr.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",N0s);Yr.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",k0s);Yr.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",S0s);Ds.addGetterSetter(Yr,"stroke",void 0,Dgt());Ds.addGetterSetter(Yr,"strokeWidth",2,ia());Ds.addGetterSetter(Yr,"fillAfterStrokeEnabled",!1);Ds.addGetterSetter(Yr,"hitStrokeWidth","auto",IIe());Ds.addGetterSetter(Yr,"strokeHitEnabled",!0,Rb());Ds.addGetterSetter(Yr,"perfectDrawEnabled",!0,Rb());Ds.addGetterSetter(Yr,"shadowForStrokeEnabled",!0,Rb());Ds.addGetterSetter(Yr,"lineJoin");Ds.addGetterSetter(Yr,"lineCap");Ds.addGetterSetter(Yr,"miterLimit");Ds.addGetterSetter(Yr,"sceneFunc");Ds.addGetterSetter(Yr,"hitFunc");Ds.addGetterSetter(Yr,"dash");Ds.addGetterSetter(Yr,"dashOffset",0,ia());Ds.addGetterSetter(Yr,"shadowColor",void 0,KM());Ds.addGetterSetter(Yr,"shadowBlur",0,ia());Ds.addGetterSetter(Yr,"shadowOpacity",1,ia());Ds.addComponentsGetterSetter(Yr,"shadowOffset",["x","y"]);Ds.addGetterSetter(Yr,"shadowOffsetX",0,ia());Ds.addGetterSetter(Yr,"shadowOffsetY",0,ia());Ds.addGetterSetter(Yr,"fillPatternImage");Ds.addGetterSetter(Yr,"fill",void 0,Dgt());Ds.addGetterSetter(Yr,"fillPatternX",0,ia());Ds.addGetterSetter(Yr,"fillPatternY",0,ia());Ds.addGetterSetter(Yr,"fillLinearGradientColorStops");Ds.addGetterSetter(Yr,"strokeLinearGradientColorStops");Ds.addGetterSetter(Yr,"fillRadialGradientStartRadius",0);Ds.addGetterSetter(Yr,"fillRadialGradientEndRadius",0);Ds.addGetterSetter(Yr,"fillRadialGradientColorStops");Ds.addGetterSetter(Yr,"fillPatternRepeat","repeat");Ds.addGetterSetter(Yr,"fillEnabled",!0);Ds.addGetterSetter(Yr,"strokeEnabled",!0);Ds.addGetterSetter(Yr,"shadowEnabled",!0);Ds.addGetterSetter(Yr,"dashEnabled",!0);Ds.addGetterSetter(Yr,"strokeScaleEnabled",!0);Ds.addGetterSetter(Yr,"fillPriority","color");Ds.addComponentsGetterSetter(Yr,"fillPatternOffset",["x","y"]);Ds.addGetterSetter(Yr,"fillPatternOffsetX",0,ia());Ds.addGetterSetter(Yr,"fillPatternOffsetY",0,ia());Ds.addComponentsGetterSetter(Yr,"fillPatternScale",["x","y"]);Ds.addGetterSetter(Yr,"fillPatternScaleX",1,ia());Ds.addGetterSetter(Yr,"fillPatternScaleY",1,ia());Ds.addComponentsGetterSetter(Yr,"fillLinearGradientStartPoint",["x","y"]);Ds.addComponentsGetterSetter(Yr,"strokeLinearGradientStartPoint",["x","y"]);Ds.addGetterSetter(Yr,"fillLinearGradientStartPointX",0);Ds.addGetterSetter(Yr,"strokeLinearGradientStartPointX",0);Ds.addGetterSetter(Yr,"fillLinearGradientStartPointY",0);Ds.addGetterSetter(Yr,"strokeLinearGradientStartPointY",0);Ds.addComponentsGetterSetter(Yr,"fillLinearGradientEndPoint",["x","y"]);Ds.addComponentsGetterSetter(Yr,"strokeLinearGradientEndPoint",["x","y"]);Ds.addGetterSetter(Yr,"fillLinearGradientEndPointX",0);Ds.addGetterSetter(Yr,"strokeLinearGradientEndPointX",0);Ds.addGetterSetter(Yr,"fillLinearGradientEndPointY",0);Ds.addGetterSetter(Yr,"strokeLinearGradientEndPointY",0);Ds.addComponentsGetterSetter(Yr,"fillRadialGradientStartPoint",["x","y"]);Ds.addGetterSetter(Yr,"fillRadialGradientStartPointX",0);Ds.addGetterSetter(Yr,"fillRadialGradientStartPointY",0);Ds.addComponentsGetterSetter(Yr,"fillRadialGradientEndPoint",["x","y"]);Ds.addGetterSetter(Yr,"fillRadialGradientEndPointX",0);Ds.addGetterSetter(Yr,"fillRadialGradientEndPointY",0);Ds.addGetterSetter(Yr,"fillPatternRotation",0);Ds.addGetterSetter(Yr,"fillRule",void 0,KM());Ds.backCompat(Yr,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const C0s="beforeDraw",T0s="draw",e0t=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],E0s=e0t.length;let YM=class extends my{constructor(t){super(t),this.canvas=new fS,this.hitCanvas=new MIe({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(C0s,{node:this}),this.clearBeforeDraw()&&i.getContext().clear(),my.prototype.drawScene.call(this,i,n,r),this._fire(T0s,{node:this}),this}drawHit(t,n){const r=this.getLayer(),a=t||r&&r.hitCanvas;return r&&r.clearBeforeDraw()&&r.getHitCanvas().getContext().clear(),my.prototype.drawHit.call(this,a,n),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){vn.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return vn.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 vn.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};YM.prototype.nodeType="Layer";qu(YM);Ds.addGetterSetter(YM,"imageSmoothingEnabled",!0);Ds.addGetterSetter(YM,"clearBeforeDraw",!0);Ds.addGetterSetter(YM,"hitGraphEnabled",!0,Rb());class LIe extends YM{constructor(t){super(t),this.listening(!1),vn.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}LIe.prototype.nodeType="FastLayer";qu(LIe);let L8=class extends my{_validateAdd(t){const n=t.getType();n!=="Group"&&n!=="Shape"&&vn.throw("You may only add groups and shapes to groups.")}};L8.prototype.nodeType="Group";qu(L8);const A2e=function(){return eA.performance&&eA.performance.now?function(){return eA.performance.now()}:function(){return new Date().getTime()}}();class Nv{constructor(t,n){this.id=Nv.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:A2e(),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=rHe,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=aHe,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===rHe?this.setTime(t):this.state===aHe&&this.setTime(this.duration-t)}pause(){this.state=M0s,this.fire("onPause")}getTimer(){return new Date().getTime()}}class gd{constructor(t){const n=this,r=t.node,a=r._id,i=t.easing||gz.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=I0s++;const d=r.getLayer()||(r instanceof pa.Stage?r.getLayers():null);d||vn.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new Nv(function(){n.tween.onEnterFrame()},d),this.tween=new P0s(c,function(u){n._tweenFunc(u)},i,0,1,o*1e3,l),this._addListeners(),gd.attrs[a]||(gd.attrs[a]={}),gd.attrs[a][this._id]||(gd.attrs[a][this._id]={}),gd.tweens[a]||(gd.tweens[a]={});for(c in t)A0s[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=gd.tweens[a][t];u&&delete gd.attrs[a][u][t];let h=r.getAttr(t);if(vn._isArray(n))if(i=[],l=Math.max(n.length,h.length),t==="points"&&n.length!==h.length&&(n.length>h.length?(c=h,h=vn._prepareArrayForTween(h,n,r.closed())):(o=n,n=vn._prepareArrayForTween(n,h,r.closed()))),t.indexOf("fill")===0)for(let p=0;p{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const t=this.node,n=gd.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=gd.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=gd.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const a in r)delete gd.tweens[t][a];delete gd.attrs[t][n],gd.tweens[t]&&(Object.keys(gd.tweens[t]).length===0&&delete gd.tweens[t],Object.keys(gd.attrs[t]).length===0&&delete gd.attrs[t])}}gd.attrs={};gd.tweens={};ba.prototype.to=function(s){const t=s.onFinish;s.node=this,s.onFinish=function(){this.destroy(),t&&t()},new gd(s).play()};const gz={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),p=c*(c>0?n:t);return{x:d,y:r?-1*p:h,width:u-d,height:p-h}}}SN.prototype._centroid=!0;SN.prototype.className="Arc";SN.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];qu(SN);Ds.addGetterSetter(SN,"innerRadius",0,ia());Ds.addGetterSetter(SN,"outerRadius",0,ia());Ds.addGetterSetter(SN,"angle",0,ia());Ds.addGetterSetter(SN,"clockwise",!1,Rb());function d3e(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),p=r-d*(i-t),f=n+u*(a-s),g=r+u*(i-t);return[h,p,f,g]}function oHe(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 CN=class extends Yr{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*D0s[20][o]+l,r+=R0s[20][o]*F0s(s,t,a);return l*r},cHe=(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,p=n+u,f=h-u*u,g=p*p+f>0?Math.sqrt(p*p+f):0,_=u*u+f>0?Math.sqrt(u*u+f):0,v=u+Math.sqrt(u*u+f)!==0?f*Math.log(Math.abs((p+g)/(u+_))):0;return Math.sqrt(o)/2*(p*g-u*_+v)};function F0s(s,t,n){const r=u3e(1,n,s),a=u3e(1,n,t),i=r*r+a*a;return Math.sqrt(i)}const u3e=(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+=O0s[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 kv=class Sg extends Yr{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=Sg.parsePathData(this.data()),this.pathLength=Sg.getPathLength(this.dataArray)}_sceneFunc(t){const n=this.dataArray;t.beginPath();let r=!1;for(let a=0;au?d:u,v=d>u?1:d/u,j=d>u?u/d:1;t.translate(o,c),t.rotate(f),t.scale(v,j),t.arc(0,0,_,h,h+p,1-g),t.scale(1/v,1/j),t.rotate(-f),t.translate(-o,-c);break;case"z":r=!0,t.closePath();break}}!r&&!this.hasFill()?t.strokeShape(this):t.fillStrokeShape(this)}getSelfRect(){let t=[];this.dataArray.forEach(function(c){if(c.command==="A"){const d=c.points[4],u=c.points[5],h=c.points[4]+u;let p=Math.PI/180;if(Math.abs(d-h)h;f-=p){const g=Sg.getPointOnEllipticalArc(c.points[0],c.points[1],c.points[2],c.points[3],f,0);t.push(g.x,g.y)}else for(let f=d+p;fn[a].pathLength;)t-=n[a].pathLength,++a;if(a===i)return r=n[a-1].points.slice(-2),{x:r[0],y:r[1]};if(t<.01)return n[a].command==="M"?(r=n[a].points.slice(0,2),{x:r[0],y:r[1]}):{x:n[a].start.x,y:n[a].start.y};const l=n[a],o=l.points;switch(l.command){case"L":return Sg.getPointOnLine(t,l.start.x,l.start.y,o[0],o[1]);case"C":return Sg.getPointOnCubicBezier(dHe(t,Sg.getPathLength(n),_=>lHe([l.start.x,o[0],o[2],o[4]],[l.start.y,o[1],o[3],o[5]],_)),l.start.x,l.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return Sg.getPointOnQuadraticBezier(dHe(t,Sg.getPathLength(n),_=>cHe([l.start.x,o[0],o[2]],[l.start.y,o[1],o[3]],_)),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],p=o[5],f=o[6];let g=o[4];return g+=p*t/l.pathLength,Sg.getPointOnEllipticalArc(c,d,u,h,g,f)}return null}static getPointOnLine(t,n,r,a,i,l,o){l=l??n,o=o??r;const c=this.getLineLength(n,r,a,i);if(c<1e-10)return{x:n,y:r};if(a===n)return{x:l,y:o+(i>r?t:-t)};const d=(i-r)/(a-n),u=Math.sqrt(t*t/(1+d*d))*(a=0&&(_+=2,_>=7&&(_-=7));continue}if(_>=0){if(_===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(b)){g.push(parseInt(b[0],10)),g.push(parseInt(b[1],10)),g.push(parseFloat(b.slice(2))),_+=3,_>=7&&(_-=7);continue}if(b==="11"||b==="10"||b==="01"){g.push(parseInt(b[0],10)),g.push(parseInt(b[1],10)),_+=2,_>=7&&(_-=7);continue}if(b==="0"||b==="1"){g.push(parseInt(b,10)),_+=1,_>=7&&(_-=7);continue}}else if(_===4){if(/^[01]\d+(?:\.\d+)?$/.test(b)){g.push(parseInt(b[0],10)),g.push(parseFloat(b.slice(1))),_+=2,_>=7&&(_-=7);continue}if(b==="0"||b==="1"){g.push(parseInt(b,10)),_+=1,_>=7&&(_-=7);continue}}const S=parseFloat(b);isNaN(S)?g.push(0):g.push(S),_+=1,_>=7&&(_-=7)}else{const S=parseFloat(b);isNaN(S)?g.push(0):g.push(S)}}for(;g.length>0&&!isNaN(g[0]);){let v="",j=[];const b=o,S=c;let A,T,L,D,M,F,z,V,W,Y;switch(f){case"l":o+=g.shift(),c+=g.shift(),v="L",j.push(o,c);break;case"L":o=g.shift(),c=g.shift(),j.push(o,c);break;case"m":const K=g.shift(),J=g.shift();if(o+=K,c+=J,v="M",i.length>2&&i[i.length-1].command==="z"){for(let ne=i.length-2;ne>=0;ne--)if(i[ne].command==="M"){o=i[ne].points[0]+K,c=i[ne].points[1]+J;break}}j.push(o,c),f="l";break;case"M":o=g.shift(),c=g.shift(),v="M",j.push(o,c),f="L";break;case"h":o+=g.shift(),v="L",j.push(o,c);break;case"H":o=g.shift(),v="L",j.push(o,c);break;case"v":c+=g.shift(),v="L",j.push(o,c);break;case"V":c=g.shift(),v="L",j.push(o,c);break;case"C":j.push(g.shift(),g.shift(),g.shift(),g.shift()),o=g.shift(),c=g.shift(),j.push(o,c);break;case"c":j.push(o+g.shift(),c+g.shift(),o+g.shift(),c+g.shift()),o+=g.shift(),c+=g.shift(),v="C",j.push(o,c);break;case"S":T=o,L=c,A=i[i.length-1],A.command==="C"&&(T=o+(o-A.points[2]),L=c+(c-A.points[3])),j.push(T,L,g.shift(),g.shift()),o=g.shift(),c=g.shift(),v="C",j.push(o,c);break;case"s":T=o,L=c,A=i[i.length-1],A.command==="C"&&(T=o+(o-A.points[2]),L=c+(c-A.points[3])),j.push(T,L,o+g.shift(),c+g.shift()),o+=g.shift(),c+=g.shift(),v="C",j.push(o,c);break;case"Q":j.push(g.shift(),g.shift()),o=g.shift(),c=g.shift(),j.push(o,c);break;case"q":j.push(o+g.shift(),c+g.shift()),o+=g.shift(),c+=g.shift(),v="Q",j.push(o,c);break;case"T":T=o,L=c,A=i[i.length-1],A.command==="Q"&&(T=o+(o-A.points[0]),L=c+(c-A.points[1])),o=g.shift(),c=g.shift(),v="Q",j.push(T,L,o,c);break;case"t":T=o,L=c,A=i[i.length-1],A.command==="Q"&&(T=o+(o-A.points[0]),L=c+(c-A.points[1])),o+=g.shift(),c+=g.shift(),v="Q",j.push(T,L,o,c);break;case"A":D=g.shift(),M=g.shift(),F=g.shift(),z=g.shift(),V=g.shift(),W=o,Y=c,o=g.shift(),c=g.shift(),v="A",j=this.convertEndpointToCenterParameterization(W,Y,o,c,z,V,D,M,F);break;case"a":D=g.shift(),M=g.shift(),F=g.shift(),z=g.shift(),V=g.shift(),W=o,Y=c,o+=g.shift(),c+=g.shift(),v="A",j=this.convertEndpointToCenterParameterization(W,Y,o,c,z,V,D,M,F);break}i.push({command:v||f,points:j,start:{x:b,y:S},pathLength:this.calcLength(b,S,v||f,j)})}(f==="z"||f==="Z")&&i.push({command:"z",points:[],start:void 0,pathLength:0})}return i}static calcLength(t,n,r,a){let i,l,o,c;const d=Sg;switch(r){case"L":return d.getLineLength(t,n,a[0],a[1]);case"C":return lHe([t,a[0],a[2],a[4]],[n,a[1],a[3],a[5]],1);case"Q":return cHe([t,a[0],a[2]],[n,a[1],a[3]],1);case"A":i=0;const u=a[4],h=a[5],p=a[4]+h;let f=Math.PI/180;if(Math.abs(u-p)p;c-=f)o=d.getPointOnEllipticalArc(a[0],a[1],a[2],a[3],c,0),i+=d.getLineLength(l.x,l.y,o.x,o.y),l=o;else for(c=u+f;c1&&(o*=Math.sqrt(f),c*=Math.sqrt(f));let g=Math.sqrt((o*o*(c*c)-o*o*(p*p)-c*c*(h*h))/(o*o*(p*p)+c*c*(h*h)));i===l&&(g*=-1),isNaN(g)&&(g=0);const _=g*o*p/c,v=g*-c*h/o,j=(t+r)/2+Math.cos(u)*_-Math.sin(u)*v,b=(n+a)/2+Math.sin(u)*_+Math.cos(u)*v,S=function(z){return Math.sqrt(z[0]*z[0]+z[1]*z[1])},A=function(z,V){return(z[0]*V[0]+z[1]*V[1])/(S(z)*S(V))},T=function(z,V){return(z[0]*V[1]=1&&(F=0),l===0&&F>0&&(F=F-2*Math.PI),l===1&&F<0&&(F=F+2*Math.PI),[j,b,o,c,L,F,u,l]}};kv.prototype.className="Path";kv.prototype._attrsAffectingSize=["data"];qu(kv);Ds.addGetterSetter(kv,"data");class ZM extends CN{_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 p=[a[a.length-4],a[a.length-3],a[a.length-2],a[a.length-1],r[o-2],r[o-1]],f=kv.calcLength(a[a.length-4],a[a.length-3],"C",p),g=kv.getPointOnQuadraticBezier(Math.min(1,1-l/f),p[0],p[1],p[2],p[3],p[4],p[5]);c=r[o-2]-g.x,d=r[o-1]-g.y}else c=r[o-2]-r[o-4],d=r[o-1]-r[o-3];const u=(Math.atan2(d,c)+n)%n,h=this.pointerWidth();this.pointerAtEnding()&&(t.save(),t.beginPath(),t.translate(r[o-2],r[o-1]),t.rotate(u),t.moveTo(0,0),t.lineTo(-l,h/2),t.lineTo(-l,-h/2),t.closePath(),t.restore(),this.__fillStroke(t)),this.pointerAtBeginning()&&(t.save(),t.beginPath(),t.translate(r[0],r[1]),i?(c=(a[0]+a[2])/2-r[0],d=(a[1]+a[3])/2-r[1]):(c=r[2]-r[0],d=r[3]-r[1]),t.rotate((Math.atan2(-d,-c)+n)%n),t.moveTo(0,0),t.lineTo(-l,h/2),t.lineTo(-l,-h/2),t.closePath(),t.restore(),this.__fillStroke(t))}__fillStroke(t){const n=this.dashEnabled();n&&(this.attrs.dashEnabled=!1,t.setLineDash([])),t.fillStrokeShape(this),n&&(this.attrs.dashEnabled=!0)}getSelfRect(){const t=super.getSelfRect(),n=this.pointerWidth()/2;return{x:t.x,y:t.y-n,width:t.width,height:t.height+n*2}}}ZM.prototype.className="Arrow";qu(ZM);Ds.addGetterSetter(ZM,"pointerLength",10,ia());Ds.addGetterSetter(ZM,"pointerWidth",10,ia());Ds.addGetterSetter(ZM,"pointerAtBeginning",!1);Ds.addGetterSetter(ZM,"pointerAtEnding",!0);class JD extends Yr{_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)}}JD.prototype._centroid=!0;JD.prototype.className="Circle";JD.prototype._attrsAffectingSize=["radius"];qu(JD);Ds.addGetterSetter(JD,"radius",0,ia());class aC extends Yr{_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)}}aC.prototype.className="Ellipse";aC.prototype._centroid=!0;aC.prototype._attrsAffectingSize=["radiusX","radiusY"];qu(aC);Ds.addComponentsGetterSetter(aC,"radius",["x","y"]);Ds.addGetterSetter(aC,"radiusX",0,ia());Ds.addGetterSetter(aC,"radiusY",0,ia());let Ob=class t0t extends Yr{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?vn.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?vn.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=vn.createImageElement();a.onload=function(){const i=new t0t({image:a});n(i)},a.onerror=r,a.crossOrigin="Anonymous",a.src=t}};Ob.prototype.className="Image";Ob.prototype._attrsAffectingSize=["image"];qu(Ob);Ds.addGetterSetter(Ob,"cornerRadius",0,xve(4));Ds.addGetterSetter(Ob,"image");Ds.addComponentsGetterSetter(Ob,"crop",["x","y","width","height"]);Ds.addGetterSetter(Ob,"cropX",0,ia());Ds.addGetterSetter(Ob,"cropY",0,ia());Ds.addGetterSetter(Ob,"cropWidth",0,ia());Ds.addGetterSetter(Ob,"cropHeight",0,ia());const s0t=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],z0s="Change.konva",B0s="none",h3e="up",m3e="right",p3e="down",f3e="left",$0s=s0t.length;let DIe=class extends L8{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<$0s;r++)t.on(s0t[r]+z0s,a)}getWidth(){return this.getText().width()}getHeight(){return this.getText().height()}_sync(){let t=this.getText(),n=this.getTag(),r,a,i,l,o,c,d;if(t&&n){switch(r=t.width(),a=t.height(),i=n.pointerDirection(),l=n.pointerWidth(),d=n.pointerHeight(),o=0,c=0,i){case h3e:o=r/2,c=-1*d;break;case m3e:o=r+l,c=a/2;break;case p3e:o=r/2,c=a+d;break;case f3e:o=-1*l,c=a/2;break}n.setAttrs({x:-1*o,y:-1*c,width:r,height:a}),t.setAttrs({x:-1*o,y:-1*c})}}};DIe.prototype.className="Label";qu(DIe);class QM extends Yr{_sceneFunc(t){const n=this.width(),r=this.height(),a=this.pointerDirection(),i=this.pointerWidth(),l=this.pointerHeight(),o=this.cornerRadius();let c=0,d=0,u=0,h=0;typeof o=="number"?c=d=u=h=Math.min(o,n/2,r/2):(c=Math.min(o[0]||0,n/2,r/2),d=Math.min(o[1]||0,n/2,r/2),h=Math.min(o[2]||0,n/2,r/2),u=Math.min(o[3]||0,n/2,r/2)),t.beginPath(),t.moveTo(c,0),a===h3e&&(t.lineTo((n-i)/2,0),t.lineTo(n/2,-1*l),t.lineTo((n+i)/2,0)),t.lineTo(n-d,0),t.arc(n-d,d,d,Math.PI*3/2,0,!1),a===m3e&&(t.lineTo(n,(r-l)/2),t.lineTo(n+i,r/2),t.lineTo(n,(r+l)/2)),t.lineTo(n,r-h),t.arc(n-h,r-h,h,0,Math.PI/2,!1),a===p3e&&(t.lineTo((n+i)/2,r),t.lineTo(n/2,r+l),t.lineTo((n-i)/2,r)),t.lineTo(u,r),t.arc(u,r-u,u,Math.PI/2,Math.PI,!1),a===f3e&&(t.lineTo(0,(r+l)/2),t.lineTo(-1*i,r/2),t.lineTo(0,(r-l)/2)),t.lineTo(0,c),t.arc(c,c,c,Math.PI,Math.PI*3/2,!1),t.closePath(),t.fillStrokeShape(this)}getSelfRect(){let t=0,n=0,r=this.pointerWidth(),a=this.pointerHeight(),i=this.pointerDirection(),l=this.width(),o=this.height();return i===h3e?(n-=a,o+=a):i===p3e?o+=a:i===f3e?(t-=r*1.5,l+=r):i===m3e&&(l+=r*1.5),{x:t,y:n,width:l,height:o}}}QM.prototype.className="Tag";qu(QM);Ds.addGetterSetter(QM,"pointerDirection",B0s);Ds.addGetterSetter(QM,"pointerWidth",0,ia());Ds.addGetterSetter(QM,"pointerHeight",0,ia());Ds.addGetterSetter(QM,"cornerRadius",0,xve(4));let NU=class extends Yr{_sceneFunc(t){const n=this.cornerRadius(),r=this.width(),a=this.height();t.beginPath(),n?vn.drawRoundedRectPath(t,r,a,n):t.rect(0,0,r,a),t.closePath(),t.fillStrokeShape(this)}};NU.prototype.className="Rect";qu(NU);Ds.addGetterSetter(NU,"cornerRadius",0,xve(4));class iC extends Yr{_sceneFunc(t){const n=this._getPoints(),r=this.radius(),a=this.sides(),i=this.cornerRadius();if(t.beginPath(),i)vn.drawRoundedPolygonPath(t,n,a,r,i);else{t.moveTo(n[0].x,n[0].y);for(let l=1;l{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)}}iC.prototype.className="RegularPolygon";iC.prototype._centroid=!0;iC.prototype._attrsAffectingSize=["radius"];qu(iC);Ds.addGetterSetter(iC,"radius",0,ia());Ds.addGetterSetter(iC,"sides",0,ia());Ds.addGetterSetter(iC,"cornerRadius",0,xve(4));const uHe=Math.PI*2;let XM=class extends Yr{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,uHe,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),uHe,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)}};XM.prototype.className="Ring";XM.prototype._centroid=!0;XM.prototype._attrsAffectingSize=["innerRadius","outerRadius"];qu(XM);Ds.addGetterSetter(XM,"innerRadius",0,ia());Ds.addGetterSetter(XM,"outerRadius",0,ia());class Xw extends Yr{constructor(t){super(t),this._updated=!0,this.anim=new Nv(()=>{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 p=l[n],f=r*2;t.drawImage(h,o,c,d,u,p[f+0],p[f+1],d,u)}else t.drawImage(h,o,c,d,u,0,0,d,u)}_hitFunc(t){const n=this.animation(),r=this.frameIndex(),a=r*4,i=this.animations()[n],l=this.frameOffsets(),o=i[a+2],c=i[a+3];if(t.beginPath(),l){const d=l[n],u=r*2;t.rect(d[u+0],d[u+1],o,c)}else t.rect(0,0,o,c);t.closePath(),t.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const t=this;this.interval=setInterval(function(){t._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const t=this.getLayer();this.anim.setLayers(t),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const t=this.frameIndex(),n=this.animation(),r=this.animations(),a=r[n],i=a.length/4;t{if(new RegExp("\\p{Emoji}","u").test(n)){const i=a[r+1];i&&new RegExp("\\p{Emoji_Modifier}|\\u200D","u").test(i)?(t.push(n+i),a[r+1]=""):t.push(n)}else new RegExp("\\p{Regional_Indicator}{2}","u").test(n+(a[r+1]||""))?t.push(n+a[r+1]):r>0&&new RegExp("\\p{Mn}|\\p{Me}|\\p{Mc}","u").test(n)?t[t.length-1]+=n:n&&t.push(n);return t},[])}const EI="auto",U0s="center",n0t="inherit",_F="justify",q0s="Change.konva",r0t="2d",hHe="-",a0t="left",V0s="text",H0s="Text",G0s="top",W0s="bottom",mHe="middle",i0t="normal",K0s="px ",$H=" ",Y0s="right",pHe="rtl",Z0s="word",Q0s="char",fHe="none",M2e="…",o0t=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],X0s=o0t.length;let wF=null;function J0s(){if(wF!==null)return wF;wF=!1;try{const s=document.createElement("canvas");s.width=10,s.height=10;const t=s.getContext(r0t);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){wF=!0;break}}}catch{}return wF}function eys(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 UH;function I2e(){return UH||(UH=vn.createCanvasElement().getContext(r0t),UH)}function tys(s){s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function sys(s){s.setAttr("miterLimit",2),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function nys(s){return s=s||{},!s.fillLinearGradientColorStops&&!s.fillRadialGradientColorStops&&!s.fillPatternImage&&(s.fill=s.fill||"black"),s}let Nd=class extends Yr{constructor(t){super(nys(t)),this._partialTextX=0,this._partialTextY=0;for(let n=0;nve+Hk(ge.text).length,0),le=ie+pe;_({char:he,index:le,x:M,y:L+F,lineIndex:T,column:ie,isLastInLine:Y,width:this.measureSize(he).width,context:t})}t.fillStrokeShape(this),_&&t.restore(),M+=this.measureSize(he).width+g}}else g!==0&&t.setAttr("letterSpacing",`${g}px`),this._partialTextX=M,this._partialTextY=L+F,this._partialText=V,t.fillStrokeShape(this);if(A){t.save(),t.beginPath();const J=pa.legacyTextRendering?0:-Math.round(o/4),ne=K;t.moveTo(ne,L+F+J);const ie=p===_F&&!Y?f-l*2:W;t.lineTo(ne+Math.round(ie),L+F+J),t.lineWidth=o/15;const he=this._getLinearGradient();t.strokeStyle=he||v,t.stroke(),t.restore()}t.restore(),i>1&&(L+=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=vn._isString(t)?t:t==null?"":t+"";return this._setAttr(V0s,n),this}getWidth(){return this.attrs.width===EI||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===EI||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return vn.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,p;let f=I2e(),g=this.fontSize(),_;f.save(),f.font=this._getContextFont(),_=f.measureText(t),f.restore();const v=g/100;return{actualBoundingBoxAscent:(n=_.actualBoundingBoxAscent)!==null&&n!==void 0?n:71.58203125*v,actualBoundingBoxDescent:(r=_.actualBoundingBoxDescent)!==null&&r!==void 0?r:0,actualBoundingBoxLeft:(a=_.actualBoundingBoxLeft)!==null&&a!==void 0?a:-7.421875*v,actualBoundingBoxRight:(i=_.actualBoundingBoxRight)!==null&&i!==void 0?i:75.732421875*v,alphabeticBaseline:(l=_.alphabeticBaseline)!==null&&l!==void 0?l:0,emHeightAscent:(o=_.emHeightAscent)!==null&&o!==void 0?o:100*v,emHeightDescent:(c=_.emHeightDescent)!==null&&c!==void 0?c:-20*v,fontBoundingBoxAscent:(d=_.fontBoundingBoxAscent)!==null&&d!==void 0?d:91*v,fontBoundingBoxDescent:(u=_.fontBoundingBoxDescent)!==null&&u!==void 0?u:21*v,hangingBaseline:(h=_.hangingBaseline)!==null&&h!==void 0?h:72.80000305175781*v,ideographicBaseline:(p=_.ideographicBaseline)!==null&&p!==void 0?p:-21*v,width:_.width,height:g}}_getContextFont(){return this.fontStyle()+$H+this.fontVariant()+$H+(this.fontSize()+K0s)+eys(this.fontFamily())}_addTextLine(t){this.align()===_F&&(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 I2e().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!==EI&&i!==void 0,c=l!==EI&&l!==void 0,d=this.padding(),u=i-d*2,h=l-d*2,p=0,f=this.wrap(),g=f!==fHe,_=f!==Q0s&&g,v=this.ellipsis();this.textArr=[],I2e().font=this._getContextFont();const j=v?this._getTextWidth(M2e):0;for(let b=0,S=t.length;bu)for(;A.length>0;){let L=0,D=Hk(A).length,M="",F=0;for(;L>>1,V=Hk(A),W=V.slice(0,z+1).join(""),Y=this._getTextWidth(W);(v&&c&&p+a>h?Y+j:Y)<=u?(L=z+1,M=W,F=Y):D=z}if(M){if(_){const W=Hk(A),Y=Hk(M),K=W[Y.length],J=K===$H||K===hHe;let ne;if(J&&F<=u)ne=Y.length;else{const ie=Y.lastIndexOf($H),he=Y.lastIndexOf(hHe);ne=Math.max(ie,he)+1}ne>0&&(L=ne,M=W.slice(0,L).join(""),F=this._getTextWidth(M))}if(M=M.trimRight(),this._addTextLine(M),r=Math.max(r,F),p+=a,this._shouldHandleEllipsis(p)){this._tryToAddEllipsisToLastLine();break}if(A=Hk(A).slice(L).join("").trimLeft(),A.length>0&&(T=this._getTextWidth(A),T<=u)){this._addTextLine(A),p+=a,r=Math.max(r,T);break}}else break}else this._addTextLine(A),p+=a,r=Math.max(r,T),this._shouldHandleEllipsis(p)&&bh)break}this.textHeight=n,this.textWidth=r}_shouldHandleEllipsis(t){const n=+this.fontSize(),r=this.lineHeight()*n,a=this.attrs.height,i=a!==EI&&a!==void 0,l=this.padding(),o=a-l*2;return!(this.wrap()!==fHe)||i&&t+r>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,n=t!==EI&&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+M2e)n?null:kv.getPointAtLengthOfDataArray(t,this.dataArray)}_readDataAttribute(){this.dataArray=kv.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&&j-this.pathLength<=d?this.pathLength:j);if(!b)return;const S=kv.getLineLength(g.x,g.y,b.x,b.y);let A=0;if(c)try{A=c(n[f-1].char,_)*this.fontSize()}catch{A=0}g.x+=A,b.x+=A,this.textWidth+=A;const T=kv.getPointOnLine(A+S/2,g.x,g.y,b.x,b.y),L=Math.atan2(b.y-g.y,b.x-g.x);this.glyphInfo.push({transposeX:T.x,transposeY:T.y,text:t[f],rotation:L,p0:g,p1:b,width:S}),p+=v}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const t=[];this.glyphInfo.forEach(function(d){t.push(d.p0.x),t.push(d.p0.y),t.push(d.p1.x),t.push(d.p1.y)});let n=t[0]||0,r=t[0]||0,a=t[1]||0,i=t[1]||0,l,o;for(let d=0;ds+`.${u0t}`).join(" "),xHe="nodesRect",iys=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],oys={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},lys="ontouchstart"in pa._global;function cys(s,t,n){if(s==="rotater")return n;t+=vn.degToRad(oys[s]||0);const r=(vn.radToDeg(t)%360+360)%360;return vn._inRange(r,315+22.5,360)||vn._inRange(r,0,22.5)?"ns-resize":vn._inRange(r,45-22.5,45+22.5)?"nesw-resize":vn._inRange(r,90-22.5,90+22.5)?"ew-resize":vn._inRange(r,135-22.5,135+22.5)?"nwse-resize":vn._inRange(r,180-22.5,180+22.5)?"ns-resize":vn._inRange(r,225-22.5,225+22.5)?"nesw-resize":vn._inRange(r,270-22.5,270+22.5)?"ew-resize":vn._inRange(r,315-22.5,315+22.5)?"nwse-resize":(vn.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}const kxe=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],gHe=1e8;function dys(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 h0t(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 uys(s,t){const n=dys(s);return h0t(s,t,n)}function hys(s,t,n){let r=t;for(let a=0;aa.isAncestorOf(this)?(vn.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(iys.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(xHe),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(xHe,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=(pa.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 h0t(u,-pa.getAngle(n),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-gHe,y:-gHe,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}],p=d.getAbsoluteTransform();h.forEach(function(f){const g=p.point(f);n.push(g)})});const r=new X0;r.rotate(-pa.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:pa.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(),kxe.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(t){const n=new NU({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:lys?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=pa.getAngle(this.rotation()),i=this.rotateAnchorCursor(),l=cys(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 Yr({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=vn.degToRad(c),h=Math.sin(u),p=-Math.cos(u),f=l/2,g=o/2;let _=1/0;p<0?_=Math.min(_,-g/p):p>0&&(_=Math.min(_,(o-g)/p)),h<0?_=Math.min(_,-f/h):h>0&&(_=Math.min(_,(l-f)/h));const v=f+h*_,j=g+p*_,b=vn._sign(o),S=v+h*d*b,A=j+p*d*b;n.moveTo(v,j),n.lineTo(S,A)}n.fillStrokeShape(r)},hitFunc:(n,r)=>{if(!this.shouldOverdrawWholeArea())return;const a=this.padding();n.beginPath(),n.rect(-a,-a,r.width()+a*2,r.height()+a*2),n.fillStrokeShape(r)}});this.add(t),this._proxyDrag(t),t.on("dragstart",n=>{n.cancelBubble=!0}),t.on("dragmove",n=>{n.cancelBubble=!0}),t.on("dragend",n=>{n.cancelBubble=!0}),this.on("dragmove",n=>{this.update()})}_handleMouseDown(t){if(this._transforming)return;this._movingAnchorName=t.target.name().split(" ")[0];const n=this._getNodeRect(),r=n.width,a=n.height,i=Math.sqrt(Math.pow(r,2)+Math.pow(a,2));this.sin=Math.abs(a/i),this.cos=Math.abs(r/i),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;const l=t.target.getAbsolutePosition(),o=t.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-l.x,y:o.y-l.y},x3e++,this._fire("transformstart",{evt:t.evt,target:this.getNode()}),this._nodes.forEach(c=>{c._fire("transformstart",{evt:t.evt,target:c})})}_handleMouseMove(t){let n,r,a;const i=this.findOne("."+this._movingAnchorName),l=i.getStage();l.setPointersPositions(t);const o=l.getPointerPosition();let c={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const d=i.getAbsolutePosition();this.anchorDragBoundFunc()&&(c=this.anchorDragBoundFunc()(d,c,t)),i.setAbsolutePosition(c);const u=i.getAbsolutePosition();if(d.x===u.x&&d.y===u.y)return;if(this._movingAnchorName==="rotater"){const b=this._getNodeRect();n=i.x()-b.width/2,r=-i.y()+b.height/2;const S=pa.getAngle(this.rotateAnchorAngle());let A=Math.atan2(-r,n)+Math.PI/2-S;b.height<0&&(A-=Math.PI);const L=pa.getAngle(this.rotation())+A,D=pa.getAngle(this.rotationSnapTolerance()),F=hys(this.rotationSnaps(),L,D)-b.rotation,z=uys(b,F);this._fitNodesInto(z,t);return}const h=this.shiftBehavior();let p;h==="inverted"?p=this.keepRatio()&&!t.shiftKey:h==="none"?p=this.keepRatio():p=this.keepRatio()||t.shiftKey;let f=this.centeredScaling()||t.altKey;if(this._movingAnchorName==="top-left"){if(p){const b=f?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};a=Math.sqrt(Math.pow(b.x-i.x(),2)+Math.pow(b.y-i.y(),2));const S=this.findOne(".top-left").x()>b.x?-1:1,A=this.findOne(".top-left").y()>b.y?-1:1;n=a*this.cos*S,r=a*this.sin*A,this.findOne(".top-left").x(b.x-n),this.findOne(".top-left").y(b.y-r)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(i.y());else if(this._movingAnchorName==="top-right"){if(p){const b=f?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};a=Math.sqrt(Math.pow(i.x()-b.x,2)+Math.pow(b.y-i.y(),2));const S=this.findOne(".top-right").x()b.y?-1:1;n=a*this.cos*S,r=a*this.sin*A,this.findOne(".top-right").x(b.x+n),this.findOne(".top-right").y(b.y-r)}var g=i.position();this.findOne(".top-left").y(g.y),this.findOne(".bottom-right").x(g.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(i.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(i.x());else if(this._movingAnchorName==="bottom-left"){if(p){const b=f?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};a=Math.sqrt(Math.pow(b.x-i.x(),2)+Math.pow(i.y()-b.y,2));const S=b.x{var i;a._fire("transformend",{evt:t,target:a}),(i=a.getLayer())===null||i===void 0||i.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(t,n){const r=this._getNodeRect(),a=1;if(vn._inRange(t.width,-this.padding()*2-a,a)){this.update();return}if(vn._inRange(t.height,-this.padding()*2-a,a)){this.update();return}const i=new X0;if(i.rotate(pa.getAngle(this.rotation())),this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const p=i.point({x:-this.padding()*2,y:0});t.x+=p.x,t.y+=p.y,t.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const p=i.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y,t.width+=this.padding()*2}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const p=i.point({x:0,y:-this.padding()*2});t.x+=p.x,t.y+=p.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y,t.height+=this.padding()*2}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const p=i.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y,t.height+=this.padding()*2}if(this.boundBoxFunc()){const p=this.boundBoxFunc()(r,t);p?t=p:vn.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const l=1e7,o=new X0;o.translate(r.x,r.y),o.rotate(r.rotation),o.scale(r.width/l,r.height/l);const c=new X0,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(p=>{var f;if(!p.getStage())return;const g=p.getParent().getAbsoluteTransform(),_=p.getTransform().copy();_.translate(p.offsetX(),p.offsetY());const v=new X0;v.multiply(g.copy().invert()).multiply(h).multiply(g).multiply(_);const j=v.decompose();p.setAttrs(j),(f=p.getLayer())===null||f===void 0||f.batchDraw()}),this.rotation(vn._getRotation(t.rotation)),this._nodes.forEach(p=>{this._fire("transform",{evt:n,target:p}),p._fire("transform",{evt:n,target:p})}),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(vn._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(L=>{L.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(),p=vn.degToRad(u),f=Math.sin(p),g=-Math.cos(p),_=r/2,v=a/2;let j=1/0;g<0?j=Math.min(j,-v/g):g>0&&(j=Math.min(j,(a-v)/g)),f<0?j=Math.min(j,-_/f):f>0&&(j=Math.min(j,(r-_)/f));const b=_+f*j,S=v+g*j,A=vn._sign(a);this._batchChangeChild(".rotater",{x:b+f*h*A,y:S+g*h*A-o*g,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:r,height:a,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(L=>L.draggable()),x:0,y:0});const T=this.anchorStyleFunc();T&&d.forEach(L=>{T(L)}),(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=""),L8.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...t){return this._elementsCreated?(vn.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...t)}toObject(){return ba.prototype.toObject.call(this)}clone(t){return ba.prototype.clone.call(this,t)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}};jl.isTransforming=()=>x3e>0;function mys(s){return s instanceof Array||vn.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(t){kxe.indexOf(t)===-1&&vn.warn("Unknown anchor name: "+t+". Available names are: "+kxe.join(", "))}),s||[]}jl.prototype.className="Transformer";qu(jl);Ds.addGetterSetter(jl,"enabledAnchors",kxe,mys);Ds.addGetterSetter(jl,"flipEnabled",!0,Rb());Ds.addGetterSetter(jl,"resizeEnabled",!0);Ds.addGetterSetter(jl,"anchorSize",10,ia());Ds.addGetterSetter(jl,"rotateEnabled",!0);Ds.addGetterSetter(jl,"rotateLineVisible",!0);Ds.addGetterSetter(jl,"rotationSnaps",[]);Ds.addGetterSetter(jl,"rotateAnchorOffset",50,ia());Ds.addGetterSetter(jl,"rotateAnchorAngle",0,ia());Ds.addGetterSetter(jl,"rotateAnchorCursor","crosshair");Ds.addGetterSetter(jl,"rotationSnapTolerance",5,ia());Ds.addGetterSetter(jl,"borderEnabled",!0);Ds.addGetterSetter(jl,"anchorStroke","rgb(0, 161, 255)");Ds.addGetterSetter(jl,"anchorStrokeWidth",1,ia());Ds.addGetterSetter(jl,"anchorFill","white");Ds.addGetterSetter(jl,"anchorCornerRadius",0,ia());Ds.addGetterSetter(jl,"borderStroke","rgb(0, 161, 255)");Ds.addGetterSetter(jl,"borderStrokeWidth",1,ia());Ds.addGetterSetter(jl,"borderDash");Ds.addGetterSetter(jl,"keepRatio",!0);Ds.addGetterSetter(jl,"shiftBehavior","default");Ds.addGetterSetter(jl,"centeredScaling",!1);Ds.addGetterSetter(jl,"ignoreStroke",!1);Ds.addGetterSetter(jl,"padding",0,ia());Ds.addGetterSetter(jl,"nodes");Ds.addGetterSetter(jl,"node");Ds.addGetterSetter(jl,"boundBoxFunc");Ds.addGetterSetter(jl,"anchorDragBoundFunc");Ds.addGetterSetter(jl,"anchorStyleFunc");Ds.addGetterSetter(jl,"shouldOverdrawWholeArea",!1);Ds.addGetterSetter(jl,"useSingleNodeRotation",!0);Ds.backCompat(jl,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class TN extends Yr{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,pa.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)}}TN.prototype.className="Wedge";TN.prototype._centroid=!0;TN.prototype._attrsAffectingSize=["radius"];qu(TN);Ds.addGetterSetter(TN,"radius",0,ia());Ds.addGetterSetter(TN,"angle",0,ia());Ds.addGetterSetter(TN,"clockwise",!1);Ds.backCompat(TN,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function yHe(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const pys=[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],fys=[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 xys(s,t){const n=s.data,r=s.width,a=s.height;let i,l,o,c,d,u,h,p,f,g,_,v,j,b,S,A,T,L,D,M;const F=t+t+1,z=r-1,V=a-1,W=t+1,Y=W*(W+1)/2,K=new yHe,J=pys[t],ne=fys[t];let ie=null,he=K,ce=null,pe=null;for(let le=1;le>ne,D!==0?(D=255/D,n[l]=(c*J>>ne)*D,n[l+1]=(d*J>>ne)*D,n[l+2]=(u*J>>ne)*D):n[l]=n[l+1]=n[l+2]=0,c-=p,d-=f,u-=g,h-=_,p-=ce.r,f-=ce.g,g-=ce.b,_-=ce.a,i=o+((i=ve+t+1)>ne,D>0?(D=255/D,n[i]=(c*J>>ne)*D,n[i+1]=(d*J>>ne)*D,n[i+2]=(u*J>>ne)*D):n[i]=n[i+1]=n[i+2]=0,c-=p,d-=f,u-=g,h-=_,p-=ce.r,f-=ce.g,g-=ce.b,_-=ce.a,i=le+((i=ge+W)0&&xys(t,n)};Ds.addGetterSetter(ba,"blurRadius",0,ia(),Ds.afterSetFilter);const yys=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};Ds.addGetterSetter(ba,"contrast",0,ia(),Ds.afterSetFilter);const _ys=function(s){var t,n,r,a,i,l,o,c,d;const u=s.data,h=s.width,p=s.height,f=Math.min(1,Math.max(0,(n=(t=this.embossStrength)===null||t===void 0?void 0:t.call(this))!==null&&n!==void 0?n:.5)),g=Math.min(1,Math.max(0,(a=(r=this.embossWhiteLevel)===null||r===void 0?void 0:r.call(this))!==null&&a!==void 0?a:.5)),v=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(l=(i=this.embossDirection)===null||i===void 0?void 0:i.call(this))!==null&&l!==void 0?l:"top-left"])!==null&&o!==void 0?o:315,j=!!((d=(c=this.embossBlend)===null||c===void 0?void 0:c.call(this))!==null&&d!==void 0&&d),b=f*10,S=g*255,A=v*Math.PI/180,T=Math.cos(A),L=Math.sin(A),D=128/1020*b,M=new Uint8ClampedArray(u),F=new Float32Array(h*p);for(let K=0,J=0;JK<0?0:K>255?255:K;for(let K=1;Ka&&(a=i),c=t[S+1],co&&(o=c),h=t[S+2],hu&&(u=h);a===r&&(a=255,r=0),o===l&&(o=255,l=0),u===d&&(u=255,d=0);let f,g,_,v,j,b;if(p>0)f=a+p*(255-a),g=r-p*(r-0),_=o+p*(255-o),v=l-p*(l-0),j=u+p*(255-u),b=d-p*(d-0);else{const S=(a+r)*.5;f=a+p*(a-S),g=r+p*(r-S);const A=(o+l)*.5;_=o+p*(o-A),v=l+p*(l-A);const T=(u+d)*.5;j=u+p*(u-T),b=d+p*(d-T)}for(let S=0;Sd?p:d;const f=l,g=i,_=360/g*Math.PI/180;for(let v=0;vd?p:d;const f=l,g=i,_=0;let v,j;for(u=0;ut&&(A=S,T=0,L=-1),a=0;a=0&&f=0&&g=0&&f=0&&g=255*4?255:0}return l}function Dys(s,t,n){const r=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],a=Math.round(Math.sqrt(r.length)),i=Math.floor(a/2),l=[];for(let o=0;o=0&&f=0&&g=n))for(let S=_;S=r)continue;const A=(n*S+b)*4;d+=l[A+0],u+=l[A+1],h+=l[A+2],p+=l[A+3],j+=1}d=d/j,u=u/j,h=h/j,p=p/j;for(let b=f;b=n))for(let S=_;S=r)continue;const A=(n*S+b)*4;l[A+0]=d,l[A+1]=u,l[A+2]=h,l[A+3]=p}}};Ds.addGetterSetter(ba,"pixelSize",8,ia(),Ds.afterSetFilter);const zys=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)});Ds.addGetterSetter(ba,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});Ds.addGetterSetter(ba,"blue",0,Lgt,Ds.afterSetFilter);const $ys=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)});Ds.addGetterSetter(ba,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});Ds.addGetterSetter(ba,"blue",0,Lgt,Ds.afterSetFilter);Ds.addGetterSetter(ba,"alpha",1,function(s){return this._filterUpToDate=!1,s>1?1:s<0?0:s});const Uys=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},Vys=function(s){const t=this.threshold()*255,n=s.data,r=n.length;for(let a=0;apn||et[ps]!==yt[pn]){var Wn=` `+et[ps].replace(" at new "," at ");return Q.displayName&&Wn.includes("")&&(Wn=Wn.replace("",Q.displayName)),Wn}while(1<=ps&&0<=pn);break}}}finally{Ot=!1,Error.prepareStackTrace=ke}return(Q=Q?Q.displayName||Q.name:"")?nr(Q):""}var sr=Object.prototype.hasOwnProperty,Hn=[],ta=-1;function Zr(Q){return{current:Q}}function ur(Q){0>ta||(Q.current=Hn[ta],Hn[ta]=null,ta--)}function Mr(Q,ee){ta++,Hn[ta]=Q.current,Q.current=ee}var zi={},Bi=Zr(zi),Za=Zr(!1),_i=zi;function qi(Q,ee){var ke=Q.type.contextTypes;if(!ke)return zi;var Ve=Q.stateNode;if(Ve&&Ve.__reactInternalMemoizedUnmaskedChildContext===ee)return Ve.__reactInternalMemoizedMaskedChildContext;var et={},yt;for(yt in ke)et[yt]=ee[yt];return Ve&&(Q=Q.stateNode,Q.__reactInternalMemoizedUnmaskedChildContext=ee,Q.__reactInternalMemoizedMaskedChildContext=et),et}function ga(Q){return Q=Q.childContextTypes,Q!=null}function wn(){ur(Za),ur(Bi)}function Ta(Q,ee,ke){if(Bi.current!==zi)throw Error(l(168));Mr(Bi,ee),Mr(Za,ke)}function Yi(Q,ee,ke){var Ve=Q.stateNode;if(ee=ee.childContextTypes,typeof Ve.getChildContext!="function")return ke;Ve=Ve.getChildContext();for(var et in Ve)if(!(et in ee))throw Error(l(108,M(Q)||"Unknown",et));return i({},ke,Ve)}function zo(Q){return Q=(Q=Q.stateNode)&&Q.__reactInternalMemoizedMergedChildContext||zi,_i=Bi.current,Mr(Bi,Q),Mr(Za,Za.current),!0}function rl(Q,ee,ke){var Ve=Q.stateNode;if(!Ve)throw Error(l(169));ke?(Q=Yi(Q,ee,_i),Ve.__reactInternalMemoizedMergedChildContext=Q,ur(Za),ur(Bi),Mr(Bi,Q)):ur(Za),Mr(Za,ke)}var po=Math.clz32?Math.clz32:Tf,uc=Math.log,hc=Math.LN2;function Tf(Q){return Q>>>=0,Q===0?32:31-(uc(Q)/hc|0)|0}var Hu=64,pm=4194304;function Gu(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 qd(Q,ee){var ke=Q.pendingLanes;if(ke===0)return 0;var Ve=0,et=Q.suspendedLanes,yt=Q.pingedLanes,ps=ke&268435455;if(ps!==0){var pn=ps&~et;pn!==0?Ve=Gu(pn):(yt&=ps,yt!==0&&(Ve=Gu(yt)))}else ps=ke&~et,ps!==0?Ve=Gu(ps):yt!==0&&(Ve=Gu(yt));if(Ve===0)return 0;if(ee!==0&&ee!==Ve&&!(ee&et)&&(et=Ve&-Ve,yt=ee&-ee,et>=yt||et===16&&(yt&4194240)!==0))return ee;if(Ve&4&&(Ve|=ke&16),ee=Q.entangledLanes,ee!==0)for(Q=Q.entanglements,ee&=Ve;0ke;ke++)ee.push(Q);return ee}function Ef(Q,ee,ke){Q.pendingLanes|=ee,ee!==536870912&&(Q.suspendedLanes=0,Q.pingedLanes=0),Q=Q.eventTimes,ee=31-po(ee),Q[ee]=ke}function yh(Q,ee){var ke=Q.pendingLanes&~ee;Q.pendingLanes=ee,Q.suspendedLanes=0,Q.pingedLanes=0,Q.expiredLanes&=ee,Q.mutableReadLanes&=ee,Q.entangledLanes&=ee,ee=Q.entanglements;var Ve=Q.eventTimes;for(Q=Q.expirationTimes;0>=ps,et-=ps,Zc=1<<32-po(ee)+et|ke<ro?(Yd=ri,ri=null):Yd=ri.sibling;var il=Sa(qn,ri,cn[ro],Da);if(il===null){ri===null&&(ri=Yd);break}Q&&ri&&il.alternate===null&&ee(qn,ri),Ks=yt(il,Ks,ro),$i===null?Ha=il:$i.sibling=il,$i=il,ri=Yd}if(ro===cn.length)return ke(qn,ri),fa&&Rp(qn,ro),Ha;if(ri===null){for(;roro?(Yd=ri,ri=null):Yd=ri.sibling;var yg=Sa(qn,ri,il.value,Da);if(yg===null){ri===null&&(ri=Yd);break}Q&&ri&&yg.alternate===null&&ee(qn,ri),Ks=yt(yg,Ks,ro),$i===null?Ha=yg:$i.sibling=yg,$i=yg,ri=Yd}if(il.done)return ke(qn,ri),fa&&Rp(qn,ro),Ha;if(ri===null){for(;!il.done;ro++,il=cn.next())il=oo(qn,il.value,Da),il!==null&&(Ks=yt(il,Ks,ro),$i===null?Ha=il:$i.sibling=il,$i=il);return fa&&Rp(qn,ro),Ha}for(ri=Ve(qn,ri);!il.done;ro++,il=cn.next())il=Nc(ri,qn,ro,il.value,Da),il!==null&&(Q&&il.alternate!==null&&ri.delete(il.key===null?ro:il.key),Ks=yt(il,Ks,ro),$i===null?Ha=il:$i.sibling=il,$i=il);return Q&&ri.forEach(function(FC){return ee(qn,FC)}),fa&&Rp(qn,ro),Ha}function Wp(qn,Ks,cn,Da){if(typeof cn=="object"&&cn!==null&&cn.type===u&&cn.key===null&&(cn=cn.props.children),typeof cn=="object"&&cn!==null){switch(cn.$$typeof){case c:e:{for(var Ha=cn.key,$i=Ks;$i!==null;){if($i.key===Ha){if(Ha=cn.type,Ha===u){if($i.tag===7){ke(qn,$i.sibling),Ks=et($i,cn.props.children),Ks.return=qn,qn=Ks;break e}}else if($i.elementType===Ha||typeof Ha=="object"&&Ha!==null&&Ha.$$typeof===S&&Gb(Ha)===$i.type){ke(qn,$i.sibling),Ks=et($i,cn.props),Ks.ref=gx(qn,$i,cn),Ks.return=qn,qn=Ks;break e}ke(qn,$i);break}else ee(qn,$i);$i=$i.sibling}cn.type===u?(Ks=fs(cn.props.children,qn.mode,Da,cn.key),Ks.return=qn,qn=Ks):(Da=Wo(cn.type,cn.key,cn.props,null,qn.mode,Da),Da.ref=gx(qn,Ks,cn),Da.return=qn,qn=Da)}return ps(qn);case d:e:{for($i=cn.key;Ks!==null;){if(Ks.key===$i)if(Ks.tag===4&&Ks.stateNode.containerInfo===cn.containerInfo&&Ks.stateNode.implementation===cn.implementation){ke(qn,Ks.sibling),Ks=et(Ks,cn.children||[]),Ks.return=qn,qn=Ks;break e}else{ke(qn,Ks);break}else ee(qn,Ks);Ks=Ks.sibling}Ks=Uj(cn,qn.mode,Da),Ks.return=qn,qn=Ks}return ps(qn);case S:return $i=cn._init,Wp(qn,Ks,$i(cn._payload),Da)}if(J(cn))return lo(qn,Ks,cn,Da);if(L(cn))return _h(qn,Ks,cn,Da);Dy(qn,cn)}return typeof cn=="string"&&cn!==""||typeof cn=="number"?(cn=""+cn,Ks!==null&&Ks.tag===6?(ke(qn,Ks.sibling),Ks=et(Ks,cn),Ks.return=qn,qn=Ks):(ke(qn,Ks),Ks=f_(cn,qn.mode,Da),Ks.return=qn,qn=Ks),ps(qn)):ke(qn,Ks)}return Wp}var Dl=Yu(!0),p6=Yu(!1),Ry=Zr(null),Wb=null,yx=null,vx=null;function cj(){vx=yx=Wb=null}function Kb(Q,ee,ke){Fe?(Mr(Ry,ee._currentValue),ee._currentValue=ke):(Mr(Ry,ee._currentValue2),ee._currentValue2=ke)}function Vd(Q){var ee=Ry.current;ur(Ry),Fe?Q._currentValue=ee:Q._currentValue2=ee}function np(Q,ee,ke){for(;Q!==null;){var Ve=Q.alternate;if((Q.childLanes&ee)!==ee?(Q.childLanes|=ee,Ve!==null&&(Ve.childLanes|=ee)):Ve!==null&&(Ve.childLanes&ee)!==ee&&(Ve.childLanes|=ee),Q===ke)break;Q=Q.return}}function Hd(Q,ee){Wb=Q,vx=yx=null,Q=Q.dependencies,Q!==null&&Q.firstContext!==null&&(Q.lanes&ee&&(_m=!0),Q.firstContext=null)}function Op(Q){var ee=Fe?Q._currentValue:Q._currentValue2;if(vx!==Q)if(Q={context:Q,memoizedValue:ee,next:null},yx===null){if(Wb===null)throw Error(l(308));yx=Q,Wb.dependencies={lanes:0,firstContext:Q}}else yx=yx.next=Q;return ee}var Pf=null;function Ml(Q){Pf===null?Pf=[Q]:Pf.push(Q)}function sa(Q,ee,ke,Ve){var et=ee.interleaved;return et===null?(ke.next=ke,Ml(ee)):(ke.next=et.next,et.next=ke),ee.interleaved=ke,ar(Q,Ve)}function ar(Q,ee){Q.lanes|=ee;var ke=Q.alternate;for(ke!==null&&(ke.lanes|=ee),ke=Q,Q=Q.return;Q!==null;)Q.childLanes|=ee,ke=Q.alternate,ke!==null&&(ke.childLanes|=ee),ke=Q,Q=Q.return;return ke.tag===3?ke.stateNode:null}var yl=!1;function oa(Q){Q.updateQueue={baseState:Q.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function rp(Q,ee){Q=Q.updateQueue,ee.updateQueue===Q&&(ee.updateQueue={baseState:Q.baseState,firstBaseUpdate:Q.firstBaseUpdate,lastBaseUpdate:Q.lastBaseUpdate,shared:Q.shared,effects:Q.effects})}function ym(Q,ee){return{eventTime:Q,lane:ee,tag:0,payload:null,callback:null,next:null}}function Rr(Q,ee,ke){var Ve=Q.updateQueue;if(Ve===null)return null;if(Ve=Ve.shared,xo&2){var et=Ve.pending;return et===null?ee.next=ee:(ee.next=et.next,et.next=ee),Ve.pending=ee,ar(Q,ke)}return et=Ve.interleaved,et===null?(ee.next=ee,Ml(Ve)):(ee.next=et.next,et.next=ee),Ve.interleaved=ee,ar(Q,ke)}function Oy(Q,ee,ke){if(ee=ee.updateQueue,ee!==null&&(ee=ee.shared,(ke&4194240)!==0)){var Ve=ee.lanes;Ve&=Q.pendingLanes,ke|=Ve,ee.lanes=ke,mx(Q,ke)}}function dj(Q,ee){var ke=Q.updateQueue,Ve=Q.alternate;if(Ve!==null&&(Ve=Ve.updateQueue,ke===Ve)){var et=null,yt=null;if(ke=ke.firstBaseUpdate,ke!==null){do{var ps={eventTime:ke.eventTime,lane:ke.lane,tag:ke.tag,payload:ke.payload,callback:ke.callback,next:null};yt===null?et=yt=ps:yt=yt.next=ps,ke=ke.next}while(ke!==null);yt===null?et=yt=ee:yt=yt.next=ee}else et=yt=ee;ke={baseState:Ve.baseState,firstBaseUpdate:et,lastBaseUpdate:yt,shared:Ve.shared,effects:Ve.effects},Q.updateQueue=ke;return}Q=ke.lastBaseUpdate,Q===null?ke.firstBaseUpdate=ee:Q.next=ee,ke.lastBaseUpdate=ee}function i1(Q,ee,ke,Ve){var et=Q.updateQueue;yl=!1;var yt=et.firstBaseUpdate,ps=et.lastBaseUpdate,pn=et.shared.pending;if(pn!==null){et.shared.pending=null;var Wn=pn,Ur=Wn.next;Wn.next=null,ps===null?yt=Ur:ps.next=Ur,ps=Wn;var Ua=Q.alternate;Ua!==null&&(Ua=Ua.updateQueue,pn=Ua.lastBaseUpdate,pn!==ps&&(pn===null?Ua.firstBaseUpdate=Ur:pn.next=Ur,Ua.lastBaseUpdate=Wn))}if(yt!==null){var oo=et.baseState;ps=0,Ua=Ur=Wn=null,pn=yt;do{var Sa=pn.lane,Nc=pn.eventTime;if((Ve&Sa)===Sa){Ua!==null&&(Ua=Ua.next={eventTime:Nc,lane:0,tag:pn.tag,payload:pn.payload,callback:pn.callback,next:null});e:{var lo=Q,_h=pn;switch(Sa=ee,Nc=ke,_h.tag){case 1:if(lo=_h.payload,typeof lo=="function"){oo=lo.call(Nc,oo,Sa);break e}oo=lo;break e;case 3:lo.flags=lo.flags&-65537|128;case 0:if(lo=_h.payload,Sa=typeof lo=="function"?lo.call(Nc,oo,Sa):lo,Sa==null)break e;oo=i({},oo,Sa);break e;case 2:yl=!0}}pn.callback!==null&&pn.lane!==0&&(Q.flags|=64,Sa=et.effects,Sa===null?et.effects=[pn]:Sa.push(pn))}else Nc={eventTime:Nc,lane:Sa,tag:pn.tag,payload:pn.payload,callback:pn.callback,next:null},Ua===null?(Ur=Ua=Nc,Wn=oo):Ua=Ua.next=Nc,ps|=Sa;if(pn=pn.next,pn===null){if(pn=et.shared.pending,pn===null)break;Sa=pn,pn=Sa.next,Sa.next=null,et.lastBaseUpdate=Sa,et.shared.pending=null}}while(!0);if(Ua===null&&(Wn=oo),et.baseState=Wn,et.firstBaseUpdate=Ur,et.lastBaseUpdate=Ua,ee=et.shared.interleaved,ee!==null){et=ee;do ps|=et.lane,et=et.next;while(et!==ee)}else yt===null&&(et.shared.lanes=0);j0|=ps,Q.lanes=ps,Q.memoizedState=oo}}function Yb(Q,ee,ke){if(Q=ee.effects,ee.effects=null,Q!==null)for(ee=0;eeke?ke:4,Q(!0);var Ve=xC.transition;xC.transition={};try{Q(!1),ee()}finally{fo=ke,xC.transition=Ve}}function bC(){return Qc().memoizedState}function _C(Q,ee,ke){var Ve=xg(Q);if(ke={lane:Ve,action:ke,hasEagerState:!1,eagerState:null,next:null},wC(Q))f6(ee,ke);else if(ke=sa(Q,ee,ke,Ve),ke!==null){var et=bh();cp(ke,Q,Ve,et),cl(ke,ee,Ve)}}function zR(Q,ee,ke){var Ve=xg(Q),et={lane:Ve,action:ke,hasEagerState:!1,eagerState:null,next:null};if(wC(Q))f6(ee,et);else{var yt=Q.alternate;if(Q.lanes===0&&(yt===null||yt.lanes===0)&&(yt=ee.lastRenderedReducer,yt!==null))try{var ps=ee.lastRenderedState,pn=yt(ps,ke);if(et.hasEagerState=!0,et.eagerState=pn,Xm(pn,ps)){var Wn=ee.interleaved;Wn===null?(et.next=et,Ml(ee)):(et.next=Wn.next,Wn.next=et),ee.interleaved=et;return}}catch{}finally{}ke=sa(Q,ee,et,Ve),ke!==null&&(et=bh(),cp(ke,Q,Ve,et),cl(ke,ee,Ve))}}function wC(Q){var ee=Q.alternate;return Q===Wl||ee!==null&&ee===Wl}function f6(Q,ee){Rf=Zb=!0;var ke=Q.pending;ke===null?ee.next=ee:(ee.next=ke.next,ke.next=ee),Q.pending=ee}function cl(Q,ee,ke){if(ke&4194240){var Ve=ee.lanes;Ve&=Q.pendingLanes,ke|=Ve,ee.lanes=ke,mx(Q,ke)}}var yj={readContext:Op,useCallback:Bh,useContext:Bh,useEffect:Bh,useImperativeHandle:Bh,useInsertionEffect:Bh,useLayoutEffect:Bh,useMemo:Bh,useReducer:Bh,useRef:Bh,useState:Bh,useDebugValue:Bh,useDeferredValue:Bh,useTransition:Bh,useMutableSource:Bh,useSyncExternalStore:Bh,useId:Bh,unstable_isNewReconciler:!1},BR={readContext:Op,useCallback:function(Q,ee){return Of().memoizedState=[Q,ee===void 0?null:ee],Q},useContext:Op,useEffect:zy,useImperativeHandle:function(Q,ee,ke){return ke=ke!=null?ke.concat([Q]):null,xj(4194308,4,Jb.bind(null,ee,Q),ke)},useLayoutEffect:function(Q,ee){return xj(4194308,4,Q,ee)},useInsertionEffect:function(Q,ee){return xj(4,2,Q,ee)},useMemo:function(Q,ee){var ke=Of();return ee=ee===void 0?null:ee,Q=Q(),ke.memoizedState=[Q,ee],Q},useReducer:function(Q,ee,ke){var Ve=Of();return ee=ke!==void 0?ke(ee):ee,Ve.memoizedState=Ve.baseState=ee,Q={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Q,lastRenderedState:ee},Ve.queue=Q,Q=Q.dispatch=_C.bind(null,Wl,Q),[Ve.memoizedState,Q]},useRef:function(Q){var ee=Of();return Q={current:Q},ee.memoizedState=Q},useState:ip,useDebugValue:gC,useDeferredValue:function(Q){return Of().memoizedState=Q},useTransition:function(){var Q=ip(!1),ee=Q[0];return Q=xi.bind(null,Q[1]),Of().memoizedState=Q,[ee,Q]},useMutableSource:function(){},useSyncExternalStore:function(Q,ee,ke){var Ve=Wl,et=Of();if(fa){if(ke===void 0)throw Error(l(407));ke=ke()}else{if(ke=ee(),mc===null)throw Error(l(349));m0&30||ON(Ve,ee,ke)}et.memoizedState=ke;var yt={value:ke,getSnapshot:ee};return et.queue=yt,zy(u1.bind(null,Ve,yt,Q),[Q]),Ve.flags|=2048,p0(9,d1.bind(null,Ve,yt,ke,ee),void 0,null),ke},useId:function(){var Q=Of(),ee=mc.identifierPrefix;if(fa){var ke=sp,Ve=Zc;ke=(Ve&~(1<<32-po(Ve)-1)).toString(32)+ke,ee=":"+ee+"R"+ke,ke=hj++,0zf&&(ee.flags|=128,Ve=!0,r_(et,!1),ee.lanes=4194304)}else{if(!Ve)if(Q=o1(yt),Q!==null){if(ee.flags|=128,Ve=!0,Q=Q.updateQueue,Q!==null&&(ee.updateQueue=Q,ee.flags|=4),r_(et,!0),et.tail===null&&et.tailMode==="hidden"&&!yt.alternate&&!fa)return cd(ee),null}else 2*al()-et.renderingStartTime>zf&&ke!==1073741824&&(ee.flags|=128,Ve=!0,r_(et,!1),ee.lanes=4194304);et.isBackwards?(yt.sibling=ee.child,ee.child=yt):(Q=et.last,Q!==null?Q.sibling=yt:ee.child=yt,et.last=yt)}return et.tail!==null?(ee=et.tail,et.rendering=ee,et.tail=ee.sibling,et.renderingStartTime=al(),ee.sibling=null,Q=ec.current,Mr(ec,Ve?Q&1|2:Q&1),ee):(cd(ee),null);case 22:case 23:return zj(),ke=ee.memoizedState!==null,Q!==null&&Q.memoizedState!==null!==ke&&(ee.flags|=8192),ke&&ee.mode&1?Uh&1073741824&&(cd(ee),qe&&ee.subtreeFlags&6&&(ee.flags|=8192)):cd(ee),null;case 24:return null;case 25:return null}throw Error(l(156,ee.tag))}function HN(Q,ee){switch(zn(ee),ee.tag){case 1:return ga(ee.type)&&wn(),Q=ee.flags,Q&65536?(ee.flags=Q&-65537|128,ee):null;case 3:return Fp(),ur(Za),ur(Bi),zp(),Q=ee.flags,Q&65536&&!(Q&128)?(ee.flags=Q&-65537|128,ee):null;case 5:return PN(ee),null;case 13:if(ur(ec),Q=ee.memoizedState,Q!==null&&Q.dehydrated!==null){if(ee.alternate===null)throw Error(l(340));Mi()}return Q=ee.flags,Q&65536?(ee.flags=Q&-65537|128,ee):null;case 19:return ur(ec),null;case 4:return Fp(),null;case 10:return Vd(ee.type._context),null;case 22:case 23:return zj(),null;case 24:return null;default:return null}}var GN=!1,vh=!1,UR=typeof WeakSet=="function"?WeakSet:Set,$a=null;function g0(Q,ee){var ke=Q.ref;if(ke!==null)if(typeof ke=="function")try{ke(null)}catch(Ve){La(Q,ee,Ve)}else ke.current=null}function a_(Q,ee,ke){try{ke()}catch(Ve){La(Q,ee,Ve)}}var TC=!1;function i_(Q,ee){for(ce(Q.containerInfo),$a=ee;$a!==null;)if(Q=$a,ee=Q.child,(Q.subtreeFlags&1028)!==0&&ee!==null)ee.return=Q,$a=ee;else for(;$a!==null;){Q=$a;try{var ke=Q.alternate;if(Q.flags&1024)switch(Q.tag){case 0:case 11:case 15:break;case 1:if(ke!==null){var Ve=ke.memoizedProps,et=ke.memoizedState,yt=Q.stateNode,ps=yt.getSnapshotBeforeUpdate(Q.elementType===Q.type?Ve:Ff(Q.type,Ve),et);yt.__reactInternalSnapshotBeforeUpdate=ps}break;case 3:qe&&rn(Q.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(l(163))}}catch(pn){La(Q,Q.return,pn)}if(ee=Q.sibling,ee!==null){ee.return=Q.return,$a=ee;break}$a=Q.return}return ke=TC,TC=!1,ke}function o_(Q,ee,ke){var Ve=ee.updateQueue;if(Ve=Ve!==null?Ve.lastEffect:null,Ve!==null){var et=Ve=Ve.next;do{if((et.tag&Q)===Q){var yt=et.destroy;et.destroy=void 0,yt!==void 0&&a_(ee,ke,yt)}et=et.next}while(et!==Ve)}}function Ej(Q,ee){if(ee=ee.updateQueue,ee=ee!==null?ee.lastEffect:null,ee!==null){var ke=ee=ee.next;do{if((ke.tag&Q)===Q){var Ve=ke.create;ke.destroy=Ve()}ke=ke.next}while(ke!==ee)}}function _1(Q){var ee=Q.ref;if(ee!==null){var ke=Q.stateNode;switch(Q.tag){case 5:Q=ne(ke);break;default:Q=ke}typeof ee=="function"?ee(Q):ee.current=Q}}function Aj(Q){var ee=Q.alternate;ee!==null&&(Q.alternate=null,Aj(ee)),Q.child=null,Q.deletions=null,Q.sibling=null,Q.tag===5&&(ee=Q.stateNode,ee!==null&&Ge(ee)),Q.stateNode=null,Q.return=null,Q.dependencies=null,Q.memoizedProps=null,Q.memoizedState=null,Q.pendingProps=null,Q.stateNode=null,Q.updateQueue=null}function y0(Q){return Q.tag===5||Q.tag===3||Q.tag===4}function Mj(Q){e:for(;;){for(;Q.sibling===null;){if(Q.return===null||y0(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 l_(Q,ee,ke){var Ve=Q.tag;if(Ve===5||Ve===6)Q=Q.stateNode,ee?Jt(ke,Q,ee):Zt(ke,Q);else if(Ve!==4&&(Q=Q.child,Q!==null))for(l_(Q,ee,ke),Q=Q.sibling;Q!==null;)l_(Q,ee,ke),Q=Q.sibling}function WN(Q,ee,ke){var Ve=Q.tag;if(Ve===5||Ve===6)Q=Q.stateNode,ee?Pt(ke,Q,ee):Bt(ke,Q);else if(Ve!==4&&(Q=Q.child,Q!==null))for(WN(Q,ee,ke),Q=Q.sibling;Q!==null;)WN(Q,ee,ke),Q=Q.sibling}var $c=null,wm=!1;function Up(Q,ee,ke){for(ke=ke.child;ke!==null;)KN(Q,ee,ke),ke=ke.sibling}function KN(Q,ee,ke){if(Qa&&typeof Qa.onCommitFiberUnmount=="function")try{Qa.onCommitFiberUnmount(Af,ke)}catch{}switch(ke.tag){case 5:vh||g0(ke,ee);case 6:if(qe){var Ve=$c,et=wm;$c=null,Up(Q,ee,ke),$c=Ve,wm=et,$c!==null&&(wm?Vt($c,ke.stateNode):ft($c,ke.stateNode))}else Up(Q,ee,ke);break;case 18:qe&&$c!==null&&(wm?ln($c,ke.stateNode):ks($c,ke.stateNode));break;case 4:qe?(Ve=$c,et=wm,$c=ke.stateNode.containerInfo,wm=!0,Up(Q,ee,ke),$c=Ve,wm=et):(be&&(Ve=ke.stateNode.containerInfo,et=er(Ve),Zn(Ve,et)),Up(Q,ee,ke));break;case 0:case 11:case 14:case 15:if(!vh&&(Ve=ke.updateQueue,Ve!==null&&(Ve=Ve.lastEffect,Ve!==null))){et=Ve=Ve.next;do{var yt=et,ps=yt.destroy;yt=yt.tag,ps!==void 0&&(yt&2||yt&4)&&a_(ke,ee,ps),et=et.next}while(et!==Ve)}Up(Q,ee,ke);break;case 1:if(!vh&&(g0(ke,ee),Ve=ke.stateNode,typeof Ve.componentWillUnmount=="function"))try{Ve.props=ke.memoizedProps,Ve.state=ke.memoizedState,Ve.componentWillUnmount()}catch(pn){La(ke,ee,pn)}Up(Q,ee,ke);break;case 21:Up(Q,ee,ke);break;case 22:ke.mode&1?(vh=(Ve=vh)||ke.memoizedState!==null,Up(Q,ee,ke),vh=Ve):Up(Q,ee,ke);break;default:Up(Q,ee,ke)}}function YN(Q){var ee=Q.updateQueue;if(ee!==null){Q.updateQueue=null;var ke=Q.stateNode;ke===null&&(ke=Q.stateNode=new UR),ee.forEach(function(Ve){var et=p_.bind(null,Q,Ve);ke.has(Ve)||(ke.add(Ve),Ve.then(et,et))})}}function lp(Q,ee){var ke=ee.deletions;if(ke!==null)for(var Ve=0;Ve";case w1:return":has("+(qp(Q)||"")+")";case Hy:return'[role="'+Q.value+'"]';case v0:return'"'+Q.value+'"';case wx:return'[data-testname="'+Q.value+'"]';default:throw Error(l(365))}}function QN(Q,ee){var ke=[];Q=[Q,0];for(var Ve=0;Veet&&(et=ps),Ve&=~yt}if(Ve=et,Ve=al()-Ve,Ve=(120>Ve?120:480>Ve?480:1080>Ve?1080:1920>Ve?1920:3e3>Ve?3e3:4320>Ve?4320:1960*Lj(Ve/1960))-Ve,10Q?16:Q,fg===null)var Ve=!1;else{if(Q=fg,fg=null,u_=0,xo&6)throw Error(l(331));var et=xo;for(xo|=4,$a=Q.current;$a!==null;){var yt=$a,ps=yt.child;if($a.flags&16){var pn=yt.deletions;if(pn!==null){for(var Wn=0;Wnal()-d_?gg(Q,0):j1|=ke),Vh(Q,ee)}function Bj(Q,ee){ee===0&&(Q.mode&1?(ee=pm,pm<<=1,!(pm&130023424)&&(pm=4194304)):ee=1);var ke=bh();Q=ar(Q,ee),Q!==null&&(Ef(Q,ee,ke),Vh(Q,ke))}function tk(Q){var ee=Q.memoizedState,ke=0;ee!==null&&(ke=ee.retryLane),Bj(Q,ke)}function p_(Q,ee){var ke=0;switch(Q.tag){case 13:var Ve=Q.stateNode,et=Q.memoizedState;et!==null&&(ke=et.retryLane);break;case 19:Ve=Q.stateNode;break;default:throw Error(l(314))}Ve!==null&&Ve.delete(ee),Bj(Q,ke)}var sk;sk=function(Q,ee,ke){if(Q!==null)if(Q.memoizedProps!==ee.pendingProps||Za.current)_m=!0;else{if(!(Q.lanes&ke)&&!(ee.flags&128))return _m=!1,Cj(Q,ee,ke);_m=!!(Q.flags&131072)}else _m=!1,fa&&ee.flags&1048576&&Lt(ee,Hb,ee.index);switch(ee.lanes=0,ee.tag){case 2:var Ve=ee.type;v1(Q,ee),Q=ee.pendingProps;var et=qi(ee,Bi.current);Hd(ee,ke),et=mj(null,ee,Ve,Q,et,ke);var yt=Qb();return ee.flags|=1,typeof et=="object"&&et!==null&&typeof et.render=="function"&&et.$$typeof===void 0?(ee.tag=1,ee.memoizedState=null,ee.updateQueue=null,ga(Ve)?(yt=!0,zo(ee)):yt=!1,ee.memoizedState=et.state!==null&&et.state!==void 0?et.state:null,oa(ee),et.updater=p1,ee.stateNode=et,et._reactInternals=ee,Uy(ee,Ve,Q,ke),ee=kj(null,ee,Ve,!0,yt,ke)):(ee.tag=0,fa&&yt&&hn(ee),$h(null,ee,et,ke),ee=ee.child),ee;case 16:Ve=ee.elementType;e:{switch(v1(Q,ee),Q=ee.pendingProps,et=Ve._init,Ve=et(Ve._payload),ee.type=Ve,et=ee.tag=jn(Ve),Q=Ff(Ve,Q),et){case 0:ee=kC(null,ee,Ve,Q,ke);break e;case 1:ee=qN(null,ee,Ve,Q,ke);break e;case 11:ee=jC(null,ee,Ve,Q,ke);break e;case 14:ee=x1(null,ee,Ve,Ff(Ve.type,Q),ke);break e}throw Error(l(306,Ve,""))}return ee;case 0:return Ve=ee.type,et=ee.pendingProps,et=ee.elementType===Ve?et:Ff(Ve,et),kC(Q,ee,Ve,et,ke);case 1:return Ve=ee.type,et=ee.pendingProps,et=ee.elementType===Ve?et:Ff(Ve,et),qN(Q,ee,Ve,et,ke);case 3:e:{if(e_(ee),Q===null)throw Error(l(387));Ve=ee.pendingProps,yt=ee.memoizedState,et=yt.element,rp(Q,ee),i1(ee,Ve,null,ke);var ps=ee.memoizedState;if(Ve=ps.element,Ze&&yt.isDehydrated)if(yt={element:Ve,isDehydrated:!1,cache:ps.cache,pendingSuspenseBoundaries:ps.pendingSuspenseBoundaries,transitions:ps.transitions},ee.updateQueue.baseState=yt,ee.memoizedState=yt,ee.flags&256){et=bm(Error(l(423)),ee),ee=g1(Q,ee,Ve,ke,et);break e}else if(Ve!==et){et=bm(Error(l(424)),ee),ee=g1(Q,ee,Ve,ke,et);break e}else for(Ze&&(Gn=Oe(ee.stateNode.containerInfo),Dr=ee,fa=!0,ii=null,Xa=!1),ke=p6(ee,null,Ve,ke),ee.child=ke;ke;)ke.flags=ke.flags&-3|4096,ke=ke.sibling;else{if(Mi(),Ve===et){ee=$p(Q,ee,ke);break e}$h(Q,ee,Ve,ke)}ee=ee.child}return ee;case 5:return uj(ee),Q===null&&Ku(ee),Ve=ee.type,et=ee.pendingProps,yt=Q!==null?Q.memoizedProps:null,ps=et.children,Me(Ve,et)?ps=null:yt!==null&&Me(Ve,yt)&&(ee.flags|=32),y6(Q,ee),$h(Q,ee,ps,ke),ee.child;case 6:return Q===null&&Ku(ee),null;case 13:return v6(Q,ee,ke);case 4:return Bc(ee,ee.stateNode.containerInfo),Ve=ee.pendingProps,Q===null?ee.child=Dl(ee,null,Ve,ke):$h(Q,ee,Ve,ke),ee.child;case 11:return Ve=ee.type,et=ee.pendingProps,et=ee.elementType===Ve?et:Ff(Ve,et),jC(Q,ee,Ve,et,ke);case 7:return $h(Q,ee,ee.pendingProps,ke),ee.child;case 8:return $h(Q,ee,ee.pendingProps.children,ke),ee.child;case 12:return $h(Q,ee,ee.pendingProps.children,ke),ee.child;case 10:e:{if(Ve=ee.type._context,et=ee.pendingProps,yt=ee.memoizedProps,ps=et.value,Kb(ee,Ve,ps),yt!==null)if(Xm(yt.value,ps)){if(yt.children===et.children&&!Za.current){ee=$p(Q,ee,ke);break e}}else for(yt=ee.child,yt!==null&&(yt.return=ee);yt!==null;){var pn=yt.dependencies;if(pn!==null){ps=yt.child;for(var Wn=pn.firstContext;Wn!==null;){if(Wn.context===Ve){if(yt.tag===1){Wn=ym(-1,ke&-ke),Wn.tag=2;var Ur=yt.updateQueue;if(Ur!==null){Ur=Ur.shared;var Ua=Ur.pending;Ua===null?Wn.next=Wn:(Wn.next=Ua.next,Ua.next=Wn),Ur.pending=Wn}}yt.lanes|=ke,Wn=yt.alternate,Wn!==null&&(Wn.lanes|=ke),np(yt.return,ke,ee),pn.lanes|=ke;break}Wn=Wn.next}}else if(yt.tag===10)ps=yt.type===ee.type?null:yt.child;else if(yt.tag===18){if(ps=yt.return,ps===null)throw Error(l(341));ps.lanes|=ke,pn=ps.alternate,pn!==null&&(pn.lanes|=ke),np(ps,ke,ee),ps=yt.sibling}else ps=yt.child;if(ps!==null)ps.return=yt;else for(ps=yt;ps!==null;){if(ps===ee){ps=null;break}if(yt=ps.sibling,yt!==null){yt.return=ps.return,ps=yt;break}ps=ps.return}yt=ps}$h(Q,ee,et.children,ke),ee=ee.child}return ee;case 9:return et=ee.type,Ve=ee.pendingProps.children,Hd(ee,ke),et=Op(et),Ve=Ve(et),ee.flags|=1,$h(Q,ee,Ve,ke),ee.child;case 14:return Ve=ee.type,et=Ff(Ve,ee.pendingProps),et=Ff(Ve.type,et),x1(Q,ee,Ve,et,ke);case 15:return NC(Q,ee,ee.type,ee.pendingProps,ke);case 17:return Ve=ee.type,et=ee.pendingProps,et=ee.elementType===Ve?et:Ff(Ve,et),v1(Q,ee),ee.tag=1,ga(Ve)?(Q=!0,zo(ee)):Q=!1,Hd(ee,ke),By(ee,Ve,et),Uy(ee,Ve,et,ke),kj(null,ee,Ve,!0,Q,ke);case 19:return s_(Q,ee,ke);case 22:return g6(Q,ee,ke)}throw Error(l(156,ee.tag))};function nk(Q,ee){return xm(Q,ee)}function k1(Q,ee,ke,Ve){this.tag=Q,this.key=ke,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=ee,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=Ve,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Kd(Q,ee,ke,Ve){return new k1(Q,ee,ke,Ve)}function kn(Q){return Q=Q.prototype,!(!Q||!Q.isReactComponent)}function jn(Q){if(typeof Q=="function")return kn(Q)?1:0;if(Q!=null){if(Q=Q.$$typeof,Q===_)return 11;if(Q===b)return 14}return 2}function Gp(Q,ee){var ke=Q.alternate;return ke===null?(ke=Kd(Q.tag,ee,Q.key,Q.mode),ke.elementType=Q.elementType,ke.type=Q.type,ke.stateNode=Q.stateNode,ke.alternate=Q,Q.alternate=ke):(ke.pendingProps=ee,ke.type=Q.type,ke.flags=0,ke.subtreeFlags=0,ke.deletions=null),ke.flags=Q.flags&14680064,ke.childLanes=Q.childLanes,ke.lanes=Q.lanes,ke.child=Q.child,ke.memoizedProps=Q.memoizedProps,ke.memoizedState=Q.memoizedState,ke.updateQueue=Q.updateQueue,ee=Q.dependencies,ke.dependencies=ee===null?null:{lanes:ee.lanes,firstContext:ee.firstContext},ke.sibling=Q.sibling,ke.index=Q.index,ke.ref=Q.ref,ke}function Wo(Q,ee,ke,Ve,et,yt){var ps=2;if(Ve=Q,typeof Q=="function")kn(Q)&&(ps=1);else if(typeof Q=="string")ps=5;else e:switch(Q){case u:return fs(ke.children,et,yt,ee);case h:ps=8,et|=8;break;case p:return Q=Kd(12,ke,ee,et|2),Q.elementType=p,Q.lanes=yt,Q;case v:return Q=Kd(13,ke,ee,et),Q.elementType=v,Q.lanes=yt,Q;case j:return Q=Kd(19,ke,ee,et),Q.elementType=j,Q.lanes=yt,Q;case A:return $j(ke,et,yt,ee);default:if(typeof Q=="object"&&Q!==null)switch(Q.$$typeof){case f:ps=10;break e;case g:ps=9;break e;case _:ps=11;break e;case b:ps=14;break e;case S:ps=16,Ve=null;break e}throw Error(l(130,Q==null?Q:typeof Q,""))}return ee=Kd(ps,ke,ee,et),ee.elementType=Q,ee.type=Ve,ee.lanes=yt,ee}function fs(Q,ee,ke,Ve){return Q=Kd(7,Q,Ve,ee),Q.lanes=ke,Q}function $j(Q,ee,ke,Ve){return Q=Kd(22,Q,Ve,ee),Q.elementType=A,Q.lanes=ke,Q.stateNode={isHidden:!1},Q}function f_(Q,ee,ke){return Q=Kd(6,Q,null,ee),Q.lanes=ke,Q}function Uj(Q,ee,ke){return ee=Kd(4,Q.children!==null?Q.children:[],Q.key,ee),ee.lanes=ke,ee.stateNode={containerInfo:Q.containerInfo,pendingChildren:null,implementation:Q.implementation},ee}function rk(Q,ee,ke,Ve,et){this.tag=ee,this.containerInfo=Q,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Ie,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=My(0),this.expirationTimes=My(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=My(0),this.identifierPrefix=Ve,this.onRecoverableError=et,Ze&&(this.mutableSourceEagerHydrationData=null)}function DC(Q,ee,ke,Ve,et,yt,ps,pn,Wn){return Q=new rk(Q,ee,ke,pn,Wn),ee===1?(ee=1,yt===!0&&(ee|=8)):ee=0,yt=Kd(3,null,null,ee),Q.current=yt,yt.stateNode=Q,yt.memoizedState={element:Ve,isDehydrated:ke,cache:null,transitions:null,pendingSuspenseBoundaries:null},oa(yt),Q}function RC(Q){if(!Q)return zi;Q=Q._reactInternals;e:{if(F(Q)!==Q||Q.tag!==1)throw Error(l(170));var ee=Q;do{switch(ee.tag){case 3:ee=ee.stateNode.context;break e;case 1:if(ga(ee.type)){ee=ee.stateNode.__reactInternalMemoizedMergedChildContext;break e}}ee=ee.return}while(ee!==null);throw Error(l(171))}if(Q.tag===1){var ke=Q.type;if(ga(ke))return Yi(Q,ke,ee)}return ee}function S1(Q){var ee=Q._reactInternals;if(ee===void 0)throw typeof Q.render=="function"?Error(l(188)):(Q=Object.keys(Q).join(","),Error(l(268,Q)));return Q=W(ee),Q===null?null:Q.stateNode}function OC(Q,ee){if(Q=Q.memoizedState,Q!==null&&Q.dehydrated!==null){var ke=Q.retryLane;Q.retryLane=ke!==0&&ke=Ur&&yt>=oo&&et<=Ua&&ps<=Sa){Q.splice(ee,1);break}else if(Ve!==Ur||ke.width!==Wn.width||Saps){if(!(yt!==oo||ke.height!==Wn.height||Uaet)){Ur>Ve&&(Wn.width+=Ur-Ve,Wn.x=Ve),Uayt&&(Wn.height+=oo-yt,Wn.y=yt),Sake&&(ke=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 ne(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:T6,findFiberByHostInstance:Q.findFiberByHostInstance||ik,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")Q=!1;else{var ee=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(ee.isDisabled||!ee.supportsFiber)Q=!0;else{try{Af=ee.inject(Q),Qa=ee}catch{}Q=!!ee.checkDCE}}return Q},n.isAlreadyRendering=function(){return!1},n.observeVisibleRects=function(Q,ee,ke,Ve){if(!We)throw Error(l(363));Q=XN(Q,ee);var et=vt(Q,ke,Ve).disconnect;return{disconnect:function(){et()}}},n.registerMutableSourceForHydration=function(Q,ee){var ke=ee._getVersion;ke=ke(ee._source),Q.mutableSourceEagerHydrationData==null?Q.mutableSourceEagerHydrationData=[ee,ke]:Q.mutableSourceEagerHydrationData.push(ee,ke)},n.runWithPriority=function(Q,ee){var ke=fo;try{return fo=Q,ee()}finally{fo=ke}},n.shouldError=function(){return null},n.shouldSuspend=function(){return!1},n.updateContainer=function(Q,ee,ke,Ve){var et=ee.current,yt=bh(),ps=xg(et);return ke=RC(ke),ee.context===null?ee.context=ke:ee.pendingContext=ke,ee=ym(yt,ps),ee.payload={element:Q},Ve=Ve===void 0?null:Ve,Ve!==null&&(ee.callback=Ve),Q=Rr(et,ee,ps),Q!==null&&(cp(Q,et,ps,yt),Oy(Q,et,ps)),ps},n};m0t.exports=Hys;var Gys=m0t.exports;const Wys=wl(Gys);var p0t={exports:{}},JM={};/** * @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. */JM.ConcurrentRoot=1;JM.ContinuousEventPriority=4;JM.DefaultEventPriority=16;JM.DiscreteEventPriority=1;JM.IdleEventPriority=536870912;JM.LegacyRoot=0;p0t.exports=JM;var f0t=p0t.exports;const vHe={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0};let bHe=!1,_He=!1;const RIe=".react-konva-event",Kys=`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 `,Yys=`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 `,Zys={};function yve(s,t,n=Zys){if(!bHe&&"zIndex"in t&&(console.warn(Yys),bHe=!0),!_He&&t.draggable){var r=t.x!==void 0||t.y!==void 0,a=t.onDragEnd||t.onDragMove;r&&!a&&(console.warn(Kys),_He=!0)}for(var i in n)if(!vHe[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={},p=!1;const f={};for(var i in t)if(!vHe[i]){var l=i.slice(0,2)==="on",g=n[i]!==t[i];if(l&&g){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),t[i]&&(f[c]=t[i])}!l&&(t[i]!==n[i]||u&&t[i]!==s.getAttr(i))&&(p=!0,h[i]=t[i])}p&&(s.setAttrs(h),lC(s));for(var c in f)s.on(c+RIe,f[c])}function lC(s){if(!pa.autoDrawEnabled){var t=s.getLayer()||s.getStage();t&&t.batchDraw()}}const x0t={},Qys={};TM.Node.prototype._applyProps=yve;function Xys(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),lC(s)}function Jys(s,t,n){let r=TM[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=TM.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 yve(c,i),c}function evs(s,t,n){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${s}"`)}function tvs(s,t,n){return!1}function svs(s){return s}function nvs(){return null}function rvs(){return null}function avs(s,t,n,r){return Qys}function ivs(){}function ovs(s){}function lvs(s,t){return!1}function cvs(){return x0t}function dvs(){return x0t}const uvs=setTimeout,hvs=clearTimeout,mvs=-1;function pvs(s,t){return!1}const fvs=!1,xvs=!0,gvs=!0;function yvs(s,t){t.parent===s?t.moveToTop():s.add(t),lC(s)}function vvs(s,t){t.parent===s?t.moveToTop():s.add(t),lC(s)}function g0t(s,t,n){t._remove(),s.add(t),t.setZIndex(n.getZIndex()),lC(s)}function bvs(s,t,n){g0t(s,t,n)}function _vs(s,t){t.destroy(),t.off(RIe),lC(s)}function wvs(s,t){t.destroy(),t.off(RIe),lC(s)}function jvs(s,t,n){console.error(`Text components are not yet supported in ReactKonva. You text is: "${n}"`)}function Nvs(s,t,n){}function kvs(s,t,n,r,a){yve(s,a,r)}function Svs(s){s.hide(),lC(s)}function Cvs(s){}function Tvs(s,t){(t.visible==null||t.visible)&&s.show()}function Evs(s,t){}function Avs(s){}function Mvs(){}const Ivs=()=>f0t.DefaultEventPriority,Pvs=Object.freeze(Object.defineProperty({__proto__:null,appendChild:yvs,appendChildToContainer:vvs,appendInitialChild:Xys,cancelTimeout:hvs,clearContainer:Avs,commitMount:Nvs,commitTextUpdate:jvs,commitUpdate:kvs,createInstance:Jys,createTextInstance:evs,detachDeletedInstance:Mvs,finalizeInitialChildren:tvs,getChildHostContext:dvs,getCurrentEventPriority:Ivs,getPublicInstance:svs,getRootHostContext:cvs,hideInstance:Svs,hideTextInstance:Cvs,idlePriority:P7.unstable_IdlePriority,insertBefore:g0t,insertInContainerBefore:bvs,isPrimaryRenderer:fvs,noTimeout:mvs,now:P7.unstable_now,prepareForCommit:nvs,preparePortalMount:rvs,prepareUpdate:avs,removeChild:_vs,removeChildFromContainer:wvs,resetAfterCommit:ivs,resetTextContent:ovs,run:P7.unstable_runWithPriority,scheduleTimeout:uvs,shouldDeprioritizeSubtree:lvs,shouldSetTextContent:pvs,supportsMutation:gvs,unhideInstance:Tvs,unhideTextInstance:Evs,warnsIfNotActing:xvs},Symbol.toStringTag,{value:"Module"}));var Lvs=Object.defineProperty,Dvs=Object.defineProperties,Rvs=Object.getOwnPropertyDescriptors,wHe=Object.getOwnPropertySymbols,Ovs=Object.prototype.hasOwnProperty,Fvs=Object.prototype.propertyIsEnumerable,jHe=(s,t,n)=>t in s?Lvs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,NHe=(s,t)=>{for(var n in t||(t={}))Ovs.call(t,n)&&jHe(s,n,t[n]);if(wHe)for(var n of wHe(t))Fvs.call(t,n)&&jHe(s,n,t[n]);return s},zvs=(s,t)=>Dvs(s,Rvs(t)),kHe,SHe;typeof window<"u"&&((kHe=window.document)!=null&&kHe.createElement||((SHe=window.navigator)==null?void 0:SHe.product)==="ReactNative")?N.useLayoutEffect:N.useEffect;function y0t(s,t,n){if(!s)return;if(n(s)===!0)return s;let r=s.child;for(;r;){const a=y0t(r,t,n);if(a)return a;r=r.sibling}}function v0t(s){try{return Object.defineProperties(s,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return s}}const CHe=console.error;console.error=function(){const s=[...arguments].join("");if(s!=null&&s.startsWith("Warning:")&&s.includes("useContext")){console.error=CHe;return}return CHe.apply(this,arguments)};const OIe=v0t(N.createContext(null));class b0t extends N.Component{render(){return N.createElement(OIe.Provider,{value:this._reactInternals},this.props.children)}}function Bvs(){const s=N.useContext(OIe);if(s===null)throw new Error("its-fine: useFiber must be called within a !");const t=N.useId();return N.useMemo(()=>{for(const r of[s,s==null?void 0:s.alternate]){if(!r)continue;const a=y0t(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 $vs(){const s=Bvs(),[t]=N.useState(()=>new Map);t.clear();let n=s;for(;n;){if(n.type&&typeof n.type=="object"){const a=n.type._context===void 0&&n.type.Provider===n.type?n.type:n.type._context;a&&a!==OIe&&!t.has(a)&&t.set(a,N.useContext(v0t(a)))}n=n.return}return t}function Uvs(){const s=$vs();return N.useMemo(()=>Array.from(s.keys()).reduce((t,n)=>r=>N.createElement(t,null,N.createElement(n.Provider,zvs(NHe({},r),{value:s.get(n)}))),t=>N.createElement(b0t,NHe({},t))),[s])}function qvs(s){const t=St.useRef({});return St.useLayoutEffect(()=>{t.current=s}),St.useLayoutEffect(()=>()=>{t.current={}},[]),t.current}const Vvs=s=>{const t=St.useRef(null),n=St.useRef(null),r=St.useRef(null),a=qvs(s),i=Uvs(),l=o=>{const{forwardedRef:c}=s;c&&(typeof c=="function"?c(o):c.current=o)};return St.useLayoutEffect(()=>(n.current=new TM.Stage({width:s.width,height:s.height,container:t.current}),l(n.current),r.current=N7.createContainer(n.current,f0t.LegacyRoot,!1,null),N7.updateContainer(St.createElement(i,{},s.children),r.current),()=>{TM.isBrowser&&(l(null),N7.updateContainer(null,r.current,null),n.current.destroy())}),[]),St.useLayoutEffect(()=>{l(n.current),yve(n.current,s,a),N7.updateContainer(St.createElement(i,{},s.children),r.current,null)}),St.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})},Hvs="Layer",DS="Group",R_="Rect",PP="Image",AI="Text",ngn="Transformer",N7=Wys(Pvs);N7.injectIntoDevTools({findHostInstanceByFiber:()=>null,bundleType:0,version:St.version,rendererPackageName:"react-konva"});const Gvs=St.forwardRef((s,t)=>St.createElement(b0t,{},St.createElement(Vvs,{...s,forwardedRef:t})));function Wvs({imageUrl:s,preset:t,barStyleId:n,overrides:r,maxDisplayWidth:a=720,stageRef:i}){const l=N.useRef(null),[o,c]=N.useState(null),[d,u]=N.useState(null),[h,p]=N.useState(null),f=(t==null?void 0:t.headshot_url)??"",g=(t==null?void 0:t.brokerage_logo_url)??"";N.useEffect(()=>{if(!s){c(null);return}const Y=new window.Image;Y.crossOrigin="anonymous",Y.onload=()=>c(Y),Y.onerror=()=>c(null),Y.src=s},[s]),N.useEffect(()=>{if(!f){u(null);return}const Y=new window.Image;Y.crossOrigin="anonymous",Y.onload=()=>u(Y),Y.onerror=()=>u(null),Y.src=f},[f]),N.useEffect(()=>{if(!g){p(null);return}const Y=new window.Image;Y.crossOrigin="anonymous",Y.onload=()=>p(Y),Y.onerror=()=>p(null),Y.src=g},[g]);const _=ygs(n),v=(o==null?void 0:o.naturalWidth)??1080,j=(o==null?void 0:o.naturalHeight)??1080,b=N.useMemo(()=>Math.min(1,a/v),[v,a]),S=v*b,A=j*b,T=(r==null?void 0:r.brand_color)??(t==null?void 0:t.brand_color)??"#0f172a",L=(r==null?void 0:r.accent_color)??(t==null?void 0:t.accent_color)??"#3b82f6",D=(r==null?void 0:r.display_name)??(t==null?void 0:t.display_name)??"",M=(r==null?void 0:r.phone)??(t==null?void 0:t.phone)??"",F=(r==null?void 0:r.email)??(t==null?void 0:t.email)??"",z=(r==null?void 0:r.tagline)??(t==null?void 0:t.tagline)??"",V=new Set((r==null?void 0:r.hidden_fields)??(t==null?void 0:t.hidden_fields)??[]),W=Y=>_.fields.includes(Y)&&!V.has(Y);return e.jsx("div",{className:"border rounded-lg overflow-hidden bg-muted/40 inline-block",children:e.jsx(Gvs,{ref:Y=>{l.current=Y,i&&(i.current=Y)},width:S,height:A,scaleX:b,scaleY:b,children:e.jsxs(Hvs,{children:[o&&e.jsx(PP,{image:o,width:v,height:j,listening:!1}),!o&&e.jsx(R_,{x:0,y:0,width:v,height:j,fill:"#e2e8f0"}),e.jsx(Kvs,{style:_,canvasW:v,canvasH:j,brandColor:T,accentColor:L,name:D,phone:M,email:F,tagline:z,headshot:d,logo:h,hidden:V,has:W})]})})})}function Kvs({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 p=n*s.heightRatio,f=p*.18,g=s.textColor==="light"?"#ffffff":s.textColor==="dark"?"#0f172a":s.background==="dark"||s.background==="gradient"?"#ffffff":vgs(r),_=g==="#ffffff"?"rgba(255,255,255,0.78)":"rgba(15,23,42,0.7)";if(s.position==="bottom"||s.position==="top"){const v=s.position==="bottom"?n-p:0;return e.jsxs(DS,{children:[e.jsx(R_,{x:0,y:v,width:t,height:p,fill:r}),e.jsx(R_,{x:0,y:s.position==="bottom"?v:p-4,width:t,height:4,fill:a}),e.jsx(VH,{x:f,y:v+f,width:t-f*2,height:p-f*2,textColor:g,subTextColor:_,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot})]})}if(s.position==="corner-br"){const v=t*.42,j=p,b=t-v-n*.025,S=n-j-n*.025;return e.jsxs(DS,{children:[e.jsx(R_,{x:b,y:S,width:v,height:j,fill:r,cornerRadius:j*.12,opacity:.92}),e.jsx(R_,{x:b,y:S+j-4,width:v,height:4,fill:a,cornerRadius:2}),e.jsx(VH,{x:b+f,y:S+f,width:v-f*2,height:j-f*2,textColor:g,subTextColor:_,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot})]})}if(s.position==="side-right"){const v=Math.max(t*.22,Math.min(t*.3,260)),j=v*.12;return e.jsxs(DS,{children:[e.jsx(R_,{x:t-v,y:0,width:v,height:n,fill:r}),e.jsx(R_,{x:t-v,y:0,width:4,height:n,fill:a}),e.jsx(VH,{x:t-v+j,y:n*.08,width:v-j*2,height:n*.84,textColor:g,subTextColor:_,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot,vertical:!0,railWidth:v})]})}return s.position==="letterbox"?e.jsxs(DS,{children:[e.jsx(R_,{x:0,y:0,width:t,height:p,fill:"#0a0a0a"}),e.jsx(R_,{x:0,y:n-p,width:t,height:p,fill:"#0a0a0a"}),e.jsx(R_,{x:0,y:n-p,width:t,height:3,fill:a}),e.jsx(VH,{x:f,y:n-p+f,width:t-f*2,height:p-f*2,textColor:"#ffffff",subTextColor:"rgba(255,255,255,0.75)",name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot}),u&&h("logo")&&e.jsx(PP,{image:u,x:t-f-p*.7,y:f,height:p-f*2,width:p*.7})]}):null}function VH({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:p,circular:f,vertical:g,railWidth:_}){if(g){const Y=_??n,K=Math.min(n,Y*.7),J=Math.max(14,Y*.13),ne=Math.max(11,Y*.085),ie=Y*.08,he=Y*.35;let ce=t;const pe=ce;ce+=K+ie;const le=ce,ve=l.length>12?2:1;ce+=J*1.15*ve+ie*.5;const ge=ce;p("phone")&&o&&(ce+=ne*1.3+ie*.4);const Te=ce;p("email")&&c&&(ce+=ne*1.3+ie*.4);const Me=ce+ie*.5;return e.jsxs(DS,{children:[p("headshot")&&u&&e.jsx(DS,{clipFunc:f?Ce=>{Ce.beginPath(),Ce.arc(s+n/2,pe+K/2,K/2,0,Math.PI*2),Ce.closePath()}:void 0,children:e.jsx(PP,{image:u,x:s+(n-K)/2,y:pe,width:K,height:K})}),p("name")&&l&&e.jsx(AI,{text:l,x:s,y:le,width:n,align:"center",fontSize:J,fontStyle:"bold",fill:a}),p("phone")&&o&&e.jsx(AI,{text:o,x:s,y:ge,width:n,align:"center",fontSize:ne,fill:i}),p("email")&&c&&e.jsx(AI,{text:c,x:s,y:Te,width:n,align:"center",fontSize:ne,fill:i,ellipsis:!0,wrap:"none"}),p("logo")&&h&&e.jsx(PP,{image:h,x:s,y:Me,width:n,height:he})]})}const v=r*.95,j=u&&p("headshot")?s+v+r*.18:s,b=n-(j-s)-(h&&p("logo")?r*1.6:0),S=Math.max(20,r*.34),A=Math.max(13,r*.22),T=r*.06,L=p("tagline")&&d?1:0,D=p("phone")&&o?1:0,M=p("email")&&c?1:0,F=1+L+(D||M?1:0),z=F*S+(F-1)*T;let W=t+(r-z)/2;return e.jsxs(DS,{children:[p("headshot")&&u&&e.jsx(DS,{clipFunc:f?Y=>{Y.beginPath(),Y.arc(s+v/2,t+v/2,v/2,0,Math.PI*2),Y.closePath()}:void 0,children:e.jsx(PP,{image:u,x:s,y:t+(r-v)/2,width:v,height:v})}),p("name")&&l&&e.jsx(AI,{text:l,x:j,y:W,width:b,fontSize:S,fontStyle:"bold",fill:a,ellipsis:!0,wrap:"none"}),(W+=S+T,null),p("tagline")&&d&&e.jsxs(e.Fragment,{children:[e.jsx(AI,{text:d,x:j,y:W,width:b,fontSize:A*1.1,fontStyle:"italic",fill:i,ellipsis:!0,wrap:"none"}),(W+=A*1.1+T,null)]}),D||M?e.jsx(AI,{text:[o,c].filter(Boolean).join(" • "),x:j,y:W,width:b,fontSize:A,fill:i,ellipsis:!0,wrap:"none"}):null,p("logo")&&h&&e.jsx(PP,{image:h,x:s+n-r*1.4,y:t+(r-r*.8)/2,width:r*1.4,height:r*.8})]})}function Yvs(){const{data:s}=jU(),t=(s==null?void 0:s.find(W=>W.is_default))??(s==null?void 0:s[0])??null,[n,r]=N.useState(void 0),a=(s==null?void 0:s.find(W=>W.id===n))??t,[i,l]=N.useState([]),[o,c]=N.useState(0),[d,u]=N.useState("minimal-stripe"),[h,p]=N.useState({}),[f,g]=N.useState(!1),_=N.useRef(null),[v,j]=N.useState(780),b=N.useRef(null),S=W=>{if(b.current&&(b.current.disconnect(),b.current=null),!W)return;const Y=()=>{const J=W.clientWidth;J>0&&j(Math.min(780,J-16))};Y();const K=new ResizeObserver(Y);K.observe(W),b.current=K};N.useEffect(()=>()=>{var W;(W=b.current)==null||W.disconnect()},[]);const A=N.useRef(null),T=W=>{if(!W)return;const Y=[];Array.from(W).forEach(K=>{K.type.startsWith("image/")&&Y.push({id:crypto.randomUUID(),url:URL.createObjectURL(K),file:K,name:K.name})}),l(K=>[...K,...Y])},L=W=>{l(Y=>{const K=Y.find(J=>J.id===W);return K&&URL.revokeObjectURL(K.url),Y.filter(J=>J.id!==W)}),c(0)},D=typeof navigator<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent),M=W=>{var he;const[Y,K]=W.split(","),J=((he=Y.match(/:(.*?);/))==null?void 0:he[1])??"image/jpeg",ne=atob(K),ie=new Uint8Array(ne.length);for(let ce=0;ce{var W;if(A.current){g(!0);try{const Y=A.current,K=Y.toDataURL({pixelRatio:1/(Y.scaleX()||1),mimeType:"image/jpeg",quality:.95}),ne=`${((W=i[o])==null?void 0:W.name.replace(/\.[^.]+$/,""))||"branded"}-branded.jpg`,ie=M(K),he=URL.createObjectURL(ie);if(D)window.open(he,"_blank")||(window.location.href=he),ae.success('Long-press the image and tap "Save to Photos"');else{const ce=document.createElement("a");ce.href=he,ce.download=ne,document.body.appendChild(ce),ce.click(),ce.remove(),ae.success("Image exported")}setTimeout(()=>URL.revokeObjectURL(he),6e4)}catch(Y){ae.error(Y.message||"Export failed")}finally{g(!1)}}},z=async()=>{if(i.length){g(!0);try{const W=new Pgt,Y=i.length,K=o;for(let ie=0;iesetTimeout(ve,600)),!A.current)continue;const he=A.current,pe=he.toDataURL({pixelRatio:1/(he.scaleX()||1),mimeType:"image/jpeg",quality:.95}).split(",")[1],le=i[ie].name.replace(/\.[^.]+$/,"")||`image-${ie+1}`;W.file(`${le}-branded.jpg`,pe,{base64:!0})}c(K);const J=await W.generateAsync({type:"blob"}),ne=document.createElement("a");ne.href=URL.createObjectURL(J),ne.download=`branded-images-${Date.now()}.zip`,ne.click(),URL.revokeObjectURL(ne.href),ae.success(`${Y} images exported`)}catch(W){ae.error(W.message||"Batch export failed")}finally{g(!1)}}},V=i[o];return e.jsx(Ts,{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(Go,{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(Ln,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Hr,{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(Ln,{to:"/marketing-studio/brand-kit",children:[e.jsx(fl,{className:"h-4 w-4 mr-1"})," Brand Kit"]})})]}),!a&&e.jsx(fe,{className:"border-dashed border-amber-500/50 bg-amber-500/5",children:e.jsxs(Ee,{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(Ln,{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(fe,{className:"overflow-hidden",children:e.jsxs(Ee,{className:"p-4",children:[V?e.jsx("div",{ref:S,className:"flex justify-center bg-muted/30 rounded p-2 overflow-hidden",children:e.jsx(Wvs,{imageUrl:V.url,preset:a,barStyleId:d,overrides:h,maxDisplayWidth:v,stageRef:A})}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-12 text-center space-y-3 cursor-pointer hover:bg-muted/30 transition-colors",onClick:()=>{var W;return(W=_.current)==null?void 0:W.click()},onDragOver:W=>W.preventDefault(),onDrop:W=>{W.preventDefault(),T(W.dataTransfer.files)},children:[e.jsx(nl,{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(Na,{className:"h-4 w-4 mr-1"})," Choose images"]})]}),e.jsx("input",{ref:_,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:W=>T(W.target.files)})]})}),i.length>0&&e.jsx(fe,{className:"overflow-hidden",children:e.jsx(Ee,{className:"p-3",children:e.jsxs("div",{className:"flex gap-2 overflow-x-auto py-1",children:[i.map((W,Y)=>e.jsxs("div",{className:"relative group flex-shrink-0",children:[e.jsx("button",{onClick:()=>c(Y),className:`block h-16 w-16 rounded overflow-hidden border-2 transition-all ${Y===o?"border-primary":"border-transparent hover:border-muted-foreground/30"}`,children:e.jsx("img",{src:W.url,alt:"",className:"h-full w-full object-cover"})}),e.jsx("button",{onClick:()=>L(W.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(Bn,{className:"h-3 w-3"})})]},W.id)),e.jsx("button",{onClick:()=>{var W;return(W=_.current)==null?void 0:W.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(Is,{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(W=>URL.revokeObjectURL(W.url)),l([])},children:"Clear all"}),e.jsxs(B,{onClick:F,disabled:f||!V,children:[f?e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Pa,{className:"h-4 w-4 mr-1"}),"Download this image"]}),i.length>1&&e.jsxs(B,{onClick:z,disabled:f,children:[f?e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Pa,{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(fe,{className:"overflow-hidden",children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-base",children:"Brand preset"})}),e.jsx(Ee,{children:e.jsxs(ds,{value:(a==null?void 0:a.id)??"",onValueChange:r,children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Choose preset"})}),e.jsx(cs,{children:s==null?void 0:s.map(W=>e.jsxs(Qe,{value:W.id,children:[W.name," ",W.is_default?"(default)":""]},W.id))})]})})]}),e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-base",children:"Bar style"})}),e.jsx(Ee,{children:e.jsx(bgs,{value:d,onChange:u,mediaType:"image"})})]}),e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-base",children:"Tweak this design"})}),e.jsx(Ee,{children:e.jsxs(Br,{defaultValue:"text",children:[e.jsxs(Fr,{className:"grid grid-cols-2 w-full",children:[e.jsx(Kt,{value:"text",children:"Text"}),e.jsx(Kt,{value:"colors",children:"Colors"})]}),e.jsxs(is,{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:W=>p({...h,display_name:W.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:h.phone??(a==null?void 0:a.phone)??"",onChange:W=>p({...h,phone:W.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ye,{value:h.email??(a==null?void 0:a.email)??"",onChange:W=>p({...h,email:W.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Tagline"}),e.jsx(ye,{value:h.tagline??(a==null?void 0:a.tagline)??"",onChange:W=>p({...h,tagline:W.target.value})})]})]}),e.jsxs(is,{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:W=>p({...h,brand_color:W.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:W=>p({...h,brand_color:W.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:W=>p({...h,accent_color:W.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:W=>p({...h,accent_color:W.target.value})})]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>p({}),children:"Reset to preset"})]})]})})]})]})]})]})})}function Zvs(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 Qvs=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function b4(s){const t=[];for(let n=0,r=s.length;nA0||s.height>A0)&&(s.width>A0&&s.height>A0?s.width>s.height?(s.height*=A0/s.width,s.width=A0):(s.width*=A0/s.height,s.height=A0):s.width>A0?(s.height*=A0/s.width,s.width=A0):(s.width*=A0/s.height,s.height=A0))}function Cxe(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 s1s(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function n1s(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),s1s(a)}const Yg=(s,t)=>{if(s instanceof t)return!0;const n=Object.getPrototypeOf(s);return n===null?!1:n.constructor.name===t.name||Yg(n,t)};function r1s(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function a1s(s,t){return _0t(t).map(n=>{const r=s.getPropertyValue(n),a=s.getPropertyPriority(n);return`${n}: ${r}${a?" !important":""};`}).join(" ")}function i1s(s,t,n,r){const a=`.${s}:${t}`,i=n.cssText?r1s(n):a1s(n,r);return document.createTextNode(`${a}{${i}}`)}function THe(s,t,n,r){const a=window.getComputedStyle(s,n),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=Qvs();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild(i1s(l,n,a,r)),t.appendChild(o)}function o1s(s,t,n){THe(s,t,":before",n),THe(s,t,":after",n)}const EHe="application/font-woff",AHe="image/jpeg",l1s={woff:EHe,woff2:EHe,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:AHe,jpeg:AHe,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function c1s(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function FIe(s){const t=c1s(s).toLowerCase();return l1s[t]||""}function d1s(s){return s.split(/,/)[1]}function g3e(s){return s.search(/^(data:)/)!==-1}function u1s(s,t){return`data:${t};base64,${s}`}async function j0t(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 L2e={};function h1s(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 zIe(s,t,n){const r=h1s(s,t,n.includeQueryParams);if(L2e[r]!=null)return L2e[r];n.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await j0t(s,n.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),d1s(o)));a=u1s(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 L2e[r]=a,a}async function m1s(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):Cxe(t)}async function p1s(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 Cxe(o)}const n=s.poster,r=FIe(n),a=await zIe(n,r,t);return Cxe(a)}async function f1s(s,t){var n;try{if(!((n=s==null?void 0:s.contentDocument)===null||n===void 0)&&n.body)return await vve(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function x1s(s,t){return Yg(s,HTMLCanvasElement)?m1s(s):Yg(s,HTMLVideoElement)?p1s(s,t):Yg(s,HTMLIFrameElement)?f1s(s,t):s.cloneNode(N0t(s))}const g1s=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",N0t=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function y1s(s,t,n){var r,a;if(N0t(t))return t;let i=[];return g1s(s)&&s.assignedNodes?i=b4(s.assignedNodes()):Yg(s,HTMLIFrameElement)&&(!((r=s.contentDocument)===null||r===void 0)&&r.body)?i=b4(s.contentDocument.body.childNodes):i=b4(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||Yg(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>vve(o,n)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function v1s(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):_0t(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`),Yg(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 b1s(s,t){Yg(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),Yg(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function _1s(s,t){if(Yg(s,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(a=>s.value===a.getAttribute("value"));r&&r.setAttribute("selected","")}}function w1s(s,t,n){return Yg(t,Element)&&(v1s(s,t,n),o1s(s,t,n),b1s(s,t),_1s(s,t)),t}async function j1s(s,t){const n=s.querySelectorAll?s.querySelectorAll("use"):[];if(n.length===0)return s;const r={};for(let i=0;ix1s(r,t)).then(r=>y1s(s,r,t)).then(r=>w1s(s,r,t)).then(r=>j1s(r,t))}const k0t=/url\((['"]?)([^'"]+?)\1\)/g,N1s=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,k1s=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function S1s(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function C1s(s){const t=[];return s.replace(k0t,(n,r,a)=>(t.push(a),n)),t.filter(n=>!g3e(n))}async function T1s(s,t,n,r,a){try{const i=n?Zvs(t,n):t,l=FIe(t);let o;return a||(o=await zIe(i,l,r)),s.replace(S1s(t),`$1${o}$3`)}catch{}return s}function E1s(s,{preferredFontFormat:t}){return t?s.replace(k1s,n=>{for(;;){const[r,,a]=N1s.exec(n)||[];if(!a)return"";if(a===t)return`src: ${r};`}}):s}function S0t(s){return s.search(k0t)!==-1}async function C0t(s,t,n){if(!S0t(s))return s;const r=E1s(s,n);return C1s(r).reduce((i,l)=>i.then(o=>T1s(o,l,t,n)),Promise.resolve(r))}async function II(s,t,n){var r;const a=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(s);if(a){const i=await C0t(a,null,n);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function A1s(s,t){await II("background",s,t)||await II("background-image",s,t),await II("mask",s,t)||await II("-webkit-mask",s,t)||await II("mask-image",s,t)||await II("-webkit-mask-image",s,t)}async function M1s(s,t){const n=Yg(s,HTMLImageElement);if(!(n&&!g3e(s.src))&&!(Yg(s,SVGImageElement)&&!g3e(s.href.baseVal)))return;const r=n?s.src:s.href.baseVal,a=await zIe(r,FIe(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 I1s(s,t){const r=b4(s.childNodes).map(a=>T0t(a,t));await Promise.all(r).then(()=>s)}async function T0t(s,t){Yg(s,Element)&&(await A1s(s,t),await M1s(s,t),await I1s(s,t))}function P1s(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 MHe={};async function IHe(s){let t=MHe[s];if(t!=null)return t;const r=await(await fetch(s)).text();return t={url:s,cssText:r},MHe[s]=t,t}async function PHe(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),j0t(o,t.fetchRequestInit,({result:c})=>(n=n.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>n)}function LHe(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 L1s(s,t){const n=[],r=[];return s.forEach(a=>{if("cssRules"in a)try{b4(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=IHe(c).then(u=>PHe(u,t)).then(u=>LHe(u).forEach(h=>{try{a.insertRule(h,h.startsWith("@import")?o+=1:a.cssRules.length)}catch(p){console.error("Error inserting rule from remote css",{rule:h,error:p})}})).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(IHe(a.href).then(o=>PHe(o,t)).then(o=>LHe(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{b4(a.cssRules||[]).forEach(i=>{n.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),n))}function D1s(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>S0t(t.style.getPropertyValue("src")))}async function R1s(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const n=b4(s.ownerDocument.styleSheets),r=await L1s(n,t);return D1s(r)}function E0t(s){return s.trim().replace(/["']/g,"")}function O1s(s){const t=new Set;function n(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(i=>{t.add(E0t(i))}),Array.from(r.children).forEach(i=>{i instanceof HTMLElement&&n(i)})}return n(s),t}async function F1s(s,t){const n=await R1s(s,t),r=O1s(s);return(await Promise.all(n.filter(i=>r.has(E0t(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return C0t(i.cssText,l,t)}))).join(` `)}async function z1s(s,t){const n=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await F1s(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 B1s(s,t={}){const{width:n,height:r}=w0t(s,t),a=await vve(s,t,!0);return await z1s(a,t),await T0t(a,t),P1s(a,t),await n1s(a,n,r)}async function $1s(s,t={}){const{width:n,height:r}=w0t(s,t),a=await B1s(s,t),i=await Cxe(a),l=document.createElement("canvas"),o=l.getContext("2d"),c=t.pixelRatio||e1s(),d=t.canvasWidth||n,u=t.canvasHeight||r;return l.width=d*c,l.height=u*c,t.skipAutoScale||t1s(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 BIe(s,t={}){return(await $1s(s,t)).toDataURL()}const D8=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),bve={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},RS={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},U1s=({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})]})]}),$Ie=St.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=bve[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:D8(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",D8(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(U1s,{branding:r,dim:l})]})]})]})});$Ie.displayName="LuxuryDarkTemplate";const q1s=({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})]})]}),UIe=St.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var f;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(f=s.photos)==null?void 0:f[a],d=bve[t],u=n==="instagram-story",h=n==="facebook-post",p=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:p,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:p,marginBottom:l.w*.012},children:D8(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:`${p}10`,border:`2px solid ${p}`,borderRadius:l.w*.01,padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.022,fontWeight:700,color:p,display:"inline-block",marginBottom:l.w*.015},children:"SAT & SUN • 1–4 PM"}),e.jsx(q1s,{branding:r,dim:l,accentColor:p})]})]})});UIe.displayName="ModernCleanTemplate";const V1s=({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})]})]}),qIe=St.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=bve[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:D8(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(V1s,{branding:r,dim:l})]})]})]})});qIe.displayName="BoldColorfulTemplate";const H1s=({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})]})]}),VIe=St.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=bve[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:D8(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",D8(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(H1s,{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"}})]})]})})});VIe.displayName="EditorialTemplate";const G1s=[{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:"📉"}],DHe=[{value:"instagram-square",label:"IG Post",dimensions:"1080×1080",icon:e.jsx(du,{className:"h-4 w-4"})},{value:"instagram-story",label:"IG Story",dimensions:"1080×1920",icon:e.jsx(du,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook",dimensions:"1200×630",icon:e.jsx(Lh,{className:"h-4 w-4"})}],W1s=[{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:"📰"}],RHe={"luxury-dark":$Ie,"modern-clean":UIe,"bold-colorful":qIe,editorial:VIe},D2e=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function K1s(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;oDe.is_default))??(s==null?void 0:s[0])??null,[n,r]=N.useState(void 0),a=(s==null?void 0:s.find(De=>De.id===n))??t,i=ma(),[l,o]=N.useState("mine"),[c,d]=N.useState(""),[u,h]=N.useState("address"),[p,f]=N.useState(!1),[g,_]=N.useState([]),[v,j]=N.useState(null),[b,S]=N.useState(0),[A,T]=N.useState("just-listed"),[L,D]=N.useState(["instagram-square"]),[M,F]=N.useState("luxury-dark"),[z,V]=N.useState(!0),[W,Y]=N.useState(!1),[K,J]=N.useState([]),[ne,ie]=N.useState("search"),he=N.useRef({}),{data:ce=[],isLoading:pe}=ct({queryKey:["marketing-studio-my-listings",i],enabled:!!i,queryFn:async()=>{const{data:De,error:Ie}=await q.from("listings").select("id, property_address, city, state, price, status, bedrooms, bathrooms, square_footage, year_built, property_type, description, created_at, listing_photos(photo_url, sort_order, is_primary)").eq("agent_id",i).order("created_at",{ascending:!1}).limit(60);if(Ie)throw Ie;return(De||[]).map(Fe=>{const qe=(Fe.listing_photos||[]).slice().sort((Ze,Ne)=>(Ne.is_primary?1:0)-(Ze.is_primary?1:0)||(Ze.sort_order??0)-(Ne.sort_order??0)).map(Ze=>Ze.photo_url).filter(Boolean),be=String(Fe.status||"");return{mlsNumber:Fe.id,address:Fe.property_address||"",city:Fe.city||"",state:Fe.state||"",zip:"",price:Number(Fe.price||0),status:be,bedrooms:Number(Fe.bedrooms||0),bathrooms:Number(Fe.bathrooms||0),sqft:Number(Fe.square_footage||0),lotSize:"",yearBuilt:Fe.year_built??null,propertyType:Fe.property_type||"",description:Fe.description||"",photos:qe,listDate:Fe.created_at,soldDate:be.toLowerCase().includes("sold")?Fe.created_at:null,soldPrice:null,agent:{name:"",office:""}}})}}),le=N.useMemo(()=>!z||!a?{enabled:!1}:{enabled:!0,agentName:a.display_name||"",brokerage:a.tagline||"",agentPhotoUrl:a.headshot_url||void 0},[z,a]),ve=async()=>{if(c.trim()){f(!0),_([]);try{const{data:De,error:Ie}=await q.functions.invoke("repliers-mls-search",{body:{searchType:u,query:c.trim()}});if(Ie)throw Ie;if(De!=null&&De.error)throw new Error(De.error);_((De==null?void 0:De.listings)||[]),((De==null?void 0:De.listings)||[]).length===0&&ae.info("No listings found. Try a different search.")}catch(De){ae.error(De.message||"Search failed")}finally{f(!1)}}},ge=De=>{var Ie;j(De),S(0),ie("customize"),De.soldDate||(Ie=De.status)!=null&&Ie.toLowerCase().includes("sold")?T("just-sold"):T("just-listed")},Te=De=>D(Ie=>Ie.includes(De)?Ie.filter(Fe=>Fe!==De):[...Ie,De]),Me=v?{listing:v,postType:A,format:"instagram-square",branding:le,selectedPhotoIndex:b}:null,Ce=N.useCallback(async()=>{if(!(!v||L.length===0)){Y(!0),J([]),ie("generate");try{await new Promise(Ie=>setTimeout(Ie,600));const De=[];for(const Ie of L){const Fe=`${M}-${Ie}`,qe=he.current[Fe];if(!qe)continue;const be=RS[Ie],Ze=await BIe(qe,{width:be.width,height:be.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});De.push({format:Ie,url:Ze})}J(De),ae.success(`Generated ${De.length} design${De.length>1?"s":""}!`)}catch(De){ae.error(De.message||"Generation failed")}finally{Y(!1)}}},[v,L,M]),Ae=(De,Ie)=>{const Fe=`${((v==null?void 0:v.address)||"listing").replace(/\s+/g,"-")}-${A}-${Ie}.png`;try{const qe=K1s(De),be=URL.createObjectURL(qe);if(Y1s)window.open(be,"_blank"),ae.message("Long-press the image to save to Photos");else{const Ze=document.createElement("a");Ze.href=be,Ze.download=Fe,document.body.appendChild(Ze),Ze.click(),document.body.removeChild(Ze)}setTimeout(()=>URL.revokeObjectURL(be),6e4)}catch{const qe=document.createElement("a");qe.href=De,qe.download=Fe,qe.click()}};return N.useEffect(()=>{!n&&t&&r(t.id)},[t,n]),e.jsx(Ts,{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(Go,{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(Ln,{to:"/marketing-studio",children:[e.jsx(Hr,{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(ze,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(un,{className:"h-3 w-3"})," Listing Templates"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight",children:"Just Listed. Just Stunning."}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground max-w-2xl mt-1",children:"Search any MLS listing and get pixel-perfect, on-brand graphics for Instagram, Stories and Facebook in one click."})]}),s&&s.length>0&&e.jsxs("div",{className:"min-w-0 sm:min-w-[220px]",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Brand preset"}),e.jsxs(ds,{value:n,onValueChange:r,children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Default"})}),e.jsx(cs,{children:s.map(De=>e.jsxs(Qe,{value:De.id,children:[De.name,De.is_default?" (default)":""]},De.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:()=>ie("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${ne==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:[e.jsx(vr,{className:"h-3.5 w-3.5"})," 1. Find listing"]}),e.jsx(xa,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{onClick:()=>v&&ie("customize"),disabled:!v,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${ne==="customize"?"bg-primary text-primary-foreground":v?"bg-muted text-muted-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(un,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(xa,{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 ${ne==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(Pa,{className:"h-3.5 w-3.5"})," 3. Download"]})]}),ne==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Br,{value:l,onValueChange:De=>o(De),children:e.jsxs(Fr,{className:"grid grid-cols-2 w-full sm:w-auto",children:[e.jsxs(Kt,{value:"mine",children:[e.jsx(Or,{className:"h-4 w-4 mr-1.5"})," My Listings"]}),e.jsxs(Kt,{value:"mls",children:[e.jsx(vr,{className:"h-4 w-4 mr-1.5"})," MLS Search"]})]})}),l==="mine"&&e.jsx("div",{className:"space-y-3",children:pe?e.jsx(fe,{children:e.jsx(Ee,{className:"py-12 flex items-center justify-center",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):ce.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-10 text-center space-y-2",children:[e.jsx(Or,{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(Ln,{to:"/mission-control/listings",children:"Go to Listings"})})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[ce.length," listing",ce.length!==1?"s":""," from your Listing Exchange"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:ce.map((De,Ie)=>{var Fe;return e.jsx(fe,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>ge(De),children:e.jsx(Ee,{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:(Fe=De.photos)!=null&&Fe[0]?e.jsx("img",{src:De.photos[0],alt:De.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(Or,{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:De.price>0?D2e(De.price):"—"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:De.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[De.city,De.state?`, ${De.state}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[De.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(H2,{className:"h-3 w-3"})," ",De.bedrooms]}),De.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Cp,{className:"h-3 w-3"})," ",De.bathrooms]}),De.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(RA,{className:"h-3 w-3"})," ",De.sqft.toLocaleString()]})]}),De.status&&e.jsx("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:e.jsx(ze,{variant:"outline",className:"text-[10px]",children:De.status})})]})]})})},De.mlsNumber||Ie)})})]})}),l==="mls"&&e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"overflow-hidden",children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2 text-base md:text-lg",children:[e.jsx(vr,{className:"h-5 w-5 text-primary"})," Search MLS"]}),e.jsxs(Vn,{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(Ee,{className:"space-y-3",children:[e.jsx(Br,{value:u,onValueChange:De=>h(De),children:e.jsxs(Fr,{children:[e.jsxs(Kt,{value:"address",children:[e.jsx(ka,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Kt,{value:"mls",children:[e.jsx(uh,{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:De=>d(De.target.value),placeholder:u==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:De=>De.key==="Enter"&&ve()}),e.jsxs(B,{onClick:ve,disabled:p||!c.trim(),className:"sm:w-auto w-full",children:[p?e.jsx(ts,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx(vr,{className:"h-4 w-4 mr-1.5"})," Search"]})]})]})]}),g.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[g.length," listing",g.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:g.map((De,Ie)=>{var Fe;return e.jsx(fe,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>ge(De),children:e.jsx(Ee,{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:(Fe=De.photos)!=null&&Fe[0]?e.jsx("img",{src:De.photos[0],alt:De.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(Or,{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:D2e(De.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:De.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[De.city,", ",De.state," ",De.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[De.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(H2,{className:"h-3 w-3"})," ",De.bedrooms]}),De.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Cp,{className:"h-3 w-3"})," ",De.bathrooms]}),De.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(RA,{className:"h-3 w-3"})," ",De.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[De.mlsNumber&&e.jsx(ze,{variant:"outline",className:"text-[10px]",children:De.mlsNumber}),De.status&&e.jsx(ze,{variant:"outline",className:"text-[10px]",children:De.status})]})]})]})})},De.mlsNumber||Ie)})})]})]})]}),ne==="customize"&&v&&Me&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-6",children:[e.jsxs(fe,{className:"lg:col-span-1 overflow-hidden min-w-0",children:[e.jsx(Mt,{className:"pb-3",children:e.jsx(It,{className:"text-base",children:"Selected listing"})}),e.jsxs(Ee,{className:"space-y-3",children:[v.photos.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"aspect-[4/3] rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:v.photos[b],alt:"",className:"w-full h-full object-cover"})}),v.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx(B,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>S(De=>Math.max(0,De-1)),disabled:b===0,children:e.jsx(pl,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b+1," of ",v.photos.length]}),e.jsx(B,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>S(De=>Math.min(v.photos.length-1,De+1)),disabled:b===v.photos.length-1,children:e.jsx(xa,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:D2e(v.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:v.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.city,", ",v.state," ",v.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[v.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:v.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),v.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:v.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),v.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:v.sqft.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sq Ft"})]})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{ie("search"),j(null)},children:[e.jsx(cm,{className:"h-3.5 w-3.5 mr-1.5"})," Choose different listing"]})]})]}),e.jsxs(fe,{className:"lg:col-span-2 overflow-hidden min-w-0",children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(un,{className:"h-5 w-5 text-primary"})," Customize"]}),e.jsx(Vn,{children:"Pick a template, post type, and output format."})]}),e.jsxs(Ee,{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(fl,{className:"h-4 w-4"})," Template style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:W1s.map(De=>e.jsxs("button",{onClick:()=>F(De.value),className:`flex flex-col items-center gap-1 px-2 py-3 rounded-lg border-2 transition-all text-center ${M===De.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:De.preview}),e.jsx("span",{className:"text-sm font-medium",children:De.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:De.description})]},De.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:G1s.map(De=>e.jsxs("button",{onClick:()=>T(De.value),className:`flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${A===De.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:De.icon})," ",e.jsx("span",{className:"truncate",children:De.label})]},De.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:DHe.map(De=>e.jsxs("button",{onClick:()=>Te(De.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${L.includes(De.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[De.icon,e.jsxs("div",{className:"text-left min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:De.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:De.dimensions})]})]},De.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(Xi,{className:"h-4 w-4"})," Show my branding"]}),e.jsx(bn,{checked:z,onCheckedChange:V})]}),z&&!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No brand preset yet. ",e.jsx(Ln,{to:"/marketing-studio/brand-kit",className:"underline",children:"Create one"})," to add your headshot and name."]}),z&&a&&e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-muted/30",children:[a.headshot_url&&e.jsx("img",{src:a.headshot_url,alt:"",className:"w-10 h-10 rounded-full object-cover border"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:a.display_name||"Unnamed agent"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.tagline||a.email||""})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(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*(RS[L[0]||"instagram-square"].height/RS[L[0]||"instagram-square"].width)},children:(()=>{const De=RHe[M],Ie=L[0]||"instagram-square";return e.jsx(De,{...Me,format:Ie})})()})})]}),e.jsx(B,{onClick:Ce,disabled:L.length===0||W,size:"lg",className:"w-full gap-2",children:W?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-5 w-5 animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(un,{className:"h-5 w-5"})," Generate ",L.length," design",L.length>1?"s":""]})})]})]})]}),ne==="generate"&&e.jsxs("div",{className:"space-y-4",children:[W&&e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(ts,{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."})]})}),K.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:()=>ie("customize"),children:[e.jsx(cm,{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:K.map((De,Ie)=>{const Fe=DHe.find(qe=>qe.value===De.format);return e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:De.url,alt:"",className:"w-full rounded"})}),e.jsxs(Ee,{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:[Fe==null?void 0:Fe.icon,e.jsx("span",{className:"text-sm font-medium",children:Fe==null?void 0:Fe.label})]}),e.jsx(ze,{variant:"outline",className:"text-[10px]",children:Fe==null?void 0:Fe.dimensions})]}),e.jsxs(B,{size:"sm",className:"w-full gap-1.5",onClick:()=>Ae(De.url,De.format),children:[e.jsx(Pa,{className:"h-3.5 w-3.5"})," Download"]})]})]},Ie)})})]})]}),ne==="generate"&&v&&Me&&e.jsx("div",{style:{position:"fixed",left:"-99999px",top:0,pointerEvents:"none"},"aria-hidden":!0,children:L.map(De=>{const Ie=RHe[M],Fe=RS[De];return e.jsx("div",{style:{width:Fe.width,height:Fe.height},children:e.jsx(Ie,{ref:qe=>{he.current[`${M}-${De}`]=qe},...Me,format:De})},`${M}-${De}`)})})]})})}var A0t="Toggle",HIe=N.forwardRef((s,t)=>{const{pressed:n,defaultPressed:r,onPressedChange:a,...i}=s,[l,o]=hm({prop:n,onChange:a,defaultProp:r??!1,caller:A0t});return e.jsx(Jr.button,{type:"button","aria-pressed":l,"data-state":l?"on":"off","data-disabled":s.disabled?"":void 0,...i,ref:t,onClick:_r(s.onClick,()=>{s.disabled||o(!l)})})});HIe.displayName=A0t;var M0t=HIe,cC="ToggleGroup",[I0t,rgn]=pu(cC,[W4]),P0t=W4(),GIe=St.forwardRef((s,t)=>{const{type:n,...r}=s;if(n==="single"){const a=r;return e.jsx(Q1s,{...a,ref:t})}if(n==="multiple"){const a=r;return e.jsx(X1s,{...a,ref:t})}throw new Error(`Missing prop \`type\` expected on \`${cC}\``)});GIe.displayName=cC;var[L0t,D0t]=I0t(cC),Q1s=St.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=hm({prop:n,defaultProp:r??"",onChange:a,caller:cC});return e.jsx(L0t,{scope:s.__scopeToggleGroup,type:"single",value:St.useMemo(()=>l?[l]:[],[l]),onItemActivate:o,onItemDeactivate:St.useCallback(()=>o(""),[o]),children:e.jsx(R0t,{...i,ref:t})})}),X1s=St.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=hm({prop:n,defaultProp:r??[],onChange:a,caller:cC}),c=St.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=St.useCallback(u=>o((h=[])=>h.filter(p=>p!==u)),[o]);return e.jsx(L0t,{scope:s.__scopeToggleGroup,type:"multiple",value:l,onItemActivate:c,onItemDeactivate:d,children:e.jsx(R0t,{...i,ref:t})})});GIe.displayName=cC;var[J1s,ebs]=I0t(cC),R0t=St.forwardRef((s,t)=>{const{__scopeToggleGroup:n,disabled:r=!1,rovingFocus:a=!0,orientation:i,dir:l,loop:o=!0,...c}=s,d=P0t(n),u=NN(l),h={role:"group",dir:u,...c};return e.jsx(J1s,{scope:n,rovingFocus:a,disabled:r,children:a?e.jsx(W0e,{asChild:!0,...d,orientation:i,dir:u,loop:o,children:e.jsx(Jr.div,{...h,ref:t})}):e.jsx(Jr.div,{...h,ref:t})})}),Txe="ToggleGroupItem",O0t=St.forwardRef((s,t)=>{const n=D0t(Txe,s.__scopeToggleGroup),r=ebs(Txe,s.__scopeToggleGroup),a=P0t(s.__scopeToggleGroup),i=n.value.includes(s.value),l=r.disabled||s.disabled,o={...s,pressed:i,disabled:l},c=St.useRef(null);return r.rovingFocus?e.jsx(K0e,{asChild:!0,...a,focusable:!l,active:i,ref:c,children:e.jsx(OHe,{...o,ref:t})}):e.jsx(OHe,{...o,ref:t})});O0t.displayName=Txe;var OHe=St.forwardRef((s,t)=>{const{__scopeToggleGroup:n,value:r,...a}=s,i=D0t(Txe,n),l={role:"radio","aria-checked":s.pressed,"aria-pressed":void 0},o=i.type==="single"?l:void 0;return e.jsx(HIe,{...o,...a,ref:t,onPressedChange:c=>{c?i.onItemActivate(r):i.onItemDeactivate(r)}})}),F0t=GIe,z0t=O0t;const B0t=UM("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"}}),tbs=N.forwardRef(({className:s,variant:t,size:n,...r},a)=>e.jsx(M0t,{ref:a,className:Et(B0t({variant:t,size:n,className:s})),...r}));tbs.displayName=M0t.displayName;const $0t=N.createContext({size:"default",variant:"default"}),FL=N.forwardRef(({className:s,variant:t,size:n,children:r,...a},i)=>e.jsx(F0t,{ref:i,className:Et("flex items-center justify-center gap-1",s),...a,children:e.jsx($0t.Provider,{value:{variant:t,size:n},children:r})}));FL.displayName=F0t.displayName;const QA=N.forwardRef(({className:s,children:t,variant:n,size:r,...a},i)=>{const l=N.useContext($0t);return e.jsx(z0t,{ref:i,className:Et(B0t({variant:l.variant||n,size:l.size||r}),s),...a,children:t})});QA.displayName=z0t.displayName;const sbs=[{id:"meet",label:"Meet Your Agent",icon:Xi,description:"Polished intro card with your headshot, story, and contact."},{id:"testimonial",label:"Testimonial",icon:gb,description:"Turn a Zillow / Google review into a branded graphic."},{id:"milestone",label:"Milestone",icon:vo,description:"Celebrate homes sold, awards, anniversaries, achievements."},{id:"tip",label:"Pro Tip",icon:vw,description:"Drop a value-bomb tip — buyer/seller advice, market insight."},{id:"quote",label:"Quote / Mantra",icon:$d,description:"Personal philosophy, mantra, or rallying call."}],R2e={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"}},nbs=[{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."}],FHe={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 rbs(){const{data:s}=hgs(),{data:t}=jU(),[n,r]=N.useState(void 0),a=N.useMemo(()=>(t==null?void 0:t.find(g=>g.id===n))??s??null,[t,n,s]),[i,l]=N.useState({template:"meet",style:"editorial",aspect:"portrait",rating:5,...FHe.meet}),o=g=>l(_=>({..._,...g})),c=g=>l(_=>({..._,template:g,...FHe[g]})),d=N.useRef(null),[u,h]=N.useState(!1),p=async()=>{if(!d.current)return;h(!0);const g=d.current,_=g.style.transform;try{g.style.transform="none",await new Promise(b=>requestAnimationFrame(()=>b(null)));const v=await BIe(g,{cacheBust:!0,pixelRatio:2,width:g.offsetWidth,height:g.offsetHeight,backgroundColor:"#ffffff"}),j=document.createElement("a");j.href=v,j.download=`personal-branding-${i.template}-${Date.now()}.png`,document.body.appendChild(j),j.click(),j.remove(),ae.success("Downloaded to your device")}catch(v){ae.error((v==null?void 0:v.message)||"Export failed")}finally{g.style.transform=_,h(!1)}},f=R2e[i.aspect];return e.jsx(Ts,{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(Go,{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(Ln,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Hr,{className:"h-3 w-3"})," Back to Marketing Studio"]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(un,{className:"h-3 w-3"})," New"]})}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Personal Branding"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground max-w-2xl",children:"Five editorial-grade templates, four distinct aesthetics. Pick one, drop in your story, export in seconds."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs(Ln,{to:"/marketing-studio/brand-kit",children:[e.jsx(fl,{className:"h-4 w-4 mr-1"})," Brand Kit"]})}),e.jsxs(B,{onClick:p,disabled:u,children:[e.jsx(Pa,{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(fe,{children:e.jsxs(Ee,{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:sbs.map(g=>{const _=g.icon,v=i.template===g.id;return e.jsxs("button",{onClick:()=>c(g.id),className:`text-left rounded-lg border p-3 transition-all ${v?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[e.jsx(_,{className:"h-4 w-4 mb-1"}),e.jsx("div",{className:"text-xs font-semibold",children:g.label})]},g.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Style"}),e.jsx(FL,{type:"single",value:i.style,onValueChange:g=>g&&o({style:g}),className:"grid grid-cols-2 gap-1",children:nbs.map(g=>e.jsx(QA,{value:g.id,className:"text-xs h-9",children:g.label},g.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(FL,{type:"single",value:i.aspect,onValueChange:g=>g&&o({aspect:g}),className:"grid grid-cols-3 gap-1",children:Object.keys(R2e).map(g=>e.jsx(QA,{value:g,className:"text-xs h-9",children:R2e[g].label},g))})]}),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(ds,{value:n??(s==null?void 0:s.id)??"",onValueChange:r,children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Choose preset"})}),e.jsx(cs,{children:t.map(g=>e.jsx(Qe,{value:g.id,children:g.name},g.id))})]})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{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(Es,{id:"headline",value:i.headline,onChange:g=>o({headline:g.target.value}),rows:2})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"subline",className:"text-xs",children:"Subline"}),e.jsx(ye,{id:"subline",value:i.subline,onChange:g=>o({subline:g.target.value})})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"body",className:"text-xs",children:"Body"}),e.jsx(Es,{id:"body",value:i.body,onChange:g=>o({body:g.target.value}),rows:4})]}),(i.template==="testimonial"||i.template==="quote")&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"attribution",className:"text-xs",children:"Attribution"}),e.jsx(ye,{id:"attribution",value:i.attribution,onChange:g=>o({attribution:g.target.value}),placeholder:"— Client name / Source"})]}),i.template==="testimonial"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Rating"}),e.jsx(FL,{type:"single",value:String(i.rating),onValueChange:g=>g&&o({rating:Number(g)}),className:"grid grid-cols-5 gap-1",children:[1,2,3,4,5].map(g=>e.jsxs(QA,{value:String(g),className:"text-xs h-9",children:[g,"★"]},g))})]}),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:g=>o({badgeText:g.target.value})})]})]})})]}),e.jsx(abs,{aspect:f,canvasRef:d,children:e.jsx(ibs,{form:i,preset:a,width:f.w,height:f.h})})]})]})})}function abs({aspect:s,canvasRef:t,children:n}){const r=N.useRef(null),[a,i]=N.useState(.5);return N.useEffect(()=>{const l=r.current;if(!l)return;const o=()=>{const d=l.clientWidth-32;i(Math.min(1,d/s.w))};o();const c=new ResizeObserver(o);return c.observe(l),()=>c.disconnect()},[s.w]),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{ref:r,className:"rounded-xl bg-muted/40 p-4 md:p-6 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:s.w*a,height:s.h*a,position:"relative"},className:"shadow-2xl",children:e.jsx("div",{ref:t,style:{width:s.w,height:s.h,transform:`scale(${a})`,transformOrigin:"top left",position:"absolute",top:0,left:0},children:n})})}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2 text-center",children:["Preview scaled. Export is ",s.w,"×",s.h,"px @ 2× retina."]})]})}function ibs({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)||"",p=(t==null?void 0:t.website_url)||"",f={form:s,brandColor:a,accentColor:i,headshot:l,logo:o,name:c,phone:d,email:u,tagline:h,website:p,width:n,height:r};return s.style==="editorial"?e.jsx(obs,{...f}):s.style==="bold"?e.jsx(lbs,{...f}):s.style==="luxury"?e.jsx(dbs,{...f}):e.jsx(cbs,{...f})}function U0t({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 _ve({rating:s,color:t}){return e.jsx("div",{style:{display:"flex",gap:4},children:Array.from({length:5}).map((n,r)=>e.jsx(ca,{size:28,fill:r1.5;return e.jsxs("div",{style:{width:h,height:p,background:"#FAF7F2",position:"relative",fontFamily:"Georgia, serif",color:"#1a1a1a",overflow:"hidden"},children:[e.jsxs("div",{style:{position:"absolute",top:64,left:64,right:64,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:14,letterSpacing:"0.3em",color:n},children:t.badgeText}),e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:12,letterSpacing:"0.2em",color:"#888"},children:["EST. ",new Date().getFullYear()]})]}),e.jsx("div",{style:{position:"absolute",top:100,left:64,right:64,height:1,background:"#1a1a1a",opacity:.15}}),a&&(t.template==="meet"||t.template==="milestone")&&e.jsx("div",{style:{position:"absolute",top:140,left:64,width:h-128,height:f?700:480,overflow:"hidden",borderRadius:4},children:e.jsx("img",{src:a,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top",filter:"grayscale(0.15)"}})}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:220,textAlign:t.template==="quote"?"center":"left"},children:[t.template==="testimonial"&&e.jsx("div",{style:{fontSize:120,lineHeight:.7,color:r,fontFamily:"Georgia, serif"},children:'"'}),e.jsx("h1",{style:{fontSize:t.template==="quote"?76:92,lineHeight:1.05,fontWeight:400,margin:0,letterSpacing:"-0.02em",whiteSpace:"pre-wrap"},children:t.headline}),t.subline&&e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:22,marginTop:16,color:"#555",fontStyle:"italic"},children:t.subline}),t.body&&e.jsx("p",{style:{fontFamily:"Inter, sans-serif",fontSize:22,lineHeight:1.5,color:"#333",marginTop:28,maxWidth:820},children:t.body}),t.template==="testimonial"&&e.jsxs("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16},children:[e.jsx(_ve,{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(U0t,{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 lbs(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%, ${ubs(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(_ve,{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(U0t,{name:l,phone:o,email:c,website:d,color:"#fff"})]})]})}function cbs(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(_ve,{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 dbs(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(_ve,{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 ubs(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 hbs=()=>{const{swagId:s}=bi(),{user:t}=ys(),{toast:n}=Ba(),r=Ht(),{trackEngagement:a}=KD(),[i,l]=N.useState(""),{data:o,isLoading:c}=ct({queryKey:["social-swag-detail",s],queryFn:async()=>{const{data:j,error:b}=await q.from("social_swag").select("*").eq("id",s).single();if(b)throw b;const{data:S}=await q.from("social_swag_links").select("*").eq("swag_id",s).order("sort_order");return{...j,links:S||[]}},enabled:!!s});N.useEffect(()=>{o&&a("social_swag",o.id,o.title,"view")},[o==null?void 0:o.id]);const{data:d=[]}=ct({queryKey:["social-swag-likes",s],queryFn:async()=>{const{data:j,error:b}=await q.from("social_swag_likes").select("*").eq("swag_id",s);if(b)throw b;return j},enabled:!!s}),{data:u=[]}=ct({queryKey:["social-swag-comments",s],queryFn:async()=>{const{data:j,error:b}=await q.from("social_swag_comments").select("*").eq("swag_id",s).order("created_at",{ascending:!1});if(b)throw b;const S=[...new Set(j.map(L=>L.user_id))],{data:A}=await q.from("profiles").select("id, name").in("id",S),T=new Map((A==null?void 0:A.map(L=>[L.id,L.name]))||[]);return j.map(L=>({...L,user_name:T.get(L.user_id)||"Unknown User"}))},enabled:!!s}),h=gt({mutationFn:async j=>{const{error:b}=await q.from("social_swag_comments").insert({swag_id:s,user_id:t.id,content:j});if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),l(""),n({title:"Comment added!"})},onError:j=>{n({title:"Error adding comment",description:j.message,variant:"destructive"})}}),p=gt({mutationFn:async j=>{const{error:b}=await q.from("social_swag_comments").delete().eq("id",j);if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),n({title:"Comment deleted"})}}),f=gt({mutationFn:async()=>{const j=d.find(b=>b.user_id===(t==null?void 0:t.id));if(j){const{error:b}=await q.from("social_swag_likes").delete().eq("id",j.id);if(b)throw b}else{const{error:b}=await q.from("social_swag_likes").insert({swag_id:s,user_id:t.id});if(b)throw b}},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-likes",s]})}}),g=d.some(j=>j.user_id===(t==null?void 0:t.id)),_=j=>j.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),v=j=>{j.preventDefault(),!(!i.trim()||!t)&&h.mutate(i.trim())};return c?e.jsx(Ts,{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(Ts,{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(Ln,{to:"/social-swag",children:[e.jsx(Hr,{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(XD,{resourceType:"social_swag",resourceId:o.id,resourceTitle:o.title}),e.jsxs(B,{variant:g?"default":"outline",className:"gap-2 w-fit",onClick:()=>f.mutate(),disabled:!t||f.isPending,children:[e.jsx(Vm,{className:`h-4 w-4 ${g?"fill-current":""}`}),d.length," ",d.length===1?"Like":"Likes"]})]})]}),o.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:o.description}})]}),o.links.length>0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Jo,{className:"h-4 w-4"}),o.links.length===1?"Canva Link":"Canva Links"]}),e.jsx("div",{className:"grid gap-2",children:o.links.map(j=>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(j.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:j.title}),e.jsx(tr,{className:"h-4 w-4 text-muted-foreground"})]},j.id))})]})}),e.jsx(ll,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ql,{className:"h-5 w-5"}),"Comments (",u.length,")"]}),t?e.jsxs("form",{onSubmit:v,className:"flex gap-2",children:[e.jsx(Es,{placeholder:"Add a comment...",value:i,onChange:j=>l(j.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(cr,{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(fe,{children:e.jsx(Ee,{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(j=>e.jsx(fe,{children:e.jsx(Ee,{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(aa,{className:"text-sm",children:_(j.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:j.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Vo(new Date(j.created_at),{addSuffix:!0})}),j.user_id===(t==null?void 0:t.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>p.mutate(j.id),children:e.jsx(_n,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:j.content})]})]})})},j.id))})]})]})}):e.jsx(Ts,{title:"Social Swag",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Jo,{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(Ln,{to:"/social-swag",children:"Back to Social Swag"})})]})})},mbs=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=N.useState(!0),[o,c]=N.useState(!0),[d,u]=N.useState(!0),h=p=>p.split(" ").map(f=>f[0]).join("").toUpperCase().slice(0,2);return e.jsx("aside",{className:"w-64 shrink-0 hidden lg:block relative z-0",children:e.jsx("div",{className:"sticky top-4 space-y-4 max-h-[calc(100vh-8rem)] overflow-y-auto overscroll-contain",children:e.jsxs("div",{className:"space-y-2 pr-4",children:[e.jsxs(B,{variant:n==="all"?"secondary":"ghost",className:"w-full justify-start",onClick:()=>r("all"),children:[e.jsx(XS,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(dy,{open:i,onOpenChange:l,children:[e.jsx(uy,{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(io,{className:"h-4 w-4"}):e.jsx(xa,{className:"h-4 w-4"})]})}),e.jsx(hy,{className:"space-y-1 pl-2",children:s.map(p=>e.jsxs(B,{variant:n===p.id?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>r(p.id),children:[e.jsx("span",{className:"mr-2",children:p.icon||"📂"}),e.jsx("span",{className:"truncate",children:p.name})]},p.id))})]}),t.length>0&&e.jsxs(dy,{open:o,onOpenChange:c,children:[e.jsx(uy,{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(Kc,{className:"h-3 w-3"}),"Your Groups"]}),o?e.jsx(io,{className:"h-4 w-4"}):e.jsx(xa,{className:"h-4 w-4"})]})}),e.jsx(hy,{className:"space-y-1 pl-2",children:t.map(p=>e.jsxs(B,{variant:n===`group:${p.id}`?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>r(`group:${p.id}`),children:[e.jsx("span",{className:"mr-2",children:p.icon||"🔒"}),e.jsx("span",{className:"truncate",children:p.name})]},p.id))})]}),e.jsxs(dy,{open:d,onOpenChange:u,children:[e.jsx(uy,{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(Nn,{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(io,{className:"h-4 w-4"}):e.jsx(xa,{className:"h-4 w-4"})]})}),e.jsx(hy,{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(p=>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(ni,{src:p.avatarUrl}),e.jsx(aa,{className:"text-xs",children:h(p.name)})]}),e.jsx(lm,{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:p.name})]},p.id))})]})]})})})},pbs=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=N.useState(!1),o=d=>d.split(" ").map(u=>u[0]).join("").toUpperCase().slice(0,2),c=()=>{if(n==="all")return"All Posts";if(n.startsWith("group:")){const u=n.replace("group:",""),h=t.find(p=>p.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(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"flex-1 justify-between",children:[e.jsx("span",{className:"truncate",children:c()}),e.jsx(io,{className:"h-4 w-4 ml-2 shrink-0"})]})}),e.jsxs(cc,{className:"w-56 bg-background border",children:[e.jsxs(Qr,{onClick:()=>r("all"),children:[e.jsx(XS,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(Zg,{}),e.jsx(M4,{className:"text-xs text-muted-foreground",children:"Categories"}),s.map(d=>e.jsxs(Qr,{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(Zg,{}),e.jsxs(M4,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Kc,{className:"h-3 w-3"}),"Your Groups"]}),t.map(d=>e.jsxs(Qr,{onClick:()=>r(`group:${d.id}`),children:[e.jsx("span",{className:"mr-2",children:d.icon||"🔒"}),d.name]},d.id))]})]})]}),e.jsxs(cg,{open:i,onOpenChange:l,children:[e.jsx(rU,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"icon",className:"relative",children:[e.jsx(Nn,{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(ix,{children:[e.jsx(n0,{children:e.jsxs(r0,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5"}),"Online Now (",a.length,")"]})}),e.jsx(hi,{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(ni,{src:d.avatarUrl}),e.jsx(aa,{children:o(d.name)})]}),e.jsx(lm,{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 O2e,wve="HoverCard",[q0t,agn]=pu(wve,[Gw]),jve=Gw(),[fbs,WIe]=q0t(wve),V0t=s=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=jve(t),d=N.useRef(0),u=N.useRef(0),h=N.useRef(!1),p=N.useRef(!1),[f,g]=hm({prop:r,defaultProp:a??!1,onChange:i,caller:wve}),_=N.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>g(!0),l)},[l,g]),v=N.useCallback(()=>{clearTimeout(d.current),!h.current&&!p.current&&(u.current=window.setTimeout(()=>g(!1),o))},[o,g]),j=N.useCallback(()=>g(!1),[g]);return N.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),e.jsx(fbs,{scope:t,open:f,onOpenChange:g,onOpen:_,onClose:v,onDismiss:j,hasSelectionRef:h,isPointerDownOnContentRef:p,children:e.jsx($$,{...c,children:n})})};V0t.displayName=wve;var H0t="HoverCardTrigger",G0t=N.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=WIe(H0t,n),i=jve(n);return e.jsx(PD,{asChild:!0,...i,children:e.jsx(Jr.a,{"data-state":a.open?"open":"closed",...r,ref:t,onPointerEnter:_r(s.onPointerEnter,Axe(a.onOpen)),onPointerLeave:_r(s.onPointerLeave,Axe(a.onClose)),onFocus:_r(s.onFocus,a.onOpen),onBlur:_r(s.onBlur,a.onClose),onTouchStart:_r(s.onTouchStart,l=>l.preventDefault())})})});G0t.displayName=H0t;var xbs="HoverCardPortal",[ign,gbs]=q0t(xbs,{forceMount:void 0}),Exe="HoverCardContent",W0t=N.forwardRef((s,t)=>{const n=gbs(Exe,s.__scopeHoverCard),{forceMount:r=n.forceMount,...a}=s,i=WIe(Exe,s.__scopeHoverCard);return e.jsx(Rh,{present:r||i.open,children:e.jsx(ybs,{"data-state":i.open?"open":"closed",...a,onPointerEnter:_r(s.onPointerEnter,Axe(i.onOpen)),onPointerLeave:_r(s.onPointerLeave,Axe(i.onClose)),ref:t})})});W0t.displayName=Exe;var ybs=N.forwardRef((s,t)=>{const{__scopeHoverCard:n,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,...o}=s,c=WIe(Exe,n),d=jve(n),u=N.useRef(null),h=Si(t,u),[p,f]=N.useState(!1);return N.useEffect(()=>{if(p){const g=document.body;return O2e=g.style.userSelect||g.style.webkitUserSelect,g.style.userSelect="none",g.style.webkitUserSelect="none",()=>{g.style.userSelect=O2e,g.style.webkitUserSelect=O2e}}},[p]),N.useEffect(()=>{if(u.current){const g=()=>{f(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var v;((v=document.getSelection())==null?void 0:v.toString())!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",g),()=>{document.removeEventListener("pointerup",g),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),N.useEffect(()=>{u.current&&_bs(u.current).forEach(_=>_.setAttribute("tabindex","-1"))}),e.jsx(H4,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:l,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:_r(i,g=>{g.preventDefault()}),onDismiss:c.onDismiss,children:e.jsx(U$,{...d,...o,onPointerDown:_r(o.onPointerDown,g=>{g.currentTarget.contains(g.target)&&f(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:h,style:{...o.style,userSelect:p?"text":void 0,WebkitUserSelect:p?"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)"}})})}),vbs="HoverCardArrow",bbs=N.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=jve(n);return e.jsx(q$,{...a,...r,ref:t})});bbs.displayName=vbs;function Axe(s){return t=>t.pointerType==="touch"?void 0:s()}function _bs(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 wbs=V0t,jbs=G0t,K0t=W0t;const Nbs=wbs,kbs=jbs,Y0t=N.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(K0t,{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}));Y0t.displayName=K0t.displayName;const Sbs=[{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"}],Cbs=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),Z0t=({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(Nbs,{openDelay:200,closeDelay:100,children:[e.jsx(kbs,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(Y0t,{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=Sbs.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(ni,{src:l.user_avatar||void 0}),e.jsx(aa,{className:"text-[10px]",children:Cbs(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 Tbs({images:s,initialIndex:t=0,open:n,onOpenChange:r}){const[a,i]=N.useState(t),[l,o]=N.useState(!1);N.useEffect(()=>{n&&(i(t),o(!1))},[n,t]);const c=()=>{i(p=>p>0?p-1:s.length-1),o(!1)},d=()=>{i(p=>p{n&&(p.key==="ArrowLeft"&&c(),p.key==="ArrowRight"&&d(),p.key==="Escape"&&r(!1))},[n,s.length]);N.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]);const h=s[a];return e.jsx(bs,{open:n,onOpenChange:r,children:e.jsxs(vs,{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(Bn,{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(pl,{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(xa,{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(NL,{className:"h-5 w-5"}):e.jsx(u4,{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:p=>p.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((p,f)=>e.jsx("button",{onClick:()=>{i(f),o(!1)},className:Et("w-12 h-12 rounded overflow-hidden flex-shrink-0 border-2 transition-all",a===f?"border-white":"border-transparent opacity-60 hover:opacity-100"),children:p.type==="video"?e.jsx("video",{src:p.url,className:"w-full h-full object-cover"}):e.jsx("img",{src:p.url,alt:"",className:"w-full h-full object-cover"})},f))})]})})}const HH=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],Ebs=({commentId:s,reactions:t,currentUserId:n})=>{var d,u;const r=Ht(),[a,i]=N.useState(!1),l=t.find(h=>h.user_id===n),o=gt({mutationFn:async h=>{l?l.reaction_type===h?await q.from("community_comment_reactions").delete().eq("id",l.id):await q.from("community_comment_reactions").update({reaction_type:h}).eq("id",l.id):await q.from("community_comment_reactions").insert({comment_id:s,user_id:n,reaction_type:h})},onSuccess:()=>{r.invalidateQueries({queryKey:["community-posts"]}),i(!1)}}),c={};return t.forEach(h=>{c[h.reaction_type]=(c[h.reaction_type]||0)+1}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&e.jsx(Z0t,{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 p;return e.jsx("span",{className:"text-sm",children:(p=HH.find(f=>f.type===h))==null?void 0:p.emoji},h)})}),e.jsx("span",{children:t.length})]})}),n&&e.jsxs(el,{open:a,onOpenChange:i,children:[e.jsx(tl,{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=HH.find(h=>h.type===l.reaction_type))==null?void 0:d.emoji," ",(u=HH.find(h=>h.type===l.reaction_type))==null?void 0:u.label]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gi,{className:"h-3 w-3"}),"Like"]})})}),e.jsx(Ho,{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:HH.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 KIe({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(Ln,{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(N.Fragment,{children:o},c))})}function Mxe({value:s,onChange:t,placeholder:n="What's on your mind? Use @ to mention someone",className:r,minHeight:a="80px",onMentionsChange:i,onTemplatesChange:l,onKeyDown:o,mentionFormat:c="encoded",enableTemplateMentions:d=!1}){const u=N.useRef(null),h=N.useRef(null),[p,f]=N.useState(!1),[g,_]=N.useState("user"),[v,j]=N.useState(""),[b,S]=N.useState(null),[A,T]=N.useState(0),[L,D]=N.useState({top:0,left:0,width:0}),M=N.useRef(new Map),F=N.useRef(new Map),z=ve=>{if(c==="plain"){const Ce=[];return M.current.forEach((De,Ie)=>{ve.includes(`@${Ie}`)&&Ce.push(De)}),[...new Set(Ce)]}const ge=/@\[([^\]]+)\]\(([^)]+)\)/g,Te=[];let Me;for(;(Me=ge.exec(ve))!==null;)Te.push(Me[2]);return[...new Set(Te)]},V=ve=>{if(c==="plain"){const Ce=[];return F.current.forEach((De,Ie)=>{ve.includes(`#${Ie}`)&&Ce.push(De)}),[...new Set(Ce)]}const ge=/#\[([^\]]+)\]\(([^)]+)\)/g,Te=[];let Me;for(;(Me=ge.exec(ve))!==null;)Te.push(Me[2]);return[...new Set(Te)]};N.useEffect(()=>{if(i){const ve=z(s);i(ve)}if(l){const ve=V(s);l(ve)}},[s,i,l,c]);const{data:W=[],isLoading:Y}=ct({queryKey:["mention-users",v],queryFn:async()=>{const ve=q.from("profiles").select("id, name").limit(8),ge=v.length>=1?ve.ilike("name",`%${v}%`):ve.order("name"),{data:Te,error:Me}=await ge;if(Me)throw Me;const Ce=Te.map(De=>De.id),Ae=await Ght(Ce);return Te.map(De=>({id:De.id,name:De.name||"Unknown",avatar_url:Ae.get(De.id)}))},enabled:p&&g==="user",staleTime:3e4}),{data:K=[],isLoading:J}=ct({queryKey:["mention-templates",v],queryFn:async()=>{let ve=q.from("canva_templates").select("id, name, preview_image_url").lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(8);v.length>=1&&(ve=ve.ilike("name",`%${v}%`));const{data:ge,error:Te}=await ve;if(Te)throw Te;return ge||[]},enabled:p&&g==="template"&&d,staleTime:3e4}),ne=g==="user"?Y:J,ie=g==="user"?W:K,he=ve=>ve.split(" ").map(ge=>ge[0]).join("").toUpperCase().slice(0,2),ce=ve=>{const ge=ve.target.value,Te=ve.target.selectionStart;t(ge);const Me=ge.substring(0,Te),Ce=Me.lastIndexOf("@"),Ae=d?Me.lastIndexOf("#"):-1;let De=-1,Ie="user";if(Ce>Ae?(De=Ce,Ie="user"):Ae>Ce&&d&&(De=Ae,Ie="template"),De!==-1){const Fe=Me.substring(De+1),qe=Fe.includes(" "),be=Fe.includes(` `);if(!qe&&!be&&Fe.length<=30){S(De),j(Fe),_(Ie),f(!0),T(0);return}}f(!1),S(null)},pe=ve=>{if(b===null)return;const ge=s.substring(0,b),Te=s.substring(b+v.length+1),Me=g==="user"?"@":"#",Ce=c==="plain"?`${Me}${ve.name} `:`${Me}[${ve.name}](${ve.id}) `;c==="plain"&&(g==="user"?M.current.set(ve.name,ve.id):F.current.set(ve.name,ve.id));const Ae=ge+Ce+Te;t(Ae),f(!1),S(null),j(""),setTimeout(()=>{if(u.current){const De=ge.length+Ce.length;u.current.focus(),u.current.setSelectionRange(De,De)}},0)},le=ve=>{if(!(!p||ie.length===0))switch(ve.key){case"ArrowDown":ve.preventDefault(),T(ge=>(ge+1)%ie.length);break;case"ArrowUp":ve.preventDefault(),T(ge=>(ge-1+ie.length)%ie.length);break;case"Enter":ie[A]&&(ve.preventDefault(),pe(ie[A]));break;case"Escape":ve.preventDefault(),f(!1);break;case"Tab":ie[A]&&(ve.preventDefault(),pe(ie[A]));break}};return N.useEffect(()=>{const ve=ge=>{h.current&&!h.current.contains(ge.target)&&u.current&&!u.current.contains(ge.target)&&f(!1)};return document.addEventListener("mousedown",ve),()=>document.removeEventListener("mousedown",ve)},[]),N.useEffect(()=>{if(!p)return;const ve=()=>{const ge=u.current;if(!ge)return;const Te=ge.getBoundingClientRect();D({top:Te.bottom+4,left:Te.left,width:Te.width})};return ve(),window.addEventListener("resize",ve),window.addEventListener("scroll",ve,!0),()=>{window.removeEventListener("resize",ve),window.removeEventListener("scroll",ve,!0)}},[p,s]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Es,{ref:u,value:s,onChange:ce,onKeyDown:ve=>{le(ve),ve.defaultPrevented||o==null||o(ve)},placeholder:n,className:Et("resize-none",r),style:{minHeight:a}}),p&&Hx.createPortal(e.jsxs("div",{ref:h,className:"fixed z-[1000] max-h-[220px] overflow-hidden rounded-lg border bg-popover shadow-lg",style:{top:L.top,left:L.left,width:L.width,maxWidth:"320px"},children:[e.jsx("div",{className:"px-3 py-1.5 text-xs font-medium text-muted-foreground border-b bg-muted/30",children:g==="user"?"👤 Mention a person":"📋 Link a template"}),ne?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Searching..."}):ie.length===0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:v.length<1?`Type to search ${g==="user"?"people":"templates"}...`:`No ${g==="user"?"users":"templates"} found`}):e.jsx("ul",{className:"py-1 max-h-[180px] overflow-y-auto",children:ie.map((ve,ge)=>e.jsx("li",{className:Et("flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors",ge===A?"bg-accent":"hover:bg-accent/50"),onClick:()=>pe(ve),onMouseEnter:()=>T(ge),children:g==="user"?e.jsxs(e.Fragment,{children:[e.jsxs(ra,{className:"h-6 w-6",children:[e.jsx(ni,{src:ve.avatar_url}),e.jsx(aa,{className:"text-xs",children:he(ve.name)})]}),e.jsx("span",{className:"text-sm font-medium truncate",children:ve.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:ve.preview_image_url?e.jsx("img",{src:ve.preview_image_url,alt:"",className:"w-full h-full object-cover"}):e.jsx(fl,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate",children:ve.name})]})},ve.id))})]}),document.body)]})}function Abs(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,n=[];let r;for(;(r=t.exec(s))!==null;)n.push(r[2]);return[...new Set(n)]}const zHe=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function Q0t({comment:s,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l=0}){const o=Ht(),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState([]),g=gt({mutationFn:async({content:b,parentCommentId:S})=>{const{data:A,error:T}=await q.from("community_comments").insert({post_id:t,user_id:n,content:b,parent_comment_id:S}).select("id").single();if(T)throw T;const L=p;if(L.length>0&&A){const D=L.filter(M=>M!==n).map(M=>({comment_id:A.id,mentioned_user_id:M,mentioned_by_user_id:n}));D.length>0&&await q.from("community_comment_mentions").insert(D)}},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),h(""),f([]),d(!1)}}),_=gt({mutationFn:async b=>{const{error:S}=await q.from("community_comments").delete().eq("id",b);if(S)throw S},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),v=()=>{u.trim()&&g.mutate({content:u,parentCommentId:s.id})};return e.jsxs("div",{className:l>0?"ml-8 border-l-2 border-muted pl-3":"",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ra,{className:"h-8 w-8 shrink-0",children:[e.jsx(ni,{src:s.user_avatar||void 0}),e.jsx(aa,{className:"text-xs",children:zHe(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(KIe,{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:Vo(new Date(s.created_at),{addSuffix:!0})}),e.jsx(Ebs,{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(w9,{className:"h-3 w-3"}),"Reply"]}),(s.user_id===n||i)&&e.jsx("button",{onClick:()=>_.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(ni,{src:r||void 0}),e.jsx(aa,{className:"text-xs",children:zHe((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(Mxe,{placeholder:`Reply to ${s.user_name}...`,value:u,onChange:h,onMentionsChange:f,mentionFormat:"plain",className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:v,disabled:!u.trim()||g.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx(cr,{className:"h-3 w-3"})})]})]})]})]}),s.replies&&s.replies.length>0&&e.jsx("div",{className:"mt-2 space-y-2",children:s.replies.map(b=>e.jsx(Q0t,{comment:b,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l+1},b.id))})]})}const GH=[{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"}],Mbs=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:n,isAdmin:r}=ys(),{avatarUrl:a}=Hht(s==null?void 0:s.id),{onlineUsers:i}=pit(),{toast:l}=Ba(),o=Ht(),c=N.useRef(null),[d,u]=N.useState("all"),[h,p]=N.useState(""),[f,g]=N.useState(""),[_,v]=N.useState(""),[j,b]=N.useState([]),[S,A]=N.useState([]),[T,L]=N.useState(""),[D,M]=N.useState(!1),[F,z]=N.useState(null),[V,W]=N.useState(""),[Y,K]=N.useState(new Set),[J,ne]=N.useState({}),[ie,he]=N.useState({}),[ce,pe]=N.useState([]),[le,ve]=N.useState([]),[ge,Te]=N.useState({open:!1,images:[],index:0});N.useEffect(()=>{if(d.startsWith("group:")){const vt=d.replace("group:","");v(vt),g("")}else d!=="all"?(g(d),v("")):(g(""),v(""))},[d]);const{data:Me=[]}=ct({queryKey:["community-categories"],queryFn:async()=>{const{data:vt,error:Bt}=await q.from("community_categories").select("*").order("sort_order");if(Bt)throw Bt;return vt}}),{data:Ce=[]}=ct({queryKey:["community-private-groups"],queryFn:async()=>{const{data:vt,error:Bt}=await q.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if(Bt)throw Bt;return vt}}),Ae=20,{data:De,isLoading:Ie,hasNextPage:Fe,fetchNextPage:qe,isFetchingNextPage:be}=dLt({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:vt})=>{var Xe;const Bt=vt*Ae,Zt=Bt+Ae;let Fs=q.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(Bt,Zt);if(d.startsWith("group:")){const ot=d.replace("group:","");Fs=Fs.eq("private_group_id",ot)}else d==="all"||(Fs=Fs.eq("category_id",d).is("private_group_id",null));const{data:Rs,error:ms}=await Fs;if(ms)throw ms;const Pt=((Rs==null?void 0:Rs.length)||0)>Ae,Jt=(Rs||[]).slice(0,Ae);if(Jt.length===0)return{posts:[],hasMore:!1,nextPage:vt+1};const ft=Jt.map(ot=>ot.id),Vt=[...new Set(Jt.filter(ot=>ot.category_id).map(ot=>ot.category_id))].filter(Boolean),[Ms,Xt,Js,Cs,As]=await Promise.all([Vt.length?q.from("community_categories").select("*").in("id",Vt):Promise.resolve({data:[]}),q.from("community_post_media").select("*").in("post_id",ft).order("sort_order"),q.from("community_reactions").select("*").in("post_id",ft),q.from("community_comments").select("*").in("post_id",ft).order("created_at",{ascending:!0}),q.from("community_post_resources").select("*").in("post_id",ft)]),rn=Ms==null?void 0:Ms.data,tn=Xt==null?void 0:Xt.data,er=Js==null?void 0:Js.data,gn=Cs==null?void 0:Cs.data,In=As==null?void 0:As.data,Zn=(gn||[]).map(ot=>ot.id),[ea,vi]=await Promise.all([Zn.length?q.from("community_comment_reactions").select("*").in("comment_id",Zn):Promise.resolve({data:[]}),(()=>{const ot=(In||[]).filter(Nt=>Nt.resource_type==="template").map(Nt=>Nt.resource_id);return ot.length===0?Promise.resolve({data:[]}):q.from("canva_templates").select("id, name, preview_image_url").in("id",ot)})()]),Ls=(ea==null?void 0:ea.data)||[],fi=(vi==null?void 0:vi.data)||[],Lr=new Map(fi.map(ot=>[ot.id,{name:ot.name,preview_image_url:ot.preview_image_url}])),Jn=Array.from(new Set([...Jt.map(ot=>ot.user_id),...(er||[]).map(ot=>ot.user_id),...(gn||[]).map(ot=>ot.user_id),...Ls.map(ot=>ot.user_id)])),[js,Dn]=await Promise.all([Jn.length?q.from("profiles").select("id, name").in("id",Jn):Promise.resolve({data:[]}),Ght(Jn)]),wr=new Map(((Xe=js==null?void 0:js.data)==null?void 0:Xe.map(ot=>[ot.id,ot.name]))||[]),$r=new Map((rn||[]).map(ot=>[ot.id,ot])),ss=ot=>{const Nt=new Map,Rt=[];return ot.forEach(qt=>{Nt.set(qt.id,{...qt,user_name:wr.get(qt.user_id)||"Unknown User",user_avatar:Dn.get(qt.user_id),reactions:Ls.filter(xs=>xs.comment_id===qt.id).map(xs=>({...xs,user_name:wr.get(xs.user_id)||"Unknown User",user_avatar:Dn.get(xs.user_id)})),replies:[]})}),ot.forEach(qt=>{const xs=Nt.get(qt.id);if(qt.parent_comment_id&&Nt.has(qt.parent_comment_id)){const rs=Nt.get(qt.parent_comment_id);rs.replies=rs.replies||[],rs.replies.push(xs)}else Rt.push(xs)}),Rt};return{posts:Jt.map(ot=>{const Nt=(In||[]).filter(Rt=>Rt.post_id===ot.id).map(Rt=>{let qt="",xs=null;if(Rt.resource_type==="template"){const rs=Lr.get(Rt.resource_id);qt=(rs==null?void 0:rs.name)||"Unknown Template",xs=(rs==null?void 0:rs.preview_image_url)||null}return{id:Rt.id,resource_type:Rt.resource_type,resource_id:Rt.resource_id,resource_name:qt,resource_preview_url:xs}});return{...ot,user_name:wr.get(ot.user_id)||"Unknown User",user_avatar:Dn.get(ot.user_id),category:ot.category_id?$r.get(ot.category_id):null,media:(tn||[]).filter(Rt=>Rt.post_id===ot.id),reactions:((er||[]).filter(Rt=>Rt.post_id===ot.id)||[]).map(Rt=>({...Rt,user_name:wr.get(Rt.user_id)||"Unknown User",user_avatar:Dn.get(Rt.user_id)})),comments:ss((gn||[]).filter(Rt=>Rt.post_id===ot.id)),resources:Nt}}),hasMore:Pt,nextPage:vt+1}},getNextPageParam:vt=>vt.hasMore?vt.nextPage:void 0}),Ze=N.useMemo(()=>(De==null?void 0:De.pages.flatMap(vt=>vt.posts))??[],[De]),Ne=gt({mutationFn:async()=>{M(!0);const{data:vt,error:Bt}=await q.from("community_posts").insert({user_id:s.id,category_id:_?null:f||null,private_group_id:_||null,content:h,link_url:T||null}).select().single();if(Bt)throw Bt;for(let Fs=0;Fs0){const Fs=ce.filter(Rs=>Rs!==s.id).map(Rs=>({post_id:vt.id,mentioned_user_id:Rs,mentioned_by_user_id:s.id}));Fs.length>0&&await q.from("community_post_mentions").insert(Fs)}const Zt=Abs(h);if(Zt.length>0){const Fs=Zt.map(Rs=>({post_id:vt.id,resource_type:"template",resource_id:Rs}));await q.from("community_post_resources").insert(Fs)}return vt},onSuccess:async vt=>{var Bt;o.invalidateQueries({queryKey:["community-posts"]}),p(""),pe([]),ve([]),g(""),v(""),b([]),A([]),L(""),l({title:"Post created!"});try{const Zt=((Bt=s==null?void 0:s.user_metadata)==null?void 0:Bt.name)||"Someone",Fs=h.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),Rs=Fs.length>50?Fs.substring(0,50)+"...":Fs;await q.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${Zt}: ${Rs}`,url:"/community"}})}catch(Zt){console.error("Failed to send push notification:",Zt)}},onError:vt=>{l({title:"Error creating post",description:vt.message,variant:"destructive"})},onSettled:()=>M(!1)}),it=gt({mutationFn:async({postId:vt,content:Bt})=>{const{error:Zt}=await q.from("community_posts").update({content:Bt}).eq("id",vt);if(Zt)throw Zt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),z(null),W(""),l({title:"Post updated!"})}}),je=gt({mutationFn:async vt=>{const{error:Bt}=await q.from("community_posts").delete().eq("id",vt);if(Bt)throw Bt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),Ge=gt({mutationFn:async({postId:vt,isPinned:Bt})=>{const{error:Zt}=await q.from("community_posts").update({is_pinned:!Bt,pinned_at:Bt?null:new Date().toISOString(),pinned_by:Bt?null:s==null?void 0:s.id}).eq("id",vt);if(Zt)throw Zt},onSuccess:(vt,{isPinned:Bt})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:Bt?"Post unpinned":"Post pinned to top"})}}),Be=gt({mutationFn:async({postId:vt,reactionType:Bt})=>{var Fs;const Zt=(Fs=Ze.find(Rs=>Rs.id===vt))==null?void 0:Fs.reactions.find(Rs=>Rs.user_id===(s==null?void 0:s.id));Zt?Zt.reaction_type===Bt?await q.from("community_reactions").delete().eq("id",Zt.id):await q.from("community_reactions").update({reaction_type:Bt}).eq("id",Zt.id):await q.from("community_reactions").insert({post_id:vt,user_id:s.id,reaction_type:Bt})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),Ye=gt({mutationFn:async({postId:vt,content:Bt})=>{const{data:Zt,error:Fs}=await q.from("community_comments").insert({post_id:vt,user_id:s.id,content:Bt}).select("id").single();if(Fs)throw Fs;const Rs=ie[vt]||[];if(Rs.length>0&&Zt){const ms=Rs.filter(Pt=>Pt!==s.id).map(Pt=>({comment_id:Zt.id,mentioned_user_id:Pt,mentioned_by_user_id:s.id}));ms.length>0&&await q.from("community_comment_mentions").insert(ms)}},onSuccess:(vt,{postId:Bt})=>{o.invalidateQueries({queryKey:["community-posts"]}),ne(Zt=>({...Zt,[Bt]:""})),he(Zt=>({...Zt,[Bt]:[]}))}});gt({mutationFn:async vt=>{const{error:Bt}=await q.from("community_comments").delete().eq("id",vt);if(Bt)throw Bt},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const We=vt=>{const Bt=Array.from(vt.target.files||[]);if(Bt.length+j.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}b(Zt=>[...Zt,...Bt]),Bt.forEach(Zt=>{const Fs=new FileReader;Fs.onloadend=()=>{A(Rs=>[...Rs,Fs.result])},Fs.readAsDataURL(Zt)})},rt=vt=>{b(Bt=>Bt.filter((Zt,Fs)=>Fs!==vt)),A(Bt=>Bt.filter((Zt,Fs)=>Fs!==vt))},tt=vt=>vt.split(" ").map(Bt=>Bt[0]).join("").toUpperCase().slice(0,2),at=vt=>{const Bt={};return vt.forEach(Zt=>{Bt[Zt.reaction_type]=(Bt[Zt.reaction_type]||0)+1}),Bt},He=vt=>{var Bt;return(Bt=vt.find(Zt=>Zt.user_id===(s==null?void 0:s.id)))==null?void 0:Bt.reaction_type},dt=vt=>vt.reduce((Bt,Zt)=>Bt+1+(Zt.replies?dt(Zt.replies):0),0),bt=vt=>{if(r)return!0;if(!t||!vt.private_group_id)return!1;const Bt=Ce.find(Zt=>Zt.id===vt.private_group_id);return Bt!=null&&Bt.brokerage_id?n.some(Zt=>Zt.id===Bt.brokerage_id):!1};return e.jsx(Ts,{title:"Community",children:e.jsxs("div",{className:"flex gap-6 w-full isolate z-0",children:[e.jsx(mbs,{categories:Me,privateGroups:Ce,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(pbs,{categories:Me,privateGroups:Ce,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(ra,{className:"h-10 w-10",children:[e.jsx(ni,{src:a||void 0}),e.jsx(aa,{children:s!=null&&s.email?tt(s.email.split("@")[0]):"U"})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(Mxe,{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:p,onMentionsChange:pe,onTemplatesChange:ve,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:r}),S.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:S.map((vt,Bt)=>{var Zt;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(Zt=j[Bt])!=null&&Zt.type.startsWith("video/")?e.jsx("video",{src:vt,className:"w-full h-full object-cover"}):e.jsx("img",{src:vt,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:()=>rt(Bt),children:e.jsx(Bn,{className:"h-3 w-3"})})]},Bt)})}),T&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:T,onChange:vt=>L(vt.target.value),placeholder:"https://...",className:"flex-1"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>L(""),children:e.jsx(Bn,{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:We,accept:"image/*,video/*",multiple:!0,className:"hidden"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>{var vt;return(vt=c.current)==null?void 0:vt.click()},children:[e.jsx(nl,{className:"h-4 w-4 mr-1"}),"Photo"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>{var vt;return(vt=c.current)==null?void 0:vt.click()},children:[e.jsx(br,{className:"h-4 w-4 mr-1"}),"Video"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>L("https://"),children:[e.jsx(Jo,{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:[Ce.length>0?e.jsxs(ds,{value:_||f||"none",onValueChange:vt=>{vt==="none"?(g(""),v("")):vt.startsWith("group:")?(v(vt.replace("group:","")),g("")):(g(vt),v(""))},children:[e.jsx(ls,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:e.jsx(us,{placeholder:"Select..."})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"No category"}),Me.map(vt=>e.jsxs(Qe,{value:vt.id,children:[vt.icon," ",vt.name]},vt.id)),Ce.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"}),Ce.map(vt=>e.jsxs(Qe,{value:`group:${vt.id}`,children:[vt.icon||"🔒"," ",vt.name]},vt.id))]})]})]}):e.jsxs(ds,{value:f,onValueChange:g,children:[e.jsx(ls,{className:"w-[110px] sm:w-[140px] h-8 text-xs sm:text-sm",children:e.jsx(us,{placeholder:"Category"})}),e.jsx(cs,{children:Me.map(vt=>e.jsxs(Qe,{value:vt.id,children:[vt.icon," ",vt.name]},vt.id))})]}),e.jsxs(B,{size:"sm",onClick:()=>Ne.mutate(),disabled:!h.trim()||D,children:[e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),Ie?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((vt,Bt)=>e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ws,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Ws,{className:"h-4 w-32"}),e.jsx(Ws,{className:"h-4 w-full"}),e.jsx(Ws,{className:"h-4 w-3/4"})]})]})})},Bt))}):Ze.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(Ql,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No posts yet"}),e.jsx("p",{className:"text-muted-foreground",children:"Be the first to start a conversation!"})]})}):e.jsxs("div",{className:"space-y-4",children:[Ze.map(vt=>{var Bt,Zt,Fs,Rs;return e.jsx(fe,{children:e.jsxs(Ee,{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(ni,{src:vt.user_avatar||void 0}),e.jsx(aa,{children:tt(vt.user_name||"U")})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold break-words",children:vt.user_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:Vo(new Date(vt.created_at),{addSuffix:!0})}),vt.category&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs(ze,{variant:"secondary",className:"text-xs",children:[vt.category.icon," ",vt.category.name]})]})]})]})]}),(vt.user_id===(s==null?void 0:s.id)||bt(vt))&&e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Qf,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",children:[bt(vt)&&vt.private_group_id&&e.jsx(Qr,{onClick:()=>Ge.mutate({postId:vt.id,isPinned:vt.is_pinned}),children:vt.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(y9,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(i4,{className:"h-4 w-4 mr-2"}),"Pin to Top"]})}),vt.user_id===(s==null?void 0:s.id)&&e.jsxs(Qr,{onClick:()=>{z(vt),W(vt.content)},children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Qr,{className:"text-destructive",onClick:()=>je.mutate(vt.id),children:[e.jsx(_n,{className:"h-4 w-4 mr-2"}),vt.user_id!==(s==null?void 0:s.id)?"Remove (Moderate)":"Delete"]})]})]})]}),vt.is_pinned&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-sm text-primary",children:[e.jsx(i4,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(KIe,{content:vt.content})}),vt.media.length>0&&e.jsx("div",{className:`grid gap-2 mb-3 ${vt.media.length===1?"grid-cols-1":vt.media.length===2?"grid-cols-2":vt.media.length===3?"grid-cols-3":"grid-cols-2"}`,children:vt.media.slice(0,4).map((ms,Pt)=>{const Jt=Pt===3&&vt.media.length>4,ft=vt.media.length-4;return e.jsxs("div",{className:`relative rounded-lg overflow-hidden bg-muted cursor-pointer group ${vt.media.length===1?"max-h-[500px]":vt.media.length===2?"aspect-[4/3]":"aspect-square"}`,onClick:()=>Te({open:!0,images:vt.media.map(Vt=>({url:Vt.media_url,type:Vt.media_type==="video"?"video":"image"})),index:Pt}),children:[ms.media_type==="video"?e.jsx("video",{src:ms.media_url,className:"w-full h-full object-cover transition-transform group-hover:scale-105"}):e.jsx("img",{src:ms.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"})})})}),Jt&&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:["+",ft]})})]},ms.id)})}),vt.link_url&&e.jsxs("a",{href:vt.link_url,target:"_blank",rel:"noopener noreferrer",className:"block rounded-lg border hover:bg-muted transition-colors mb-3 overflow-hidden",children:[vt.link_image&&e.jsx("div",{className:"aspect-video bg-muted",children:e.jsx("img",{src:vt.link_image,alt:vt.link_title||"Link preview",className:"w-full h-full object-cover",onError:ms=>{ms.currentTarget.style.display="none"}})}),e.jsx("div",{className:"p-3",children:vt.link_title?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-foreground line-clamp-2",children:vt.link_title}),vt.link_description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mt-1",children:vt.link_description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 truncate",children:new URL(vt.link_url).hostname})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[e.jsx(Jo,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:vt.link_url})]})})]}),vt.reactions.length>0&&e.jsx(Z0t,{reactions:vt.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(at(vt.reactions)).slice(0,3).map(([ms])=>{var Pt;return e.jsx("span",{className:"text-base",children:(Pt=GH.find(Jt=>Jt.type===ms))==null?void 0:Pt.emoji},ms)})}),e.jsx("span",{children:vt.reactions.length})]})}),e.jsxs("div",{className:"flex items-center gap-1 border-t border-b py-1 my-2",children:[e.jsxs(el,{children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"flex-1",children:[He(vt.reactions)?e.jsx("span",{className:"mr-1",children:(Bt=GH.find(ms=>ms.type===He(vt.reactions)))==null?void 0:Bt.emoji}):e.jsx(Vm,{className:"h-4 w-4 mr-1"}),He(vt.reactions)?(Zt=GH.find(ms=>ms.type===He(vt.reactions)))==null?void 0:Zt.label:"Like"]})}),e.jsx(Ho,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:GH.map(ms=>e.jsx("button",{onClick:()=>Be.mutate({postId:vt.id,reactionType:ms.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:ms.label,children:ms.emoji},ms.type))})})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>K(ms=>{const Pt=new Set(ms);return Pt.has(vt.id)?Pt.delete(vt.id):Pt.add(vt.id),Pt}),children:[e.jsx(Ql,{className:"h-4 w-4 mr-1"}),(()=>{const ms=dt(vt.comments);return ms>0?`Comment (${ms})`:"Comment"})()]})]}),Y.has(vt.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[vt.comments.map(ms=>e.jsx(Q0t,{comment:ms,postId:vt.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:bt(vt)},ms.id)),s&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ra,{className:"h-8 w-8",children:[e.jsx(ni,{src:a||void 0}),e.jsx(aa,{className:"text-xs",children:tt(((Fs=s.email)==null?void 0:Fs.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(Mxe,{placeholder:"Write a comment... (use @ to mention)",value:J[vt.id]||"",onChange:ms=>ne(Pt=>({...Pt,[vt.id]:ms})),onMentionsChange:ms=>he(Pt=>({...Pt,[vt.id]:ms})),mentionFormat:"plain",onKeyDown:ms=>{var Pt;ms.defaultPrevented||ms.key==="Enter"&&!ms.shiftKey&&((Pt=J[vt.id])!=null&&Pt.trim())&&(ms.preventDefault(),Ye.mutate({postId:vt.id,content:J[vt.id]}))},className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{var ms;(ms=J[vt.id])!=null&&ms.trim()&&Ye.mutate({postId:vt.id,content:J[vt.id]})},disabled:!((Rs=J[vt.id])!=null&&Rs.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx(cr,{className:"h-4 w-4"})})]})]})]})]})},vt.id)}),Fe&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(B,{variant:"outline",onClick:()=>qe(),disabled:be,children:be?"Loading…":"Load more posts"})})]}),e.jsx(bs,{open:!!F,onOpenChange:()=>z(null),children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Edit Post"})}),e.jsx(Es,{value:V,onChange:vt=>W(vt.target.value),className:"min-h-[120px]"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>z(null),children:"Cancel"}),e.jsx(B,{onClick:()=>{F&&it.mutate({postId:F.id,content:V})},disabled:!V.trim(),children:"Save Changes"})]})]})}),e.jsx(Tbs,{images:ge.images,initialIndex:ge.index,open:ge.open,onOpenChange:vt=>Te(Bt=>({...Bt,open:vt}))})]})]})})},Ibs=50*1024*1024;function X0t({value:s,onChange:t,disabled:n}){const{user:r}=ys(),a=N.useRef(null),[i,l]=N.useState(!1),o=async d=>{if(!d||!r)return;const u=[];l(!0);try{for(const h of Array.from(d)){if(!h.type.startsWith("image/")&&!h.type.startsWith("video/")){ae.error(`${h.name}: only images and videos allowed`);continue}if(h.size>Ibs){ae.error(`${h.name}: must be under 50MB`);continue}const p=h.name.split(".").pop()||"bin",f=`${r.id}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${p}`,{error:g}=await q.storage.from("support-attachments").upload(f,h,{contentType:h.type,upsert:!1});if(g){ae.error(`${h.name}: ${g.message}`);continue}u.push({path:f,type:h.type,name:h.name,size:h.size})}u.length&&t([...s,...u])}finally{l(!1),a.current&&(a.current.value="")}},c=async d=>{const u=s[d];t(s.filter((h,p)=>p!==d)),await q.storage.from("support-attachments").remove([u.path])};return e.jsxs("div",{className:"space-y-2",children:[s.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map((d,u)=>e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 rounded-md border bg-muted/40 text-xs",children:[d.type.startsWith("video/")?e.jsx(s9,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(W2,{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(Bn,{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(ts,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(n4,{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 J0t({attachments:s}){const[t,n]=N.useState({}),[r,a]=N.useState(!0);return N.useEffect(()=>{if(!(s!=null&&s.length)){a(!1);return}let i=!1;return(async()=>{const l=s.map(d=>d.path),{data:o}=await q.storage.from("support-attachments").createSignedUrls(l,60*60*24);if(i||!o)return;const c={};o.forEach((d,u)=>{d.signedUrl&&(c[l[u]]=d.signedUrl)}),n(c),a(!1)})(),()=>{i=!0}},[s]),s!=null&&s.length?r?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-2",children:[e.jsx(ts,{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 PI={open:{label:"Open",icon:gr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Ql,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Ri,color:"bg-green-500"},closed:{label:"Closed",icon:Hc,color:"bg-muted-foreground"}},BHe={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function Pbs(){const{user:s}=ys(),t=Ht(),[n,r]=N.useState(null),[a,i]=N.useState(""),[l,o]=N.useState([]),{data:c=[],isLoading:d}=ct({queryKey:["support-tickets"],queryFn:async()=>{const{data:f,error:g}=await q.from("support_tickets").select("*").eq("user_id",s==null?void 0:s.id).order("created_at",{ascending:!1});if(g)throw g;return f},enabled:!!s}),{data:u=[]}=ct({queryKey:["ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:f,error:g}=await q.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(g)throw g;return f},enabled:!!n}),h=gt({mutationFn:async({content:f,attachments:g})=>{if(!n||!s)throw new Error("Missing data");const{error:_}=await q.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:f,is_admin_reply:!1,attachments:g});if(_)throw _},onSuccess:()=>{t.invalidateQueries({queryKey:["ticket-replies",n==null?void 0:n.id]}),i(""),o([]),ae.success("Reply sent!")},onError:()=>{ae.error("Failed to send reply")}}),p=()=>{!a.trim()&&l.length===0||h.mutate({content:a,attachments:l})};if(n){const f=PI[n.status].icon;return e.jsx(Ts,{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(Hr,{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(ze,{variant:"secondary",children:BHe[n.category]}),e.jsxs(ze,{className:PI[n.status].color,children:[e.jsx(f,{className:"h-3 w-3 mr-1"}),PI[n.status].label]})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Vn,{children:["Created on ",Ss(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Ee,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-lg",children:"Conversation"})}),e.jsxs(Ee,{children:[e.jsx(hi,{className:"h-[300px] pr-4",children:u.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No replies yet"}):e.jsx("div",{className:"space-y-4",children:u.map(g=>{var _;return e.jsxs("div",{className:`p-4 rounded-lg ${g.is_admin_reply?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsx("span",{className:"font-medium text-sm",children:g.is_admin_reply?"Support Team":((_=g.profiles)==null?void 0:_.name)||"You"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date(g.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:g.content}),g.attachments&&g.attachments.length>0&&e.jsx(J0t,{attachments:g.attachments})]},g.id)})})}),n.status!=="closed"&&e.jsxs(e.Fragment,{children:[e.jsx(ll,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Es,{placeholder:"Type your reply...",value:a,onChange:g=>i(g.target.value),className:"min-h-[80px]"}),e.jsx(B,{onClick:p,disabled:!a.trim()&&l.length===0||h.isPending,className:"self-end",children:e.jsx(cr,{className:"h-4 w-4"})})]}),e.jsx(X0t,{value:l,onChange:o,disabled:h.isPending})]})]})]})]})]})})}return e.jsx(Ts,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(fe,{className:"bg-gradient-to-br from-primary/10 via-primary/5 to-background border-primary/20",children:e.jsx(Ee,{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(K_,{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(pCe,{trigger:e.jsxs(B,{size:"lg",className:"gap-2",children:[e.jsx(Is,{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(Ar,{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(pCe,{trigger:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(Is,{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(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"text-center py-12",children:[e.jsx(Ql,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets yet"}),e.jsx("p",{className:"text-muted-foreground",children:"You haven't submitted any support tickets. Use the button above to get started!"})]})}):e.jsx("div",{className:"space-y-3",children:c.map(f=>{const g=PI[f.status].icon;return e.jsx(fe,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(f),children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:f.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ze,{variant:"outline",className:"text-xs",children:BHe[f.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date(f.created_at),"MMM d, yyyy")})]})]}),e.jsxs(ze,{className:PI[f.status].color,children:[e.jsx(g,{className:"h-3 w-3 mr-1"}),PI[f.status].label]})]})})},f.id)})})]})})}function Lbs({open:s,onOpenChange:t}){return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(ws,{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(yr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(_s,{children:"Schedule Agent Onboarding"}),e.jsx(Qn,{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 Dbs({open:s,onOpenChange:t}){const{brokerageId:n}=ys(),[r,a]=N.useState(""),[i,l]=N.useState([]),[o,c]=N.useState(!1),{data:d,isLoading:u}=ct({queryKey:["brokerage-agents-for-onboarding",n],queryFn:async()=>{if(!n)return[];const{data:_,error:v}=await q.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name",{ascending:!0});if(v)throw v;return _},enabled:s&&!!n}),h=d==null?void 0:d.filter(_=>_.name.toLowerCase().includes(r.toLowerCase())||_.email.toLowerCase().includes(r.toLowerCase())),p=_=>{l(v=>v.includes(_)?v.filter(j=>j!==_):[...v,_])},f=async()=>{if(i.length===0){ae.error("Please select at least one agent");return}c(!0);try{const{data:_,error:v}=await q.functions.invoke("send-onboarding-link",{body:{agentIds:i}});if(v)throw v;ae.success(`Onboarding link sent to ${i.length} agent${i.length>1?"s":""}`),l([]),t(!1)}catch(_){console.error("Error sending onboarding link:",_),ae.error(_.message||"Failed to send onboarding link")}finally{c(!1)}},g=_=>{_||(l([]),a("")),t(_)};return e.jsx(bs,{open:s,onOpenChange:g,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{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(cr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(_s,{children:"Send Onboarding Link"}),e.jsx(Qn,{children:"Select agents to receive the onboarding booking link"})]})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents...",value:r,onChange:_=>a(_.target.value),className:"pl-10"})]}),u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ts,{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(Nn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No agents found"})]}):e.jsx(hi,{className:"h-[300px] border rounded-lg",children:e.jsx("div",{className:"p-2 space-y-1",children:h==null?void 0:h.map(_=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted cursor-pointer",onClick:()=>p(_.id),children:[e.jsx(ui,{checked:i.includes(_.id),onCheckedChange:()=>p(_.id)}),e.jsx(ra,{className:"h-8 w-8",children:e.jsx(aa,{className:"text-xs",children:_.name.split(" ").map(v=>v[0]).join("").toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:_.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:_.email})]})]},_.id))})}),i.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[i.length," agent",i.length>1?"s":""," selected"]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx(B,{onClick:f,disabled:i.length===0||o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function Rbs(){const[s,t]=N.useState(!1),[n,r]=N.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"mb-8",children:[e.jsx(Mt,{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(Nn,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(It,{children:"Agent Onboarding"}),e.jsx(Vn,{children:"Schedule onboarding sessions for yourself or your agents"})]})]})}),e.jsx(Ee,{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(yr,{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(cr,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(Lbs,{open:s,onOpenChange:t}),e.jsx(Dbs,{open:n,onOpenChange:r})]})}function Obs({open:s,onOpenChange:t}){return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(ws,{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(sx,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(_s,{children:"Schedule Launch Meeting"}),e.jsx(Qn,{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 Fbs(){const[s,t]=N.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"mb-8",children:[e.jsx(Mt,{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(sx,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(It,{children:"Launch or ReLaunch Meeting"}),e.jsx(Vn,{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(Ee,{children:e.jsxs(B,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(sx,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(Obs,{open:s,onOpenChange:t})]})}function zbs(){const s=Mn(),[t,n]=N.useState(""),[r,a]=N.useState(null),{data:i,isLoading:l}=ct({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:_,error:v}=await q.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(v)throw v;return _}}),{data:o}=ct({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:_,error:v}=await q.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(v)throw v;return _}}),{data:c}=ct({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:_,error:v}=await q.from("brokerage_resource_pdfs").select("resource_id");if(v)throw v;return _}}),{data:d}=ct({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:_,error:v}=await q.from("brokerage_resource_videos").select("resource_id");if(v)throw v;return _}}),{data:u}=ct({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:_,error:v}=await q.from("brokerage_resource_links").select("resource_id");if(v)throw v;return _}}),h=i==null?void 0:i.filter(_=>{var b;const v=_.title.toLowerCase().includes(t.toLowerCase())||((b=_.description)==null?void 0:b.toLowerCase().includes(t.toLowerCase())),j=!r||_.category_id===r;return v&&j}),p=o==null?void 0:o.filter(_=>i==null?void 0:i.some(v=>v.category_id===_.id)),f=_=>{const v=(c==null?void 0:c.filter(S=>S.resource_id===_).length)||0,j=(d==null?void 0:d.filter(S=>S.resource_id===_).length)||0,b=(u==null?void 0:u.filter(S=>S.resource_id===_).length)||0;return{pdfCount:v,videoCount:j,linkCount:b}},g=_=>{s(`/brokerage-resources/${_}`)};return e.jsx(Ts,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Rbs,{}),e.jsx(Fbs,{}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search resources...",value:t,onChange:_=>n(_.target.value),className:"pl-10"})]}),p&&p.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(ze,{variant:r===null?"default":"outline",className:"cursor-pointer",onClick:()=>a(null),children:"All"}),p.map(_=>e.jsx(ze,{variant:r===_.id?"default":"outline",className:"cursor-pointer",onClick:()=>a(_.id),children:_.name},_.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((_,v)=>e.jsxs(fe,{children:[e.jsx(Ws,{className:"h-40 w-full"}),e.jsx(Mt,{children:e.jsx(Ws,{className:"h-5 w-3/4"})}),e.jsxs(Ee,{children:[e.jsx(Ws,{className:"h-4 w-full mb-2"}),e.jsx(Ws,{className:"h-4 w-2/3"})]})]},v))}):(h==null?void 0:h.length)===0?e.jsxs(fe,{className:"p-12 text-center",children:[e.jsx(qm,{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(_=>{const{pdfCount:v,videoCount:j,linkCount:b}=f(_.id),S=o==null?void 0:o.find(A=>A.id===_.category_id);return e.jsxs(fe,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>g(_.id),children:[_.preview_image_url?e.jsx("img",{src:_.preview_image_url,alt:_.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(qm,{className:"h-16 w-16 text-muted-foreground"})}),e.jsx(Mt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(It,{className:"text-lg line-clamp-1",children:_.title}),S&&e.jsx(ze,{variant:"secondary",className:"shrink-0 text-xs",children:S.name})]})}),e.jsxs(Ee,{children:[_.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:_.description}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[v>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nr,{className:"h-4 w-4"}),v]}),j>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(br,{className:"h-4 w-4"}),j]}),b>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jo,{className:"h-4 w-4"}),b]})]})]})]},_.id)})})]})})}const Bbs=()=>{const{resourceId:s}=bi(),{data:t,isLoading:n}=ct({queryKey:["brokerage-resource-detail",s],queryFn:async()=>{const{data:a,error:i}=await q.from("brokerage_resources").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;const{data:l}=await q.from("brokerage_resource_pdfs").select("*").eq("resource_id",s).order("sort_order"),{data:o}=await q.from("brokerage_resource_videos").select("*").eq("resource_id",s).order("sort_order"),{data:c}=await q.from("brokerage_resource_links").select("*").eq("resource_id",s).order("sort_order");return{...a,pdfs:l||[],videos:o||[],links:c||[]}},enabled:!!s}),r=a=>a?a<1024?a+" B":a<1024*1024?(a/1024).toFixed(1)+" KB":(a/(1024*1024)).toFixed(1)+" MB":"";return n?e.jsx(Ts,{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(Ts,{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(Ln,{to:"/brokerage-resources",children:[e.jsx(Hr,{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(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(br,{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(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Nr,{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(Nr,{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(Pa,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})}),t.links&&t.links.length>0&&e.jsx(fe,{children:e.jsxs(Ee,{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(Ts,{title:"Brokerage Resources",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(qm,{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(Ln,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function $bs(){const{onlineUsers:s,totalOnline:t}=pit();return e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Online Now"]}),e.jsxs(ze,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(lm,{className:"h-2 w-2 fill-green-500 text-green-500 mr-1"}),t," online"]})]})}),e.jsx(Ee,{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(hi,{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(ni,{src:n.avatarUrl,alt:n.name}),e.jsx(aa,{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 ",Vo(new Date(n.onlineSince),{addSuffix:!1})]})]})]},n.id)})})})})]})}const $He={users:{label:"Users & Access",sections:[{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:Nn,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:D9,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:pf,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:X7,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:uh,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:Hl,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"},{title:"Teams",description:"Manage agent teams across all brokerages",icon:Nn,path:"/admin/members?tab=teams",color:"bg-violet-500/10 text-violet-600"},{title:"Prospector",description:"Send free trial invites and track conversions",icon:Oc,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:Fo,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:vo,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:fl,path:"/admin/templates",color:"bg-pink-500/10 text-pink-600"},{title:"Manage Programs",description:"Cohorts, enrollments and delayed billing",icon:_d,path:"/admin/programs",color:"bg-emerald-500/10 text-emerald-600"},{title:"Manage Academy",description:"Upload videos and training content",icon:_d,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:_b,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:un,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Social Swag 2.0",description:"New monthly social media images",icon:un,path:"/admin/social-swag-2",color:"bg-cyan-500/10 text-cyan-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:ay,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Newsletter Graphics",description:"Upload branded graphics agents drop into newsletters & emails",icon:ay,path:"/admin/newsletter-graphics",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:Tl,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"LevelUp Live",description:"Public streaming pages, invite links, and live leads",icon:_f,path:"/admin/live",color:"bg-red-500/10 text-red-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:qm,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:qm,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"},{title:"Agent Email Templates",description:"Manage curated email templates for agents",icon:Vs,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:$d,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:e4,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:pv,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:Vs,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:$d,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:G2,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:_w,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:Oi,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:vo,path:"/admin/agent-points",color:"bg-amber-500/10 text-amber-600"},{title:"Integrations",description:"Connect Canva, Facebook & Instagram for platform-level features",icon:El,path:"/admin/integrations",color:"bg-blue-500/10 text-blue-600"},{title:"Agent Cards",description:"Manage digital business cards for agents",icon:Nn,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:$d,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:Ei,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:aL,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:vw,path:"/admin/wishlist",color:"bg-yellow-500/10 text-yellow-600"},{title:"Membership Reviews",description:"View member feedback and ratings",icon:ca,path:"/admin/membership-reviews",color:"bg-amber-500/10 text-amber-600"},{title:"Weekly Digest",description:"Configure automated weekly email digests",icon:Vs,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:yo,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:Ou,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:iy,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:_d,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:gi,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:Or,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:Fo,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:Fo,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:iy,path:"/admin/presentation-analytics",color:"bg-gradient-to-br from-violet-500/20 to-indigo-500/10 text-violet-600"},{title:"Guest Book Analytics",description:"Track open house sign-in usage, visitors, and lead generation",icon:Ou,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:nl,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:Vs,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:QS,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:lc,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:J7,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:mo,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:Nr,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:Nr,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:Zl,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function UHe(){const s=Mn();return console.log("[AdminDashboard] render"),e.jsx(Ts,{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($bs,{})})]}),e.jsxs(Br,{defaultValue:"users",className:"w-full",children:[e.jsx(Fr,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries($He).map(([t,n])=>e.jsx(Kt,{value:t,className:"data-[state=active]:bg-background",children:n.label},t))}),Object.entries($He).map(([t,n])=>e.jsx(is,{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(fe,{className:"cursor-pointer hover:shadow-md transition-all hover:border-primary/50 group",onClick:()=>s(r.path),children:[e.jsxs(Mt,{className:"pb-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg flex items-center justify-center ${r.color} mb-2 group-hover:scale-110 transition-transform`,children:e.jsx(r.icon,{className:"h-5 w-5"})}),e.jsx(It,{className:"text-base",children:r.title})]}),e.jsx(Ee,{className:"pt-0",children:e.jsx(Vn,{className:"text-sm",children:r.description})})]},r.path))})},t))]})]})})}const Ubs=()=>{const{isAdmin:s}=ys(),t=Mn(),[n,r]=N.useState([]),[a,i]=N.useState(!0),[l,o]=N.useState(!1),[c,d]=N.useState(null);N.useEffect(()=>{if(!s){t("/dashboard");return}u()},[s]);const u=async()=>{try{const{data:_,error:v}=await q.from("app_tiles").select("*").order("name");if(v)throw v;r(_||[])}catch(_){console.error("Error loading apps:",_),ae.error("Failed to load apps")}finally{i(!1)}},h=async _=>{_.preventDefault();const v=new FormData(_.currentTarget),j={name:v.get("name"),description:v.get("description"),icon:v.get("icon"),app_id:v.get("app_id"),target_url:v.get("target_url"),required_tags:v.get("required_tags").split(",").map(b=>b.trim()).filter(Boolean)};try{if(c){const{error:b}=await q.from("app_tiles").update(j).eq("id",c.id);if(b)throw b;ae.success("App updated successfully")}else{const{error:b}=await q.from("app_tiles").insert([j]);if(b)throw b;ae.success("App created successfully")}o(!1),d(null),u()}catch(b){console.error("Error saving app:",b),ae.error("Failed to save app")}},p=async _=>{if(confirm("Are you sure you want to delete this app?"))try{const{error:v}=await q.from("app_tiles").delete().eq("id",_);if(v)throw v;ae.success("App deleted successfully"),u()}catch(v){console.error("Error deleting app:",v),ae.error("Failed to delete app")}},f=_=>{d(_),o(!0)},g=()=>{d(null),o(!0)};return a?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}):e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/dashboard"),children:[e.jsx(Hr,{className:"h-4 w-4 mr-2"}),"Back"]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Manage Apps"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create and configure application tiles"})]})]}),e.jsxs(bs,{open:l,onOpenChange:o,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{onClick:g,children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:c?"Edit App":"Create New App"}),e.jsx(Qn,{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(Es,{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(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Application Tiles"}),e.jsx(Vn,{children:"Manage the apps that appear on the member dashboard"})]}),e.jsx(Ee,{children:n.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsxs(B,{onClick:g,children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Icon"}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"App ID"}),e.jsx(Ct,{children:"Target URL"}),e.jsx(Ct,{children:"Tags"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:n.map(_=>e.jsxs(Hs,{children:[e.jsx(ut,{className:"text-2xl",children:_.icon}),e.jsx(ut,{className:"font-medium",children:_.name}),e.jsx(ut,{className:"font-mono text-sm",children:_.app_id}),e.jsx(ut,{className:"text-sm text-muted-foreground max-w-xs truncate",children:_.target_url}),e.jsx(ut,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:_.required_tags.map(v=>e.jsx("span",{className:"text-xs bg-secondary text-secondary-foreground px-2 py-1 rounded",children:v},v))})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>f(_),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>p(_.id),children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},_.id))})]})})]})})]})};function Ud({title:s,description:t,children:n}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ln,{to:"/admin",children:e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",children:[e.jsx(Hr,{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 qHe=({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(ze,{variant:"destructive",className:Et("gap-1",t),children:[e.jsx($l,{className:"h-3 w-3"}),"Trial Expired"]}):a<=1?e.jsxs(ze,{variant:"destructive",className:Et("gap-1",t),children:[e.jsx(gr,{className:"h-3 w-3"}),"Trial: <1 day left"]}):a<=3?e.jsxs(ze,{className:Et("gap-1 bg-amber-500 hover:bg-amber-600",t),children:[e.jsx(gr,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs(ze,{variant:"secondary",className:Et("gap-1",t),children:[e.jsx(gr,{className:"h-3 w-3"}),"Trial: ",a," days left"]})},eyt=({open:s,onOpenChange:t,brokerages:n,fixedBrokerageId:r,onSuccess:a})=>{const{toast:i}=Ba(),l=N.useRef(null),[o,c]=N.useState([]),[d,u]=N.useState(""),[h,p]=N.useState(!1),[f,g]=N.useState("upload"),[_,v]=N.useState(null),j=()=>{c([]),u(""),g("upload"),v(null),l.current&&(l.current.value="")},b=()=>{j(),t(!1)},S=M=>{const F=M.split(` `).map(K=>K.trim()).filter(K=>K);if(F.length===0)return[];const z=F[0].toLowerCase(),W=z.includes("first")||z.includes("last")||z.includes("email")||z.includes("name")||z.includes("phone")||z.includes("sms")||z.includes("consent")?F.slice(1):F,Y=[];for(const K of W){const ne=(K.includes(" ")?K.split(" "):K.split(",")).map(ie=>ie.trim().replace(/^["']|["']$/g,""));if(ne.length>=2){let ie="",he="",ce="",pe="",le;if(ne.length===2){const Te=ne[0].split(" ");ie=Te[0]||"",he=Te.slice(1).join(" ")||"",ce=ne[1]}else if(ne.length===3)ie=ne[0],he=ne[1],ce=ne[2];else if(ne.length===4)ie=ne[0],he=ne[1],ce=ne[2],pe=ne[3];else if(ne.length>=5){ie=ne[0],he=ne[1],ce=ne[2],pe=ne[3];const Te=ne[4].toLowerCase();le=Te==="true"||Te==="yes"||Te==="1"||Te==="y"}const ge=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ce);Y.push({firstName:ie.trim(),lastName:he.trim(),email:ce.trim().toLowerCase(),phone:pe.trim()||void 0,smsConsent:le,isValid:ge&&ie.trim().length>0,error:ge?ie.trim()?void 0:"Missing name":"Invalid email"})}}return Y},A=M=>{var V;const F=(V=M.target.files)==null?void 0:V[0];if(!F)return;const z=new FileReader;z.onload=W=>{var J;const Y=(J=W.target)==null?void 0:J.result,K=S(Y);if(K.length===0){i({title:"No data found",description:"The CSV file appears to be empty or in an unsupported format.",variant:"destructive"});return}c(K),g("preview")},z.readAsText(F)},T=async()=>{const M=o.filter(z=>z.isValid);if(M.length===0){i({title:"No valid users",description:"There are no valid users to import.",variant:"destructive"});return}const F=r||d||null;p(!0);try{const{data:{session:z}}=await q.auth.getSession(),V=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-create-users",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${z==null?void 0:z.access_token}`},body:JSON.stringify({users:M.map(Y=>({firstName:Y.firstName,lastName:Y.lastName,email:Y.email,phone:Y.phone,smsConsent:Y.smsConsent})),brokerageId:F})}),W=await V.json();if(!V.ok)throw new Error(W.error||"Failed to import users");v(W),g("result"),W.created>0&&a(),i({title:"Import Complete",description:`${W.created} user(s) created successfully.${W.failed>0?` ${W.failed} failed.`:""}`})}catch(z){console.error("Import error:",z),i({title:"Import Failed",description:z.message||"Failed to import users",variant:"destructive"})}finally{p(!1)}},L=o.filter(M=>M.isValid).length,D=o.filter(M=>!M.isValid).length;return e.jsx(bs,{open:s,onOpenChange:b,children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(gw,{className:"h-5 w-5"}),"Import Agents from CSV"]}),e.jsx(Qn,{children:"Upload a CSV file with agent information. Each row should contain First Name, Last Name, and Email."})]}),f==="upload"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx("input",{type:"file",accept:".csv,.txt",ref:l,onChange:A,className:"hidden"}),e.jsx(Na,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Click to upload or drag and drop a CSV file"}),e.jsx(B,{onClick:()=>{var M;return(M=l.current)==null?void 0:M.click()},children:"Select CSV File"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-sm",children:[e.jsx("p",{className:"font-medium mb-2",children:"Expected CSV Format:"}),e.jsxs("code",{className:"text-xs block bg-background p-2 rounded",children:["First Name, Last Name, Email, Phone, SMS Consent",e.jsx("br",{}),"John, Doe, john@example.com, 555-123-4567, yes",e.jsx("br",{}),"Jane, Smith, jane@example.com, 555-987-6543, true"]}),e.jsx("p",{className:"text-muted-foreground mt-2 text-xs",children:"Phone and SMS Consent columns are optional. SMS Consent accepts: yes/no, true/false, 1/0, y/n."})]})]}),f==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[!r&&n&&n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Assign to Brokerage (optional)"}),e.jsxs(ds,{value:d||"none",onValueChange:M=>u(M==="none"?"":M),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select a brokerage..."})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"No brokerage"}),n.map(M=>e.jsx(Qe,{value:M.id,children:M.name},M.id))]})]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xr,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[L," valid"]})]}),D>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Gi,{className:"h-4 w-4"}),e.jsxs("span",{children:[D," invalid"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{className:"bg-muted/30",children:[e.jsx(Ct,{children:"First Name"}),e.jsx(Ct,{children:"Last Name"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Phone"}),e.jsx(Ct,{children:"SMS"}),e.jsx(Ct,{children:"Status"})]})}),e.jsx(ha,{children:o.slice(0,100).map((M,F)=>e.jsxs(Hs,{children:[e.jsx(ut,{children:M.firstName}),e.jsx(ut,{children:M.lastName}),e.jsx(ut,{children:M.email}),e.jsx(ut,{className:"text-muted-foreground",children:M.phone||"-"}),e.jsx(ut,{className:"text-muted-foreground",children:M.smsConsent===!0?"✓":M.smsConsent===!1?"✗":"-"}),e.jsx(ut,{children:M.isValid?e.jsx(ze,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):e.jsx(ze,{variant:"destructive",children:M.error||"Invalid"})})]},F))})]}),o.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",o.length," users"]})]})]}),f==="result"&&_&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(xr,{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:[_.created," agent(s) created and invited"]}),_.failed>0&&e.jsxs("p",{className:"text-destructive mt-1",children:[_.failed," failed to create"]})]}),_.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:[_.errors.slice(0,10).map((M,F)=>e.jsxs("li",{children:["• ",M]},F)),_.errors.length>10&&e.jsxs("li",{children:["...and ",_.errors.length-10," more"]})]})]})]}),e.jsxs(Xn,{children:[f==="upload"&&e.jsx(B,{variant:"outline",onClick:b,children:"Cancel"}),f==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:j,children:"Back"}),e.jsx(B,{onClick:T,disabled:h||L===0,children:h?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${L} Agent${L!==1?"s":""}`})]}),f==="result"&&e.jsx(B,{onClick:b,children:"Done"})]})]})})};function Ic({sortKey:s,currentSortKey:t,currentDirection:n,onSort:r,children:a,className:i,...l}){const o=t===s;return e.jsx(Ct,{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(Ru,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(am,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(em,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function kU(s=null,t=null){const[n,r]=N.useState(s),[a,i]=N.useState(t),l=N.useCallback(c=>{n===c?a==="asc"?i("desc"):a==="desc"?(r(null),i(null)):i("asc"):(r(c),i("asc"))},[n,a]),o=N.useCallback((c,d)=>{if(!n||!a||!d[n])return c;const u=d[n];return[...c].sort((h,p)=>{const f=u(h),g=u(p);if(f==null&&g==null)return 0;if(f==null)return 1;if(g==null)return-1;let _;return typeof f=="string"&&typeof g=="string"?_=f.localeCompare(g,void 0,{sensitivity:"base"}):_=f-g,a==="asc"?_:-_})},[n,a]);return{sortKey:n,sortDirection:a,handleSort:l,sortData:o}}const qbs=[{type:"custom",title:"Great job!",message:"Keep up the amazing work!",icon:ca},{type:"custom",title:"You're on fire!",message:"Your dedication is inspiring!",icon:vo},{type:"custom",title:"Congratulations!",message:"You earned this celebration!",icon:ch}];function tyt({open:s,onOpenChange:t,userId:n,userName:r}){const[a,i]=N.useState("custom"),[l,o]=N.useState(""),[c,d]=N.useState(""),u=V7t(),h=f=>{i(f.type),o(f.title),d(f.message)},p=async f=>{if(f.preventDefault(),!l.trim()){Pr({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}),Pr({title:"Celebration sent! 🎉",description:`${r} will see confetti on their next visit!`}),t(!1),o(""),d(""),i("custom")}catch{Pr({title:"Error",description:"Failed to send celebration",variant:"destructive"})}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(ch,{className:"h-5 w-5 text-primary"}),"Send Celebration to ",r]}),e.jsx(Qn,{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:qbs.map((f,g)=>e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>h(f),className:"text-xs",children:[e.jsx(f.icon,{className:"h-3 w-3 mr-1"}),f.title]},g))})]}),e.jsxs("form",{onSubmit:p,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"type",children:"Celebration Type"}),e.jsxs(ds,{value:a,onValueChange:f=>i(f),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"custom",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ca,{className:"h-4 w-4"})," Custom"]})}),e.jsx(Qe,{value:"points_earned",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vo,{className:"h-4 w-4"})," Points Earned"]})}),e.jsx(Qe,{value:"listing_created",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{className:"h-4 w-4"})," Listing Created"]})}),e.jsx(Qe,{value:"deal_closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zl,{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:f=>o(f.target.value),placeholder:"e.g., Congratulations!",maxLength:100})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"message",children:"Message (optional)"}),e.jsx(Es,{id:"message",value:c,onChange:f=>d(f.target.value),placeholder:"Add a personal message...",rows:3,maxLength:500})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:u.isPending,children:[e.jsx(ch,{className:"h-4 w-4 mr-2"}),u.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const F2e={points_earned:{label:"Points Earned",icon:vo,color:"bg-yellow-500"},listing_created:{label:"Listing Created",icon:Or,color:"bg-blue-500"},deal_closed:{label:"Deal Closed",icon:Zl,color:"bg-green-500"},custom:{label:"Custom",icon:un,color:"bg-purple-500"}};function Vbs(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("all"),{data:l=[],isLoading:o}=ct({queryKey:["admin-celebrations"],queryFn:async()=>{const{data:u,error:h}=await q.from("celebration_queue").select("*").order("created_at",{ascending:!1}).limit(500);if(h)throw h;const p=[...new Set([...u.map(_=>_.user_id),...u.map(_=>_.created_by).filter(Boolean)])],{data:f}=await q.from("profiles").select("id, name, email").in("id",p),g=new Map((f==null?void 0:f.map(_=>[_.id,_]))||[]);return u.map(_=>{var v,j,b;return{..._,user_name:((v=g.get(_.user_id))==null?void 0:v.name)||"Unknown",user_email:((j=g.get(_.user_id))==null?void 0:j.email)||"",creator_name:_.created_by?((b=g.get(_.created_by))==null?void 0:b.name)||"System":"Auto-triggered"}})}}),c=l.filter(u=>{var g,_;const h=((g=u.user_name)==null?void 0:g.toLowerCase().includes(s.toLowerCase()))||((_=u.user_email)==null?void 0:_.toLowerCase().includes(s.toLowerCase()))||u.title.toLowerCase().includes(s.toLowerCase()),p=n==="all"||u.celebration_type===n,f=a==="all"||a==="seen"&&u.seen_at||a==="unseen"&&!u.seen_at;return h&&p&&f}),d={total:l.length,seen:l.filter(u=>u.seen_at).length,unseen:l.filter(u=>!u.seen_at).length,byType:Object.keys(F2e).reduce((u,h)=>(u[h]=l.filter(p=>p.celebration_type===h).length,u),{})};return o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ts,{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(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium",children:"Total Celebrations"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.total})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-green-600",children:"Seen"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold text-green-600",children:d.seen})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-orange-600",children:"Pending"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:d.unseen})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-purple-600",children:"Custom Sent"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold text-purple-600",children:d.byType.custom||0})})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(ch,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(Vn,{children:"View all celebrations awarded to agents"})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by agent name, email, or title...",value:s,onChange:u=>t(u.target.value),className:"pl-9"})]}),e.jsxs(ds,{value:n,onValueChange:r,children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(us,{placeholder:"Filter by type"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Types"}),Object.entries(F2e).map(([u,h])=>e.jsx(Qe,{value:u,children:h.label},u))]})]}),e.jsxs(ds,{value:a,onValueChange:i,children:[e.jsx(ls,{className:"w-[140px]",children:e.jsx(us,{placeholder:"Status"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Status"}),e.jsx(Qe,{value:"seen",children:"Seen"}),e.jsx(Qe,{value:"unseen",children:"Pending"})]})]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Type"}),e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Points"}),e.jsx(Ct,{children:"Created By"}),e.jsx(Ct,{children:"Created"}),e.jsx(Ct,{children:"Status"})]})}),e.jsx(ha,{children:c.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(u=>{const h=F2e[u.celebration_type],p=h.icon;return e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(p,{className:"h-3 w-3"}),h.label]})}),e.jsx(ut,{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(ut,{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(ut,{children:u.points_amount?e.jsxs(ze,{variant:"secondary",children:["+",u.points_amount]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(ut,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:u.creator_name})}),e.jsx(ut,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Ss(new Date(u.created_at),"MMM d, yyyy h:mm a")})}),e.jsx(ut,{children:u.seen_at?e.jsx(ze,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:"Seen"}):e.jsx(ze,{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 Hbs=()=>{const{user:s}=ys(),{toast:t}=Ba(),[n,r]=N.useState([]),[a,i]=N.useState(!0),[l,o]=N.useState(!1),[c,d]=N.useState("all"),[u,h]=N.useState("all"),[p,f]=N.useState("new"),[g,_]=N.useState(new Set),v=N.useCallback(async()=>{try{i(!0);const{data:Y,error:K}=await q.from("profiles").select("id, name, email, phone, is_trial, trial_started_at, trial_expires_at, subscription_status, subscription_end_date, converted_from_trial_at, created_at, last_login").or("is_trial.eq.true,subscription_status.eq.trialing,converted_from_trial_at.not.is.null");if(K)throw K;const{data:J,error:ne}=await q.from("trial_email_exports").select("user_id");if(ne)throw ne;const ie=new Set((J||[]).map(ce=>ce.user_id)),he=(Y||[]).map(ce=>({...ce,converted_from_trial_at:ce.converted_from_trial_at??null,already_exported:ie.has(ce.id)}));he.sort((ce,pe)=>new Date(pe.created_at).getTime()-new Date(ce.created_at).getTime()),r(he)}catch(Y){console.error("Error loading trial users:",Y),t({title:"Error",description:"Failed to load trial users",variant:"destructive"})}finally{i(!1)}},[t]);N.useEffect(()=>{v()},[v]);const j=Y=>Y.trial_started_at?"ghl":"stripe",b=Y=>Y.trial_expires_at?Y.trial_expires_at:Y.subscription_end_date?Y.subscription_end_date:null,S=Y=>Y.converted_from_trial_at!==null,A=Y=>{if(S(Y))return!1;const K=b(Y);return K?new Date(K).getTime()<=Date.now():!1},T=n.filter(Y=>!(c!=="all"&&j(Y)!==c||u==="active"&&(A(Y)||S(Y))||u==="expired"&&!A(Y)||u==="converted"&&!S(Y)||p==="new"&&Y.already_exported||p==="exported"&&!Y.already_exported)),L=()=>{g.size===T.length?_(new Set):_(new Set(T.map(Y=>Y.id)))},D=Y=>{const K=new Set(g);K.has(Y)?K.delete(Y):K.add(Y),_(K)},M=async()=>{if(g.size===0){t({title:"No users selected",description:"Select users to export",variant:"destructive"});return}o(!0);try{const Y=n.filter(le=>g.has(le.id)),K="First Name,Last Name,Email,Phone,Trial Type,Status,Signup Date,Expiry Date",J=Y.map(le=>{const ve=(le.name||"").split(" "),ge=ve[0]||"",Te=ve.slice(1).join(" ")||"",Me=j(le)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",Ce=S(le)?"Converted":A(le)?"Expired":"Active",Ae=le.created_at?new Date(le.created_at).toLocaleDateString():"",De=b(le)?new Date(b(le)).toLocaleDateString():"";return`"${ge}","${Te}","${le.email}","${le.phone||""}","${Me}","${Ce}","${Ae}","${De}"`}),ne=[K,...J].join(` `),ie=new Blob([ne],{type:"text/csv"}),he=URL.createObjectURL(ie),ce=document.createElement("a");ce.href=he,ce.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,ce.click(),URL.revokeObjectURL(he);const pe=Y.filter(le=>!le.already_exported).map(le=>({user_id:le.id,exported_by:s.id}));if(pe.length>0){const{error:le}=await q.from("trial_email_exports").upsert(pe,{onConflict:"user_id"});le&&console.error("Error marking exports:",le)}t({title:"Export complete",description:`Downloaded ${Y.length} trial user(s). ${pe.length} newly marked as exported.`}),_(new Set),v()}catch(Y){console.error("Export error:",Y),t({title:"Error",description:"Failed to export",variant:"destructive"})}finally{o(!1)}},F=n.filter(Y=>!Y.already_exported).length,z=n.filter(Y=>Y.already_exported).length,V=n.filter(Y=>S(Y)).length,W=n.filter(Y=>!A(Y)&&!S(Y)).length;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ts,{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(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Vn,{children:"Total"}),e.jsx(It,{className:"text-2xl",children:n.length})]})}),e.jsx(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Vn,{children:"New (Not Exported)"}),e.jsx(It,{className:"text-2xl text-green-600",children:F})]})}),e.jsx(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Vn,{children:"Active Trials"}),e.jsx(It,{className:"text-2xl",children:W})]})}),e.jsx(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Vn,{children:"Converted 🎉"}),e.jsx(It,{className:"text-2xl text-primary",children:V})]})}),e.jsx(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Vn,{children:"Already Exported"}),e.jsx(It,{className:"text-2xl text-muted-foreground",children:z})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(ds,{value:p,onValueChange:Y=>f(Y),children:[e.jsx(ls,{className:"w-[160px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Users"}),e.jsx(Qe,{value:"new",children:"New Only"}),e.jsx(Qe,{value:"exported",children:"Already Exported"})]})]}),e.jsxs(ds,{value:c,onValueChange:Y=>d(Y),children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Trial Types"}),e.jsx(Qe,{value:"stripe",children:"Credit Card Trial"}),e.jsx(Qe,{value:"ghl",children:"Free Trial (No CC)"})]})]}),e.jsxs(ds,{value:u,onValueChange:Y=>h(Y),children:[e.jsx(ls,{className:"w-[160px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Statuses"}),e.jsx(Qe,{value:"active",children:"Active Trial"}),e.jsx(Qe,{value:"expired",children:"Expired"}),e.jsx(Qe,{value:"converted",children:"Converted ✓"})]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs(B,{onClick:M,disabled:l||g.size===0,children:[l?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Export Selected (",g.size,")"]})})]}),e.jsx("div",{className:"border rounded-lg",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Ct,{className:"w-[40px]",children:e.jsx(ui,{checked:T.length>0&&g.size===T.length,onCheckedChange:L})}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Trial Type"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Signup Date"}),e.jsx(Ct,{children:"Last Login"}),e.jsx(Ct,{children:"Expires / Renews"}),e.jsx(Ct,{children:"Exported"})]})}),e.jsx(ha,{children:T.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):T.map(Y=>{const K=j(Y),J=S(Y),ne=A(Y),ie=b(Y);return e.jsxs(Hs,{className:`hover:bg-muted/30 ${J?"bg-primary/5":""}`,children:[e.jsx(ut,{children:e.jsx(ui,{checked:g.has(Y.id),onCheckedChange:()=>D(Y.id)})}),e.jsx(ut,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Y.name,J&&e.jsx(mo,{className:"h-3.5 w-3.5 text-primary"})]})}),e.jsx(ut,{className:"text-muted-foreground",children:Y.email}),e.jsx(ut,{children:K==="stripe"?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(pf,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Vs,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(ut,{children:J?e.jsxs(ze,{className:"bg-primary/10 text-primary hover:bg-primary/20 gap-1",children:[e.jsx(mo,{className:"h-3 w-3"}),"Converted"]}):ne?e.jsx(ze,{variant:"destructive",children:"Expired"}):e.jsx(ze,{className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active Trial"})}),e.jsx(ut,{className:"text-sm",children:Y.created_at?new Date(Y.created_at).toLocaleDateString():"—"}),e.jsx(ut,{className:"text-sm",children:Y.last_login?e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:new Date(Y.last_login).toLocaleDateString()}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(Y.last_login).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}):e.jsx("span",{className:"text-muted-foreground",children:"Never"})}),e.jsx(ut,{className:"text-sm",children:J&&ie?e.jsxs("span",{className:"text-muted-foreground",children:["Renews ",new Date(ie).toLocaleDateString()]}):ie?new Date(ie).toLocaleDateString():"—"}),e.jsx(ut,{children:Y.already_exported?e.jsx(xr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(ze,{variant:"outline",className:"text-green-600 border-green-300",children:"New"})})]},Y.id)})})]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",T.length," of ",n.length," trial users · ",V," converted to paid"]})]})},Gbs=s=>s==null?'""':`"${String(s).replace(/"/g,'""')}"`,Wbs=()=>{const[s,t]=N.useState([]),[n,r]=N.useState(!0);N.useEffect(()=>{(async()=>{const{data:l,error:o}=await q.from("user_deletion_log").select("*").order("created_at",{ascending:!1});!o&&l&&t(l),r(!1)})()},[]);const a=()=>{if(s.length===0){ae.info("No deletion records to export");return}const i=["Date","Deleted User","Deleted Email","Brokerage","Type","Deleted By"],l=s.map(h=>[Ss(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(Gbs).join(","))].join(` `),c=new Blob([o],{type:"text/csv"}),d=URL.createObjectURL(c),u=document.createElement("a");u.href=d,u.download=`deletion-log-${new Date().toISOString().split("T")[0]}.csv`,u.click(),URL.revokeObjectURL(d),ae.success(`Exported ${s.length} deletion record(s)`)};return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(_n,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"No deletion records yet"})]})}):e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(It,{className:"text-lg",children:"User Deletion History"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]}),e.jsx(Ee,{children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Date"}),e.jsx(Ct,{children:"User"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Brokerage"}),e.jsx(Ct,{children:"Type"}),e.jsx(Ct,{children:"Deleted By"})]})}),e.jsx(ha,{children:s.map(i=>e.jsxs(Hs,{children:[e.jsx(ut,{className:"whitespace-nowrap text-sm",children:Ss(new Date(i.created_at),"MMM d, yyyy h:mm a")}),e.jsx(ut,{className:"font-medium",children:i.deleted_user_name||"—"}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:i.deleted_user_email||"—"}),e.jsx(ut,{children:i.brokerage_name||"—"}),e.jsx(ut,{children:e.jsx(ze,{variant:i.deletion_type==="deleted"?"destructive":"secondary",children:i.deletion_type==="deleted"?"Account Deleted":"Removed"})}),e.jsx(ut,{className:"text-sm",children:i.deleted_by_name||i.deleted_by_email||"—"})]},i.id))})]})})]})},e6=s=>{const{user:t}=ys(),n=Ht(),r=ct({queryKey:["teams",s],queryFn:async()=>{let h=q.from("teams").select("*").order("created_at",{ascending:!1});s&&(h=h.eq("brokerage_id",s));const{data:p,error:f}=await h;if(f)throw f;return p||[]},enabled:!!t}),a=h=>ct({queryKey:["team-members",h],queryFn:async()=>{const{data:p,error:f}=await q.from("team_members").select("*").eq("team_id",h).order("role",{ascending:!0});if(f)throw f;const g=(p||[]).map(j=>j.user_id),{data:_}=await q.from("profiles").select("id, name, email, avatar_url").in("id",g),v=new Map((_||[]).map(j=>[j.id,j]));return(p||[]).map(j=>({...j,profile:v.get(j.user_id)||null}))},enabled:!!h}),i=gt({mutationFn:async h=>{const p={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&&(p.brokerage_id=h.brokerage_id);const{data:f,error:g}=await q.from("teams").insert(p).select().single();if(g)throw g;return f},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ae.success("Team created!")},onError:h=>{ae.error("Failed to create team: "+h.message)}}),l=gt({mutationFn:async({id:h,...p})=>{const{data:f,error:g}=await q.from("teams").update(p).eq("id",h).select().single();if(g)throw g;return f},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ae.success("Team updated")},onError:h=>{ae.error("Failed to update team: "+h.message)}}),o=gt({mutationFn:async h=>{const{error:p}=await q.from("teams").delete().eq("id",h);if(p)throw p},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ae.success("Team deleted")},onError:h=>{ae.error("Failed to delete team: "+h.message)}}),c=gt({mutationFn:async h=>{const{data:p,error:f}=await q.from("team_members").insert({team_id:h.team_id,user_id:h.user_id,role:h.role||"team_member"}).select().single();if(f)throw f.message.includes("duplicate")||f.message.includes("unique")?new Error("This agent is already on a team. They must be removed from their current team first."):f;return p},onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["team-members",p.team_id]}),ae.success("Member added to team")},onError:h=>{ae.error(h.message)}}),d=gt({mutationFn:async h=>{const{error:p}=await q.from("team_members").delete().eq("id",h.member_id);if(p)throw p},onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["team-members",p.team_id]}),ae.success("Member removed from team")},onError:h=>{ae.error("Failed to remove member: "+h.message)}}),u=gt({mutationFn:async h=>{const{error:p}=await q.from("team_members").update({role:h.role}).eq("id",h.member_id);if(p)throw p},onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["team-members",p.team_id]}),ae.success("Member role updated")},onError:h=>{ae.error("Failed to update role: "+h.message)}});return{teams:r.data||[],isLoading:r.isLoading,createTeam:i,updateTeam:l,deleteTeam:o,addMember:c,removeMember:d,updateMemberRole:u,useTeamMembers:a}},Kbs=()=>{const{user:s}=ys();return ct({queryKey:["team-contacts",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.rpc("get_team_contacts",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},syt=s=>{const{user:t}=ys(),n=Ht(),r=ct({queryKey:["lead-pond",s],queryFn:async()=>{const{data:o,error:c}=await q.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(j=>j.contact_id),u=[...new Set(o.map(j=>j.added_by))],h=o.filter(j=>j.claimed_by).map(j=>j.claimed_by),p=[...new Set([...u,...h])],[f,g]=await Promise.all([q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",d),q.from("profiles").select("id, name, avatar_url").in("id",p)]),_=new Map((f.data||[]).map(j=>[j.id,j])),v=new Map((g.data||[]).map(j=>[j.id,j]));return o.map(j=>({...j,status:j.claimed_by?"claimed":"available",contact:_.get(j.contact_id)||null,contributor:v.get(j.added_by)||null,claimer:j.claimed_by&&v.get(j.claimed_by)||null}))},enabled:!!s&&!!t}),a=gt({mutationFn:async o=>{const{data:c,error:d}=await q.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"]}),ae.success("Contact added to Lead Pond")},onError:o=>{ae.error(o.message)}}),i=gt({mutationFn:async o=>{const{error:c}=await q.rpc("claim_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-pond"]}),ae.success("Lead claimed!")},onError:o=>{ae.error(o.message)}}),l=gt({mutationFn:async o=>{const{error:c}=await q.rpc("return_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-pond"]}),ae.success("Lead returned to pond")},onError:o=>{ae.error(o.message)}});return{leadPondItems:r.data||[],isLoading:r.isLoading,addToLeadPond:a,claimLead:i,returnLead:l}},Ybs=()=>{const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("transfer_contact",{_contact_id:t.contactId,_to_user_id:t.toUserId,_notes:t.notes||null});if(r)throw r;const a=n;if(!a.success)throw new Error(a.error);return a},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["team-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ae.success("Contact transferred successfully")},onError:t=>{ae.error(t.message||"Failed to transfer contact")}})};function nyt({open:s,onOpenChange:t,contactIds:n,contactNames:r=[],onComplete:a}){var T;const{user:i}=ys(),{data:l}=Zv(),{useTeamMembers:o}=e6(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=Ybs(),[u,h]=N.useState(null),[p,f]=N.useState(""),[g,_]=N.useState(!1),v=c.filter(L=>L.user_id!==(i==null?void 0:i.id)),j=async()=>{if(u){_(!0);try{for(const L of n)await d.mutateAsync({contactId:L,toUserId:u,notes:p||void 0});t(!1),h(null),f(""),a==null||a()}catch{}finally{_(!1)}}},b=v.find(L=>L.user_id===u),S=n.length>1,A=r.length>0?S?`${r.length} contacts`:r[0]:S?`${n.length} contacts`:"this contact";return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(mw,{className:"h-5 w-5"}),"Transfer ",A]}),e.jsxs(Qn,{children:["Select a team member to transfer ",S?"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:v.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No other team members available"}):v.map(L=>{var D,M,F;return e.jsxs("button",{onClick:()=>h(L.user_id),className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${u===L.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(ni,{src:((D=L.profile)==null?void 0:D.avatar_url)||""}),e.jsx(aa,{className:"text-xs",children:(((M=L.profile)==null?void 0:M.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:((F=L.profile)==null?void 0:F.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:L.role.replace("_"," ")})]})]},L.user_id)})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"transfer-notes",className:"text-sm font-medium",children:"Notes (optional)"}),e.jsx(Es,{id:"transfer-notes",value:p,onChange:L=>f(L.target.value),placeholder:"Reason for transfer...",className:"mt-1",rows:2})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:j,disabled:!u||g,children:[g?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(mw,{className:"h-4 w-4 mr-2"}),"Transfer",b?` to ${(T=b.profile)==null?void 0:T.name}`:""]})]})]})})}const YIe=()=>{const s=Mn(),{data:t,isLoading:n}=Kbs(),{data:r}=Zv(),[a,i]=N.useState(""),[l,o]=N.useState("all"),[c,d]=N.useState(null),[u,h]=N.useState(""),p=(r==null?void 0:r.role)==="team_leader",f=N.useMemo(()=>{if(!t)return[];const _=new Map;return t.forEach(v=>{_.has(v.owner_user_id)||_.set(v.owner_user_id,{id:v.owner_user_id,name:v.owner_name||"Unknown",avatar:v.owner_avatar_url})}),Array.from(_.values())},[t]),g=N.useMemo(()=>{if(!t)return[];let _=t;if(l!=="all"&&(_=_.filter(v=>v.owner_user_id===l)),a.trim()){const v=a.toLowerCase();_=_.filter(j=>{var b,S,A;return(j.first_name+" "+(j.last_name||"")).toLowerCase().includes(v)||((b=j.email)==null?void 0:b.toLowerCase().includes(v))||((S=j.phone)==null?void 0:S.includes(v))||((A=j.owner_name)==null?void 0:A.toLowerCase().includes(v))})}return _},[t,a,l]);return n?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-10 w-full"}),e.jsx(Ws,{className:"h-64 w-full"})]}):!t||t.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Nn,{className:"h-12 w-12 text-muted-foreground mb-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(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, phone, or agent...",value:a,onChange:_=>i(_.target.value),className:"pl-9"})]}),e.jsxs(ds,{value:l,onValueChange:o,children:[e.jsx(ls,{className:"w-[200px]",children:e.jsx(us,{placeholder:"Filter by agent"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Team Members"}),f.map(_=>e.jsx(Qe,{value:_.id,children:_.name},_.id))]})]})]})})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[g.length," contact",g.length!==1?"s":""," from ",f.length," teammate",f.length!==1?"s":""]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0 overflow-x-auto",children:e.jsxs(da,{className:"min-w-[800px]",children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Contact Info"}),e.jsx(Ct,{children:"Address"}),e.jsx(Ct,{children:"Lead Source"}),e.jsx(Ct,{children:"Date Added"}),p&&e.jsx(Ct,{className:"w-[80px]",children:"Actions"})]})}),e.jsx(ha,{children:g.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:p?7:6,className:"text-center py-8 text-muted-foreground",children:a||l!=="all"?"No contacts match your filters":"No team contacts available"})}):g.map(_=>e.jsxs(Hs,{className:`hover:bg-accent/50 ${p?"cursor-pointer":""}`,onClick:p?()=>s(`/mission-control/contacts/${_.id}`):void 0,children:[e.jsx(ut,{className:"font-medium",children:e.jsxs("span",{className:p?"hover:text-primary hover:underline transition-colors":"",children:[_.first_name," ",_.last_name||""]})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ra,{className:"h-6 w-6",children:[e.jsx(ni,{src:_.owner_avatar_url||""}),e.jsx(aa,{className:"text-[10px]",children:(_.owner_name||"?").charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-sm text-muted-foreground truncate max-w-[120px]",children:_.owner_name||"Unknown"})]})}),e.jsx(ut,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[_.email&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Vs,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:_.email})]}),_.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Ar,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{children:_.phone})]}),!_.email&&!_.phone&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"No contact info"})]})}),e.jsx(ut,{children:_.address?e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(ka,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate max-w-[180px]",children:_.address})]}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(ut,{children:_.lead_source?e.jsx(ze,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:_.lead_source}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(ut,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Ss(new Date(_.created_at),"MMM d, yyyy")})}),p&&e.jsx(ut,{children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:v=>{v.stopPropagation(),d(_.id),h(`${_.first_name} ${_.last_name||""}`.trim())},title:"Transfer to team member",children:e.jsx(mw,{className:"h-4 w-4"})})})]},_.id))})]})})}),e.jsx(nyt,{open:!!c,onOpenChange:_=>{_||d(null)},contactIds:c?[c]:[],contactNames:u?[u]:[],onComplete:()=>d(null)})]})},ZIe=({teamId:s})=>{const{user:t}=ys(),{leadPondItems:n,isLoading:r,claimLead:a,returnLead:i}=syt(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(Ws,{className:"h-20 w-full"},c))});if(n.length===0)return e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(mb,{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,p,f,g,_;return e.jsx(fe,{children:e.jsxs(Ee,{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(Vs,{className:"h-3 w-3"})," ",c.contact.email]}),((p=c.contact)==null?void 0:p.phone)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ar,{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(ni,{src:((f=c.contributor)==null?void 0:f.avatar_url)||""}),e.jsx(aa,{className:"text-[8px]",children:(((g=c.contributor)==null?void 0:g.name)||"?").charAt(0)})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["from ",((_=c.contributor)==null?void 0:_.name)||"Unknown"]})]})]}),e.jsxs(B,{size:"sm",onClick:()=>a.mutate(c.id),disabled:a.isPending,children:[e.jsx(a9,{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(fe,{className:"opacity-75",children:e.jsxs(Ee,{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(ze,{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(cm,{className:"mr-1 h-3 w-3"}),"Return"]})]})},c.id)})})]})]})},ryt=({teamId:s})=>{const{useTeamMembers:t}=e6(),{data:n=[]}=t(s),r=n.map(f=>f.user_id),a=new Map(n.map(f=>[f.user_id,f.profile])),{data:i=[],isLoading:l}=ct({queryKey:["team-shared-presentations",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:f,error:g}=await q.from("smart_presentations").select("id, owner_user_id, title, client_name, status, view_count, cta_clicked_count, share_token, created_at, published_at").in("owner_user_id",r).neq("status","archived").order("created_at",{ascending:!1});if(g)throw g;return f||[]},enabled:r.length>0}),{data:o=[],isLoading:c}=ct({queryKey:["team-shared-open-houses",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:f,error:g}=await q.from("open_houses").select("id, agent_id, property_address, city, state, event_date, is_active, visitor_count, slug, created_at").in("agent_id",r).order("event_date",{ascending:!1});if(g)throw g;return f||[]},enabled:r.length>0}),{data:d=[],isLoading:u}=ct({queryKey:["team-shared-videos",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:f,error:g}=await q.from("agent_videos").select("id, owner_user_id, title, recipient_name, status, view_count, touch_type, share_token, created_at").in("owner_user_id",r).eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(g)throw g;return f||[]},enabled:r.length>0});if(l||c||u)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(f=>e.jsx(Ws,{className:"h-20 w-full"},f))});const p=f=>{const g=a.get(f);return{name:(g==null?void 0:g.name)||"Unknown",avatar:(g==null?void 0:g.avatar_url)||"",initials:((g==null?void 0:g.name)||"?").charAt(0).toUpperCase()}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-3",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"flex items-center gap-3 p-4",children:[e.jsx(iy,{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(fe,{children:e.jsxs(Ee,{className:"flex items-center gap-3 p-4",children:[e.jsx(Or,{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(fe,{children:e.jsxs(Ee,{className:"flex items-center gap-3 p-4",children:[e.jsx(br,{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(Br,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(Fr,{children:[e.jsxs(Kt,{value:"presentations",children:["Presentations (",i.length,")"]}),e.jsxs(Kt,{value:"guest-books",children:["Guest Books (",o.length,")"]}),e.jsxs(Kt,{value:"videos",children:["Videos (",d.length,")"]})]}),e.jsx(is,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(z2e,{icon:e.jsx(iy,{className:"h-10 w-10"}),label:"No presentations yet"}):i.map(f=>{const g=p(f.owner_user_id);return e.jsx(fe,{children:e.jsxs(Ee,{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(ni,{src:g.avatar}),e.jsx(aa,{className:"text-xs",children:g.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:f.title||"Untitled"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.name," · ",Ss(new Date(f.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(ze,{variant:f.status==="published"?"default":"secondary",className:"text-xs capitalize",children:f.status}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Er,{className:"h-3 w-3"}),f.view_count||0]})]})]})},f.id)})}),e.jsx(is,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(z2e,{icon:e.jsx(Or,{className:"h-10 w-10"}),label:"No guest books yet"}):o.map(f=>{const g=p(f.agent_id);return e.jsx(fe,{children:e.jsxs(Ee,{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(ni,{src:g.avatar}),e.jsx(aa,{className:"text-xs",children:g.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:f.property_address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.name," · ",Ss(new Date(f.event_date),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[f.is_active?e.jsx(ze,{className:"text-xs",children:"Active"}):e.jsx(ze,{variant:"secondary",className:"text-xs",children:"Inactive"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Nn,{className:"h-3 w-3"}),f.visitor_count||0]})]})]})},f.id)})}),e.jsx(is,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(z2e,{icon:e.jsx(br,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(f=>{const g=p(f.owner_user_id);return e.jsx(fe,{children:e.jsxs(Ee,{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(ni,{src:g.avatar}),e.jsx(aa,{className:"text-xs",children:g.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:f.title||f.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.name," · ",Ss(new Date(f.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(ze,{variant:"secondary",className:"text-xs capitalize",children:f.touch_type}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Er,{className:"h-3 w-3"}),f.view_count||0]})]})]})},f.id)})})]})]})},z2e=({icon:s,label:t})=>e.jsx(fe,{children:e.jsxs(Ee,{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})]})}),ayt=({team:s,brokerageAgents:t,onBack:n,onUpdate:r,onAddMember:a,onRemoveMember:i,onUpdateRole:l,onDeleteTeam:o,isUpdating:c,isAddingMember:d})=>{var D,M;const{useTeamMembers:u}=e6(),{data:h=[],isLoading:p}=u(s.id),[f,g]=N.useState(!1),[_,v]=N.useState(""),[j,b]=N.useState("team_member"),{data:S}=ct({queryKey:["agents-on-other-teams",s.id],queryFn:async()=>{const{data:F}=await q.from("team_members").select("user_id, team_id, teams:team_id(name)").neq("team_id",s.id),z=new Map;return(F||[]).forEach(V=>{var W;z.set(V.user_id,((W=V.teams)==null?void 0:W.name)||"another team")}),z}}),A=new Set(h.map(F=>F.user_id)),T=t.filter(F=>!A.has(F.id)),L=async()=>{_&&(await a(_,j),v(""),b("team_member"),g(!1))};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(B,{variant:"ghost",onClick:n,className:"mb-2",children:"← Back to Teams"}),e.jsxs(Br,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(Fr,{children:[e.jsx(Kt,{value:"members",children:"Members"}),e.jsxs(Kt,{value:"contacts",children:[e.jsx(SA,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(Kt,{value:"lead-pond",children:[e.jsx(mb,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(Kt,{value:"shared-assets",children:[e.jsx(gf,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(Kt,{value:"settings",children:"Settings"})]}),e.jsxs(is,{value:"members",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-lg font-semibold",children:[s.name," — Members"]}),e.jsxs(bs,{open:f,onOpenChange:g,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Fo,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Add Team Member"}),e.jsxs(Qn,{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(el,{children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[_&&(((D=T.find(F=>F.id===_))==null?void 0:D.name)||((M=T.find(F=>F.id===_))==null?void 0:M.email))||"Select an agent",e.jsx(qg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ho,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Qg,{children:[e.jsx(Xg,{placeholder:"Search agents..."}),e.jsxs(Jg,{children:[e.jsx(e0,{children:"No agents found."}),e.jsx(t0,{children:T.map(F=>{const z=S==null?void 0:S.get(F.id);return e.jsxs(Jf,{value:F.name||F.email||F.id,disabled:!!z,onSelect:()=>v(F.id),children:[e.jsx(Ir,{className:Et("mr-2 h-4 w-4",_===F.id?"opacity-100":"opacity-0")}),F.name||F.email,z&&e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(on ",z,")"]})]},F.id)})})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Role"}),e.jsxs(ds,{value:j,onValueChange:b,children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"team_leader",children:"Team Leader"}),e.jsx(Qe,{value:"team_member",children:"Team Member"})]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx(B,{onClick:L,disabled:!_||d,children:d?"Adding...":"Add to Team"})]})]})]})]}),p?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(F=>e.jsx(Ws,{className:"h-16 w-full"},F))}):h.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(Nn,{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(F=>{var z,V,W,Y,K;return e.jsx(fe,{children:e.jsxs(Ee,{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(ni,{src:((z=F.profile)==null?void 0:z.avatar_url)||""}),e.jsx(aa,{children:(((V=F.profile)==null?void 0:V.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((W=F.profile)==null?void 0:W.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(Y=F.profile)==null?void 0:Y.email})]}),F.role==="team_leader"?e.jsxs(ze,{className:"bg-[hsl(var(--chart-4)/0.1)] text-[hsl(var(--chart-4))] border-[hsl(var(--chart-4))]",children:[e.jsx(ff,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(ze,{variant:"secondary",children:"Member"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ds,{value:F.role,onValueChange:J=>l(F.id,J),children:[e.jsx(ls,{className:"w-[140px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"team_leader",children:"Team Leader"}),e.jsx(Qe,{value:"team_member",children:"Team Member"})]})]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx(F9,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Remove Member?"}),e.jsxs(Mo,{children:["Remove ",((K=F.profile)==null?void 0:K.name)||"this member"," from ",s.name,"?"]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>i(F.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})]})]})]})},F.id)})})]}),e.jsx(is,{value:"contacts",className:"space-y-4",children:e.jsx(YIe,{})}),s.lead_pond_enabled&&e.jsx(is,{value:"lead-pond",className:"space-y-4",children:e.jsx(ZIe,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(is,{value:"shared-assets",className:"space-y-4",children:e.jsx(ryt,{teamId:s.id})}),e.jsxs(is,{value:"settings",className:"space-y-4",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{className:"text-lg",children:"Team Settings"}),e.jsx(Vn,{children:"Configure how this team operates."})]}),e.jsxs(Ee,{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:F=>{F.target.value!==s.name&&r({name:F.target.value})}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Es,{defaultValue:s.description||"",onBlur:F=>{F.target.value!==(s.description||"")&&r({description:F.target.value||null})},rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Contact Visibility"}),e.jsxs(ds,{defaultValue:s.contact_visibility,onValueChange:F=>r({contact_visibility:F}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(Qe,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(Qe,{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(bn,{checked:s.lead_pond_enabled,onCheckedChange:F=>r({lead_pond_enabled:F})})]}),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(bn,{checked:s.shared_assets_enabled,onCheckedChange:F=>r({shared_assets_enabled:F})})]}),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(bn,{checked:s.shared_videos_enabled??!1,onCheckedChange:F=>r({shared_videos_enabled:F})})]})]})]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsxs(B,{variant:"destructive",size:"sm",children:[e.jsx(_n,{className:"mr-2 h-4 w-4"}),"Delete Team"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Team?"}),e.jsxs(Mo,{children:['This will permanently delete "',s.name,'" and remove all team members. This cannot be undone.']})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>{o(),n()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Team"})]})]})]})]})]})]})},iyt=({open:s,onOpenChange:t,onCreateTeam:n,isCreating:r,brokerageAgents:a,isAdmin:i,allBrokerages:l,activeBrokerageId:o})=>{const[c,d]=N.useState(1),[u,h]=N.useState(""),[p,f]=N.useState(""),[g,_]=N.useState(""),[v,j]=N.useState(""),[b,S]=N.useState([]),A=()=>{d(1),h(""),f(""),_(""),j(""),S([])},T=F=>{F||A(),t(F)},L=async()=>{const F=g&&g!=="none"?g:o||null;await n({name:u.trim(),description:p.trim()||void 0,brokerage_id:F,leaderId:v||void 0,memberIds:b.length>0?b:void 0}),A()},D=F=>{F!==v&&S(z=>z.includes(F)?z.filter(V=>V!==F):[...z,F])},M=a.filter(F=>F.id!==v);return e.jsx(bs,{open:s,onOpenChange:T,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:c===1?"Create New Team":"Assign Team Members"}),e.jsx(Qn,{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:F=>h(F.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(Es,{id:"team-desc",value:p,onChange:F=>f(F.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(ds,{value:g,onValueChange:_,children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"No brokerage (independent team)"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"No brokerage (independent)"}),l.map(F=>e.jsx(Qe,{value:F.id,children:F.name},F.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(ff,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(ds,{value:v,onValueChange:F=>{j(F),S(z=>z.filter(V=>V!==F))},children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select a team leader (optional)"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"No leader for now"}),a.map(F=>e.jsx(Qe,{value:F.id,children:F.name||F.email||"Unknown"},F.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-1.5",children:[e.jsx(Fo,{className:"h-3.5 w-3.5"}),"Initial Members",b.length>0&&e.jsxs(ze,{variant:"secondary",className:"ml-1 text-xs",children:[b.length," selected"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click agents to add them. You can always add more later."}),e.jsx("div",{className:"border rounded-lg max-h-[240px] overflow-y-auto divide-y",children:M.length===0?e.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[e.jsx(Nn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No agents available"]}):M.map(F=>{const z=b.includes(F.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",z&&"bg-primary/5"),onClick:()=>D(F.id),children:[e.jsxs(ra,{className:"h-8 w-8",children:[e.jsx(ni,{src:F.avatar_url||""}),e.jsx(aa,{className:"text-xs",children:(F.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:F.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:F.email})]}),e.jsx("div",{className:Et("h-5 w-5 rounded-full border-2 flex items-center justify-center transition-colors shrink-0",z?"bg-primary border-primary text-primary-foreground":"border-muted-foreground/30"),children:z&&e.jsx(Ir,{className:"h-3 w-3"})})]},F.id)})})]})]})}),e.jsx(Xn,{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(Oa,{className:"ml-2 h-4 w-4"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",onClick:()=>d(1),children:[e.jsx(Hr,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsx(B,{onClick:L,disabled:r,children:r?"Creating…":"Create Team"})]})})]})})},Zbs=()=>{const{teams:s,isLoading:t,createTeam:n,updateTeam:r,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=e6(),[c,d]=N.useState(!1),[u,h]=N.useState(null),[p,f]=N.useState(""),{data:g}=ct({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:T,error:L}=await q.from("brokerages").select("id, name").order("name");if(L)throw L;return T||[]}}),{data:_}=ct({queryKey:["admin-team-member-info",s.map(T=>T.id).join(",")],queryFn:async()=>{var F;if(s.length===0)return{};const{data:T}=await q.from("team_members").select("team_id, user_id, role").in("team_id",s.map(z=>z.id));if(!T)return{};const L=T.filter(z=>z.role==="team_leader").map(z=>z.user_id);let D={};if(L.length>0){const{data:z}=await q.from("profiles").select("id, name").in("id",L);z&&(D=Object.fromEntries(z.map(V=>[V.id,{name:V.name}])))}const M={};for(const z of s){const V=T.filter(Y=>Y.team_id===z.id),W=V.find(Y=>Y.role==="team_leader");M[z.id]={count:V.length,leaderName:W&&((F=D[W.user_id])==null?void 0:F.name)||null}}return M},enabled:s.length>0}),v=(u==null?void 0:u.brokerage_id)||null,{data:j}=ct({queryKey:["brokerage-agents-for-teams",v],queryFn:async()=>{let T=q.from("profiles").select("id, name, email, avatar_url").order("name");v&&(T=T.eq("brokerage_id",v));const{data:L,error:D}=await T;if(D)throw D;return L||[]},enabled:!!u}),b=Object.fromEntries((g||[]).map(T=>[T.id,T.name])),S=async T=>{const L=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:L.id,user_id:T.leaderId,role:"team_leader"}),T.memberIds)for(const D of T.memberIds)await i.mutateAsync({team_id:L.id,user_id:D,role:"team_member"});d(!1)};if(u)return e.jsx(ayt,{team:u,brokerageAgents:j||[],onBack:()=>h(null),onUpdate:T=>r.mutateAsync({id:u.id,...T}).then(L=>h(L)),onAddMember:(T,L)=>i.mutateAsync({team_id:u.id,user_id:T,role:L}),onRemoveMember:T=>l.mutateAsync({team_id:u.id,member_id:T}),onUpdateRole:(T,L)=>o.mutateAsync({team_id:u.id,member_id:T,role:L}),onDeleteTeam:()=>{a.mutate(u.id),h(null)},isUpdating:r.isPending,isAddingMember:i.isPending});const A=s.filter(T=>T.name.toLowerCase().includes(p.toLowerCase())||(T.description||"").toLowerCase().includes(p.toLowerCase()));return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search teams...",value:p,onChange:T=>f(T.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[A.length," of ",s.length," teams"]})]}),e.jsxs(B,{size:"sm",onClick:()=>d(!0),children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(iyt,{open:c,onOpenChange:d,onCreateTeam:S,isCreating:n.isPending,brokerageAgents:[],isAdmin:!0,allBrokerages:g,activeBrokerageId:null}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Ct,{className:"font-semibold",children:"Team Name"}),e.jsx(Ct,{className:"font-semibold",children:"Brokerage"}),e.jsx(Ct,{className:"font-semibold",children:"Leader"}),e.jsx(Ct,{className:"font-semibold",children:"Members"}),e.jsx(Ct,{className:"font-semibold",children:"Visibility"}),e.jsx(Ct,{className:"w-[100px]"})]})}),e.jsx(ha,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(T=>e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsx(Ws,{className:"h-4 w-32"})}),e.jsx(ut,{children:e.jsx(Ws,{className:"h-4 w-24"})}),e.jsx(ut,{children:e.jsx(Ws,{className:"h-4 w-28"})}),e.jsx(ut,{children:e.jsx(Ws,{className:"h-4 w-12"})}),e.jsx(ut,{children:e.jsx(Ws,{className:"h-4 w-20"})}),e.jsx(ut,{children:e.jsx(Ws,{className:"h-4 w-16"})})]},T))}):A.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:6,className:"text-center py-12 text-muted-foreground",children:p?"No teams match your search":"No teams found. Create one to get started."})}):A.map(T=>{const L=_==null?void 0:_[T.id];return e.jsxs(Hs,{className:"hover:bg-muted/30",children:[e.jsxs(ut,{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(ut,{children:T.brokerage_id?e.jsx("span",{className:"text-sm",children:b[T.brokerage_id]||"—"}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Independent"})}),e.jsx(ut,{children:L!=null&&L.leaderName?e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(ff,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),L.leaderName]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No leader"})}),e.jsx(ut,{children:e.jsxs(ze,{variant:"secondary",className:"text-xs",children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),(L==null?void 0:L.count)??0]})}),e.jsx(ut,{children:e.jsxs("span",{className:"text-xs text-muted-foreground capitalize flex items-center gap-1",children:[e.jsx(dh,{className:"h-3 w-3"}),T.contact_visibility.replace("_"," ")]})}),e.jsx(ut,{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(_a,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>{confirm(`Delete team "${T.name}"? This cannot be undone.`)&&a.mutate(T.id)},title:"Delete team",children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})})]},T.id)})})]})})]})};function VHe(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 Qbs({open:s,onOpenChange:t,recipients:n}){const{toast:r}=Ba(),[a,i]=N.useState([]),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState(""),[g,_]=N.useState(!1),[v,j]=N.useState(!1),b=N.useMemo(()=>a.find(L=>L.id===c)||null,[a,c]);N.useEffect(()=>{s&&(o(!0),(async()=>{const L=new Date().toISOString(),{data:D,error:M}=await q.from("events").select("id,title,description,event_date,zoom_link,image_url,is_published").gte("event_date",L).order("event_date",{ascending:!0}).limit(50);M?r({title:"Could not load events",description:M.message,variant:"destructive"}):i(D||[]),o(!1)})())},[s,r]);const S=N.useMemo(()=>n.filter(L=>L.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(L.email)),[n]),A=()=>{if(!b){r({title:"Pick an event first",variant:"destructive"});return}if(S.length===0){r({title:"No valid recipient emails",variant:"destructive"});return}j(!0)},T=async()=>{if(b){j(!1),_(!0);try{const{data:{session:L}}=await q.auth.getSession(),D=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L==null?void 0:L.access_token}`},body:JSON.stringify({event_id:b.id,recipients:S.map(V=>({email:V.email,name:V.name,user_id:V.id})),custom_subject:u.trim()||void 0,custom_intro:p.trim()||void 0})}),M=await D.json().catch(()=>({}));if(!D.ok)throw new Error((M==null?void 0:M.error)||"Failed to send event invite");const F=(M==null?void 0:M.sent)??0,z=(M==null?void 0:M.failed)??0;r({title:"Invites sent",description:`Sent: ${F}${z?` · Failed: ${z}`:""}`}),t(!1),f(""),h(""),d("")}catch(L){const D=L instanceof Error?L.message:"Send failed";r({title:"Send failed",description:D,variant:"destructive"})}finally{_(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(Qn,{children:["Send a beautiful event invitation to ",S.length," selected member",S.length===1?"":"s",".",n.length!==S.length&&e.jsxs("span",{className:"block text-amber-600 mt-1",children:[n.length-S.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(ts,{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(ds,{value:c,onValueChange:d,children:[e.jsx(ls,{id:"event-select",children:e.jsx(us,{placeholder:"Pick an upcoming event..."})}),e.jsx(cs,{children:a.map(L=>e.jsx(Qe,{value:L.id,children:e.jsxs("div",{className:"flex flex-col text-left",children:[e.jsx("span",{className:"font-medium",children:L.title}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[VHe(L.event_date),!L.is_published&&" · (Draft)"]})]})},L.id))})]})]}),b&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(yr,{className:"h-4 w-4 text-primary"}),b.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:VHe(b.event_date)}),b.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:b.description})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"subject",children:"Subject line (optional)"}),e.jsx(ye,{id:"subject",placeholder:b?`You're invited: ${b.title}`:"You're invited to...",value:u,onChange:L=>h(L.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(Es,{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:p,onChange:L=>f(L.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 (",S.length,")"]}),e.jsxs("div",{className:"flex flex-wrap gap-1 max-h-24 overflow-y-auto",children:[S.slice(0,30).map(L=>e.jsx(ze,{variant:"secondary",className:"text-xs font-normal",children:L.name||L.email},L.id)),S.length>30&&e.jsxs(ze,{variant:"outline",className:"text-xs",children:["+",S.length-30," more"]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:g,children:"Cancel"}),e.jsx(B,{onClick:A,disabled:g||!c||S.length===0,children:g?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-2"})," Send to ",S.length]})})]})]})}),e.jsx(Oo,{open:v,onOpenChange:j,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Send event invite?"}),e.jsx(Mo,{children:b?e.jsxs(e.Fragment,{children:["Send invite for ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',b.title,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[S.length," member",S.length===1?"":"s"]}),"?"]}):null})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsxs(jo,{onClick:T,children:[e.jsx(cr,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const Xbs=()=>{const s=Mn(),{user:t,isAdmin:n}=ys(),{startImpersonation:r,isLoading:a}=H0e(),{toast:i}=Ba(),[l,o]=N.useState([]),[c,d]=N.useState([]),[u,h]=N.useState([]),[p,f]=N.useState({}),[g,_]=N.useState(!0);N.useState({});const[v,j]=N.useState(!1),[b,S]=N.useState({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),[A,T]=N.useState(!1),[L,D]=N.useState(""),[M,F]=N.useState(1),[z,V]=N.useState(50),[W,Y]=N.useState("all"),[K,J]=N.useState("all"),[ne,ie]=N.useState("all"),[he,ce]=N.useState("all"),[pe,le]=N.useState("all"),[ve,ge]=N.useState(!1),[Te,Me]=N.useState(!1),[Ce,Ae]=N.useState(!1),[De,Ie]=N.useState(null),[Fe,qe]=N.useState(null),[be,Ze]=N.useState(!1),[Ne,it]=N.useState({name:"",email:"",brokerage_id:"",phone:""}),[je,Ge]=N.useState(null),[Be,Ye]=N.useState(!1),[We,rt]=N.useState(""),[tt,at]=N.useState(!1),[He,dt]=N.useState(!1),[bt,vt]=N.useState(null),[Bt,Zt]=N.useState(""),[Fs,Rs]=N.useState(!1),[ms,Pt]=N.useState(!1),[Jt,ft]=N.useState(null),[Vt,Ms]=N.useState(!1),[Xt,Js]=N.useState(!1),[Cs,As]=N.useState(null),[rn,tn]=N.useState(""),[er,gn]=N.useState(!1),[In,Zn]=N.useState({email:"",name:"",password:"",phone:""}),[ea,vi]=N.useState(!1),[Ls,fi]=N.useState(!1),[Lr,Jn]=N.useState(""),[js,Dn]=N.useState(!1),[wr,$r]=N.useState(!1),[ss,Oe]=N.useState(""),[Xe,ot]=N.useState(new Set),[Nt,Rt]=N.useState(!1),[qt,xs]=N.useState(!1),[rs,ks]=N.useState(null),[ln,Gs]=N.useState(!1),[Un,jr]=N.useState(null),[Sr,nr]=N.useState([]),[Ot,fn]=N.useState([]),[sr,Hn]=N.useState(!1),[ta,Zr]=N.useState({});N.useEffect(()=>{!t||!n||(Mr(),zi())},[t,n]);const ur=async()=>{try{const{data:Lt,error:hn}=await q.from("brokerage_manager_assignments").select("user_id, brokerage_id");if(hn)throw hn;const zn={};for(const Dr of Lt??[])zn[Dr.brokerage_id]||(zn[Dr.brokerage_id]=[]),zn[Dr.brokerage_id].push(Dr.user_id);f(zn)}catch(Lt){console.error("Error loading brokerage manager assignments:",Lt)}},Mr=async()=>{try{_(!0);const{data:Lt,error:hn}=await q.functions.invoke("get-user-details");if(hn)throw hn;const zn=Lt.users||[];o(zn),h(Lt.brokerages||[]),await ur();const Dr=zn.filter(Gn=>Gn.roles.includes("assistant"));if(Dr.length>0){const Gn=Dr.map(Xa=>Xa.id),{data:fa}=await q.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",Gn);if(fa&&fa.length>0){const Xa=[...new Set(fa.map(Cd=>Cd.agent_id))],{data:ii}=await q.from("profiles").select("id, name, email").in("id",Xa),zr={};for(const Cd of fa){const gm=ii==null?void 0:ii.find(Ku=>Ku.id===Cd.agent_id);gm&&(zr[Cd.assistant_id]={agent_name:gm.name||"",agent_email:gm.email||""})}Zr(zr)}}}catch(Lt){console.error("Error loading members:",Lt),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{_(!1)}},zi=async()=>{try{const{data:Lt,error:hn}=await q.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(hn)throw hn;d(Lt||[])}catch(Lt){console.error("Error loading apps:",Lt),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},Bi=async Lt=>{if(!Ne.name.trim()||!Ne.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Ne.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:zn}=await q.from("profiles").update({name:Ne.name.trim(),email:Ne.email.trim(),brokerage_id:Ne.brokerage_id||null,phone:Ne.phone.trim()||null}).eq("id",Lt);if(zn)throw zn;i({title:"Success",description:"Member details updated successfully"}),Ie(null),Mr()}catch(zn){console.error("Error updating member:",zn),i({title:"Error",description:zn.message||"Failed to update member",variant:"destructive"})}},Za=async Lt=>{try{const{data:{session:hn}}=await q.auth.getSession(),zn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${hn==null?void 0:hn.access_token}`},body:JSON.stringify({userId:Lt})}),Dr=await zn.json();if(!zn.ok)throw new Error(Dr.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch(hn){console.error("Error resending welcome email:",hn),i({title:"Error",description:hn.message||"Failed to resend welcome email",variant:"destructive"})}},_i=async(Lt,hn)=>{try{const{error:zn}=await q.functions.invoke("send-password-reset",{body:{email:Lt,redirectTo:window.location.origin}});if(zn)throw zn;i({title:"Password Reset Sent",description:`Password reset email sent to ${hn}`})}catch(zn){console.error("Error sending password reset:",zn),i({title:"Error",description:zn.message||"Failed to send password reset email",variant:"destructive"})}},qi=async(Lt,hn)=>{if(confirm(`Are you sure you want to delete ${hn}? This action cannot be undone.`))try{const{data:{session:zn}}=await q.auth.getSession(),Dr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${zn==null?void 0:zn.access_token}`},body:JSON.stringify({userId:Lt})}),Gn=await Dr.json();if(!Dr.ok)throw new Error(Gn.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),Mr()}catch(zn){console.error("Error deleting user:",zn),i({title:"Error",description:zn.message||"Failed to delete user",variant:"destructive"})}},ga=async()=>{if(!b.email||!b.name||!b.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}if(b.role==="brokerage_manager"&&!b.brokerage_id){i({title:"Error",description:"Please select a brokerage for this manager",variant:"destructive"});return}j(!0);try{const{data:{session:Lt}}=await q.auth.getSession(),hn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Lt==null?void 0:Lt.access_token}`},body:JSON.stringify(b)}),zn=await hn.json();if(!hn.ok)throw new Error(zn.error||"Failed to create user");if(b.role&&b.role!=="user"&&zn.userId){const Dr=b.role==="brokerage_manager"?b.brokerage_id:void 0;await wn(zn.userId,b.role,"add",Dr)}i({title:"Success",description:`User ${b.email} created successfully`}),S({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),T(!1),Mr()}catch(Lt){console.error("Error creating user:",Lt),i({title:"Error",description:Lt.message||"Failed to create user",variant:"destructive"})}finally{j(!1)}},wn=async(Lt,hn,zn,Dr)=>{try{const{data:{session:Gn}}=await q.auth.getSession(),fa={userId:Lt,role:hn,action:zn};if(hn==="brokerage_manager"){if(!Dr){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}fa.brokerageId=Dr}const Xa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gn==null?void 0:Gn.access_token}`},body:JSON.stringify(fa)}),ii=await Xa.json();if(!Xa.ok)throw new Error(ii.error||"Failed to manage user role");i({title:"Success",description:`Role ${zn==="add"?"added":"removed"} successfully`}),Mr()}catch(Gn){console.error("Error managing user role:",Gn),i({title:"Error",description:Gn.message||"Failed to manage user role",variant:"destructive"})}},Ta=(Lt,hn)=>hn.length===0?!0:hn.some(zn=>Lt.includes(zn)),Yi=async(Lt,hn,zn)=>{const Dr=`${Lt}-${hn.id}`;Ge(Dr);try{if(zn){const Gn=l.find(Xa=>Xa.id===Lt),fa=hn.required_tags.filter(Xa=>Gn==null?void 0:Gn.tags.includes(Xa));for(const Xa of fa){const{error:ii}=await q.from("user_tags").delete().eq("user_id",Lt).eq("tag",Xa);if(ii)throw ii}i({title:"Access Removed",description:`Removed access to ${hn.name}`})}else if(hn.required_tags.length>0){const{error:Gn}=await q.from("user_tags").insert({user_id:Lt,tag:hn.required_tags[0]});if(Gn)throw Gn;i({title:"Access Granted",description:`Granted access to ${hn.name}`})}await Mr()}catch(Gn){console.error("Error toggling access:",Gn),i({title:"Error",description:Gn.message||"Failed to update access",variant:"destructive"})}finally{Ge(null)}},zo=async()=>{const Lt=We.trim();if(!Lt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Lt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}if(u.find(zn=>zn.name.toLowerCase()===Lt.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}at(!0);try{const{error:zn}=await q.from("brokerages").insert({name:Lt});if(zn)throw zn;i({title:"Success",description:`Brokerage "${Lt}" created successfully`}),rt(""),Ye(!1),Mr()}catch(zn){console.error("Error creating brokerage:",zn),i({title:"Error",description:zn.message||"Failed to create brokerage",variant:"destructive"})}finally{at(!1)}},rl=Lt=>{vt(Lt),Zt(Lt.name),dt(!0)},po=()=>{vt(null),Zt(""),dt(!1)},uc=async()=>{if(!bt)return;const Lt=Bt.trim();if(!Lt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Lt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}Rs(!0);try{const{error:hn}=await q.from("brokerages").update({name:Lt}).eq("id",bt.id);if(hn)throw hn;i({title:"Success",description:"Brokerage updated successfully"}),po(),Mr()}catch(hn){console.error("Error updating brokerage:",hn),i({title:"Error",description:hn.message||"Failed to update brokerage",variant:"destructive"})}finally{Rs(!1)}},hc=async(Lt,hn)=>{var zn;if(!hn||typeof hn!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const Dr={userId:Lt,role:"brokerage_manager",action:"add",brokerageId:hn};console.debug("[assignManagerToBrokerage] payload",Dr);const{data:{session:Gn}}=await q.auth.getSession(),fa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gn==null?void 0:Gn.access_token}`},body:JSON.stringify(Dr)}),Xa=await fa.json();if(!fa.ok&&!((zn=Xa.error)!=null&&zn.includes("duplicate")))throw new Error(Xa.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await Mr()}catch(Dr){console.error("Error assigning manager:",Dr),i({title:"Error",description:Dr.message||"Failed to assign manager",variant:"destructive"})}},Tf=Lt=>{ft(Lt),Pt(!0)},Hu=async()=>{if(Jt){Ms(!0);try{const Lt=l.filter(Dr=>Dr.brokerage_id===Jt.id),{data:{session:hn}}=await q.auth.getSession();for(const Dr of Lt){const Gn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${hn==null?void 0:hn.access_token}`},body:JSON.stringify({userId:Dr.id})});if(!Gn.ok){const fa=await Gn.json();console.error(`Failed to delete user ${Dr.email}:`,fa.error)}}const{error:zn}=await q.from("brokerages").delete().eq("id",Jt.id);if(zn)throw zn;i({title:"Success",description:`Brokerage "${Jt.name}" and ${Lt.length} member(s) deleted`}),Pt(!1),ft(null),Mr()}catch(Lt){console.error("Error deleting brokerage:",Lt),i({title:"Error",description:Lt.message||"Failed to delete brokerage",variant:"destructive"})}finally{Ms(!1)}}},pm=Lt=>{As(Lt),tn(""),Js(!0)},Gu=()=>{As(null),tn(""),Js(!1)},qd=async Lt=>{try{const{error:hn}=await q.from("profiles").update({brokerage_id:null}).eq("id",Lt);if(hn)throw hn;i({title:"Success",description:"User removed from brokerage"}),Mr()}catch(hn){console.error("Error removing user from brokerage:",hn),i({title:"Error",description:hn.message||"Failed to remove user",variant:"destructive"})}},a1=async(Lt,hn)=>{try{const{error:zn}=await q.from("profiles").update({brokerage_id:hn}).eq("id",Lt);if(zn)throw zn;i({title:"Success",description:"User added to brokerage"}),Mr()}catch(zn){console.error("Error adding user to brokerage:",zn),i({title:"Error",description:zn.message||"Failed to add user",variant:"destructive"})}},oj=async()=>{if(!Cs||!In.email||!In.name||!In.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}vi(!0);try{const{data:{session:Lt}}=await q.auth.getSession(),hn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Lt==null?void 0:Lt.access_token}`},body:JSON.stringify({...In,brokerage_id:Cs.id,role:"user"})}),zn=await hn.json();if(!hn.ok)throw new Error(zn.error||"Failed to create agent");i({title:"Success",description:`Agent ${In.email} created successfully`}),Zn({email:"",name:"",password:"",phone:""}),gn(!1),Mr()}catch(Lt){console.error("Error creating agent:",Lt),i({title:"Error",description:Lt.message||"Failed to create agent",variant:"destructive"})}finally{vi(!1)}},fm=Lt=>l.filter(hn=>hn.brokerage_id===Lt),Ay=Lt=>{const hn=fm(Lt);if(!rn)return hn;const zn=rn.toLowerCase();return hn.filter(Dr=>Dr.name.toLowerCase().includes(zn)||Dr.email.toLowerCase().includes(zn))},My=Lt=>l.filter(hn=>hn.brokerage_id!==Lt),Ef=l.filter(Lt=>{var zn;if(L){const Dr=L.toLowerCase();if(!(Lt.name.toLowerCase().includes(Dr)||Lt.email.toLowerCase().includes(Dr)||((zn=Lt.brokerage_name)==null?void 0:zn.toLowerCase().includes(Dr))))return!1}if(W==="claimed"&&!Lt.claimed||W==="unclaimed"&&Lt.claimed||K!=="all"&&!Lt.roles.includes(K))return!1;const hn=Lt.is_trial||Lt.subscription_status==="trialing";if(ne==="trial"&&!hn||ne==="non-trial"&&hn||he==="none"&&Lt.brokerage_id||he!=="all"&&he!=="none"&&Lt.brokerage_id!==he)return!1;if(pe!=="all"){if(!Lt.created_at)return!1;const Dr=parseInt(pe,10),Gn=Date.now()-Dr*24*60*60*1e3;if(new Date(Lt.created_at).getTime(){var hn;return((hn=Lt.name)==null?void 0:hn.toLowerCase())||""},brokerage:Lt=>{var hn;return((hn=Lt.brokerage_name)==null?void 0:hn.toLowerCase())||""},status:Lt=>Lt.claimed?"active":"pending",role:Lt=>Lt.roles[0]||"",last_login:Lt=>Lt.last_sign_in_at?new Date(Lt.last_sign_in_at).getTime():null,created_at:Lt=>Lt.created_at?new Date(Lt.created_at).getTime():null}),Fh=xm.length,px=z===0,Wu=px?1:Math.ceil(Fh/z),al=px?0:(M-1)*z,d0=px?Fh:al+z,xu=xm.slice(al,d0),u0=Lt=>{D(Lt),F(1)},lj=Lt=>{V(Lt),F(1)},Af=(Lt,hn)=>{Lt(hn),F(1)},Qa=async(Lt,hn)=>{Me(!0);try{const zn=l.find(Xa=>Xa.id===Lt);if(!zn)return;const Dr=zn.trial_expires_at?new Date(zn.trial_expires_at):new Date,Gn=new Date(Dr.getTime()+hn*24*60*60*1e3),{error:fa}=await q.from("profiles").update({trial_expires_at:Gn.toISOString()}).eq("id",Lt);if(fa)throw fa;i({title:"Trial Extended",description:`Trial extended by ${hn} days`}),Mr()}catch(zn){console.error("Error extending trial:",zn),i({title:"Error",description:zn.message||"Failed to extend trial",variant:"destructive"})}finally{Me(!1)}},Iy=async Lt=>{Ae(!0);try{const{error:hn}=await q.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",Lt);if(hn)throw hn;i({title:"Account Converted",description:"User has been converted to a full account"}),Mr(),dg()}catch(hn){console.error("Error converting trial:",hn),i({title:"Error",description:hn.message||"Failed to convert account",variant:"destructive"})}finally{Ae(!1)}},[Py,Xm]=N.useState(!1),Jm=async(Lt,hn)=>{if(confirm(`Revert this user to a ${hn}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){Xm(!0);try{const zn=new Date,Dr=new Date(zn.getTime()+hn*24*60*60*1e3),{error:Gn}=await q.from("profiles").update({is_trial:!0,trial_started_at:zn.toISOString(),trial_expires_at:Dr.toISOString(),trial_claimed_at:zn.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",Lt);if(Gn)throw Gn;i({title:"Reverted to Trial",description:`User is now on a ${hn}-day free trial.`}),Mr()}catch(zn){console.error("Error reverting to trial:",zn),i({title:"Error",description:zn.message||"Failed to revert to trial",variant:"destructive"})}finally{Xm(!1)}}},Lp=async Lt=>{Hn(!0);try{const{data:hn}=await q.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",Lt);if(hn&&hn.length>0){const Dr=hn.map(fa=>fa.assistant_id),{data:Gn}=await q.from("profiles").select("id, name, email").in("id",Dr);nr(hn.map(fa=>{const Xa=Gn==null?void 0:Gn.find(ii=>ii.id===fa.assistant_id);return{id:fa.id,assistant_id:fa.assistant_id,assistant_name:(Xa==null?void 0:Xa.name)||"Unknown",assistant_email:(Xa==null?void 0:Xa.email)||"",permissions:fa.permissions||{}}}))}else nr([]);const{data:zn}=await q.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",Lt);if(zn&&zn.length>0){const Dr=zn.map(fa=>fa.agent_id),{data:Gn}=await q.from("profiles").select("id, name, email").in("id",Dr);fn(zn.map(fa=>{const Xa=Gn==null?void 0:Gn.find(ii=>ii.id===fa.agent_id);return{id:fa.id,agent_id:fa.agent_id,agent_name:(Xa==null?void 0:Xa.name)||"Unknown",agent_email:(Xa==null?void 0:Xa.email)||"",permissions:fa.permissions||{}}}))}else fn([])}catch(hn){console.error("Error loading assistant data:",hn)}finally{Hn(!1)}},fx=Lt=>{qe(Lt),it({name:Lt.name,email:Lt.email,brokerage_id:Lt.brokerage_id||"",phone:Lt.phone||""}),Ze(!0),Lp(Lt.id)},dg=()=>{qe(null),Ze(!1),it({name:"",email:"",brokerage_id:"",phone:""})},Vb=async()=>{Fe&&(await Bi(Fe.id),dg())},Dp=Lt=>{ot(hn=>{const zn=new Set(hn);return zn.has(Lt)?zn.delete(Lt):zn.add(Lt),zn})},ep=()=>{if(Xe.size===xu.length&&xu.every(Lt=>Xe.has(Lt.id))){const Lt=new Set(Xe);xu.forEach(hn=>Lt.delete(hn.id)),ot(Lt)}else{const Lt=new Set(Xe);xu.forEach(hn=>Lt.add(hn.id)),ot(Lt)}},Mf=()=>{ot(new Set)},Ly=async()=>{if(Xe.size===0)return;Rt(!0);let Lt=0,hn=0;try{const{data:{session:zn}}=await q.auth.getSession();for(const Dr of Xe)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${zn==null?void 0:zn.access_token}`},body:JSON.stringify({userId:Dr})})).ok?Lt++:hn++}catch{hn++}i({title:"Bulk Email Complete",description:`Sent ${Lt} emails${hn>0?`, ${hn} failed`:""}`}),Mf()}catch(zn){i({title:"Error",description:zn.message||"Failed to send emails",variant:"destructive"})}finally{Rt(!1)}},Hb=async()=>{if(Xe.size===0)return;Rt(!0);let Lt=0,hn=0;try{const{data:{session:zn}}=await q.auth.getSession();for(const Dr of Xe)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${zn==null?void 0:zn.access_token}`},body:JSON.stringify({userId:Dr})})).ok?Lt++:hn++}catch{hn++}i({title:"Bulk Password Reset Complete",description:`Sent ${Lt} reset emails${hn>0?`, ${hn} failed`:""}`}),Mf()}catch(zn){i({title:"Error",description:zn.message||"Failed to send password reset emails",variant:"destructive"})}finally{Rt(!1)}},Sd=async()=>{if(Xe.size===0)return;const Lt=l.filter(Gn=>Xe.has(Gn.id)).map(Gn=>Gn.name).slice(0,5).join(", "),hn=Xe.size>5?` and ${Xe.size-5} more`:"";if(!confirm(`Are you sure you want to delete ${Xe.size} users (${Lt}${hn})? This action cannot be undone.`))return;Rt(!0);let zn=0,Dr=0;try{const{data:{session:Gn}}=await q.auth.getSession();for(const fa of Xe)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gn==null?void 0:Gn.access_token}`},body:JSON.stringify({userId:fa})})).ok?zn++:Dr++}catch{Dr++}i({title:"Bulk Delete Complete",description:`Deleted ${zn} users${Dr>0?`, ${Dr} failed`:""}`}),Mf(),Mr()}catch(Gn){i({title:"Error",description:Gn.message||"Failed to delete users",variant:"destructive"})}finally{Rt(!1)}},zc=async()=>{xs(!0);try{const{data:{session:Lt}}=await q.auth.getSession(),hn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-phone-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Lt==null?void 0:Lt.access_token}`}});if(!hn.ok){const Dr=await hn.json();throw new Error(Dr.error||"Failed to sync phones")}const zn=await hn.json();i({title:"Phone Sync Complete",description:`Pulled ${zn.summary.pulledFromGHL} from GHL, pushed ${zn.summary.pushedToGHL} to GHL, ${zn.summary.alreadySynced} already synced`}),Mr()}catch(Lt){i({title:"Error",description:Lt.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{xs(!1)}},tp=async(Lt,hn)=>{ks(Lt);try{const{data:{session:zn}}=await q.auth.getSession(),{data:Dr}=await q.from("profiles").select("phone").eq("id",Lt).single(),Gn=(Dr==null?void 0:Dr.phone)||"",fa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${zn==null?void 0:zn.access_token}`},body:JSON.stringify({email:hn,action:"update",phone:Gn||void 0})});if(!fa.ok){const ii=await fa.json();throw new Error(ii.error||"Failed to sync with GHL")}const Xa=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent(hn)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:Gn?`Phone ${Gn} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),Mr()}catch(zn){i({title:"Error",description:zn.message||"Failed to sync phone",variant:"destructive"})}finally{ks(null)}},Zc=async Lt=>{await r(Lt)},sp=()=>{if(Xe.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const Lt=l.filter(ii=>Xe.has(ii.id)),hn=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],zn=Lt.map(ii=>[ii.name,ii.email,ii.phone||"",ii.brokerage_name||"",ii.roles.join("; "),ii.claimed?"Claimed":"Unclaimed",new Date(ii.created_at).toLocaleDateString()]),Dr=[hn.join(","),...zn.map(ii=>ii.map(zr=>`"${(zr||"").replace(/"/g,'""')}"`).join(","))].join(` `),Gn=new Blob([Dr],{type:"text/csv"}),fa=URL.createObjectURL(Gn),Xa=document.createElement("a");Xa.href=fa,Xa.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,Xa.click(),URL.revokeObjectURL(fa),i({title:"Export complete",description:`Exported ${Lt.length} member(s)`})},Rp=()=>{if(Ef.length===0){i({title:"No members to export",description:"Adjust filters to include at least one member",variant:"destructive"});return}const Lt=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],hn=Ef.map(ii=>[ii.name,ii.email,ii.phone||"",ii.brokerage_name||"",ii.roles.join("; "),ii.claimed?"Claimed":"Unclaimed",ii.created_at?new Date(ii.created_at).toLocaleDateString():""]),zn=[Lt.join(","),...hn.map(ii=>ii.map(zr=>`"${(zr||"").replace(/"/g,'""')}"`).join(","))].join(` `),Dr=new Blob([zn],{type:"text/csv"}),Gn=URL.createObjectURL(Dr),fa=document.createElement("a"),Xa=pe!=="all"?`-last-${pe}days`:"";fa.href=Gn,fa.download=`members-export${Xa}-${new Date().toISOString().split("T")[0]}.csv`,fa.click(),URL.revokeObjectURL(Gn),i({title:"Export complete",description:`Exported ${Ef.length} member(s)`})};return g?e.jsx(Ts,{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(Ts,{title:"Members",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{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($l,{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:zc,disabled:qt,children:[qt?e.jsx(ts,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ar,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:qt?"Syncing...":"Sync Phones with GHL"}),e.jsx("span",{className:"sm:hidden",children:qt?"Syncing...":"Sync GHL"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>fi(!0),children:[e.jsx(gw,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Import CSV"}),e.jsx("span",{className:"sm:hidden",children:"Import"})]}),e.jsxs(bs,{open:A,onOpenChange:T,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Fo,{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(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create New User"}),e.jsx(Qn,{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:b.name,onChange:Lt=>S({...b,name:Lt.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:b.email,onChange:Lt=>S({...b,email:Lt.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:b.password,onChange:Lt=>S({...b,password:Lt.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:b.phone,onChange:Lt=>S({...b,phone:Lt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"brokerage",children:["Brokerage",b.role==="brokerage_manager"?" (required)":""]}),e.jsxs(ds,{value:b.brokerage_id||"none",onValueChange:Lt=>S({...b,brokerage_id:Lt==="none"?"":Lt}),children:[e.jsx(ls,{id:"brokerage",children:e.jsx(us,{placeholder:b.role==="brokerage_manager"?"Select brokerage":"Select brokerage (optional)"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"None"}),u.map(Lt=>e.jsx(Qe,{value:Lt.id,children:Lt.name},Lt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"role",children:"Role"}),e.jsxs(ds,{value:b.role,onValueChange:Lt=>S({...b,role:Lt}),children:[e.jsx(ls,{id:"role",children:e.jsx(us,{placeholder:"Select role"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"user",children:"User"}),e.jsx(Qe,{value:"moderator",children:"Moderator"}),e.jsx(Qe,{value:"brokerage_manager",children:"Brokerage Manager"}),e.jsx(Qe,{value:"admin",children:"Admin"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"trial_days",children:"Trial Period (optional)"}),e.jsxs(ds,{value:b.trial_days||"none",onValueChange:Lt=>S({...b,trial_days:Lt==="none"?"":Lt}),children:[e.jsx(ls,{id:"trial_days",children:e.jsx(us,{placeholder:"No trial (full access)"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"No trial (full access)"}),e.jsx(Qe,{value:"7",children:"7-day trial"}),e.jsx(Qe,{value:"30",children:"30-day trial"}),e.jsx(Qe,{value:"60",children:"60-day trial"}),e.jsx(Qe,{value:"90",children:"90-day trial"}),e.jsx(Qe,{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(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>T(!1),children:"Cancel"}),e.jsx(B,{onClick:ga,disabled:v,children:v?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs(Br,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(Fr,{children:[e.jsx(Kt,{value:"members",children:"Members"}),e.jsx(Kt,{value:"brokerages",children:"Brokerages"}),e.jsx(Kt,{value:"teams",children:"Teams"}),e.jsx(Kt,{value:"trials",children:"Trial Users"}),e.jsx(Kt,{value:"access",children:"Access Matrix"}),e.jsx(Kt,{value:"celebrations",children:"Celebrations"}),e.jsx(Kt,{value:"deletions",children:"Deletion Log"})]}),e.jsxs(is,{value:"members",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search members...",value:L,onChange:Lt=>u0(Lt.target.value),className:"pl-10 h-9"})]}),e.jsxs(ds,{value:W,onValueChange:Lt=>Af(Y,Lt),children:[e.jsx(ls,{className:"w-[130px] h-9",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Status"}),e.jsx(Qe,{value:"claimed",children:"Active"}),e.jsx(Qe,{value:"unclaimed",children:"Pending"})]})]}),e.jsxs(ds,{value:K,onValueChange:Lt=>Af(J,Lt),children:[e.jsx(ls,{className:"w-[130px] h-9",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Roles"}),e.jsx(Qe,{value:"admin",children:"Admin"}),e.jsx(Qe,{value:"brokerage_manager",children:"Manager"}),e.jsx(Qe,{value:"assistant",children:"Assistant"}),e.jsx(Qe,{value:"user",children:"User"})]})]}),e.jsxs(ds,{value:ne,onValueChange:Lt=>Af(ie,Lt),children:[e.jsx(ls,{className:"w-[130px] h-9",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Users"}),e.jsx(Qe,{value:"trial",children:"Trial Only"}),e.jsx(Qe,{value:"non-trial",children:"Full Only"})]})]}),e.jsxs(ds,{value:he,onValueChange:Lt=>Af(ce,Lt),children:[e.jsx(ls,{className:"w-[150px] h-9",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Brokerages"}),e.jsx(Qe,{value:"none",children:"No Brokerage"}),u.map(Lt=>e.jsx(Qe,{value:Lt.id,children:Lt.name},Lt.id))]})]}),e.jsxs(ds,{value:pe,onValueChange:Lt=>Af(le,Lt),children:[e.jsx(ls,{className:"w-[150px] h-9",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"Any Join Date"}),e.jsx(Qe,{value:"30",children:"Joined Last 30 Days"}),e.jsx(Qe,{value:"60",children:"Joined Last 60 Days"}),e.jsx(Qe,{value:"90",children:"Joined Last 90 Days"})]})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"h-9",onClick:Rp,title:"Export currently filtered members to CSV",children:[e.jsx(Pa,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),(L||W!=="all"||K!=="all"||ne!=="all"||he!=="all"||pe!=="all")&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{D(""),Y("all"),J("all"),ie("all"),ce("all"),le("all"),F(1)},children:[e.jsx(Bn,{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:px?`Showing all ${Fh} members`:`Showing ${al+1}-${Math.min(d0,Fh)} of ${Fh} members`}),e.jsxs(ds,{value:z.toString(),onValueChange:Lt=>lj(Number(Lt)),children:[e.jsx(ls,{className:"h-9 w-[110px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"50",children:"50 / page"}),e.jsx(Qe,{value:"100",children:"100 / page"}),e.jsx(Qe,{value:"250",children:"250 / page"}),e.jsx(Qe,{value:"0",children:"All"})]})]})]})]}),Xe.size>0&&e.jsxs("div",{className:"flex flex-col gap-2 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[xu.length>0&&xu.every(Lt=>Xe.has(Lt.id))&&xm.length>Xe.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 ",Xe.size," on this page are selected."]}),e.jsxs(B,{size:"sm",variant:"link",className:"h-auto p-0 text-primary",onClick:()=>ot(new Set(xm.map(Lt=>Lt.id))),children:["Select all ",xm.length," filtered members"]})]}),xm.length>0&&Xe.size===xm.length&&e.jsxs("div",{className:"px-1 text-sm text-muted-foreground",children:["All ",xm.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(E2,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[Xe.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:Ly,disabled:Nt,children:[Nt?e.jsx(ts,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Vs,{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:Hb,disabled:Nt,children:[Nt?e.jsx(ts,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Vg,{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:()=>ge(!0),disabled:Nt,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(hb,{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:sp,children:[e.jsx(Pa,{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:Sd,disabled:Nt,children:[Nt?e.jsx(ts,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(_n,{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:Mf,disabled:Nt,children:e.jsx(Bn,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Ct,{className:"w-[50px]",children:e.jsx(ui,{checked:xu.length>0&&xu.every(Lt=>Xe.has(Lt.id)),onCheckedChange:ep,"aria-label":"Select all on page"})}),e.jsx(Ic,{sortKey:"name",currentSortKey:yh,currentDirection:mx,onSort:fo,children:"Name"}),e.jsx(Ic,{sortKey:"brokerage",currentSortKey:yh,currentDirection:mx,onSort:fo,children:"Brokerage"}),e.jsx(Ic,{sortKey:"status",currentSortKey:yh,currentDirection:mx,onSort:fo,children:"Status"}),e.jsx(Ic,{sortKey:"role",currentSortKey:yh,currentDirection:mx,onSort:fo,children:"Role"}),e.jsx(Ic,{sortKey:"last_login",currentSortKey:yh,currentDirection:mx,onSort:fo,children:"Last Login"}),e.jsx(Ic,{sortKey:"created_at",currentSortKey:yh,currentDirection:mx,onSort:fo,children:"Member Since"}),e.jsx(Ct,{className:"w-[100px]"})]})}),e.jsx(ha,{children:xu.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):xu.map(Lt=>e.jsxs(Hs,{className:`hover:bg-muted/30 ${Xe.has(Lt.id)?"bg-primary/5":""}`,children:[e.jsx(ut,{children:e.jsx(ui,{checked:Xe.has(Lt.id),onCheckedChange:()=>Dp(Lt.id),"aria-label":`Select ${Lt.name}`})}),e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>fx(Lt),className:"text-primary hover:underline font-medium text-left",children:Lt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Lt.email})]})}),e.jsx(ut,{className:"text-muted-foreground",children:Lt.brokerage_name||"—"}),e.jsx(ut,{children:e.jsx("div",{className:"flex flex-col",children:(()=>{const hn=Lt.trial_expires_at||Lt.subscription_end_date;if((Lt.is_trial||Lt.subscription_status==="trialing")&&hn){const Dr=Math.ceil((new Date(hn).getTime()-Date.now())/864e5),Gn=Dr<=0,fa=Dr<=3;return e.jsx(ze,{variant:"outline",className:Et("w-fit",Gn?"border-destructive text-destructive":fa?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:Gn?"Trial Expired":`Trial · ${Dr}d left`})}return e.jsx(ze,{variant:Lt.claimed?"default":"secondary",className:Lt.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:Lt.claimed?"Active":"Pending"})})()})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex flex-col",children:[Lt.roles.length>0?e.jsx("span",{className:"text-sm capitalize",children:Lt.roles[0]}):e.jsx("span",{className:"text-muted-foreground",children:"—"}),Lt.roles.includes("assistant")&&ta[Lt.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",ta[Lt.id].agent_name||ta[Lt.id].agent_email]})]})}),e.jsx(ut,{className:"text-muted-foreground",children:Lt.last_sign_in_at?new Date(Lt.last_sign_in_at).toLocaleDateString():"—"}),e.jsx(ut,{className:"text-muted-foreground",children:Lt.created_at?new Date(Lt.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"—"}),e.jsx(ut,{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(Lt),Gs(!0)},title:"Send celebration",children:e.jsx(ch,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>fx(Lt),title:"Edit member",children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>tp(Lt.id,Lt.email),disabled:rs===Lt.id,title:"Sync phone with GHL",children:rs===Lt.id?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(Ar,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Za(Lt.id),title:"Resend welcome email",children:e.jsx(Vs,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>_i(Lt.email,Lt.name),title:"Send password reset",children:e.jsx(IA,{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:()=>Zc(Lt.id),disabled:a||Lt.id===(t==null?void 0:t.id),title:Lt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Lt.name}`,children:a?e.jsx(ts,{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 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>qi(Lt.id,Lt.name),title:"Delete user",children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},Lt.id))})]})}),Wu>1&&e.jsxs("div",{className:"flex items-center justify-between px-2 py-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Page ",M," of ",Wu]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>F(1),disabled:M===1,children:"First"}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>F(Lt=>Math.max(1,Lt-1)),disabled:M===1,children:e.jsx(pl,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,Wu)},(Lt,hn)=>{let zn;return Wu<=5||M<=3?zn=hn+1:M>=Wu-2?zn=Wu-4+hn:zn=M-2+hn,e.jsx(B,{variant:M===zn?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>F(zn),children:zn},zn)})}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>F(Lt=>Math.min(Wu,Lt+1)),disabled:M===Wu,children:e.jsx(xa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>F(Wu),disabled:M===Wu,children:"Last"})]})]})]}),e.jsx(bs,{open:be,onOpenChange:Ze,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Edit Member"}),e.jsx(Qn,{children:"Update member details, roles, and app access"})]}),Fe&&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:Ne.name,onChange:Lt=>it({...Ne,name:Lt.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:Ne.email,onChange:Lt=>it({...Ne,email:Lt.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:Ne.phone,onChange:Lt=>it({...Ne,phone:Lt.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"edit-brokerage",children:"Brokerage"}),e.jsxs(ds,{value:Ne.brokerage_id||"none",onValueChange:Lt=>it({...Ne,brokerage_id:Lt==="none"?"":Lt}),children:[e.jsx(ls,{id:"edit-brokerage",children:e.jsx(us,{placeholder:"Select brokerage"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"None"}),u.map(Lt=>e.jsx(Qe,{value:Lt.id,children:Lt.name},Lt.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:[Fe.roles.map(Lt=>e.jsxs(ze,{variant:"default",className:"gap-1",children:[e.jsx(dh,{className:"h-3 w-3"}),Lt,Lt==="brokerage_manager"?e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(manage in Brokerages tab)"}):e.jsx("button",{onClick:()=>wn(Fe.id,Lt,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:e.jsx(Bn,{className:"h-3 w-3"})})]},Lt)),Fe.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(ds,{onValueChange:Lt=>wn(Fe.id,Lt,"add"),children:[e.jsx(ls,{className:"w-[200px]",children:e.jsx(us,{placeholder:"Add role..."})}),e.jsxs(cs,{children:[!Fe.roles.includes("admin")&&e.jsx(Qe,{value:"admin",children:"Admin"}),!Fe.roles.includes("user")&&e.jsx(Qe,{value:"user",children:"User"})]})]}),!Fe.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"})]}),(Sr.length>0||Ot.length>0||Fe.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(Nn,{className:"h-4 w-4"}),"Assistant Relationships"]}),sr?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ts,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):e.jsxs("div",{className:"space-y-3",children:[Sr.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:"}),Sr.map(Lt=>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:Lt.assistant_name}),e.jsx(ze,{variant:"outline",className:"text-xs",children:"Assistant"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Lt.assistant_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Lt.permissions).filter(([,hn])=>hn).map(([hn])=>e.jsx(ze,{variant:"secondary",className:"text-[10px] capitalize",children:hn},hn))})]},Lt.id))]}),Ot.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:"}),Ot.map(Lt=>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:Lt.agent_name}),e.jsx(ze,{variant:"outline",className:"text-xs",children:"Agent"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Lt.agent_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Lt.permissions).filter(([,hn])=>hn).map(([hn])=>e.jsx(ze,{variant:"secondary",className:"text-[10px] capitalize",children:hn},hn))})]},Lt.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(Lt=>{const hn=Ta(Fe.tags,Lt.required_tags),zn=`${Fe.id}-${Lt.id}`,Dr=je===zn,Gn=Lt.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:Lt.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:Lt.name}),Gn&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:Dr?e.jsx(ts,{className:"h-4 w-4 animate-spin text-muted-foreground"}):Gn?e.jsx(ze,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(bn,{checked:hn,onCheckedChange:()=>Yi(Fe.id,Lt,hn)})})]},Lt.id)})})]}),(Fe.is_trial||Fe.subscription_status==="trialing")&&e.jsxs("div",{className:"space-y-3 pt-4 border-t",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(gr,{className:"h-4 w-4"}),"Trial Status"]}),e.jsxs("div",{className:"p-4 rounded-lg border bg-amber-50 dark:bg-amber-950/20 border-amber-200 dark:border-amber-800",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[Fe.trial_expires_at&&e.jsx(qHe,{expiresAt:Fe.trial_expires_at}),!Fe.trial_expires_at&&Fe.subscription_status==="trialing"&&Fe.subscription_end_date&&e.jsx(qHe,{expiresAt:Fe.subscription_end_date})]}),(Fe.trial_expires_at||Fe.subscription_end_date)&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Expires: ",new Date(Fe.trial_expires_at||Fe.subscription_end_date).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Qa(Fe.id,7),disabled:Te,children:[e.jsx(Rg,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Qa(Fe.id,14),disabled:Te,children:[e.jsx(Rg,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Qa(Fe.id,30),disabled:Te,children:[e.jsx(Rg,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs(B,{size:"sm",variant:"default",onClick:()=>Iy(Fe.id),disabled:Ce,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(bb,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),Fe.trial_started_at&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(Fe.trial_started_at).toLocaleDateString(),Fe.trial_claimed_at&&e.jsxs("span",{children:[" • Claimed: ",new Date(Fe.trial_claimed_at).toLocaleDateString()]})]})]})]}),!(Fe.is_trial||Fe.subscription_status==="trialing")&&e.jsxs("div",{className:"space-y-3 pt-4 border-t",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(gr,{className:"h-4 w-4"}),"Revert to Free Trial"]}),e.jsxs("div",{className:"p-4 rounded-lg border bg-blue-50 dark:bg-blue-950/20 border-blue-200 dark:border-blue-800",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Move this user back to a free trial. Clears paid/grandfathered status. If they have an active Stripe subscription, cancel it separately in Stripe."}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[7,14,30,60,90].map(Lt=>e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Jm(Fe.id,Lt),disabled:Py,children:[e.jsx(Rg,{className:"h-4 w-4 mr-1"}),Lt,"-day trial"]},Lt))})]})]}),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:[Fe.email_confirmed_at&&e.jsxs("div",{children:["Claimed: ",new Date(Fe.email_confirmed_at).toLocaleString()]}),Fe.last_sign_in_at&&e.jsxs("div",{children:["Last login: ",new Date(Fe.last_sign_in_at).toLocaleString()]}),e.jsxs("div",{children:["Created: ",new Date(Fe.created_at).toLocaleString()]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:dg,children:"Cancel"}),e.jsx(B,{onClick:Vb,children:"Save Changes"})]})]})}),e.jsxs(is,{value:"access",children:[c.length===0?e.jsx(fe,{children:e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Member Access Matrix"}),e.jsx(Vn,{children:"Toggle switches to grant or revoke app access for each member"})]}),e.jsxs("div",{className:"relative w-full sm:w-72",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents by name or email...",value:L,onChange:Lt=>{D(Lt.target.value),F(1)},className:"pl-9"})]})]}),e.jsxs(Ee,{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(Lt=>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:Lt.icon}),e.jsx("span",{className:"text-sm",children:Lt.name})]})},Lt.id))]})}),e.jsxs("tbody",{children:[xu.map(Lt=>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:Lt.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Lt.email})]})}),c.map(hn=>{const zn=Ta(Lt.tags,hn.required_tags),Dr=`${Lt.id}-${hn.id}`,Gn=je===Dr;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:Gn?e.jsx(ts,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(bn,{checked:zn,onCheckedChange:()=>Yi(Lt.id,hn,zn),disabled:hn.required_tags.length===0})})},hn.id)})]},Lt.id)),xu.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"})})]})]})}),Wu>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 ",al+1,"-",Math.min(d0,Fh)," of ",Fh," • Page ",M," of ",Wu]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>F(Lt=>Math.max(1,Lt-1)),disabled:M===1,children:e.jsx(pl,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>F(Lt=>Math.min(Wu,Lt+1)),disabled:M===Wu,children:e.jsx(xa,{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(is,{value:"brokerages",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search brokerages...",value:Lr,onChange:Lt=>Jn(Lt.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[u.filter(Lt=>Lt.name.toLowerCase().includes(Lr.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 Lt=[];for(const Xa of u){const ii=p[Xa.id]??[];for(const zr of ii){const Cd=l.find(gm=>gm.id===zr);if(Cd){const gm=(Cd.name||"").trim().split(/\s+/),Ku=gm[0]||"",ug=gm.slice(1).join(" ")||"";Lt.push({firstName:Ku,lastName:ug,email:Cd.email,brokerageName:Xa.name})}}}if(Lt.length===0){i({title:"No managers found to export"});return}const zn=[["First Name","Last Name","Email","Brokerage Name"].join(","),...Lt.map(Xa=>[Xa.firstName,Xa.lastName,Xa.email,Xa.brokerageName].map(ii=>`"${(ii||"").replace(/"/g,'""')}"`).join(","))].join(` `),Dr=new Blob([zn],{type:"text/csv"}),Gn=URL.createObjectURL(Dr),fa=document.createElement("a");fa.href=Gn,fa.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,fa.click(),URL.revokeObjectURL(Gn),i({title:`Exported ${Lt.length} managers`})},children:[e.jsx(Pa,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(bs,{open:Be,onOpenChange:Ye,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Va,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create New Brokerage"}),e.jsx(Qn,{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:We,onChange:Lt=>rt(Lt.target.value),maxLength:100})]})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Ye(!1),children:"Cancel"}),e.jsx(B,{onClick:zo,disabled:tt,children:tt?"Creating...":"Create Brokerage"})]})]})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Ct,{className:"font-semibold",children:"Brokerage Name"}),e.jsx(Ct,{className:"font-semibold",children:"Manager(s)"}),e.jsx(Ct,{className:"font-semibold",children:"Agents"}),e.jsx(Ct,{className:"w-[150px]"})]})}),e.jsx(ha,{children:(()=>{const Lt=u.filter(hn=>hn.name.toLowerCase().includes(Lr.toLowerCase()));return Lt.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:Lr?"No brokerages match your search":"No brokerages found"})}):Lt.map(hn=>{const zn=l.filter(Xa=>Xa.brokerage_id===hn.id),Gn=(p[hn.id]??[]).map(Xa=>l.find(ii=>ii.id===Xa)).filter(Boolean),fa=zn.length;return e.jsxs(Hs,{className:"hover:bg-muted/30",children:[e.jsx(ut,{children:e.jsx("button",{onClick:()=>rl(hn),className:"text-primary hover:underline font-medium",children:hn.name})}),e.jsx(ut,{children:Gn.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:Gn.map(Xa=>e.jsx(ze,{variant:"secondary",className:"text-xs",children:Xa.name},Xa.id))}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),e.jsxs(ut,{children:[fa," member",fa!==1?"s":""]}),e.jsx(ut,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"h-8",onClick:()=>pm(hn),children:[e.jsx(Nn,{className:"h-4 w-4 mr-1"}),"Manage"]}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>rl(hn),title:"Edit brokerage",children:e.jsx(_a,{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:()=>Tf(hn),title:"Delete brokerage",children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},hn.id)})})()})]})}),e.jsx(bs,{open:He,onOpenChange:dt,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Edit Brokerage"}),e.jsx(Qn,{children:"Update brokerage details and manage managers"})]}),bt&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),e.jsx(ye,{id:"edit-brokerage-name",value:Bt,onChange:Lt=>Zt(Lt.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 hn=(p[bt.id]??[]).map(zn=>l.find(Dr=>Dr.id===zn)).filter(Boolean);return hn.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):hn.map(zn=>e.jsxs(ze,{variant:"default",className:"gap-1",children:[e.jsx(dh,{className:"h-3 w-3"}),zn.name,e.jsx("button",{onClick:()=>wn(zn.id,"brokerage_manager","remove",bt.id),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager from this brokerage",children:e.jsx(Bn,{className:"h-3 w-3"})})]},zn.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(el,{open:js,onOpenChange:Dn,children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":js,className:"w-full justify-between",children:["Search for a member...",e.jsx(vr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ho,{className:"w-full p-0",align:"start",children:e.jsxs(Qg,{children:[e.jsx(Xg,{placeholder:"Search by name or email..."}),e.jsxs(Jg,{className:"max-h-[200px]",children:[e.jsx(e0,{children:"No members found."}),e.jsx(t0,{children:(()=>{const Lt=new Set(p[bt.id]??[]);return l.filter(hn=>!Lt.has(hn.id)&&(n||hn.brokerage_id===bt.id)).map(hn=>e.jsxs(Jf,{value:`${hn.name} ${hn.email}`,onSelect:()=>{hc(hn.id,bt.id),Dn(!1)},children:[hn.name," (",hn.email,")"]},hn.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(Lt=>Lt.brokerage_id===bt.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter(Lt=>Lt.brokerage_id===bt.id).map(Lt=>e.jsxs("div",{className:"text-sm py-1 flex items-center justify-between",children:[e.jsx("span",{children:Lt.name}),Lt.roles.includes("brokerage_manager")&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"Manager"})]},Lt.id))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:po,children:"Cancel"}),e.jsx(B,{onClick:uc,disabled:Fs,children:Fs?"Saving...":"Save Changes"})]})]})}),e.jsx(bs,{open:ms,onOpenChange:Pt,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(Qn,{children:['Are you sure you want to delete "',Jt==null?void 0:Jt.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 "',Jt==null?void 0:Jt.name,'"']}),e.jsxs("li",{children:["All ",l.filter(Lt=>Lt.brokerage_id===(Jt==null?void 0:Jt.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Pt(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Hu,disabled:Vt,children:Vt?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(bs,{open:Xt,onOpenChange:Js,children:e.jsxs(vs,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Va,{className:"h-5 w-5"}),"Manage ",Cs==null?void 0:Cs.name]}),e.jsx(Qn,{children:"Add, remove, or manage users in this brokerage"})]}),Cs&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search members...",value:rn,onChange:Lt=>tn(Lt.target.value),className:"pl-10 h-9"})]}),e.jsxs(bs,{open:er,onOpenChange:gn,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Fo,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Add New Agent"}),e.jsxs(Qn,{children:["Create a new agent for ",Cs.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:In.name,onChange:Lt=>Zn({...In,name:Lt.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:In.email,onChange:Lt=>Zn({...In,email:Lt.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:In.password,onChange:Lt=>Zn({...In,password:Lt.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:In.phone,onChange:Lt=>Zn({...In,phone:Lt.target.value})})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>gn(!1),children:"Cancel"}),e.jsx(B,{onClick:oj,disabled:ea,children:ea?"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(el,{open:wr,onOpenChange:$r,children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":wr,className:"w-[300px] justify-between",children:["Select a user to add...",e.jsx(vr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ho,{className:"w-[300px] p-0",align:"start",children:e.jsxs(Qg,{children:[e.jsx(Xg,{placeholder:"Search users...",value:ss,onValueChange:Oe}),e.jsxs(Jg,{children:[e.jsx(e0,{children:"No users found."}),e.jsx(t0,{children:My(Cs.id).filter(Lt=>ss===""||Lt.name.toLowerCase().includes(ss.toLowerCase())||Lt.email.toLowerCase().includes(ss.toLowerCase())).map(Lt=>e.jsxs(Jf,{value:`${Lt.name} ${Lt.email}`,onSelect:()=>{a1(Lt.id,Cs.id),$r(!1),Oe("")},children:[Lt.name," (",Lt.email,")"]},Lt.id))})]})]})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Ct,{className:"font-semibold",children:"Name"}),e.jsx(Ct,{className:"font-semibold",children:"Email"}),e.jsx(Ct,{className:"font-semibold",children:"Status"}),e.jsx(Ct,{className:"font-semibold",children:"Role"}),e.jsx(Ct,{className:"w-[120px]"})]})}),e.jsx(ha,{children:Ay(Cs.id).length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:rn?"No matching members found":"No members in this brokerage"})}):Ay(Cs.id).map(Lt=>e.jsxs(Hs,{className:"hover:bg-muted/30",children:[e.jsx(ut,{className:"font-medium",children:Lt.name}),e.jsx(ut,{className:"text-muted-foreground",children:Lt.email}),e.jsx(ut,{children:Lt.claimed?e.jsx(ze,{variant:"default",className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active"}):e.jsx(ze,{variant:"secondary",children:"Pending"})}),e.jsx(ut,{children:Lt.roles.includes("brokerage_manager")?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(dh,{className:"h-3 w-3"}),"Manager"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Agent"})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[!Lt.claimed&&e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Za(Lt.id),title:"Resend welcome email",children:e.jsx(Vs,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>qd(Lt.id),title:"Remove from brokerage",children:e.jsx(Bn,{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:()=>Zc(Lt.id),disabled:a||Lt.id===(t==null?void 0:t.id),title:Lt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Lt.name}`,children:a?e.jsx(ts,{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 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>qi(Lt.id,Lt.name),title:"Delete user",children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},Lt.id))})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[fm(Cs.id).length," total member",fm(Cs.id).length!==1?"s":""," •",fm(Cs.id).filter(Lt=>Lt.roles.includes("brokerage_manager")).length," manager",fm(Cs.id).filter(Lt=>Lt.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(Xn,{children:e.jsx(B,{variant:"outline",onClick:Gu,children:"Close"})})]})})]}),e.jsx(is,{value:"teams",children:e.jsx(Zbs,{})}),e.jsx(is,{value:"trials",children:e.jsx(Hbs,{})}),e.jsx(is,{value:"celebrations",children:e.jsx(Vbs,{})}),e.jsx(is,{value:"deletions",children:e.jsx(Wbs,{})})]})]}),e.jsx(eyt,{open:Ls,onOpenChange:fi,brokerages:u,onSuccess:Mr}),Un&&e.jsx(tyt,{open:ln,onOpenChange:Lt=>{Gs(Lt),Lt||jr(null)},userId:Un.id,userName:Un.name}),e.jsx(Qbs,{open:ve,onOpenChange:ge,recipients:l.filter(Lt=>Xe.has(Lt.id)).map(Lt=>({id:Lt.id,name:Lt.name,email:Lt.email}))})]})};function Jbs(){const{toast:s}=Ba(),t=Ht(),[n,r]=N.useState(""),[a,i]=N.useState(new Set),[l,o]=N.useState({}),[c,d]=N.useState({}),[u,h]=N.useState(""),[p,f]=N.useState(!1),{data:g=[],isLoading:_}=ct({queryKey:["unassigned-members"],queryFn:async()=>{const{data:M,error:F}=await q.from("profiles").select("id, name, email, phone, created_at, subscription_status").is("brokerage_id",null).or("subscription_status.is.null,subscription_status.eq.none").order("created_at",{ascending:!1});if(F)throw F;return M||[]}}),{data:v=[]}=ct({queryKey:["brokerages-all"],queryFn:async()=>{const{data:M,error:F}=await q.from("brokerages").select("id, name").order("name");if(F)throw F;return M||[]}}),j=N.useMemo(()=>{const M=n.toLowerCase().trim();return M?g.filter(F=>(F.name||"").toLowerCase().includes(M)||(F.email||"").toLowerCase().includes(M)||(F.phone||"").toLowerCase().includes(M)):g},[g,n]),b=N.useMemo(()=>{var F;const M=new Map;for(const z of g){const V=(F=(z.email||"").split("@")[1])==null?void 0:F.toLowerCase();V&&(["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","aol.com","me.com","comcast.net"].includes(V)||M.set(V,(M.get(V)||0)+1))}return Array.from(M.entries()).sort((z,V)=>V[1]-z[1]).slice(0,10)},[g]),S=M=>{i(F=>{const z=new Set(F);return z.has(M)?z.delete(M):z.add(M),z})},A=()=>{a.size===j.length?i(new Set):i(new Set(j.map(M=>M.id)))},T=async(M,F)=>{if(F){d(z=>({...z,[M]:!0}));try{const{data:z,error:V}=await q.functions.invoke("assign-brokerage",{body:{userId:M,brokerageId:F}});if(V)throw V;if(z!=null&&z.error)throw new Error(z.error);s({title:"Assigned",description:"Member added to brokerage."}),t.invalidateQueries({queryKey:["unassigned-members"]}),i(W=>{const Y=new Set(W);return Y.delete(M),Y})}catch(z){s({title:"Failed",description:z.message,variant:"destructive"})}finally{d(z=>({...z,[M]:!1}))}}},L=async()=>{if(!u||a.size===0)return;f(!0);let M=0,F=0;for(const z of a)try{const{data:V,error:W}=await q.functions.invoke("assign-brokerage",{body:{userId:z,brokerageId:u}});if(W||V!=null&&V.error)throw new Error((W==null?void 0:W.message)||V.error);M++}catch{F++}f(!1),s({title:`Assigned ${M}${F?`, ${F} failed`:""}`,description:"Bulk assignment complete.",variant:F?"destructive":"default"}),i(new Set),h(""),t.invalidateQueries({queryKey:["unassigned-members"]})},D=(M,F)=>{const z={...l};for(const V of g)(V.email||"").toLowerCase().endsWith(`@${M}`)&&(z[V.id]=F);o(z),s({title:"Suggestions applied",description:`Pre-filled brokerage for @${M}`})};return e.jsx(Ts,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{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(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(It,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"})," Orphan members"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-3xl font-bold",children:g.length})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(It,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Va,{className:"h-4 w-4"})," Selected"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-3xl font-bold",children:a.size})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(It,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4"})," Top email domains"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-3xl font-bold",children:b.length})})]})]}),b.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Domain suggestions"})}),e.jsx(Ee,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:b.map(([M,F])=>{const z=v.find(V=>V.name.toLowerCase().replace(/[^a-z0-9]/g,"").includes(M.split(".")[0].toLowerCase()));return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border bg-muted/30 px-3 py-2",children:[e.jsxs("span",{className:"font-mono text-sm",children:["@",M]}),e.jsx(ze,{variant:"secondary",children:F}),e.jsxs(ds,{onValueChange:V=>D(M,V),defaultValue:z==null?void 0:z.id,children:[e.jsx(ls,{className:"h-8 w-[220px]",children:e.jsx(us,{placeholder:"Apply brokerage…"})}),e.jsx(cs,{children:v.map(V=>e.jsx(Qe,{value:V.id,children:V.name},V.id))})]})]},M)})})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{className:"relative w-full md:w-96",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:n,onChange:M=>r(M.target.value),placeholder:"Search name, email, phone…",className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ds,{value:u,onValueChange:h,children:[e.jsx(ls,{className:"w-[240px]",children:e.jsx(us,{placeholder:"Bulk assign to brokerage…"})}),e.jsx(cs,{children:v.map(M=>e.jsx(Qe,{value:M.id,children:M.name},M.id))})]}),e.jsxs(B,{onClick:L,disabled:!u||a.size===0||p,children:[p&&e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Assign ",a.size||""]})]})]}),e.jsx(Ee,{children:_?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):j.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(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{className:"w-10",children:e.jsx(ui,{checked:a.size===j.length&&j.length>0,onCheckedChange:A})}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Signed up"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Assign to brokerage"}),e.jsx(Ct,{className:"w-24"})]})}),e.jsx(ha,{children:j.map(M=>{const F=l[M.id]||"";return e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsx(ui,{checked:a.has(M.id),onCheckedChange:()=>S(M.id)})}),e.jsx(ut,{className:"font-medium",children:M.name||"—"}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:M.email}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:Vo(new Date(M.created_at),{addSuffix:!0})}),e.jsx(ut,{children:e.jsx(ze,{variant:"outline",children:M.subscription_status||"none"})}),e.jsx(ut,{children:e.jsxs(ds,{value:F,onValueChange:z=>o(V=>({...V,[M.id]:z})),children:[e.jsx(ls,{className:"h-9 w-[240px]",children:e.jsx(us,{placeholder:"Pick brokerage…"})}),e.jsx(cs,{children:v.map(z=>e.jsx(Qe,{value:z.id,children:z.name},z.id))})]})}),e.jsx(ut,{children:e.jsx(B,{size:"sm",disabled:!F||c[M.id],onClick:()=>T(M.id,F),children:c[M.id]?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):"Assign"})})]},M.id)})})]})})})]})]})})}const e_s=()=>{const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState("");N.useEffect(()=>{g()},[]);const g=async()=>{const{data:T,error:L}=await q.from("invite_codes").select("*").order("created_at",{ascending:!1});L?(ae.error("Failed to load invite codes"),console.error(L)):t(T||[]),r(!1)},_=async T=>{if(T.preventDefault(),!l.trim()){ae.error("Please enter a code");return}i(!0);const{error:L}=await q.from("invite_codes").insert({code:l.trim().toUpperCase(),description:c.trim()||null,max_uses:u?parseInt(u):null,trial_days:p?parseInt(p):null});L?L.code==="23505"?ae.error("This code already exists"):(ae.error("Failed to create invite code"),console.error(L)):(ae.success("Invite code created"),o(""),d(""),h(""),f(""),g()),i(!1)},v=async(T,L)=>{const{error:D}=await q.from("invite_codes").update({is_active:!L}).eq("id",T);D?ae.error("Failed to update code"):t(s.map(M=>M.id===T?{...M,is_active:!L}:M))},j=async T=>{const{error:L}=await q.from("invite_codes").delete().eq("id",T);L?ae.error("Failed to delete code"):(ae.success("Code deleted"),t(s.filter(D=>D.id!==T)))},b="https://dashboard.relevelup.com",S=T=>{const L=`${b}/join?code=${T}`;navigator.clipboard.writeText(L),ae.success("Link copied to clipboard")},A=`${b}/join`;return e.jsx(Ts,{title:"Invite Codes",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{title:"Invite Codes",description:"Manage signup invite codes"}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Create New Code"}),e.jsxs(Vn,{children:["Share link: ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:A})]})]}),e.jsx(Ee,{children:e.jsxs("form",{onSubmit:_,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:p,onChange:T=>f(T.target.value),className:"w-28"})]}),e.jsxs(B,{type:"submit",disabled:a,children:[a?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"Active Codes"})}),e.jsx(Ee,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ts,{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(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Code"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{children:"Uses"}),e.jsx(Ct,{children:"Trial"}),e.jsx(Ct,{children:"Created"}),e.jsx(Ct,{children:"Active"}),e.jsx(Ct,{className:"w-24",children:"Actions"})]})}),e.jsx(ha,{children:s.map(T=>e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-mono font-medium",children:T.code}),e.jsx(ut,{className:"text-muted-foreground",children:T.description||"—"}),e.jsxs(ut,{children:[T.uses_count,T.max_uses&&` / ${T.max_uses}`]}),e.jsx(ut,{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(ut,{className:"text-muted-foreground",children:Ss(new Date(T.created_at),"MMM d, yyyy")}),e.jsx(ut,{children:e.jsx(bn,{checked:T.is_active,onCheckedChange:()=>v(T.id,T.is_active)})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>S(T.code),title:"Copy invite link",children:e.jsx(Xr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>j(T.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},T.id))})]})})]})]})})},z2=q;function ogn(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 t_s(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").slice(0,70)}function lgn(s,t){const n=`${window.location.origin}/live/${s}`;return t?`${n}?i=${t}`:n}function cgn(){const s=Ht(),t=ct({queryKey:["live-events"],queryFn:async()=>{const{data:i,error:l}=await z2.from("live_events").select("*").order("starts_at",{ascending:!1});if(l)throw l;return i||[]}}),n=gt({mutationFn:async i=>{var d;const{data:l}=await q.auth.getUser(),{data:o,error:c}=await z2.from("live_events").insert({...i,created_by:(d=l.user)==null?void 0:d.id}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),ae.success("Live event created")},onError:i=>ae.error((i==null?void 0:i.message)||"Could not create event")}),r=gt({mutationFn:async({id:i,...l})=>{const{error:o}=await z2.from("live_events").update(l).eq("id",i);if(o)throw o},onSuccess:(i,l)=>{s.invalidateQueries({queryKey:["live-events"]}),s.invalidateQueries({queryKey:["live-event",l.id]}),ae.success("Saved")},onError:i=>ae.error((i==null?void 0:i.message)||"Could not save")}),a=gt({mutationFn:async i=>{const{error:l}=await z2.from("live_events").delete().eq("id",i);if(l)throw l},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),ae.success("Event deleted")},onError:i=>ae.error((i==null?void 0:i.message)||"Could not delete")});return{list:t,create:n,update:r,remove:a}}function dgn(s){return ct({queryKey:["live-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await z2.from("live_events").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}function ugn(s){return ct({queryKey:["live-registrations",s],enabled:!!s,refetchInterval:2e4,queryFn:async()=>{const{data:t,error:n}=await z2.from("live_registrations").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function hgn(s){const t=Ht(),n=ct({queryKey:["live-invites",s],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await z2.from("live_invites").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(l)throw l;return i||[]}}),r=gt({mutationFn:async i=>{const{data:l}=await q.auth.getUser(),o=i.map(u=>{var h;return{event_id:s,code:crypto.randomUUID().replace(/-/g,"").slice(0,12),name:u.name||null,email:u.email||null,phone:u.phone||null,brokerage:u.brokerage||null,created_by:(h=l.user)==null?void 0:h.id}}),{data:c,error:d}=await z2.from("live_invites").insert(o).select();if(d)throw d;return c||[]},onSuccess:i=>{t.invalidateQueries({queryKey:["live-invites",s]}),ae.success(`${i.length} invite link${i.length===1?"":"s"} created`)},onError:i=>ae.error((i==null?void 0:i.message)||"Could not create invites")}),a=gt({mutationFn:async i=>{const{error:l}=await z2.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 SU=async s=>{try{const{data:t,error:n}=await q.from("push_notification_settings").select("is_enabled").eq("setting_key",s).maybeSingle();return n?(console.error("Error checking notification setting:",n),!0):(t==null?void 0:t.is_enabled)??!0}catch(t){return console.error("Error checking notification setting:",t),!0}},eR=async s=>{try{const{data:t,error:n}=await q.functions.invoke("send-push-notification",{body:s});return n?(console.error("Error sending notification:",n),{success:!1,error:n}):(console.log("Notification sent:",t),{success:!0,data:t})}catch(t){return console.error("Error sending notification:",t),{success:!1,error:t}}},s_s=async(s,t)=>await SU("new_templates")?eR({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}),n_s=async(s,t)=>eR({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),r_s=async(s,t)=>await SU("new_events")?eR({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),a_s=async(s,t)=>await SU("new_toolbox")?eR({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),y3e=async(s,t)=>await SU("new_social_swag")?eR({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}),i_s=async(s,t)=>await SU("new_newsletters")?eR({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),B2e=400;function o_s(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 l_s(){const s=[];let t=0;const n=1e3;for(;;){const{data:r,error:a}=await q.from("profiles").select("id, name, email, event_invite_opt_out").not("email","is",null).neq("email","").eq("event_invite_opt_out",!1).order("created_at",{ascending:!1}).range(t,t+n-1);if(a)throw a;if(!r||r.length===0)break;for(const i of r)i.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i.email)&&s.push({id:i.id,name:i.name||"",email:i.email});if(r.length{if(!s||!n)return;let ne=!1;return(async()=>{h(!0);try{const[ie,he,ce]=await Promise.all([l_s(),HHe("event_registrations",n.id),HHe("event_attendees",n.id)]);if(ne)return;f(ie),_(he),j(ce)}catch(ie){ne||r({title:"Could not load audience",description:ie instanceof Error?ie.message:"Unknown error",variant:"destructive"})}finally{ne||h(!1)}})(),()=>{ne=!0}},[s,n,r]),N.useEffect(()=>{s||(T(null),d(""),o(""),i("not_registered"))},[s]);const z=N.useMemo(()=>a==="all"?p:a==="not_registered"?p.filter(ne=>!g.has(ne.id)):p.filter(ne=>g.has(ne.id)&&!v.has(ne.id)),[a,p,g,v]),V={all:p.length,not_registered:p.filter(ne=>!g.has(ne.id)).length,registered_never_attended:p.filter(ne=>g.has(ne.id)&&!v.has(ne.id)).length},W=async ne=>{const{data:{session:ie}}=await q.auth.getSession(),he=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ie==null?void 0:ie.access_token}`},body:JSON.stringify({event_id:n.id,recipients:ne.map(pe=>({email:pe.email,name:pe.name,user_id:pe.id})),custom_subject:l.trim()||void 0,custom_intro:c.trim()||void 0})}),ce=await he.json().catch(()=>({}));if(!he.ok)throw new Error((ce==null?void 0:ce.error)||`HTTP ${he.status}`);return{sent:(ce==null?void 0:ce.sent)??0,failed:(ce==null?void 0:ce.failed)??0}},Y=async()=>{var ne;if(n){F(!0);try{const{data:{session:ie}}=await q.auth.getSession(),he=ie==null?void 0:ie.user;if(!(he!=null&&he.email))throw new Error("No signed-in email found");const ce=await W([{id:he.id,name:((ne=he.user_metadata)==null?void 0:ne.name)||"",email:he.email}]);r({title:"Test sent",description:`Sent to ${he.email} · Sent: ${ce.sent} · Failed: ${ce.failed}`})}catch(ie){r({title:"Test failed",description:ie instanceof Error?ie.message:"Unknown error",variant:"destructive"})}finally{F(!1)}}},K=async()=>{if(!(!n||z.length===0)){D(!1),S(!0),T({done:0,total:z.length,sent:0,failed:0});try{let ne=0,ie=0;for(let he=0;he!b&&t(ne),children:e.jsxs(vs,{className:"max-w-2xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Invite Members to Event"]}),e.jsx(Qn,{children:n?e.jsxs("span",{className:"flex items-center gap-2 text-sm",children:[e.jsx(om,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:n.title}),e.jsx("span",{children:"·"}),e.jsx("span",{children:o_s(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(Nn,{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(ts,{className:"h-4 w-4 animate-spin"})," Loading members..."]}):e.jsxs(cb,{value:a,onValueChange:ne=>i(ne),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(Rd,{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:V.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(Rd,{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:V.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(Rd,{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:V.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:ne=>o(ne.target.value),disabled:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank for the default."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"ev-inv-intro",children:"Personal message (optional)"}),e.jsx(Es,{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:ne=>d(ne.target.value),rows:4,disabled:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Appears at the top of the email above the event details."})]}),A&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Sending ",A.done.toLocaleString()," / ",A.total.toLocaleString()]}),e.jsxs("span",{className:"font-medium",children:["✓ ",A.sent.toLocaleString(),A.failed>0&&e.jsxs("span",{className:"text-destructive",children:[" · ✗ ",A.failed.toLocaleString()]})]})]}),e.jsx(pi,{value:J})]})]}),e.jsxs(Xn,{className:"gap-2 sm:gap-2",children:[e.jsx(B,{variant:"outline",onClick:Y,disabled:b||M||u,children:M?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"})," Sending test..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"})," Send test to me"]})}),e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsx(B,{onClick:()=>D(!0),disabled:b||u||z.length===0,children:b?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-2"})," Send to ",z.length.toLocaleString()]})})]})]})}),e.jsx(Oo,{open:L,onOpenChange:D,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Send event invite?"}),e.jsxs(Mo,{children:["This will send a branded invite to"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[z.length.toLocaleString()," member",z.length===1?"":"s"]})," ","for"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:['"',n==null?void 0:n.title,'"']}),". This can't be undone."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsxs(jo,{onClick:K,children:[e.jsx(cr,{className:"h-4 w-4 mr-2"})," Send now"]})]})]})})]})}const WH={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 d_s(){const s=Mn(),t=Ht(),[n,r]=N.useState(!1),[a,i]=N.useState(null),[l,o]=N.useState(WH),[c,d]=N.useState(null),[u,h]=N.useState(null),[p,f]=N.useState(!1),g=N.useRef(null),[_,v]=N.useState(!1),[j,b]=N.useState(null),[S,A]=N.useState(!1),[T,L]=N.useState(null),[D,M]=N.useState(null),[F,z]=N.useState(!0),[V,W]=N.useState(""),[Y,K]=N.useState(!1),[J,ne]=N.useState(null),{data:ie,isLoading:he}=ct({queryKey:["admin-events"],queryFn:async()=>{const{data:He,error:dt}=await q.from("events").select("*").order("event_date",{ascending:!0});if(dt)throw dt;return He}}),{data:ce}=ct({queryKey:["event-registrations-count"],queryFn:async()=>{let He=[],dt=0;const bt=1e3;for(;;){const{data:Bt,error:Zt}=await q.from("event_registrations").select("event_id").range(dt,dt+bt-1);if(Zt)throw Zt;if(!Bt||Bt.length===0||(He=He.concat(Bt),Bt.length{vt[Bt.event_id]=(vt[Bt.event_id]||0)+1}),vt}}),{data:pe,isLoading:le}=ct({queryKey:["event-registrations-details",j==null?void 0:j.id],queryFn:async()=>{if(!j)return[];const{data:He,error:dt}=await q.from("event_registrations").select("id, user_id, registered_at, zoom_join_url, zoom_name, zoom_email").eq("event_id",j.id).order("registered_at",{ascending:!1});if(dt)throw dt;if(!He||He.length===0)return[];const bt=He.map(Zt=>Zt.user_id).filter(Boolean);let vt=[];if(bt.length>0){const{data:Zt,error:Fs}=await q.from("profiles").select("id, name, email").in("id",bt);if(Fs)throw Fs;vt=Zt||[]}const Bt=new Map((vt==null?void 0:vt.map(Zt=>[Zt.id,Zt]))||[]);return He.map(Zt=>({...Zt,profiles:Zt.user_id&&Bt.get(Zt.user_id)||null}))},enabled:!!j}),{data:ve,isLoading:ge}=ct({queryKey:["event-attendees-details",j==null?void 0:j.id],queryFn:async()=>{if(!j)return[];const{data:He,error:dt}=await q.from("event_attendees").select("id, user_id, zoom_email, zoom_name, join_time, leave_time, duration_minutes, manually_added, created_at").eq("event_id",j.id).order("created_at",{ascending:!1});if(dt)throw dt;if(!He||He.length===0)return[];const bt=He.map(Rs=>Rs.user_id).filter(Boolean);let vt=[];if(bt.length>0){const{data:Rs,error:ms}=await q.from("profiles").select("id, name, email").in("id",bt);if(ms)throw ms;vt=Rs||[]}const{data:Bt}=await q.from("agent_points").select("user_id").eq("event_id",j.id),Zt=new Set((Bt==null?void 0:Bt.map(Rs=>Rs.user_id))||[]),Fs=new Map((vt==null?void 0:vt.map(Rs=>[Rs.id,Rs]))||[]);return He.map(Rs=>({...Rs,profiles:Rs.user_id&&Fs.get(Rs.user_id)||null,points_awarded:Rs.user_id?Zt.has(Rs.user_id):!1}))},enabled:!!j}),Te=He=>{b(He),v(!0)},Me=gt({mutationFn:async He=>{const{data:{session:dt}}=await q.auth.getSession();if(!dt)throw new Error("Not authenticated");const bt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-registrations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${dt.access_token}`},body:JSON.stringify({event_id:He})}),vt=await bt.json();if(!bt.ok){const Bt=new Error(vt.error||"Failed to sync");throw Bt.scopeError=!!vt.scope_error,Bt.details=vt.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,Bt}return vt},onSuccess:He=>{if(t.invalidateQueries({queryKey:["event-registrations-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),He!=null&&He.scope_error||(He==null?void 0:He.success)===!1){ae.error("Zoom needs one more authorization step",{description:He!=null&&He.scope_error?"The app is working, but Zoom is still issuing a token without meeting:read:list_registrants:admin. Make that scope required, not Optional, then Continue/Activate/Save in Zoom and retry. If it still shows 7 scopes, update the saved Zoom credentials to the app you edited.":(He==null?void 0:He.message)||"Zoom registration sync could not complete.",duration:2e4});return}ae.success(He.message)},onError:He=>{ae.error("Failed to sync Zoom registrations",{description:He.scopeError&&He.details||He.message,duration:He.scopeError?2e4:5e3})}}),Ce=gt({mutationFn:async He=>{const{data:{session:dt}}=await q.auth.getSession();if(!dt)throw new Error("Not authenticated");const bt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-attendees",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${dt.access_token}`},body:JSON.stringify({event_id:He})}),vt=await bt.json();if(!bt.ok)throw new Error(vt.error||"Failed to sync attendees");return vt},onSuccess:He=>{if(t.invalidateQueries({queryKey:["event-attendees-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),He!=null&&He.scope_error||(He==null?void 0:He.success)===!1){ae.error((He==null?void 0:He.message)||"Zoom sync failed",{description:He!=null&&He.scope_error?"Zoom must be re-authorized after adding the missing report scope.":void 0,duration:15e3});return}He!=null&&He.message?ae.success(He.message):ae.success(`Synced ${He.synced||0} attendees. ${He.points_awarded||0} points awarded!`)},onError:He=>{ae.error("Failed to sync attendees: "+He.message)}}),Ae=gt({mutationFn:async()=>{const{data:He,error:dt}=await q.functions.invoke("zoom-retry-registrations",{body:{}});if(dt)throw dt;return He},onSuccess:He=>{t.invalidateQueries({queryKey:["event-registrations-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),ae.success(`Retry complete: ${(He==null?void 0:He.successCount)??0} fixed, ${(He==null?void 0:He.failCount)??0} still failing, ${(He==null?void 0:He.rateLimitedCount)??0} rate-limited`)},onError:He=>{ae.error("Retry failed: "+He.message)}}),De=gt({mutationFn:async({eventId:He,testMode:dt})=>{const{data:{session:bt}}=await q.auth.getSession();if(!bt)throw new Error("Not authenticated");const vt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-event-reminder",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${bt.access_token}`},body:JSON.stringify({event_id:He,test_mode:dt})}),Bt=await vt.json();if(!vt.ok)throw new Error(Bt.error||"Failed to send reminders");return Bt},onSuccess:He=>{He.test?ae.success(He.message||"Test email sent!"):ae.success(He.message||`Reminder emails sent to ${He.sent} registrants!`)},onError:He=>{ae.error("Failed to send reminders: "+He.message)}}),{data:Ie}=ct({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let He=[],dt=0;const bt=1e3;for(;;){const{data:vt,error:Bt}=await q.from("profiles").select("id, name, email").order("name",{ascending:!0}).range(dt,dt+bt-1);if(Bt)throw Bt;if(!vt||vt.length===0||(He=[...He,...vt],vt.length{const{error:Bt}=await q.from("event_attendees").update({user_id:dt}).eq("id",He);if(Bt)throw Bt;if(vt&&bt){const{error:Fs}=await q.from("zoom_email_aliases").upsert({user_id:dt,zoom_email:bt.toLowerCase()},{onConflict:"zoom_email"});Fs&&console.error("Failed to save alias:",Fs)}const Zt=j==null?void 0:j.id;if(Zt){const{data:Fs}=await q.from("user_roles").select("id").eq("user_id",dt).eq("role","admin").single();if(!Fs){const{data:Rs}=await q.from("agent_points").select("id").eq("user_id",dt).eq("event_id",Zt).single();Rs||(await q.rpc("award_attendance_points",{p_user_id:dt,p_event_id:Zt,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await q.rpc("check_and_award_badges",{p_user_id:dt}))}}return{userId:dt,zoomEmail:bt,shouldSaveAlias:vt}},onSuccess:He=>{t.invalidateQueries({queryKey:["event-attendees-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let dt="Attendee linked and points awarded!";He.shouldSaveAlias&&He.zoomEmail&&(dt+=` Email "${He.zoomEmail}" will be auto-matched in the future.`),ae.success(dt),A(!1),L(null),M(null),W("")},onError:He=>{ae.error("Failed to link attendee: "+He.message)}}),qe=He=>{L(He),M(null),z(!0),W(""),A(!0)},be=()=>{!T||!D||Fe.mutate({attendeeId:T.id,userId:D,zoomEmail:T.zoom_email,shouldSaveAlias:F})},Ze=(Ie==null?void 0:Ie.filter(He=>{var bt,vt;if(!V)return!0;const dt=V.toLowerCase();return((bt=He.name)==null?void 0:bt.toLowerCase().includes(dt))||((vt=He.email)==null?void 0:vt.toLowerCase().includes(dt))}))||[],Ne=async He=>{const dt=He.name.split(".").pop(),vt=`${`${crypto.randomUUID()}.${dt}`}`,{error:Bt}=await q.storage.from("event-images").upload(vt,He);if(Bt)throw Bt;const{data:{publicUrl:Zt}}=q.storage.from("event-images").getPublicUrl(vt);return Zt},it=He=>{var bt;const dt=(bt=He.target.files)==null?void 0:bt[0];if(dt){if(dt.size>5*1024*1024){ae.error("Image must be less than 5MB");return}d(dt),h(URL.createObjectURL(dt))}},je=()=>{d(null),h(null),o({...l,image_url:""}),g.current&&(g.current.value="")},Ge=gt({mutationFn:async He=>{f(!0);let dt=He.image_url;c&&(dt=await Ne(c)||"");const bt=new Date(He.event_date),[vt,Bt]=He.event_time.split(":");bt.setHours(parseInt(vt),parseInt(Bt));const Zt=[new Date(bt)];if(He.is_recurring&&He.recurrence_end_date){let Pt=new Date(bt);for(;He.recurrence_pattern==="weekly"?Pt=O2(Pt,1):He.recurrence_pattern==="biweekly"?Pt=O2(Pt,2):Pt=Nf(Pt,1),!(Pt>He.recurrence_end_date);)Zt.push(new Date(Pt))}const Fs=Zt.map(Pt=>({title:He.title,description:He.description||null,image_url:dt||null,video_url:He.video_url||null,event_date:Pt.toISOString(),zoom_link:He.zoom_link,zoom_meeting_id:He.zoom_meeting_id||null,capacity:He.capacity?parseInt(He.capacity):null,is_published:He.is_published})),{data:Rs,error:ms}=await q.from("events").insert(Fs).select();if(ms)throw ms;return Rs&&Rs.length>0&&r_s(He.title,Rs[0].id),Zt.length},onSuccess:He=>{t.invalidateQueries({queryKey:["admin-events"]}),ae.success(He>1?`${He} recurring events created successfully`:"Event created successfully"),r(!1),o(WH),d(null),h(null),f(!1)},onError:He=>{ae.error("Failed to create event: "+He.message),f(!1)}}),Be=gt({mutationFn:async({id:He,data:dt})=>{f(!0);let bt=dt.image_url;c&&(bt=await Ne(c)||"");const vt=new Date(dt.event_date),[Bt,Zt]=dt.event_time.split(":");vt.setHours(parseInt(Bt),parseInt(Zt));const{error:Fs}=await q.from("events").update({title:dt.title,description:dt.description||null,image_url:bt||null,video_url:dt.video_url||null,event_date:vt.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",He);if(Fs)throw Fs},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ae.success("Event updated successfully"),r(!1),i(null),o(WH),d(null),h(null),f(!1)},onError:He=>{ae.error("Failed to update event: "+He.message),f(!1)}}),Ye=gt({mutationFn:async He=>{const{error:dt}=await q.from("events").delete().eq("id",He);if(dt)throw dt},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ae.success("Event deleted successfully")},onError:He=>{ae.error("Failed to delete event: "+He.message)}}),We=gt({mutationFn:async He=>{var Pt;const{data:dt}=await q.auth.getUser(),bt=new Date(He.event_date),vt=new Date(bt.getTime()+60*60*1e3),Bt=t_s(He.title),Zt=Math.random().toString(36).slice(2,7),Fs=`${Bt}-${Zt}`,{data:Rs,error:ms}=await q.from("live_events").insert({slug:Fs,title:He.title,description:He.description||null,hero_image_url:He.image_url||null,starts_at:He.event_date,ends_at:vt.toISOString(),timezone:"America/New_York",status:"scheduled",is_published:!1,require_registration:!0,invite_only:!1,chat_enabled:!0,questions_mode:!1,replay_enabled:!0,auto_go_live:!0,auto_end:!0,zoom_meeting_id:He.zoom_meeting_id||null,cta_label:"Join the training",cta_url:He.zoom_link||"https://dashboard.relevelup.com/trial",created_by:(Pt=dt.user)==null?void 0:Pt.id,agenda:[],offer_bullets:[]}).select().single();if(ms)throw ms;return Rs},onSuccess:He=>{t.invalidateQueries({queryKey:["live-events"]}),ae.success("Cloned to LevelUp Live — configure stream next"),s(`/admin/live/${He.id}`)},onError:He=>{ae.error("Failed to clone to LevelUp Live: "+He.message)}}),rt=He=>{var bt;const dt=new Date(He.event_date);i(He),o({title:He.title,description:He.description||"",image_url:He.image_url||"",video_url:He.video_url||"",event_date:dt,event_time:Ss(dt,"HH:mm"),zoom_link:He.zoom_link,zoom_meeting_id:He.zoom_meeting_id||"",capacity:((bt=He.capacity)==null?void 0:bt.toString())||"",is_published:He.is_published,is_recurring:!1,recurrence_pattern:"weekly",recurrence_end_date:void 0}),h(He.image_url||null),d(null),r(!0)},tt=He=>{if(He.preventDefault(),!l.event_date){ae.error("Please select a date");return}if(l.is_recurring&&!l.recurrence_end_date){ae.error("Please select an end date for recurring events");return}a?Be.mutate({id:a.id,data:l}):Ge.mutate(l)},at=()=>{r(!1),i(null),o(WH),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(Ud,{title:"Event Management",description:"Create and manage upcoming events"}),e.jsxs(fe,{className:"mb-6",children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(It,{children:"All Events"}),e.jsxs(bs,{open:n,onOpenChange:He=>!He&&at(),children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{onClick:()=>r(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit:tt,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:He=>o({...l,title:He.target.value}),placeholder:"Event title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Lb,{content:l.description,onChange:He=>o({...l,description:He}),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:g,accept:"image/*",onChange:it,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:je,children:e.jsx(Bn,{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 He;return(He=g.current)==null?void 0:He.click()},children:[e.jsx(Na,{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(el,{children:[e.jsx(tl,{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(yr,{className:"mr-2 h-4 w-4"}),l.event_date?Ss(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(Ho,{className:"w-auto p-0",align:"start",children:e.jsx(Kg,{mode:"single",selected:l.event_date,onSelect:He=>o({...l,event_date:He}),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"time",children:"Time *"}),e.jsx(ye,{id:"time",type:"time",value:l.event_time,onChange:He=>o({...l,event_time:He.target.value}),required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"zoom_link",children:"Zoom Link *"}),e.jsx(ye,{id:"zoom_link",value:l.zoom_link,onChange:He=>o({...l,zoom_link:He.target.value}),placeholder:"https://zoom.us/j/...",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(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:He=>o({...l,zoom_meeting_id:He.target.value}),placeholder:"e.g., 1234567890 (find in Zoom dashboard)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional: Enter the numeric meeting ID for automatic Zoom registration"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"video_url",children:"Promo Video URL (optional)"}),e.jsx(ye,{id:"video_url",value:l.video_url,onChange:He=>o({...l,video_url:He.target.value}),placeholder:"YouTube, Vimeo, or Bunny.net embed URL"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add a preview/promo video for this event"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"capacity",children:"Capacity (optional)"}),e.jsx(ye,{id:"capacity",type:"number",value:l.capacity,onChange:He=>o({...l,capacity:He.target.value}),placeholder:"Leave empty for unlimited",min:"1"})]}),!a&&e.jsxs("div",{className:"space-y-3 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xL,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(bn,{id:"is_recurring",checked:l.is_recurring,onCheckedChange:He=>o({...l,is_recurring:He})})]}),l.is_recurring&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Frequency"}),e.jsxs(ds,{value:l.recurrence_pattern,onValueChange:He=>o({...l,recurrence_pattern:He}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"weekly",children:"Weekly"}),e.jsx(Qe,{value:"biweekly",children:"Every 2 Weeks"}),e.jsx(Qe,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Repeat Until"}),e.jsxs(el,{children:[e.jsx(tl,{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(yr,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?Ss(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(Ho,{className:"w-auto p-0",align:"start",children:e.jsx(Kg,{mode:"single",selected:l.recurrence_end_date,onSelect:He=>o({...l,recurrence_end_date:He}),disabled:He=>He<(l.event_date||new Date),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),l.event_date&&l.recurrence_end_date&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This will create ",(()=>{let He=1,dt=new Date(l.event_date);for(;dt=l.recurrence_pattern==="weekly"?O2(dt,1):l.recurrence_pattern==="biweekly"?O2(dt,2):Nf(dt,1),!(dt>l.recurrence_end_date);)He++;return He})()," events with the same Zoom link"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{htmlFor:"is_published",children:"Published"}),e.jsx(bn,{id:"is_published",checked:l.is_published,onCheckedChange:He=>o({...l,is_published:He})})]}),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:at,className:"flex-1",children:"Cancel"}),e.jsx(B,{type:"submit",className:"flex-1",disabled:Ge.isPending||Be.isPending||p,children:p?"Uploading...":a?"Update Event":l.is_recurring&&l.event_date&&l.recurrence_end_date?"Create Recurring Events":"Create Event"})]})]})]})]})]}),e.jsx(Ee,{children:he?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):(ie==null?void 0:ie.length)===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No events yet. Create your first event!"}):(()=>{const He=new Date,dt=[...ie||[]],bt=dt.filter(Rs=>new Date(Rs.event_date)>=He).sort((Rs,ms)=>new Date(Rs.event_date).getTime()-new Date(ms.event_date).getTime()),vt=dt.filter(Rs=>new Date(Rs.event_date)new Date(ms.event_date).getTime()-new Date(Rs.event_date).getTime()),Bt=bt[0],Zt=Rs=>e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:Rs.title}),e.jsx(ut,{className:"whitespace-nowrap",children:Ss(new Date(Rs.event_date),"PPP p")}),e.jsx(ut,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>Te(Rs),children:[e.jsx(Nn,{className:"h-4 w-4"}),(ce==null?void 0:ce[Rs.id])||0,Rs.capacity&&` / ${Rs.capacity}`]})}),e.jsx(ut,{children:e.jsx("span",{className:Et("px-2 py-1 rounded-full text-xs font-medium",Rs.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:Rs.is_published?"Published":"Draft"})}),e.jsx(ut,{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:()=>{ne(Rs),K(!0)},title:"Send invite email to members",children:[e.jsx(cr,{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:()=>We.mutate(Rs),disabled:We.isPending,title:"Clone to LevelUp Live",children:[e.jsx(_f,{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(Rs.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(tr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>rt(Rs),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this event?")&&Ye.mutate(Rs.id)},children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},Rs.id),Fs=(Rs,ms)=>Rs.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:ms}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Date & Time"}),e.jsx(Ct,{children:"Registrations"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:Rs.map(Zt)})]});return e.jsxs("div",{className:"space-y-6",children:[Bt&&e.jsx("div",{className:"rounded-xl border bg-gradient-to-br from-primary/10 via-primary/5 to-transparent p-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-primary mb-1",children:[e.jsx(gr,{className:"h-3.5 w-3.5"}),"Next Upcoming Event"]}),e.jsx("h3",{className:"text-xl font-bold truncate",children:Bt.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ss(new Date(Bt.event_date),"EEEE, PPP 'at' p")}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(ce==null?void 0:ce[Bt.id])||0," registered",Bt.capacity?` of ${Bt.capacity}`:""]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{size:"sm",className:"gap-1.5",onClick:()=>{ne(Bt),K(!0)},children:[e.jsx(cr,{className:"h-4 w-4"}),"Invite Members"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>Te(Bt),children:[e.jsx(Nn,{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:()=>We.mutate(Bt),disabled:We.isPending,children:[e.jsx(_f,{className:"h-4 w-4"}),"LevelUp Live"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>window.open(Bt.zoom_link,"_blank"),children:[e.jsx(tr,{className:"h-4 w-4"}),"Zoom"]})]})]})}),e.jsxs(Br,{defaultValue:"upcoming",className:"w-full",children:[e.jsxs(Fr,{children:[e.jsxs(Kt,{value:"upcoming",className:"gap-2",children:[e.jsx(gr,{className:"h-4 w-4"}),"Upcoming",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:bt.length})]}),e.jsxs(Kt,{value:"past",className:"gap-2",children:[e.jsx(xr,{className:"h-4 w-4"}),"Past",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:vt.length})]})]}),e.jsx(is,{value:"upcoming",className:"mt-4",children:Fs(bt,"No upcoming events scheduled.")}),e.jsx(is,{value:"past",className:"mt-4",children:Fs(vt,"No past events.")})]})]})})()})]}),e.jsx(c_s,{open:Y,onOpenChange:K,event:J}),e.jsx(bs,{open:_,onOpenChange:v,children:e.jsxs(vs,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5"}),j==null?void 0:j.title]}),e.jsx(Qn,{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:()=>De.mutate({eventId:j.id,testMode:!0}),disabled:De.isPending,children:[e.jsx(Vs,{className:Et("h-4 w-4 mr-2",De.isPending&&"animate-spin")}),"Send Test to Me"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>De.mutate({eventId:j.id}),disabled:De.isPending||!(pe!=null&&pe.length),children:[e.jsx(Vs,{className:Et("h-4 w-4 mr-2",De.isPending&&"animate-spin")}),De.isPending?"Sending...":"Send Reminder to All"]}),(j==null?void 0:j.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Me.mutate(j.id),disabled:Me.isPending,children:[e.jsx(Ti,{className:Et("h-4 w-4 mr-2",Me.isPending&&"animate-spin")}),Me.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Ae.mutate(),disabled:Ae.isPending,children:[e.jsx(Ti,{className:Et("h-4 w-4 mr-2",Ae.isPending&&"animate-spin")}),Ae.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs(B,{variant:"default",size:"sm",onClick:()=>Ce.mutate(j.id),disabled:Ce.isPending,children:[e.jsx(vo,{className:Et("h-4 w-4 mr-2",Ce.isPending&&"animate-spin")}),Ce.isPending?"Syncing...":"Sync Attendees & Award Points"]})]})]}),e.jsxs(Br,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(Fr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Kt,{value:"registrations",className:"gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Registrations (",(pe==null?void 0:pe.length)||0,")"]}),e.jsxs(Kt,{value:"attendees",className:"gap-2",children:[e.jsx(xr,{className:"h-4 w-4"}),"Attendees (",(ve==null?void 0:ve.length)||0,")"]})]}),e.jsx(is,{value:"registrations",className:"mt-4",children:le?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(pe==null?void 0:pe.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No registrations yet for this event."}),(j==null?void 0:j.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Registrations" to import from Zoom.'})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Registered"}),e.jsx(Ct,{children:"Status"})]})}),e.jsx(ha,{children:pe==null?void 0:pe.map(He=>{var Bt,Zt;const dt=((Bt=He.profiles)==null?void 0:Bt.name)||He.zoom_name||"Unknown",bt=((Zt=He.profiles)==null?void 0:Zt.email)||He.zoom_email||null,vt=!He.user_id;return e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[dt,vt&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),e.jsx(ut,{children:bt?e.jsxs("a",{href:`mailto:${bt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(Vs,{className:"h-3 w-3"}),bt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(ut,{className:"text-muted-foreground text-sm",children:Ss(new Date(He.registered_at),"MMM d, yyyy h:mm a")}),e.jsx(ut,{children:He.zoom_join_url?e.jsx("span",{className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",children:"Registered"}):e.jsx("span",{className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-muted text-muted-foreground",children:"Pending"})})]},He.id)})})]})}),e.jsx(is,{value:"attendees",className:"mt-4",children:ge?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading attendees..."}):(ve==null?void 0:ve.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No attendees recorded yet."}),(j==null?void 0:j.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:[(ve==null?void 0:ve.filter(He=>!He.user_id).length)>0&&e.jsxs("div",{className:"mb-6 p-4 border border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Gi,{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 (",ve==null?void 0:ve.filter(He=>!He.user_id).length,")"]})]}),e.jsx("p",{className:"text-xs text-amber-700 dark:text-amber-300 mb-3",children:"These attendees couldn't be matched to a profile. Link them to award points."}),e.jsx("div",{className:"space-y-2",children:ve==null?void 0:ve.filter(He=>!He.user_id).map(He=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-background rounded border",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium text-sm",children:He.zoom_name||"Unknown"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:He.zoom_email||"No email"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>qe(He),className:"gap-1",children:[e.jsx(El,{className:"h-3 w-3"}),"Link to Profile"]})]},He.id))})]}),e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Duration"}),e.jsx(Ct,{children:"Points"})]})}),e.jsx(ha,{children:ve==null?void 0:ve.filter(He=>He.user_id).map(He=>{var vt,Bt;const dt=((vt=He.profiles)==null?void 0:vt.name)||He.zoom_name||"Unknown",bt=((Bt=He.profiles)==null?void 0:Bt.email)||He.zoom_email||null;return e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[dt,He.manually_added&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200",children:"Manual"})]})}),e.jsx(ut,{children:bt?e.jsxs("a",{href:`mailto:${bt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(Vs,{className:"h-3 w-3"}),bt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(ut,{children:He.duration_minutes?e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground text-sm",children:[e.jsx(gr,{className:"h-3 w-3"}),He.duration_minutes," min"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ut,{children:He.points_awarded?e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",children:[e.jsx(vo,{className:"h-3 w-3"}),"+10 pts"]}):e.jsx("span",{className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-muted text-muted-foreground",children:"Pending"})})]},He.id)})})]})]})})]})]})}),e.jsx(bs,{open:S,onOpenChange:A,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(El,{className:"h-5 w-5"}),"Link Attendee to Profile"]}),e.jsx(Qn,{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(vr,{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:V,onChange:He=>W(He.target.value),className:"pl-9"})]})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-md",children:Ze.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No profiles found"}):e.jsx("div",{className:"divide-y",children:Ze.slice(0,20).map(He=>e.jsxs("button",{type:"button",onClick:()=>M(He.id),className:Et("w-full p-3 text-left hover:bg-muted/50 transition-colors",D===He.id&&"bg-primary/10 border-l-2 border-primary"),children:[e.jsx("p",{className:"text-sm font-medium",children:He.name||"Unnamed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:He.email})]},He.id))})}),T.zoom_email&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ui,{id:"save-alias",checked:F,onCheckedChange:He=>z(He)}),e.jsx("label",{htmlFor:"save-alias",className:"text-sm text-muted-foreground cursor-pointer",children:"Remember this email for future auto-matching"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),e.jsx(B,{onClick:be,disabled:!D||Fe.isPending,children:Fe.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}const u_s={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 h_s(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState("issues");async function l(){r(!0);let o=q.from("mcp_audit_log").select("id, user_id, tool_name, outcome, error_message, duration_ms, client_id, created_at").order("created_at",{ascending:!1}).limit(200);a==="issues"&&(o=o.in("outcome",["denied","rate_limited","error"]));const{data:c,error:d}=await o;d||t(c??[]),r(!1)}return N.useEffect(()=>{l()},[a]),e.jsx(Ts,{title:"MCP Audit Log",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{title:"MCP Audit Log",description:"Recent LevelUp MCP tool calls — ChatGPT / Claude / Codex activity, denials, and rate limits."}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(gL,{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(Ti,{className:`h-4 w-4 ${n?"animate-spin":""}`})})]})]}),e.jsx(Ee,{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(ze,{className:u_s[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 m_s({selectedKitIds:s,onChange:t}){const[n,r]=N.useState(""),[a,i]=N.useState(!1),{data:l=[]}=ct({queryKey:["all-resource-kits-picker"],queryFn:async()=>{const{data:h,error:p}=await q.from("resource_kits").select("id, name, featured_image_url").eq("is_published",!0).order("name");if(p)throw p;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(p=>p!==h))};return 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"}),"Linked Toolkits"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(h=>e.jsxs(ze,{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(Bn,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(el,{open:a,onOpenChange:i,children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(Rc,{className:"h-3.5 w-3.5"}),"Add Toolkit"]})}),e.jsxs(Ho,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(vr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(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(Rc,{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 p_s=()=>{const{user:s}=ys(),{toast:t}=Ba(),n=Ht(),[r,a]=gl(),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),[h,p]=N.useState(null),[f,g]=N.useState(0),[_,v]=N.useState(!1),[j,b]=N.useState(null),[S,A]=N.useState(""),[T,L]=N.useState([]),[D,M]=N.useState(""),[F,z]=N.useState(""),[V,W]=N.useState(!1),[Y,K]=N.useState(!1),{data:J=[]}=ct({queryKey:["template-categories"],queryFn:async()=>{const{data:je,error:Ge}=await q.from("template_categories").select("*").order("name");if(Ge)throw Ge;return je}}),{data:ne=[]}=ct({queryKey:["template-types"],queryFn:async()=>{const{data:je,error:Ge}=await q.from("template_types").select("*").order("name");if(Ge)throw Ge;return je}}),{data:ie=[],isLoading:he}=ct({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:je,error:Ge}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(Ge)throw Ge;const{data:Be,error:Ye}=await q.from("template_links").select("*").order("sort_order");if(Ye)throw Ye;const{data:We,error:rt}=await q.from("template_guides").select("*").order("sort_order");if(rt)throw rt;return je.map(at=>({...at,links:(Be==null?void 0:Be.filter(He=>He.template_id===at.id))||[],guides:(We==null?void 0:We.filter(He=>He.template_id===at.id))||[]}))}});N.useEffect(()=>{const je=r.get("edit");if(je&&ie.length>0){const Ge=ie.find(Be=>Be.id===je);Ge&&(Me(Ge),a({},{replace:!0}))}},[ie,r]);const ce=gt({mutationFn:async je=>{const{data:Ge,error:Be}=await q.from("template_categories").insert({name:je}).select().single();if(Be)throw Be;return Ge},onSuccess:je=>{n.invalidateQueries({queryKey:["template-categories"]}),u({...d,category_id:je.id}),M(""),W(!1),t({title:"Category added"})},onError:je=>{t({title:"Error adding category",description:je.message,variant:"destructive"})}}),pe=gt({mutationFn:async je=>{const{data:Ge,error:Be}=await q.from("template_types").insert({name:je}).select().single();if(Be)throw Be;return Ge},onSuccess:je=>{n.invalidateQueries({queryKey:["template-types"]}),u({...d,type_id:je.id}),z(""),K(!1),t({title:"Type added"})},onError:je=>{t({title:"Error adding type",description:je.message,variant:"destructive"})}}),le=gt({mutationFn:async je=>{var rt;let Ge=je.existingImageUrl;if(je.image){const tt=je.image.name.split(".").pop(),at=`${Date.now()}-${Math.random().toString(36).substring(7)}.${tt}`,{error:He}=await q.storage.from("template-previews").upload(at,je.image);if(He)throw He;const{data:dt}=q.storage.from("template-previews").getPublicUrl(at);Ge=dt.publicUrl}const Be={name:je.template.name,description:je.template.description||null,category_id:je.template.category_id||null,type_id:je.template.type_id||null,preview_image_url:Ge,video_url:je.videoUrl||null,publish_date:je.template.publish_date?new Date(je.template.publish_date).toISOString():new Date().toISOString(),created_by:s==null?void 0:s.id};let Ye=je.templateId;if(Ye){const{error:tt}=await q.from("canva_templates").update(Be).eq("id",Ye);if(tt)throw tt;const{error:at}=await q.from("template_links").delete().eq("template_id",Ye);if(at)throw at;const He=((rt=je.existingGuides)==null?void 0:rt.map(vt=>vt.id).filter(Boolean))||[],dt=je.template.guides.map(vt=>vt.id).filter(Boolean),bt=He.filter(vt=>!dt.includes(vt));bt.length>0&&await q.from("template_guides").delete().in("id",bt)}else{const{data:tt,error:at}=await q.from("canva_templates").insert(Be).select().single();if(at)throw at;Ye=tt.id,s_s(je.template.name,tt.id)}const We=je.template.links.filter(tt=>tt.title.trim()&&tt.canva_share_link.trim());if(We.length>0){const tt=We.map((He,dt)=>({template_id:Ye,title:He.title.trim(),canva_share_link:He.canva_share_link.trim(),sort_order:dt})),{error:at}=await q.from("template_links").insert(tt);if(at)throw at}for(let tt=0;tt0)){const{error:tt}=await q.from("resource_kit_templates").insert(je.linkedKitIds.map(at=>({template_id:Ye,kit_id:at})));if(tt)throw tt}},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),Te(),l(!1),t({title:o?"Template updated":"Template created"})},onError:je=>{t({title:"Error saving template",description:je.message,variant:"destructive"})}}),ve=gt({mutationFn:async je=>{const{error:Ge}=await q.from("canva_templates").delete().eq("id",je);if(Ge)throw Ge},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),t({title:"Template deleted"})},onError:je=>{t({title:"Error deleting template",description:je.message,variant:"destructive"})}}),ge=gt({mutationFn:async({id:je,is_featured:Ge})=>{const{error:Be}=await q.from("canva_templates").update({is_featured:Ge}).eq("id",je);if(Be)throw Be},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]})},onError:je=>{t({title:"Error updating featured",description:je.message,variant:"destructive"})}}),Te=()=>{u({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),b(null),A(""),c(null),W(!1),K(!1),M(""),z(""),p(null),g(0),v(!1),L([])},Me=async je=>{var Be;c(je),u({name:je.name,description:je.description||"",category_id:je.category_id||"",type_id:je.type_id||"",publish_date:je.publish_date?new Date(je.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],links:je.links&&je.links.length>0?je.links.map(Ye=>({id:Ye.id,title:Ye.title,canva_share_link:Ye.canva_share_link,sort_order:Ye.sort_order})):[{title:"",canva_share_link:"",sort_order:0}],guides:((Be=je.guides)==null?void 0:Be.map(Ye=>({id:Ye.id,name:Ye.name,file_url:Ye.file_url,file_type:Ye.file_type,file_size:Ye.file_size,sort_order:Ye.sort_order})))||[],video_url:je.video_url||""}),A(je.preview_image_url||""),p(null);const{data:Ge}=await q.from("resource_kit_templates").select("kit_id").eq("template_id",je.id);L((Ge||[]).map(Ye=>Ye.kit_id)),l(!0)},Ce=je=>{var Be;const Ge=(Be=je.target.files)==null?void 0:Be[0];Ge&&(b(Ge),A(URL.createObjectURL(Ge)))},Ae=()=>{u({...d,links:[...d.links,{title:"",canva_share_link:"",sort_order:d.links.length}]})},De=je=>{if(d.links.length<=1)return;const Ge=d.links.filter((Be,Ye)=>Ye!==je);u({...d,links:Ge})},Ie=(je,Ge,Be)=>{const Ye=[...d.links];Ye[je]={...Ye[je],[Ge]:Be},u({...d,links:Ye})},Fe=je=>{const Ge=je.target.files;if(!Ge)return;const Be=Array.from(Ge).map((Ye,We)=>({name:Ye.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:Ye.type,file_size:Ye.size,sort_order:d.guides.length+We,file:Ye}));u({...d,guides:[...d.guides,...Be]}),je.target.value=""},qe=je=>{const Ge=d.guides.filter((Be,Ye)=>Ye!==je);u({...d,guides:Ge})},be=(je,Ge)=>{const Be=[...d.guides];Be[je]={...Be[je],name:Ge},u({...d,guides:Be})},Ze=async()=>{if(!h)return null;v(!0),g(0);try{const{data:je,error:Ge}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d.name||h.name}});if(Ge)throw new Error(Ge.message);const{videoId:Be,libraryId:Ye}=je,{data:We,error:rt}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Be}});if(rt)throw new Error(rt.message);const tt=new XMLHttpRequest;return await new Promise((He,dt)=>{tt.upload.addEventListener("progress",bt=>{if(bt.lengthComputable){const vt=Math.round(bt.loaded/bt.total*100);g(vt)}}),tt.addEventListener("load",()=>{tt.status>=200&&tt.status<300?He():dt(new Error(`Upload failed with status ${tt.status}`))}),tt.addEventListener("error",()=>dt(new Error("Upload failed"))),tt.open("PUT",We.uploadUrl),tt.setRequestHeader("AccessKey",We.apiKey),tt.send(h)}),`https://player.mediadelivery.net/embed/${Ye}/${Be}`}catch(je){return console.error("Bunny upload error:",je),t({title:"Video upload failed",description:je instanceof Error?je.message:"Unknown error",variant:"destructive"}),null}finally{v(!1)}},Ne=je=>{var Be;const Ge=(Be=je.target.files)==null?void 0:Be[0];Ge&&p(Ge),je.target.value=""},it=async je=>{if(je.preventDefault(),!d.name.trim()){t({title:"Please enter a template name",variant:"destructive"});return}if(d.links.filter(Ye=>Ye.title.trim()&&Ye.canva_share_link.trim()).length===0){t({title:"Please add at least one Canva link",variant:"destructive"});return}let Be=d.video_url;if(h){const Ye=await Ze();if(!Ye)return;Be=Ye}le.mutate({template:d,image:j,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:Be,linkedKitIds:T})};return e.jsx(Ts,{title:"Manage Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{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(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:ie.length})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:J.length})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.length})})]})]}),e.jsxs(bs,{open:i,onOpenChange:je=>{l(je),je||Te()},children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:o?"Edit Template":"Add New Template"})}),e.jsxs("form",{onSubmit:it,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:je=>u({...d,name:je.target.value}),placeholder:"Template name",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Lb,{content:d.description,onChange:je=>u({...d,description:je}),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:Ae,className:"gap-1",children:[e.jsx(Is,{className:"h-3 w-3"}),"Add Link"]})]}),e.jsx("div",{className:"space-y-3",children:d.links.map((je,Ge)=>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:je.title,onChange:Be=>Ie(Ge,"title",Be.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(ye,{value:je.canva_share_link,onChange:Be=>Ie(Ge,"canva_share_link",Be.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:()=>De(Ge),children:e.jsx(Bn,{className:"h-4 w-4"})})]},Ge))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Category"}),V?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:D,onChange:je=>M(je.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>D.trim()&&ce.mutate(D.trim()),disabled:ce.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{W(!1),M("")},children:e.jsx(Bn,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ds,{value:d.category_id,onValueChange:je=>u({...d,category_id:je}),children:[e.jsx(ls,{className:"flex-1",children:e.jsx(us,{placeholder:"Select category"})}),e.jsx(cs,{children:J.map(je=>e.jsx(Qe,{value:je.id,children:je.name},je.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>W(!0),children:e.jsx(Is,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Template Type"}),Y?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:F,onChange:je=>z(je.target.value),placeholder:"New type name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>F.trim()&&pe.mutate(F.trim()),disabled:pe.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{K(!1),z("")},children:e.jsx(Bn,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ds,{value:d.type_id,onValueChange:je=>u({...d,type_id:je}),children:[e.jsx(ls,{className:"flex-1",children:e.jsx(us,{placeholder:"Select type"})}),e.jsx(cs,{children:ne.map(je=>e.jsx(Qe,{value:je.id,children:je.name},je.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>K(!0),children:e.jsx(Is,{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:je=>u({...d,publish_date:je.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:[S?e.jsxs("div",{className:"relative w-32 h-24 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("img",{src:S,alt:"Preview",className:"w-full h-full object-cover"}),e.jsx(B,{type:"button",size:"icon",variant:"destructive",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>{b(null),A("")},children:e.jsx(Bn,{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(nl,{className:"h-8 w-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ye,{type:"file",accept:"image/*",onChange:Ce,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(br,{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})})]}):_?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(ts,{className:"h-4 w-4 animate-spin"}),e.jsxs("span",{className:"text-sm",children:["Uploading video... ",f,"%"]})]}),e.jsx(pi,{value:f,className:"h-2"})]}):h?e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(br,{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:()=>p(null),children:e.jsx(Bn,{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:Ne,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(br,{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:Fe,className:"hidden"}),e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:e.jsxs("span",{children:[e.jsx(Na,{className:"h-3 w-3"}),"Add Files"]})})]})]}),d.guides.length>0?e.jsx("div",{className:"space-y-2",children:d.guides.map((je,Ge)=>e.jsxs("div",{className:"flex gap-2 items-center p-3 border rounded-lg bg-muted/30",children:[e.jsx(Nr,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(ye,{value:je.name,onChange:Be=>be(Ge,Be.target.value),placeholder:"Guide name",className:"flex-1"}),je.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(je.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:()=>qe(Ge),children:e.jsx(Bn,{className:"h-4 w-4"})})]},je.id||Ge))}):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(m_s,{selectedKitIds:T,onChange:L}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>{l(!1),Te()},children:"Cancel"}),e.jsx(B,{type:"submit",disabled:le.isPending,children:le.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:he?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):ie.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Preview"}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Links"}),e.jsx(Ct,{children:"Category"}),e.jsx(Ct,{children:"Type"}),e.jsx(Ct,{children:"Publish Date"}),e.jsx(Ct,{className:"w-[72px] text-center",children:"Featured"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:ie.map(je=>{var Ge,Be,Ye,We,rt;return e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsx("div",{className:"w-16 h-12 rounded overflow-hidden bg-muted",children:je.preview_image_url?e.jsx("img",{src:je.preview_image_url,alt:je.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(nl,{className:"h-4 w-4 text-muted-foreground"})})})}),e.jsx(ut,{className:"font-medium",children:je.name}),e.jsx(ut,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(ze,{variant:"secondary",children:[((Ge=je.links)==null?void 0:Ge.length)||0," link",(((Be=je.links)==null?void 0:Be.length)||0)!==1?"s":""]}),(((Ye=je.guides)==null?void 0:Ye.length)||0)>0&&e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Nr,{className:"h-3 w-3"}),(We=je.guides)==null?void 0:We.length," guide",(((rt=je.guides)==null?void 0:rt.length)||0)!==1?"s":""]})]})}),e.jsx(ut,{children:je.category?e.jsx(ze,{variant:"secondary",children:je.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(ut,{children:je.type?e.jsx(ze,{variant:"outline",children:je.type.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(ut,{className:"text-muted-foreground",children:new Date(je.publish_date).toLocaleDateString()}),e.jsx(ut,{className:"text-center",children:e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"mx-auto",title:je.is_featured?"Remove from featured templates":"Add to featured templates",onClick:()=>ge.mutate({id:je.id,is_featured:!je.is_featured}),children:e.jsx(ca,{className:`h-4 w-4 ${je.is_featured?"fill-yellow-400 text-yellow-400":"text-muted-foreground"}`})})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>Me(je),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&ve.mutate(je.id)},children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},je.id)})})]})})})]})})};function oyt({selectedTemplateIds:s,onChange:t}){const[n,r]=N.useState(""),[a,i]=N.useState(!1),{data:l=[]}=ct({queryKey:["all-canva-templates-picker"],queryFn:async()=>{const{data:h,error:p}=await q.from("canva_templates").select("id, name, preview_image_url").order("name");if(p)throw p;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(p=>p!==h))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(t4,{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(ze,{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(Bn,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(el,{open:a,onOpenChange:i,children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(t4,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(Ho,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(vr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(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(t4,{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 f_s=[{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"}],x_s=()=>{const{user:s}=ys(),[t,n]=gl(),{toast:r}=Ba(),a=Ht(),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState({title:"",description:"",video_url:"",video_type:"youtube",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[h,p]=N.useState(null),[f,g]=N.useState(""),[_,v]=N.useState([]),[j,b]=N.useState([]),[S,A]=N.useState([]),[T,L]=N.useState([]),[D,M]=N.useState(""),[F,z]=N.useState(!1),[V,W]=N.useState(null),[Y,K]=N.useState(0),[J,ne]=N.useState(!1),[ie,he]=N.useState(null),{data:ce=[]}=ct({queryKey:["academy-categories"],queryFn:async()=>{const{data:je,error:Ge}=await q.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(Ge)throw Ge;return je}}),{data:pe=[],isLoading:le}=ct({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:je,error:Ge}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if(Ge)throw Ge;const{data:Be,error:Ye}=await q.from("academy_resources").select("*").order("sort_order");if(Ye)throw Ye;return je.map(rt=>({...rt,resources:(Be==null?void 0:Be.filter(tt=>tt.video_id===rt.id))||[]}))}});N.useEffect(()=>{const je=t.get("edit");if(je&&pe.length>0){const Ge=pe.find(Be=>Be.id===je);Ge&&(Ie(Ge),n({},{replace:!0}))}},[pe,t]);const ve=gt({mutationFn:async je=>{const{data:Ge,error:Be}=await q.from("academy_categories").insert({name:je,sort_order:ce.length}).select().single();if(Be)throw Be;return Ge},onSuccess:je=>{a.invalidateQueries({queryKey:["academy-categories"]}),u({...d,category_id:je.id}),M(""),z(!1),r({title:"Category added"})},onError:je=>{r({title:"Error adding category",description:je.message,variant:"destructive"})}}),ge=gt({mutationFn:async je=>{let Ge=je.existingThumbnailUrl;if(je.thumbnail){const We=je.thumbnail.name.split(".").pop(),rt=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${We}`,{error:tt}=await q.storage.from("academy-resources").upload(rt,je.thumbnail);if(tt)throw tt;const{data:at}=q.storage.from("academy-resources").getPublicUrl(rt);Ge=at.publicUrl}const Be={title:je.video.title,description:je.video.description||null,video_url:je.video.video_url,video_type:je.video.video_type,duration:je.video.duration||null,thumbnail_url:Ge,category_id:je.video.category_id||null,publish_date:je.video.publish_date?new Date(je.video.publish_date).toISOString():new Date().toISOString(),is_published:je.video.is_published,created_by:s==null?void 0:s.id};let Ye=je.videoId;if(Ye){const{error:We}=await q.from("academy_videos").update(Be).eq("id",Ye);if(We)throw We}else{const{data:We,error:rt}=await q.from("academy_videos").insert(Be).select().single();if(rt)throw rt;Ye=We.id,n_s(je.video.title,We.id)}if(je.resourcesToDelete.length>0){const{error:We}=await q.from("academy_resources").delete().in("id",je.resourcesToDelete);if(We)throw We}for(let We=0;We0){const{error:We}=await q.from("academy_video_templates").insert(T.map(rt=>({video_id:Ye,template_id:rt})));if(We)throw We}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),De(),l(!1),r({title:o?"Video updated":"Video created"})},onError:je=>{r({title:"Error saving video",description:je.message,variant:"destructive"})}}),Te=gt({mutationFn:async je=>{const{error:Ge}=await q.from("academy_videos").delete().eq("id",je);if(Ge)throw Ge},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),r({title:"Video deleted"})},onError:je=>{r({title:"Error deleting video",description:je.message,variant:"destructive"})}}),Me=gt({mutationFn:async({id:je,is_published:Ge})=>{const{error:Be}=await q.from("academy_videos").update({is_published:Ge}).eq("id",je);if(Be)throw Be},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]})},onError:je=>{r({title:"Error updating video",description:je.message,variant:"destructive"})}}),Ce=async je=>{try{let Ge=je.public_slug||null,Be=!!je.is_public;if(!Ge||!Be){const We=(je.title||"video").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"video";if(!Ge){let tt=We;const{data:at}=await q.from("academy_videos").select("id").eq("public_slug",tt).maybeSingle();at&&at.id!==je.id&&(tt=`${We}-${je.id.slice(0,6)}`),Ge=tt}const{error:rt}=await q.from("academy_videos").update({public_slug:Ge,is_public:!0}).eq("id",je.id);if(rt)throw rt;a.invalidateQueries({queryKey:["academy-videos-admin"]})}const Ye=`${window.location.origin}/watch/${Ge}`;await navigator.clipboard.writeText(Ye),r({title:"Public link copied",description:Ye})}catch(Ge){r({title:"Could not copy link",description:Ge.message,variant:"destructive"})}},Ae=async je=>{if(!confirm("Disable the public teaser link for this video?"))return;const{error:Ge}=await q.from("academy_videos").update({is_public:!1}).eq("id",je.id);if(Ge){r({title:"Error",description:Ge.message,variant:"destructive"});return}a.invalidateQueries({queryKey:["academy-videos-admin"]}),r({title:"Public link disabled"})},De=()=>{u({title:"",description:"",video_url:"",video_type:"bunny_stream",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),p(null),g(""),v([]),b([]),A([]),c(null),L([]),M(""),W(null),K(0),ne(!1),he(null)},Ie=async je=>{c(je),u({title:je.title,description:je.description||"",video_url:je.video_url,video_type:je.video_type,duration:je.duration||"",category_id:je.category_id||"",publish_date:je.publish_date?new Date(je.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:je.is_published}),g(je.thumbnail_url||""),b(je.resources||[]),v([]),A([]);const{data:Ge}=await q.from("academy_video_templates").select("template_id").eq("video_id",je.id);L((Ge||[]).map(Be=>Be.template_id)),l(!0)},Fe=je=>{var Be;const Ge=(Be=je.target.files)==null?void 0:Be[0];Ge&&(p(Ge),g(URL.createObjectURL(Ge)))},qe=je=>{const Ge=je.target.files;if(Ge){const Be=Array.from(Ge).map(Ye=>({file:Ye,title:Ye.name.replace(/\.[^/.]+$/,"")}));v([..._,...Be])}je.target.value=""},be=je=>{v(_.filter((Ge,Be)=>Be!==je))},Ze=je=>{A([...S,je]),b(j.filter(Ge=>Ge.id!==je))},Ne=async()=>{if(!V)return null;ne(!0),K(0);try{const{data:je,error:Ge}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d.title||V.name}});if(Ge)throw new Error(Ge.message);const{videoId:Be,libraryId:Ye}=je;he(Be);const{data:We,error:rt}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Be}});if(rt)throw new Error(rt.message);const tt=new XMLHttpRequest;return await new Promise((He,dt)=>{tt.upload.addEventListener("progress",bt=>{if(bt.lengthComputable){const vt=Math.round(bt.loaded/bt.total*100);K(vt)}}),tt.addEventListener("load",()=>{tt.status>=200&&tt.status<300?He():dt(new Error(`Upload failed with status ${tt.status}`))}),tt.addEventListener("error",()=>dt(new Error("Upload failed"))),tt.open("PUT",We.uploadUrl),tt.setRequestHeader("AccessKey",We.apiKey),tt.send(V)}),`https://player.mediadelivery.net/embed/${Ye}/${Be}`}catch(je){return console.error("Bunny upload error:",je),r({title:"Video upload failed",description:je instanceof Error?je.message:"Unknown error",variant:"destructive"}),null}finally{ne(!1)}},it=async je=>{if(je.preventDefault(),!d.title.trim()){r({title:"Please enter a video title",variant:"destructive"});return}let Ge=d.video_url;if(d.video_type==="bunny_stream"&&V&&!o){const Be=await Ne();if(!Be)return;Ge=Be}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"&&!V&&!d.video_url&&!o){r({title:"Please select a video file to upload",variant:"destructive"});return}ge.mutate({video:{...d,video_url:Ge},thumbnail:h,existingThumbnailUrl:(o==null?void 0:o.thumbnail_url)||null,videoId:o==null?void 0:o.id,newResources:_,resourcesToDelete:S})};return e.jsx(Ts,{title:"Manage Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{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(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:pe.length})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:pe.filter(je=>je.is_published).length})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Public Teasers"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:pe.filter(je=>je.is_public).length})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total Public Views"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:pe.reduce((je,Ge)=>je+(Ge.public_view_count||0),0).toLocaleString()})})]})]}),e.jsxs(bs,{open:i,onOpenChange:je=>{l(je),je||De()},children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:o?"Edit Video":"Add New Video"})}),e.jsxs("form",{onSubmit:it,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:je=>u({...d,title:je.target.value}),placeholder:"Video title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Lb,{content:d.description,onChange:je=>u({...d,description:je}),placeholder:"Brief description of the video",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Video Type"}),e.jsxs(ds,{value:d.video_type,onValueChange:je=>{u({...d,video_type:je,video_url:""}),W(null)},disabled:J,children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:f_s.map(je=>e.jsx(Qe,{value:je.value,children:je.label},je.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:je=>{var Be;const Ge=(Be=je.target.files)==null?void 0:Be[0];Ge&&W(Ge)},disabled:J}),V&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(br,{className:"h-4 w-4"}),V.name," (",(V.size/(1024*1024)).toFixed(1)," MB)"]}),J&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Uploading to Bunny.net..."})]}),e.jsx(pi,{value:Y,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[Y,"%"]})]})]})]}):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:je=>u({...d,video_url:je.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:je=>u({...d,duration:je.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:je=>u({...d,publish_date:je.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Category"}),F?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:D,onChange:je=>M(je.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>D.trim()&&ve.mutate(D.trim()),disabled:ve.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{z(!1),M("")},children:e.jsx(Bn,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ds,{value:d.category_id,onValueChange:je=>u({...d,category_id:je}),children:[e.jsx(ls,{className:"flex-1",children:e.jsx(us,{placeholder:"Select category"})}),e.jsx(cs,{children:ce.map(je=>e.jsx(Qe,{value:je.id,children:je.name},je.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:()=>z(!0),children:e.jsx(Is,{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:[f&&e.jsx("img",{src:f,alt:"Thumbnail preview",className:"w-32 h-20 object-cover rounded-md border"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ye,{type:"file",accept:"image/*",onChange:Fe,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(Na,{className:"h-3 w-3"}),"Add Files",e.jsx("input",{type:"file",multiple:!0,accept:".pdf,.pptx,.ppt,.xlsx,.xls,.docx,.doc,.zip",onChange:qe,className:"hidden"})]})})]}),(j.length>0||_.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[j.map(je=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:je.title}),e.jsx(ze,{variant:"outline",className:"text-xs",children:je.file_type}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>Ze(je.id),className:"text-destructive hover:text-destructive",children:e.jsx(Bn,{className:"h-4 w-4"})})]},je.id)),_.map((je,Ge)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:je.title,onChange:Be=>{const Ye=[..._];Ye[Ge].title=Be.target.value,v(Ye)},className:"flex-1 h-8",placeholder:"Resource title"}),e.jsx(ze,{variant:"secondary",className:"text-xs",children:"New"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>be(Ge),className:"text-destructive hover:text-destructive",children:e.jsx(Bn,{className:"h-4 w-4"})})]},Ge))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx(oyt,{selectedTemplateIds:T,onChange:L}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bn,{id:"is_published",checked:d.is_published,onCheckedChange:je=>u({...d,is_published:je})}),e.jsx(se,{htmlFor:"is_published",children:"Published"})]}),e.jsxs(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),disabled:J,children:"Cancel"}),e.jsx(B,{type:"submit",disabled:ge.isPending||J,children:J?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):ge.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:le?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"})}):pe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(br,{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(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Category"}),e.jsx(Ct,{children:"Duration"}),e.jsx(Ct,{children:"Resources"}),e.jsx(Ct,{children:"Publish Date"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Public Views"}),e.jsx(Ct,{className:"w-[120px]",children:"Actions"})]})}),e.jsx(ha,{children:pe.map(je=>e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[je.thumbnail_url?e.jsx("img",{src:je.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(br,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:je.title}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:je.video_type.replace("_"," ")})]})]})}),e.jsx(ut,{children:je.category?e.jsx(ze,{variant:"outline",children:je.category.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(ut,{children:je.duration||"-"}),e.jsx(ut,{children:je.resources&&je.resources.length>0?e.jsxs(ze,{variant:"secondary",children:[je.resources.length," file(s)"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(ut,{children:new Date(je.publish_date).toLocaleDateString()}),e.jsx(ut,{children:e.jsx(bn,{checked:je.is_published,onCheckedChange:Ge=>Me.mutate({id:je.id,is_published:Ge})})}),e.jsx(ut,{children:je.is_public?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Er,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:(je.public_view_count||0).toLocaleString()})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",title:je.is_public?"Copy public teaser link":"Make public & copy teaser link",onClick:()=>Ce(je),children:je.is_public?e.jsx(Xr,{className:"h-4 w-4 text-primary"}):e.jsx(Hl,{className:"h-4 w-4"})}),je.is_public&&e.jsx(B,{variant:"ghost",size:"sm",title:"Disable public link",onClick:()=>Ae(je),children:e.jsx(lc,{className:"h-4 w-4 text-emerald-500"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Ie(je),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Te.mutate(je.id),className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},je.id))})]})})})]})})};function g_s(){var ge,Te,Me;const s=Ht(),[t,n]=gl(),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=N.useState(null),[h,p]=N.useState(""),[f,g]=N.useState([]),[_,v]=N.useState([]),[j,b]=N.useState([]),[S,A]=N.useState(null),{data:T,isLoading:L}=ct({queryKey:["resource-kits"],queryFn:async()=>{const{data:Ce,error:Ae}=await q.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(Ae)throw Ae;return Ce}}),{data:D}=ct({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:Ce,error:Ae}=await q.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(Ae)throw Ae;return Ce}}),{data:M}=ct({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:Ce,error:Ae}=await q.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(Ae)throw Ae;return Ce}});N.useEffect(()=>{const Ce=t.get("edit");if(Ce&&T&&T.length>0&&D&&M){const Ae=T.find(De=>De.id===Ce);Ae&&(z(Ae),n({},{replace:!0}))}},[T,D,M,t]);const F=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),p(""),g([]),v([]),b([]),l(null)},z=async Ce=>{l(Ce),c({name:Ce.name,description:Ce.description||"",publish_date:Ce.publish_date.split("T")[0],is_published:Ce.is_published}),p(Ce.featured_image_url||"");const Ae=(D==null?void 0:D.filter(Fe=>Fe.kit_id===Ce.id))||[];g(Ae.map(Fe=>({id:Fe.id,name:Fe.name,file_url:Fe.file_url,file_type:Fe.file_type,file_size:Fe.file_size,sort_order:Fe.sort_order})));const De=(M==null?void 0:M.filter(Fe=>Fe.kit_id===Ce.id))||[];v(De.map(Fe=>({id:Fe.id,title:Fe.title,canva_share_link:Fe.canva_share_link,sort_order:Fe.sort_order})));const{data:Ie}=await q.from("resource_kit_templates").select("template_id").eq("kit_id",Ce.id);b((Ie||[]).map(Fe=>Fe.template_id)),a(!0)},V=Ce=>{var De;const Ae=(De=Ce.target.files)==null?void 0:De[0];Ae&&(u(Ae),p(URL.createObjectURL(Ae)))},W=()=>{g([...f,{name:"",file_url:"",sort_order:f.length}])},Y=Ce=>{g(f.filter((Ae,De)=>De!==Ce))},K=(Ce,Ae,De)=>{const Ie=[...f];Ie[Ce]={...Ie[Ce],[Ae]:De},g(Ie)},J=()=>{v([..._,{title:"",canva_share_link:"",sort_order:_.length}])},ne=Ce=>{v(_.filter((Ae,De)=>De!==Ce))},ie=(Ce,Ae,De)=>{const Ie=[..._];Ie[Ce]={...Ie[Ce],[Ae]:De},v(Ie)},he=(Ce,Ae)=>{var Ie;const De=(Ie=Ae.target.files)==null?void 0:Ie[0];if(De){const Fe=[...f],qe=De.name.replace(/\.[^/.]+$/,"");Fe[Ce]={...Fe[Ce],file:De,file_type:De.type,file_size:De.size,name:Fe[Ce].name||qe},g(Fe)}},ce=gt({mutationFn:async()=>{let Ce=(i==null?void 0:i.featured_image_url)||null;if(d){const qe=d.name.split(".").pop(),be=`${Date.now()}.${qe}`,{error:Ze}=await q.storage.from("resource-kits").upload(`featured/${be}`,d);if(Ze)throw Ze;const{data:Ne}=q.storage.from("resource-kits").getPublicUrl(`featured/${be}`);Ce=Ne.publicUrl}const Ae={name:o.name,description:o.description||null,featured_image_url:Ce,publish_date:o.publish_date,is_published:o.is_published};let De;const Ie=!i,Fe=(i==null?void 0:i.is_published)||!1;if(i){const{error:qe}=await q.from("resource_kits").update(Ae).eq("id",i.id);if(qe)throw qe;De=i.id;const be=(D==null?void 0:D.filter(Be=>Be.kit_id===i.id).map(Be=>Be.id))||[],Ze=f.filter(Be=>Be.id).map(Be=>Be.id),Ne=be.filter(Be=>!Ze.includes(Be));Ne.length>0&&await q.from("resource_kit_files").delete().in("id",Ne);const it=(M==null?void 0:M.filter(Be=>Be.kit_id===i.id).map(Be=>Be.id))||[],je=_.filter(Be=>Be.id).map(Be=>Be.id),Ge=it.filter(Be=>!je.includes(Be));Ge.length>0&&await q.from("resource_kit_links").delete().in("id",Ge)}else{const{data:qe,error:be}=await q.from("resource_kits").insert(Ae).select().single();if(be)throw be;De=qe.id}for(let qe=0;qe0){const{error:qe}=await q.from("resource_kit_templates").insert(j.map(be=>({kit_id:De,template_id:be})));if(qe)throw qe}return{kitId:De,kitName:o.name,isNewKit:Ie,wasPublished:Fe,isPublished:o.is_published}},onSuccess:Ce=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),s.invalidateQueries({queryKey:["resource-kit-links"]}),ae.success(i?"Resource kit updated":"Resource kit created"),Ce.isPublished&&(Ce.isNewKit||!Ce.wasPublished)&&a_s(Ce.kitName,Ce.kitId),a(!1),F()},onError:Ce=>{ae.error("Failed to save resource kit: "+Ce.message)}}),pe=gt({mutationFn:async Ce=>{const{error:Ae}=await q.from("resource_kits").delete().eq("id",Ce);if(Ae)throw Ae},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),ae.success("Resource kit deleted")},onError:Ce=>{ae.error("Failed to delete: "+Ce.message)}}),le=Ce=>{if(Ce.preventDefault(),!o.name){ae.error("Please enter a name");return}ce.mutate()},ve=Ce=>(D==null?void 0:D.filter(Ae=>Ae.kit_id===Ce).length)||0;return e.jsx(Ts,{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(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total Kits"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:(T==null?void 0:T.length)||0})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:(T==null?void 0:T.filter(Ce=>Ce.is_published).length)||0})})]})]}),e.jsxs(B,{onClick:()=>{F(),a(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Files"}),e.jsx(Ct,{children:"Publish Date"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:L?e.jsx(Hs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(T==null?void 0:T.length)===0?e.jsx(Hs,{children:e.jsx(ut,{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(Ce=>e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Ce.featured_image_url?e.jsx("img",{src:Ce.featured_image_url,alt:Ce.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(Rc,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ce.name}),Ce.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Ce.description})]})]})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"}),ve(Ce.id)]})}),e.jsx(ut,{children:Ss(new Date(Ce.publish_date),"MMM d, yyyy")}),e.jsx(ut,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${Ce.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:Ce.is_published?"Published":"Draft"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{const Ae=(D==null?void 0:D.filter(Ie=>Ie.kit_id===Ce.id))||[],De=(M==null?void 0:M.filter(Ie=>Ie.kit_id===Ce.id))||[];A({...Ce,files:Ae,links:De})},children:e.jsx(Er,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>z(Ce),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource kit?")&&pe.mutate(Ce.id)},children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},Ce.id))})]})})}),e.jsx(bs,{open:r,onOpenChange:a,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:i?"Edit Resource Kit":"Add Resource Kit"})}),e.jsxs("form",{onSubmit:le,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(Rc,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(ye,{type:"file",accept:"image/*",onChange:V})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name *"}),e.jsx(ye,{id:"name",value:o.name,onChange:Ce=>c({...o,name:Ce.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Lb,{content:o.description,onChange:Ce=>c({...o,description:Ce}),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:Ce=>c({...o,publish_date:Ce.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(bn,{checked:o.is_published,onCheckedChange:Ce=>c({...o,is_published:Ce})}),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:W,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add File"]})]}),f.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center border rounded-md border-dashed",children:'No files added yet. Click "Add File" to include resources.'}):e.jsx("div",{className:"space-y-3",children:f.map((Ce,Ae)=>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 ",Ae+1]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>Y(Ae),children:e.jsx(Bn,{className:"h-4 w-4"})})]}),e.jsx(ye,{placeholder:"File name (e.g., Getting Started Guide)",value:Ce.name,onChange:De=>K(Ae,"name",De.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"file",onChange:De=>he(Ae,De),className:"flex-1"}),Ce.file_url&&!Ce.file&&e.jsx("a",{href:Ce.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),Ce.file&&e.jsx("span",{className:"text-sm text-green-600 whitespace-nowrap",children:"New file selected"})]})]},Ae))})]}),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:J,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add Canva Link"]})]}),_.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:_.map((Ce,Ae)=>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 ",Ae+1]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>ne(Ae),children:e.jsx(Bn,{className:"h-4 w-4"})})]}),e.jsx(ye,{placeholder:"Link title (e.g., Social Media Post Template)",value:Ce.title,onChange:De=>ie(Ae,"title",De.target.value)}),e.jsx(ye,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:Ce.canva_share_link,onChange:De=>ie(Ae,"canva_share_link",De.target.value)})]},Ae))})]}),e.jsx(oyt,{selectedTemplateIds:j,onChange:b}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:ce.isPending,children:ce.isPending?"Saving...":i?"Update":"Create"})]})]})]})}),e.jsx(bs,{open:!!S,onOpenChange:()=>A(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{children:e.jsx(_s,{children:S==null?void 0:S.name})}),e.jsxs("div",{className:"space-y-4",children:[(S==null?void 0:S.featured_image_url)&&e.jsx("img",{src:S.featured_image_url,alt:S.name,className:"w-full h-48 object-cover rounded-lg"}),(S==null?void 0:S.description)&&e.jsx("p",{className:"text-muted-foreground",children:S.description}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Resource Files (",((ge=S==null?void 0:S.files)==null?void 0:ge.length)||0,")"]}),((Te=S==null?void 0:S.files)==null?void 0:Te.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:(Me=S==null?void 0:S.files)==null?void 0:Me.map(Ce=>e.jsxs("a",{href:Ce.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(Nr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:Ce.name})]},Ce.id))})]}),(S==null?void 0:S.links)&&S.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Canva Links (",S.links.length,")"]}),e.jsx("div",{className:"space-y-2",children:S.links.map(Ce=>e.jsxs("a",{href:Ce.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(Jo,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:Ce.title})]},Ce.id))})]})]})]})})]})})}const y_s=()=>{const{user:s}=ys(),{toast:t}=Ba(),n=Ht(),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),[d,u]=N.useState(null),[h,p]=N.useState(""),{data:f=[],isLoading:g}=ct({queryKey:["social-swag-admin"],queryFn:async()=>{const{data:M,error:F}=await q.from("social_swag").select("*").order("publish_date",{ascending:!1});if(F)throw F;const{data:z,error:V}=await q.from("social_swag_links").select("*").order("sort_order");if(V)throw V;return M.map(Y=>({...Y,links:(z==null?void 0:z.filter(K=>K.swag_id===Y.id))||[]}))}}),_=gt({mutationFn:async M=>{let F=M.existingImageUrl;if(M.image){const J=M.image.name.split(".").pop(),ne=`${Date.now()}-${Math.random().toString(36).substring(7)}.${J}`,{error:ie}=await q.storage.from("template-previews").upload(ne,M.image);if(ie)throw ie;const{data:he}=q.storage.from("template-previews").getPublicUrl(ne);F=he.publicUrl}const z={title:M.item.title,description:M.item.description||null,preview_image_url:F,publish_date:M.item.publish_date?new Date(M.item.publish_date).toISOString():new Date().toISOString(),is_published:M.item.is_published,created_by:s==null?void 0:s.id};let V=M.itemId;const W=!V,Y=(i==null?void 0:i.is_published)||!1;if(V){const{error:J}=await q.from("social_swag").update(z).eq("id",V);if(J)throw J;await q.from("social_swag_links").delete().eq("swag_id",V)}else{const{data:J,error:ne}=await q.from("social_swag").insert(z).select().single();if(ne)throw ne;V=J.id}const K=M.item.links.filter(J=>J.title.trim()&&J.canva_share_link.trim());if(K.length>0){const J=K.map((ie,he)=>({swag_id:V,title:ie.title.trim(),canva_share_link:ie.canva_share_link.trim(),sort_order:he})),{error:ne}=await q.from("social_swag_links").insert(J);if(ne)throw ne}return{itemId:V,itemTitle:M.item.title,isNewItem:W,wasPublished:Y,isPublished:M.item.is_published}},onSuccess:M=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:i?"Item updated":"Item created"}),M.isPublished&&(M.isNewItem||!M.wasPublished)&&y3e(M.itemTitle,M.itemId),a(!1),j()},onError:M=>{t({title:"Error saving item",description:M.message,variant:"destructive"})}}),v=gt({mutationFn:async M=>{const{error:F}=await q.from("social_swag").delete().eq("id",M);if(F)throw F},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:"Item deleted"})},onError:M=>{t({title:"Error deleting item",description:M.message,variant:"destructive"})}}),j=()=>{c({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),u(null),p(""),l(null)},b=M=>{l(M),c({title:M.title,description:M.description||"",publish_date:M.publish_date?new Date(M.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:M.is_published,links:M.links&&M.links.length>0?M.links.map(F=>({id:F.id,title:F.title,canva_share_link:F.canva_share_link,sort_order:F.sort_order})):[{title:"",canva_share_link:"",sort_order:0}]}),p(M.preview_image_url||""),a(!0)},S=M=>{var z;const F=(z=M.target.files)==null?void 0:z[0];F&&(u(F),p(URL.createObjectURL(F)))},A=()=>{c({...o,links:[...o.links,{title:"",canva_share_link:"",sort_order:o.links.length}]})},T=M=>{if(o.links.length<=1)return;const F=o.links.filter((z,V)=>V!==M);c({...o,links:F})},L=(M,F,z)=>{const V=[...o.links];V[M]={...V[M],[F]:z},c({...o,links:V})},D=M=>{if(M.preventDefault(),!o.title.trim()){t({title:"Title is required",variant:"destructive"});return}_.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(Ts,{title:"Manage Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{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(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.length})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.filter(M=>M.is_published).length})})]})]}),e.jsxs(bs,{open:r,onOpenChange:M=>{a(M),M||j()},children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:i?"Edit Item":"Add New Item"})}),e.jsxs("form",{onSubmit:D,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:M=>c({...o,title:M.target.value}),placeholder:"Enter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Lb,{content:o.description,onChange:M=>c({...o,description:M}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ye,{id:"publish_date",type:"date",value:o.publish_date,onChange:M=>c({...o,publish_date:M.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(bn,{id:"is_published",checked:o.is_published,onCheckedChange:M=>c({...o,is_published:M})}),e.jsx(se,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Preview Image"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),p("")},children:e.jsx(Bn,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(nl,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(ye,{type:"file",accept:"image/*",onChange:S,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:A,children:[e.jsx(Is,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map((M,F)=>e.jsx(fe,{children:e.jsxs(Ee,{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 ",F+1]}),o.links.length>1&&e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>T(F),children:e.jsx(Bn,{className:"h-3 w-3"})})]}),e.jsx(ye,{placeholder:"Link title (e.g., Instagram Post)",value:M.title,onChange:z=>L(F,"title",z.target.value)}),e.jsx(ye,{placeholder:"Canva share link",value:M.canva_share_link,onChange:z=>L(F,"canva_share_link",z.target.value)})]})},F))]}),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:_.isPending,children:_.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:g?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):f.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No items yet. Click "Add Item" to create your first one.'}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{className:"w-16",children:"Preview"}),e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Links"}),e.jsx(Ct,{children:"Publish Date"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:f.map(M=>{var F;return e.jsxs(Hs,{children:[e.jsx(ut,{children:M.preview_image_url?e.jsx("img",{src:M.preview_image_url,alt:"",className:"w-12 h-12 object-cover rounded"}):e.jsx("div",{className:"w-12 h-12 bg-muted rounded flex items-center justify-center",children:e.jsx(nl,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(ut,{className:"font-medium",children:M.title}),e.jsxs(ut,{children:[((F=M.links)==null?void 0:F.length)||0," links"]}),e.jsx(ut,{children:new Date(M.publish_date).toLocaleDateString()}),e.jsx(ut,{children:e.jsx(ze,{variant:M.is_published?"default":"secondary",children:M.is_published?"Published":"Draft"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>window.open(`/social-swag/${M.id}`,"_blank"),children:e.jsx(Er,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>b(M),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this item?")&&v.mutate(M.id)},children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},M.id)})})]})})})]})})};function v_s(){for(var s=arguments.length,t=new Array(s),n=0;nr=>{t.forEach(a=>a(r))},t)}const Nve=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function tR(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function QIe(s){return"nodeType"in s}function i0(s){var t,n;return s?tR(s)?s:QIe(s)&&(t=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function XIe(s){const{Document:t}=i0(s);return s instanceof t}function CU(s){return tR(s)?!1:s instanceof i0(s).HTMLElement}function lyt(s){return s instanceof i0(s).SVGElement}function sR(s){return s?tR(s)?s.document:QIe(s)?XIe(s)?s:CU(s)||lyt(s)?s.ownerDocument:document:document:document}const Dw=Nve?N.useLayoutEffect:N.useEffect;function JIe(s){const t=N.useRef(s);return Dw(()=>{t.current=s}),N.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a{s.current=setInterval(r,a)},[]),n=N.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[t,n]}function PB(s,t){t===void 0&&(t=[s]);const n=N.useRef(s);return Dw(()=>{n.current!==s&&(n.current=s)},t),n}function TU(s,t){const n=N.useRef();return N.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...t])}function Ixe(s){const t=JIe(s),n=N.useRef(null),r=N.useCallback(a=>{a!==n.current&&(t==null||t(a,n.current)),n.current=a},[]);return[n,r]}function v3e(s){const t=N.useRef();return N.useEffect(()=>{t.current=s},[s]),t.current}let $2e={};function EU(s,t){return N.useMemo(()=>{if(t)return t;const n=$2e[s]==null?0:$2e[s]+1;return $2e[s]=n,s+"-"+n},[s,t])}function cyt(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 zL=cyt(1),LB=cyt(-1);function __s(s){return"clientX"in s&&"clientY"in s}function ePe(s){if(!s)return!1;const{KeyboardEvent:t}=i0(s.target);return t&&s instanceof t}function w_s(s){if(!s)return!1;const{TouchEvent:t}=i0(s.target);return t&&s instanceof t}function b3e(s){if(w_s(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 __s(s)?{x:s.clientX,y:s.clientY}:null}const O4=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[O4.Translate.toString(s),O4.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:n,easing:r}=s;return t+" "+n+"ms "+r}}}),GHe="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function j_s(s){return s.matches(GHe)?s:s.querySelector(GHe)}const N_s={display:"none"};function k_s(s){let{id:t,value:n}=s;return St.createElement("div",{id:t,style:N_s},n)}function S_s(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 St.createElement("div",{id:t,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function C_s(){const[s,t]=N.useState("");return{announce:N.useCallback(r=>{r!=null&&t(r)},[]),announcement:s}}const dyt=N.createContext(null);function T_s(s){const t=N.useContext(dyt);N.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function E_s(){const[s]=N.useState(()=>new Set),t=N.useCallback(r=>(s.add(r),()=>s.delete(r)),[s]);return[N.useCallback(r=>{let{type:a,event:i}=r;s.forEach(l=>{var o;return(o=l[a])==null?void 0:o.call(l,i)})},[s]),t]}const A_s={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. `},M_s={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 I_s(s){let{announcements:t=M_s,container:n,hiddenTextDescribedById:r,screenReaderInstructions:a=A_s}=s;const{announce:i,announcement:l}=C_s(),o=EU("DndLiveRegion"),[c,d]=N.useState(!1);if(N.useEffect(()=>{d(!0)},[]),T_s(N.useMemo(()=>({onDragStart(h){let{active:p}=h;i(t.onDragStart({active:p}))},onDragMove(h){let{active:p,over:f}=h;t.onDragMove&&i(t.onDragMove({active:p,over:f}))},onDragOver(h){let{active:p,over:f}=h;i(t.onDragOver({active:p,over:f}))},onDragEnd(h){let{active:p,over:f}=h;i(t.onDragEnd({active:p,over:f}))},onDragCancel(h){let{active:p,over:f}=h;i(t.onDragCancel({active:p,over:f}))}}),[i,t])),!c)return null;const u=St.createElement(St.Fragment,null,St.createElement(k_s,{id:r,value:a.draggable}),St.createElement(S_s,{id:o,announcement:l}));return n?Hx.createPortal(u,n):u}var Pm;(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"})(Pm||(Pm={}));function Pxe(){}function R8(s,t){return N.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function kve(){for(var s=arguments.length,t=new Array(s),n=0;n[...t].filter(r=>r!=null),[...t])}const Mb=Object.freeze({x:0,y:0});function uyt(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function hyt(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return n-r}function P_s(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return r-n}function WHe(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 myt(s,t){if(!s||s.length===0)return null;const[n]=s;return n[t]}function KHe(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 Sve=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=KHe(t,t.left,t.top),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=uyt(KHe(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(hyt)},L_s=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=WHe(t),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=WHe(c),u=a.reduce((p,f,g)=>p+uyt(d[g],f),0),h=Number((u/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:h}})}}return i.sort(hyt)};function D_s(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=D_s(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort(P_s)};function O_s(s,t,n){return{...s,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function pyt(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:Mb}function F_s(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 z_s=F_s(1);function B_s(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 $_s(s,t,n){const r=B_s(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 U_s={ignoreTransform:!1};function nR(s,t){t===void 0&&(t=U_s);let n=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=i0(s).getComputedStyle(s);d&&(n=$_s(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 YHe(s){return nR(s,{ignoreTransform:!0})}function q_s(s){const t=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function V_s(s,t){return t===void 0&&(t=i0(s).getComputedStyle(s)),t.position==="fixed"}function H_s(s,t){t===void 0&&(t=i0(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 Cve(s,t){const n=[];function r(a){if(t!=null&&n.length>=t||!a)return n;if(XIe(a)&&a.scrollingElement!=null&&!n.includes(a.scrollingElement))return n.push(a.scrollingElement),n;if(!CU(a)||lyt(a)||n.includes(a))return n;const i=i0(s).getComputedStyle(a);return a!==s&&H_s(a,i)&&n.push(a),V_s(a,i)?n:r(a.parentNode)}return s?r(s):n}function fyt(s){const[t]=Cve(s,1);return t??null}function U2e(s){return!Nve||!s?null:tR(s)?s:QIe(s)?XIe(s)||s===sR(s).scrollingElement?window:CU(s)?s:null:null}function xyt(s){return tR(s)?s.scrollX:s.scrollLeft}function gyt(s){return tR(s)?s.scrollY:s.scrollTop}function _3e(s){return{x:xyt(s),y:gyt(s)}}var _p;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(_p||(_p={}));function yyt(s){return!Nve||!s?!1:s===document.scrollingElement}function vyt(s){const t={x:0,y:0},n=yyt(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 G_s={x:.2,y:.2};function W_s(s,t,n,r,a){let{top:i,left:l,right:o,bottom:c}=n;r===void 0&&(r=10),a===void 0&&(a=G_s);const{isTop:d,isBottom:u,isLeft:h,isRight:p}=vyt(s),f={x:0,y:0},g={x:0,y:0},_={height:t.height*a.y,width:t.width*a.x};return!d&&i<=t.top+_.height?(f.y=_p.Backward,g.y=r*Math.abs((t.top+_.height-i)/_.height)):!u&&c>=t.bottom-_.height&&(f.y=_p.Forward,g.y=r*Math.abs((t.bottom-_.height-c)/_.height)),!p&&o>=t.right-_.width?(f.x=_p.Forward,g.x=r*Math.abs((t.right-_.width-o)/_.width)):!h&&l<=t.left+_.width&&(f.x=_p.Backward,g.x=r*Math.abs((t.left+_.width-l)/_.width)),{direction:f,speed:g}}function K_s(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 byt(s){return s.reduce((t,n)=>zL(t,_3e(n)),Mb)}function Y_s(s){return s.reduce((t,n)=>t+xyt(n),0)}function Z_s(s){return s.reduce((t,n)=>t+gyt(n),0)}function Q_s(s,t){if(t===void 0&&(t=nR),!s)return;const{top:n,left:r,bottom:a,right:i}=t(s);fyt(s)&&(a<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const X_s=[["x",["left","right"],Y_s],["y",["top","bottom"],Z_s]];class tPe{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=Cve(n),a=byt(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of X_s)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 yz{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 J_s(s){const{EventTarget:t}=i0(s);return s instanceof t?s:sR(s)}function q2e(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 vv;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(vv||(vv={}));function ZHe(s){s.preventDefault()}function ews(s){s.stopPropagation()}var Sl;(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"})(Sl||(Sl={}));const _yt={start:[Sl.Space,Sl.Enter],cancel:[Sl.Esc],end:[Sl.Space,Sl.Enter,Sl.Tab]},tws=(s,t)=>{let{currentCoordinates:n}=t;switch(s.code){case Sl.Right:return{...n,x:n.x+25};case Sl.Left:return{...n,x:n.x-25};case Sl.Down:return{...n,y:n.y+25};case Sl.Up:return{...n,y:n.y-25}}};class Tve{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 yz(sR(n)),this.windowListeners=new yz(i0(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(vv.Resize,this.handleCancel),this.windowListeners.add(vv.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(vv.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&Q_s(r),n(Mb)}handleKeyDown(t){if(ePe(t)){const{active:n,context:r,options:a}=this.props,{keyboardCodes:i=_yt,coordinateGetter:l=tws,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}:Mb;this.referenceCoordinates||(this.referenceCoordinates=u);const h=l(t,{active:n,context:r.current,currentCoordinates:u});if(h){const p=LB(h,u),f={x:0,y:0},{scrollableAncestors:g}=r.current;for(const _ of g){const v=t.code,{isTop:j,isRight:b,isLeft:S,isBottom:A,maxScroll:T,minScroll:L}=vyt(_),D=K_s(_),M={x:Math.min(v===Sl.Right?D.right-D.width/2:D.right,Math.max(v===Sl.Right?D.left:D.left+D.width/2,h.x)),y:Math.min(v===Sl.Down?D.bottom-D.height/2:D.bottom,Math.max(v===Sl.Down?D.top:D.top+D.height/2,h.y))},F=v===Sl.Right&&!b||v===Sl.Left&&!S,z=v===Sl.Down&&!A||v===Sl.Up&&!j;if(F&&M.x!==h.x){const V=_.scrollLeft+p.x,W=v===Sl.Right&&V<=T.x||v===Sl.Left&&V>=L.x;if(W&&!p.y){_.scrollTo({left:V,behavior:o});return}W?f.x=_.scrollLeft-V:f.x=v===Sl.Right?_.scrollLeft-T.x:_.scrollLeft-L.x,f.x&&_.scrollBy({left:-f.x,behavior:o});break}else if(z&&M.y!==h.y){const V=_.scrollTop+p.y,W=v===Sl.Down&&V<=T.y||v===Sl.Up&&V>=L.y;if(W&&!p.x){_.scrollTo({top:V,behavior:o});return}W?f.y=_.scrollTop-V:f.y=v===Sl.Down?_.scrollTop-T.y:_.scrollTop-L.y,f.y&&_.scrollBy({top:-f.y,behavior:o});break}}this.handleMove(t,zL(LB(h,this.referenceCoordinates),f))}}}handleMove(t,n){const{onMove:r}=this.props;t.preventDefault(),r(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}Tve.activators=[{eventName:"onKeyDown",handler:(s,t,n)=>{let{keyboardCodes:r=_yt,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 QHe(s){return!!(s&&"distance"in s)}function XHe(s){return!!(s&&"delay"in s)}class sPe{constructor(t,n,r){var a;r===void 0&&(r=J_s(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=sR(l),this.documentListeners=new yz(this.document),this.listeners=new yz(r),this.windowListeners=new yz(i0(l)),this.initialCoordinates=(a=b3e(i))!=null?a:Mb,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(vv.Resize,this.handleCancel),this.windowListeners.add(vv.DragStart,ZHe),this.windowListeners.add(vv.VisibilityChange,this.handleCancel),this.windowListeners.add(vv.ContextMenu,ZHe),this.documentListeners.add(vv.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(XHe(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(QHe(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(vv.Click,ews,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(vv.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=b3e(t))!=null?n:Mb,d=LB(a,c);if(!r&&o){if(QHe(o)){if(o.tolerance!=null&&q2e(d,o.tolerance))return this.handleCancel();if(q2e(d,o.distance))return this.handleStart()}if(XHe(o)&&q2e(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===Sl.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const sws={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class rR extends sPe{constructor(t){const{event:n}=t,r=sR(n.target);super(t,sws,r)}}rR.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 nws={move:{name:"mousemove"},end:{name:"mouseup"}};var w3e;(function(s){s[s.RightClick=2]="RightClick"})(w3e||(w3e={}));class rws extends sPe{constructor(t){super(t,nws,sR(t.event.target))}}rws.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;return n.button===w3e.RightClick?!1:(r==null||r({event:n}),!0)}}];const V2e={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class aws extends sPe{constructor(t){super(t,V2e)}static setup(){return window.addEventListener(V2e.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(V2e.move.name,t)};function t(){}}}aws.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 vz;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(vz||(vz={}));var Lxe;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(Lxe||(Lxe={}));function iws(s){let{acceleration:t,activator:n=vz.Pointer,canScroll:r,draggingRect:a,enabled:i,interval:l=5,order:o=Lxe.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:h,threshold:p}=s;const f=lws({delta:h,disabled:!i}),[g,_]=b_s(),v=N.useRef({x:0,y:0}),j=N.useRef({x:0,y:0}),b=N.useMemo(()=>{switch(n){case vz.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case vz.DraggableRect:return a}},[n,a,c]),S=N.useRef(null),A=N.useCallback(()=>{const L=S.current;if(!L)return;const D=v.current.x*j.current.x,M=v.current.y*j.current.y;L.scrollBy(D,M)},[]),T=N.useMemo(()=>o===Lxe.TreeOrder?[...d].reverse():d,[o,d]);N.useEffect(()=>{if(!i||!d.length||!b){_();return}for(const L of T){if((r==null?void 0:r(L))===!1)continue;const D=d.indexOf(L),M=u[D];if(!M)continue;const{direction:F,speed:z}=W_s(L,M,b,t,p);for(const V of["x","y"])f[V][F[V]]||(z[V]=0,F[V]=0);if(z.x>0||z.y>0){_(),S.current=L,g(A,l),v.current=z,j.current=F;return}}v.current={x:0,y:0},j.current={x:0,y:0},_()},[t,A,r,_,i,l,JSON.stringify(b),JSON.stringify(f),g,d,T,u,JSON.stringify(p)])}const ows={x:{[_p.Backward]:!1,[_p.Forward]:!1},y:{[_p.Backward]:!1,[_p.Forward]:!1}};function lws(s){let{delta:t,disabled:n}=s;const r=v3e(t);return TU(a=>{if(n||!r||!a)return ows;const i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[_p.Backward]:a.x[_p.Backward]||i.x===-1,[_p.Forward]:a.x[_p.Forward]||i.x===1},y:{[_p.Backward]:a.y[_p.Backward]||i.y===-1,[_p.Forward]:a.y[_p.Forward]||i.y===1}}},[n,t,r])}function cws(s,t){const n=t!=null?s.get(t):void 0,r=n?n.node.current:null;return TU(a=>{var i;return t==null?null:(i=r??a)!=null?i:null},[r,t])}function dws(s,t){return N.useMemo(()=>s.reduce((n,r)=>{const{sensor:a}=r,i=a.activators.map(l=>({eventName:l.eventName,handler:t(l.handler,r)}));return[...n,...i]},[]),[s,t])}var DB;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(DB||(DB={}));var j3e;(function(s){s.Optimized="optimized"})(j3e||(j3e={}));const JHe=new Map;function uws(s,t){let{dragging:n,dependencies:r,config:a}=t;const[i,l]=N.useState(null),{frequency:o,measure:c,strategy:d}=a,u=N.useRef(s),h=v(),p=PB(h),f=N.useCallback(function(j){j===void 0&&(j=[]),!p.current&&l(b=>b===null?j:b.concat(j.filter(S=>!b.includes(S))))},[p]),g=N.useRef(null),_=TU(j=>{if(h&&!n)return JHe;if(!j||j===JHe||u.current!==s||i!=null){const b=new Map;for(let S of s){if(!S)continue;if(i&&i.length>0&&!i.includes(S.id)&&S.rect.current){b.set(S.id,S.rect.current);continue}const A=S.node.current,T=A?new tPe(c(A),A):null;S.rect.current=T,T&&b.set(S.id,T)}return b}return j},[s,i,n,h,c]);return N.useEffect(()=>{u.current=s},[s]),N.useEffect(()=>{h||f()},[n,h]),N.useEffect(()=>{i&&i.length>0&&l(null)},[JSON.stringify(i)]),N.useEffect(()=>{h||typeof o!="number"||g.current!==null||(g.current=setTimeout(()=>{f(),g.current=null},o))},[o,h,f,...r]),{droppableRects:_,measureDroppableContainers:f,measuringScheduled:i!=null};function v(){switch(d){case DB.Always:return!1;case DB.BeforeDragging:return n;default:return!n}}}function wyt(s,t){return TU(n=>s?n||(typeof t=="function"?t(s):s):null,[t,s])}function hws(s,t){return wyt(s,t)}function mws(s){let{callback:t,disabled:n}=s;const r=JIe(t),a=N.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(r)},[r,n]);return N.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function Eve(s){let{callback:t,disabled:n}=s;const r=JIe(t),a=N.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(r)},[n]);return N.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function pws(s){return new tPe(nR(s),s)}function eGe(s,t,n){t===void 0&&(t=pws);const[r,a]=N.useState(null);function i(){a(c=>{if(!s)return null;if(s.isConnected===!1){var d;return(d=c??n)!=null?d:null}const u=t(s);return JSON.stringify(c)===JSON.stringify(u)?c:u})}const l=mws({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=Eve({callback:i});return Dw(()=>{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 fws(s){const t=wyt(s);return pyt(s,t)}const tGe=[];function xws(s){const t=N.useRef(s),n=TU(r=>s?r&&r!==tGe&&s&&t.current&&s.parentNode===t.current.parentNode?r:Cve(s):tGe,[s]);return N.useEffect(()=>{t.current=s},[s]),n}function gws(s){const[t,n]=N.useState(null),r=N.useRef(s),a=N.useCallback(i=>{const l=U2e(i.target);l&&n(o=>o?(o.set(l,_3e(l)),new Map(o)):null)},[]);return N.useEffect(()=>{const i=r.current;if(s!==i){l(i);const o=s.map(c=>{const d=U2e(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,_3e(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=U2e(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),N.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>zL(i,l),Mb):byt(s):Mb,[s,t])}function sGe(s,t){t===void 0&&(t=[]);const n=N.useRef(null);return N.useEffect(()=>{n.current=null},t),N.useEffect(()=>{const r=s!==Mb;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?LB(s,n.current):Mb}function yws(s){N.useEffect(()=>{if(!Nve)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 vws(s,t){return N.useMemo(()=>s.reduce((n,r)=>{let{eventName:a,handler:i}=r;return n[a]=l=>{i(l,t)},n},{}),[s,t])}function jyt(s){return N.useMemo(()=>s?q_s(s):null,[s])}const nGe=[];function bws(s,t){t===void 0&&(t=nR);const[n]=s,r=jyt(n?i0(n):null),[a,i]=N.useState(nGe);function l(){i(()=>s.length?s.map(c=>yyt(c)?r:new tPe(t(c),c)):nGe)}const o=Eve({callback:l});return Dw(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function _ws(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return CU(t)?t:s}function wws(s){let{measure:t}=s;const[n,r]=N.useState(null),a=N.useCallback(d=>{for(const{target:u}of d)if(CU(u)){r(h=>{const p=t(u);return h?{...h,width:p.width,height:p.height}:p});break}},[t]),i=Eve({callback:a}),l=N.useCallback(d=>{const u=_ws(d);i==null||i.disconnect(),u&&(i==null||i.observe(u)),r(u?t(u):null)},[t,i]),[o,c]=Ixe(l);return N.useMemo(()=>({nodeRef:o,rect:n,setRef:c}),[n,o,c])}const jws=[{sensor:rR,options:{}},{sensor:Tve,options:{}}],Nws={current:{}},spe={draggable:{measure:YHe},droppable:{measure:YHe,strategy:DB.WhileDragging,frequency:j3e.Optimized},dragOverlay:{measure:nR}};class bz 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 kws={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new bz,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Pxe},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:spe,measureDroppableContainers:Pxe,windowRect:null,measuringScheduled:!1},Sws={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Pxe,draggableNodes:new Map,over:null,measureDroppableContainers:Pxe},Ave=N.createContext(Sws),Nyt=N.createContext(kws);function Cws(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new bz}}}function Tws(s,t){switch(t.type){case Pm.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case Pm.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 Pm.DragEnd:case Pm.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Pm.RegisterDroppable:{const{element:n}=t,{id:r}=n,a=new bz(s.droppable.containers);return a.set(r,n),{...s,droppable:{...s.droppable,containers:a}}}case Pm.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 bz(s.droppable.containers);return l.set(n,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case Pm.UnregisterDroppable:{const{id:n,key:r}=t,a=s.droppable.containers.get(n);if(!a||r!==a.key)return s;const i=new bz(s.droppable.containers);return i.delete(n),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function Ews(s){let{disabled:t}=s;const{active:n,activatorEvent:r,draggableNodes:a}=N.useContext(Ave),i=v3e(r),l=v3e(n==null?void 0:n.id);return N.useEffect(()=>{if(!t&&!r&&i&&l!=null){if(!ePe(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=j_s(u);if(h){h.focus();break}}})}},[r,t,a,l,i]),null}function Aws(s,t){let{transform:n,...r}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...r}),n):n}function Mws(s){return N.useMemo(()=>({draggable:{...spe.draggable,...s==null?void 0:s.draggable},droppable:{...spe.droppable,...s==null?void 0:s.droppable},dragOverlay:{...spe.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 Iws(s){let{activeNode:t,measure:n,initialRect:r,config:a=!0}=s;const i=N.useRef(!1),{x:l,y:o}=typeof a=="boolean"?{x:a,y:a}:a;Dw(()=>{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=pyt(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 p=fyt(d);p&&p.scrollBy({top:h.y,left:h.x})}},[t,l,o,r,n])}const kyt=N.createContext({...Mb,scaleX:1,scaleY:1});var sS;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(sS||(sS={}));const Mve=N.memo(function(t){var n,r,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:u=jws,collisionDetection:h=R_s,measuring:p,modifiers:f,...g}=t;const _=N.useReducer(Tws,void 0,Cws),[v,j]=_,[b,S]=E_s(),[A,T]=N.useState(sS.Uninitialized),L=A===sS.Initialized,{draggable:{active:D,nodes:M,translate:F},droppable:{containers:z}}=v,V=D!=null?M.get(D):null,W=N.useRef({initial:null,translated:null}),Y=N.useMemo(()=>{var rn;return D!=null?{id:D,data:(rn=V==null?void 0:V.data)!=null?rn:Nws,rect:W}:null},[D,V]),K=N.useRef(null),[J,ne]=N.useState(null),[ie,he]=N.useState(null),ce=PB(g,Object.values(g)),pe=EU("DndDescribedBy",l),le=N.useMemo(()=>z.getEnabled(),[z]),ve=Mws(p),{droppableRects:ge,measureDroppableContainers:Te,measuringScheduled:Me}=uws(le,{dragging:L,dependencies:[F.x,F.y],config:ve.droppable}),Ce=cws(M,D),Ae=N.useMemo(()=>ie?b3e(ie):null,[ie]),De=As(),Ie=hws(Ce,ve.draggable.measure);Iws({activeNode:D!=null?M.get(D):null,config:De.layoutShiftCompensation,initialRect:Ie,measure:ve.draggable.measure});const Fe=eGe(Ce,ve.draggable.measure,Ie),qe=eGe(Ce?Ce.parentElement:null),be=N.useRef({activatorEvent:null,active:null,activeNode:Ce,collisionRect:null,collisions:null,droppableRects:ge,draggableNodes:M,draggingNode:null,draggingNodeRect:null,droppableContainers:z,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Ze=z.getNodeFor((n=be.current.over)==null?void 0:n.id),Ne=wws({measure:ve.dragOverlay.measure}),it=(r=Ne.nodeRef.current)!=null?r:Ce,je=L?(a=Ne.rect)!=null?a:Fe:null,Ge=!!(Ne.nodeRef.current&&Ne.rect),Be=fws(Ge?null:Fe),Ye=jyt(it?i0(it):null),We=xws(L?Ze??Ce:null),rt=bws(We),tt=Aws(f,{transform:{x:F.x-Be.x,y:F.y-Be.y,scaleX:1,scaleY:1},activatorEvent:ie,active:Y,activeNodeRect:Fe,containerNodeRect:qe,draggingNodeRect:je,over:be.current.over,overlayNodeRect:Ne.rect,scrollableAncestors:We,scrollableAncestorRects:rt,windowRect:Ye}),at=Ae?zL(Ae,F):null,He=gws(We),dt=sGe(He),bt=sGe(He,[Fe]),vt=zL(tt,dt),Bt=je?z_s(je,tt):null,Zt=Y&&Bt?h({active:Y,collisionRect:Bt,droppableRects:ge,droppableContainers:le,pointerCoordinates:at}):null,Fs=myt(Zt,"id"),[Rs,ms]=N.useState(null),Pt=Ge?tt:zL(tt,bt),Jt=O_s(Pt,(i=Rs==null?void 0:Rs.rect)!=null?i:null,Fe),ft=N.useRef(null),Vt=N.useCallback((rn,tn)=>{let{sensor:er,options:gn}=tn;if(K.current==null)return;const In=M.get(K.current);if(!In)return;const Zn=rn.nativeEvent,ea=new er({active:K.current,activeNode:In,event:Zn,options:gn,context:be,onAbort(Ls){if(!M.get(Ls))return;const{onDragAbort:Lr}=ce.current,Jn={id:Ls};Lr==null||Lr(Jn),b({type:"onDragAbort",event:Jn})},onPending(Ls,fi,Lr,Jn){if(!M.get(Ls))return;const{onDragPending:Dn}=ce.current,wr={id:Ls,constraint:fi,initialCoordinates:Lr,offset:Jn};Dn==null||Dn(wr),b({type:"onDragPending",event:wr})},onStart(Ls){const fi=K.current;if(fi==null)return;const Lr=M.get(fi);if(!Lr)return;const{onDragStart:Jn}=ce.current,js={activatorEvent:Zn,active:{id:fi,data:Lr.data,rect:W}};Hx.unstable_batchedUpdates(()=>{Jn==null||Jn(js),T(sS.Initializing),j({type:Pm.DragStart,initialCoordinates:Ls,active:fi}),b({type:"onDragStart",event:js}),ne(ft.current),he(Zn)})},onMove(Ls){j({type:Pm.DragMove,coordinates:Ls})},onEnd:vi(Pm.DragEnd),onCancel:vi(Pm.DragCancel)});ft.current=ea;function vi(Ls){return async function(){const{active:Lr,collisions:Jn,over:js,scrollAdjustedTranslate:Dn}=be.current;let wr=null;if(Lr&&Dn){const{cancelDrop:$r}=ce.current;wr={activatorEvent:Zn,active:Lr,collisions:Jn,delta:Dn,over:js},Ls===Pm.DragEnd&&typeof $r=="function"&&await Promise.resolve($r(wr))&&(Ls=Pm.DragCancel)}K.current=null,Hx.unstable_batchedUpdates(()=>{j({type:Ls}),T(sS.Uninitialized),ms(null),ne(null),he(null),ft.current=null;const $r=Ls===Pm.DragEnd?"onDragEnd":"onDragCancel";if(wr){const ss=ce.current[$r];ss==null||ss(wr),b({type:$r,event:wr})}})}}},[M]),Ms=N.useCallback((rn,tn)=>(er,gn)=>{const In=er.nativeEvent,Zn=M.get(gn);if(K.current!==null||!Zn||In.dndKit||In.defaultPrevented)return;const ea={active:Zn};rn(er,tn.options,ea)===!0&&(In.dndKit={capturedBy:tn.sensor},K.current=gn,Vt(er,tn))},[M,Vt]),Xt=dws(u,Ms);yws(u),Dw(()=>{Fe&&A===sS.Initializing&&T(sS.Initialized)},[Fe,A]),N.useEffect(()=>{const{onDragMove:rn}=ce.current,{active:tn,activatorEvent:er,collisions:gn,over:In}=be.current;if(!tn||!er)return;const Zn={active:tn,activatorEvent:er,collisions:gn,delta:{x:vt.x,y:vt.y},over:In};Hx.unstable_batchedUpdates(()=>{rn==null||rn(Zn),b({type:"onDragMove",event:Zn})})},[vt.x,vt.y]),N.useEffect(()=>{const{active:rn,activatorEvent:tn,collisions:er,droppableContainers:gn,scrollAdjustedTranslate:In}=be.current;if(!rn||K.current==null||!tn||!In)return;const{onDragOver:Zn}=ce.current,ea=gn.get(Fs),vi=ea&&ea.rect.current?{id:ea.id,rect:ea.rect.current,data:ea.data,disabled:ea.disabled}:null,Ls={active:rn,activatorEvent:tn,collisions:er,delta:{x:In.x,y:In.y},over:vi};Hx.unstable_batchedUpdates(()=>{ms(vi),Zn==null||Zn(Ls),b({type:"onDragOver",event:Ls})})},[Fs]),Dw(()=>{be.current={activatorEvent:ie,active:Y,activeNode:Ce,collisionRect:Bt,collisions:Zt,droppableRects:ge,draggableNodes:M,draggingNode:it,draggingNodeRect:je,droppableContainers:z,over:Rs,scrollableAncestors:We,scrollAdjustedTranslate:vt},W.current={initial:je,translated:Bt}},[Y,Ce,Zt,Bt,M,it,je,ge,z,Rs,We,vt]),iws({...De,delta:F,draggingRect:Bt,pointerCoordinates:at,scrollableAncestors:We,scrollableAncestorRects:rt});const Js=N.useMemo(()=>({active:Y,activeNode:Ce,activeNodeRect:Fe,activatorEvent:ie,collisions:Zt,containerNodeRect:qe,dragOverlay:Ne,draggableNodes:M,droppableContainers:z,droppableRects:ge,over:Rs,measureDroppableContainers:Te,scrollableAncestors:We,scrollableAncestorRects:rt,measuringConfiguration:ve,measuringScheduled:Me,windowRect:Ye}),[Y,Ce,Fe,ie,Zt,qe,Ne,M,z,ge,Rs,Te,We,rt,ve,Me,Ye]),Cs=N.useMemo(()=>({activatorEvent:ie,activators:Xt,active:Y,activeNodeRect:Fe,ariaDescribedById:{draggable:pe},dispatch:j,draggableNodes:M,over:Rs,measureDroppableContainers:Te}),[ie,Xt,Y,Fe,j,pe,M,Rs,Te]);return St.createElement(dyt.Provider,{value:S},St.createElement(Ave.Provider,{value:Cs},St.createElement(Nyt.Provider,{value:Js},St.createElement(kyt.Provider,{value:Jt},d)),St.createElement(Ews,{disabled:(o==null?void 0:o.restoreFocus)===!1})),St.createElement(I_s,{...o,hiddenTextDescribedById:pe}));function As(){const rn=(J==null?void 0:J.autoScrollEnabled)===!1,tn=typeof c=="object"?c.enabled===!1:c===!1,er=L&&!rn&&!tn;return typeof c=="object"?{...c,enabled:er}:{enabled:er}}}),Pws=N.createContext(null),rGe="button",Lws="Draggable";function Dws(s){let{id:t,data:n,disabled:r=!1,attributes:a}=s;const i=EU(Lws),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:p}=N.useContext(Ave),{role:f=rGe,roleDescription:g="draggable",tabIndex:_=0}=a??{},v=(c==null?void 0:c.id)===t,j=N.useContext(v?kyt:Pws),[b,S]=Ixe(),[A,T]=Ixe(),L=vws(l,t),D=PB(n);Dw(()=>(h.set(t,{id:t,key:i,node:b,activatorNode:A,data:D}),()=>{const F=h.get(t);F&&F.key===i&&h.delete(t)}),[h,t]);const M=N.useMemo(()=>({role:f,tabIndex:_,"aria-disabled":r,"aria-pressed":v&&f===rGe?!0:void 0,"aria-roledescription":g,"aria-describedby":u.draggable}),[r,f,_,v,g,u.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:M,isDragging:v,listeners:r?void 0:L,node:b,over:p,setNodeRef:S,setActivatorNodeRef:T,transform:j}}function Rws(){return N.useContext(Nyt)}const Ows="Droppable",Fws={timeout:25};function zws(s){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:a}=s;const i=EU(Ows),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=N.useContext(Ave),u=N.useRef({disabled:n}),h=N.useRef(!1),p=N.useRef(null),f=N.useRef(null),{disabled:g,updateMeasurementsFor:_,timeout:v}={...Fws,...a},j=PB(_??r),b=N.useCallback(()=>{if(!h.current){h.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{d(Array.isArray(j.current)?j.current:[j.current]),f.current=null},v)},[v]),S=Eve({callback:b,disabled:g||!l}),A=N.useCallback((M,F)=>{S&&(F&&(S.unobserve(F),h.current=!1),M&&S.observe(M))},[S]),[T,L]=Ixe(A),D=PB(t);return N.useEffect(()=>{!S||!T.current||(S.disconnect(),h.current=!1,S.observe(T.current))},[T,S]),N.useEffect(()=>(o({type:Pm.RegisterDroppable,element:{id:r,key:i,disabled:n,node:T,rect:p,data:D}}),()=>o({type:Pm.UnregisterDroppable,key:i,id:r})),[r]),N.useEffect(()=>{n!==u.current.disabled&&(o({type:Pm.SetDroppableDisabled,id:r,key:i,disabled:n}),u.current.disabled=n)},[r,i,n,o]),{active:l,rect:p,isOver:(c==null?void 0:c.id)===r,node:T,over:c,setNodeRef:L}}function Ive(s,t,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function Bws(s,t){return s.reduce((n,r,a)=>{const i=t.get(r);return i&&(n[a]=i),n},Array(s.length))}function KH(s){return s!==null&&s>=0}function $ws(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=qws(n,l,a);if(l===a){const d=n[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...YH}:l=i?{x:o.width+c,y:0,...YH}:{x:0,y:0,...YH}};function qws(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=Ive(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}},ZH={scaleX:1,scaleY:1},Vws=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,...ZH}:a=l?{x:0,y:o.height+c,...ZH}:{x:0,y:0,...ZH}};function Hws(s,t,n){const r=s[t],a=s[t-1],i=s[t+1];return r?nr.map(L=>typeof L=="object"&&"id"in L?L.id:L),[r]),g=l!=null,_=l?f.indexOf(l.id):-1,v=d?f.indexOf(d.id):-1,j=N.useRef(f),b=!$ws(f,j.current),S=v!==-1&&_===-1||b,A=Uws(i);Dw(()=>{b&&g&&u(f)},[b,f,g,u]),N.useEffect(()=>{j.current=f},[f]);const T=N.useMemo(()=>({activeIndex:_,containerId:h,disabled:A,disableTransforms:S,items:f,overIndex:v,useDragOverlay:p,sortedRects:Bws(f,c),strategy:a}),[_,h,A.draggable,A.droppable,S,f,v,c,p,a]);return St.createElement(Cyt.Provider,{value:T},t)}const Gws=s=>{let{id:t,items:n,activeIndex:r,overIndex:a}=s;return Ive(n,r,a).indexOf(t)},Wws=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},Kws={duration:200,easing:"ease"},Tyt="transform",Yws=O4.Transition.toString({property:Tyt,duration:0,easing:"linear"}),Zws={roleDescription:"sortable"};function Qws(s){let{disabled:t,index:n,node:r,rect:a}=s;const[i,l]=N.useState(null),o=N.useRef(n);return Dw(()=>{if(!t&&n!==o.current&&r.current){const c=a.current;if(c){const d=nR(r.current,{ignoreTransform:!0}),u={x:c.left-d.left,y:c.top-d.top,scaleX:c.width/d.width,scaleY:c.height/d.height};(u.x||u.y)&&l(u)}}n!==o.current&&(o.current=n)},[t,n,r,a]),N.useEffect(()=>{i&&l(null)},[i]),i}function Lve(s){let{animateLayoutChanges:t=Wws,attributes:n,disabled:r,data:a,getNewIndex:i=Gws,id:l,strategy:o,resizeObserverConfig:c,transition:d=Kws}=s;const{items:u,containerId:h,activeIndex:p,disabled:f,disableTransforms:g,sortedRects:_,overIndex:v,useDragOverlay:j,strategy:b}=N.useContext(Cyt),S=Xws(r,f),A=u.indexOf(l),T=N.useMemo(()=>({sortable:{containerId:h,index:A,items:u},...a}),[h,a,A,u]),L=N.useMemo(()=>u.slice(u.indexOf(l)),[u,l]),{rect:D,node:M,isOver:F,setNodeRef:z}=zws({id:l,data:T,disabled:S.droppable,resizeObserverConfig:{updateMeasurementsFor:L,...c}}),{active:V,activatorEvent:W,activeNodeRect:Y,attributes:K,setNodeRef:J,listeners:ne,isDragging:ie,over:he,setActivatorNodeRef:ce,transform:pe}=Dws({id:l,data:T,attributes:{...Zws,...n},disabled:S.draggable}),le=v_s(z,J),ve=!!V,ge=ve&&!g&&KH(p)&&KH(v),Te=!j&&ie,Me=Te&&ge?pe:null,Ae=ge?Me??(o??b)({rects:_,activeNodeRect:Y,activeIndex:p,overIndex:v,index:A}):null,De=KH(p)&&KH(v)?i({id:l,items:u,activeIndex:p,overIndex:v}):A,Ie=V==null?void 0:V.id,Fe=N.useRef({activeId:Ie,items:u,newIndex:De,containerId:h}),qe=u!==Fe.current.items,be=t({active:V,containerId:h,isDragging:ie,isSorting:ve,id:l,index:A,items:u,newIndex:Fe.current.newIndex,previousItems:Fe.current.items,previousContainerId:Fe.current.containerId,transition:d,wasDragging:Fe.current.activeId!=null}),Ze=Qws({disabled:!be,index:A,node:M,rect:D});return N.useEffect(()=>{ve&&Fe.current.newIndex!==De&&(Fe.current.newIndex=De),h!==Fe.current.containerId&&(Fe.current.containerId=h),u!==Fe.current.items&&(Fe.current.items=u)},[ve,De,h,u]),N.useEffect(()=>{if(Ie===Fe.current.activeId)return;if(Ie!=null&&Fe.current.activeId==null){Fe.current.activeId=Ie;return}const it=setTimeout(()=>{Fe.current.activeId=Ie},50);return()=>clearTimeout(it)},[Ie]),{active:V,activeIndex:p,attributes:K,data:T,rect:D,index:A,newIndex:De,items:u,isOver:F,isSorting:ve,isDragging:ie,listeners:ne,node:M,overIndex:v,over:he,setNodeRef:le,setActivatorNodeRef:ce,setDroppableNodeRef:z,setDraggableNodeRef:J,transform:Ze??Ae,transition:Ne()};function Ne(){if(Ze||qe&&Fe.current.newIndex===A)return Yws;if(!(Te&&!ePe(W)||!d)&&(ve||be))return O4.Transition.toString({...d,property:Tyt})}}function Xws(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 Dxe(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 Jws=[Sl.Down,Sl.Right,Sl.Up,Sl.Left],Eyt=(s,t)=>{let{context:{active:n,collisionRect:r,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(Jws.includes(s.code)){if(s.preventDefault(),!n||!r)return;const c=[];i.getEnabled().forEach(h=>{if(!h||h!=null&&h.disabled)return;const p=a.get(h.id);if(p)switch(s.code){case Sl.Down:r.topp.top&&c.push(h);break;case Sl.Left:r.left>p.left&&c.push(h);break;case Sl.Right:r.left1&&(u=d[1].id),u!=null){const h=i.get(n.id),p=i.get(u),f=p?a.get(p.id):null,g=p==null?void 0:p.node.current;if(g&&f&&h&&p){const v=Cve(g).some((L,D)=>o[D]!==L),j=Ayt(h,p),b=ejs(h,p),S=v||!j?{x:0,y:0}:{x:b?r.width-f.width:0,y:b?r.height-f.height:0},A={x:f.left,y:f.top};return S.x&&S.y?A:LB(A,S)}}}};function Ayt(s,t){return!Dxe(s)||!Dxe(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function ejs(s,t){return!Dxe(s)||!Dxe(t)||!Ayt(s,t)?!1:s.data.current.sortable.indext(s),children:e.jsx(_a,{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(_n,{className:"h-3.5 w-3.5"})})]}),s.post_date&&e.jsx("div",{className:"absolute bottom-2 left-2",children:e.jsxs(ze,{className:"bg-primary/90 text-primary-foreground text-[10px] gap-1 backdrop-blur-sm px-1.5 py-0.5",children:[e.jsx(yr,{className:"h-2.5 w-2.5"}),Ss(new Date(s.post_date+"T00:00:00"),"MMM d")]})})]}),e.jsxs(Ee,{className:"p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3",children:s.caption}),e.jsxs(el,{children:[e.jsx(tl,{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(yr,{className:"h-3 w-3"}),s.post_date?Ss(new Date(s.post_date+"T00:00:00"),"MMM d, yyyy"):"Set post date"]})}),e.jsxs(Ho,{className:"w-auto p-0",align:"start",children:[e.jsx(Kg,{mode:"single",selected:s.post_date?new Date(s.post_date+"T00:00:00"):void 0,onSelect:h=>r(s.id,h?Ss(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 sjs=()=>{const s=Ht(),[t,n]=N.useState("all"),[r,a]=N.useState(!1),[i,l]=N.useState(Ss(new Date,"yyyy-MM")),[o,c]=N.useState([]),[d,u]=N.useState(!1),[h,p]=N.useState(null),[f,g]=N.useState(null),[_,v]=N.useState(""),[j,b]=N.useState(null),[S,A]=N.useState(!1),[T,L]=N.useState(!1),[D,M]=N.useState(Ss(new Date,"yyyy-MM")),[F,z]=N.useState(null),[V,W]=N.useState(""),[Y,K]=N.useState(""),[J,ne]=N.useState(""),[ie,he]=N.useState(!1),ce=kve(R8(rR,{activationConstraint:{distance:5}}),R8(Tve,{coordinateGetter:Eyt})),{data:pe=[],isLoading:le}=ct({queryKey:["admin-social-swag-2"],queryFn:async()=>{const{data:at,error:He}=await q.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(He)throw He;return at}}),{data:ve=[]}=ct({queryKey:["admin-social-swag-2-months"],queryFn:async()=>{const{data:at,error:He}=await q.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(He)throw He;return at}}),{data:ge=[]}=ct({queryKey:["admin-social-swag-2-reels"],queryFn:async()=>{const{data:at,error:He}=await q.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(He)throw He;return at}}),Te=[...new Set(pe.map(at=>at.month))].sort((at,He)=>He.localeCompare(at)),Me=t==="all"?pe:pe.filter(at=>at.month===t),Ce=at=>{const He=cMe(at,"yyyy-MM",new Date);return Ss(He,"MMMM yyyy")},Ae=at=>{g(at),v(at.caption),b(at.post_date)},De=async()=>{if(f){A(!0);try{const{error:at}=await q.from("social_swag_2").update({caption:_,post_date:j}).eq("id",f.id);if(at)throw at;ae.success("Image updated"),g(null),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})}catch{ae.error("Failed to update image")}finally{A(!1)}}},Ie=async at=>{const{active:He,over:dt}=at;if(!dt||He.id===dt.id)return;const bt=Me,vt=bt.findIndex(Fs=>Fs.id===He.id),Bt=bt.findIndex(Fs=>Fs.id===dt.id);if(vt===-1||Bt===-1)return;const Zt=Ive(bt,vt,Bt);s.setQueryData(["admin-social-swag-2"],Fs=>{if(!Fs)return Fs;const Rs={};return Zt.forEach((ms,Pt)=>{Rs[ms.id]=Pt}),Fs.map(ms=>Rs[ms.id]!==void 0?{...ms,sort_order:Rs[ms.id]}:ms).sort((ms,Pt)=>ms.month!==Pt.month?Pt.month.localeCompare(ms.month):ms.sort_order-Pt.sort_order)});try{await Promise.all(Zt.map((Fs,Rs)=>q.from("social_swag_2").update({sort_order:Rs}).eq("id",Fs.id)))}catch{ae.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},Fe=at=>{const dt=Array.from(at.target.files||[]).sort((bt,vt)=>bt.name.localeCompare(vt.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(bt=>({file:bt,preview:URL.createObjectURL(bt),caption:""}));c(bt=>[...bt,...dt].slice(0,16))},qe=at=>{c(He=>{const dt=[...He];return URL.revokeObjectURL(dt[at].preview),dt.splice(at,1),dt})},be=(at,He)=>{c(dt=>{const bt=[...dt];return bt[at]={...bt[at],caption:He},bt})},Ze=async()=>{var He;if(o.length===0){ae.error("Please add at least one image");return}if(o.filter(dt=>!dt.caption.trim()).length>0){ae.error("Please add captions to all images");return}u(!0);try{const{data:dt}=await q.from("social_swag_2").select("sort_order").eq("month",i).order("sort_order",{ascending:!1}).limit(1),bt=(((He=dt==null?void 0:dt[0])==null?void 0:He.sort_order)??-1)+1;for(let vt=0;vt{const He=at.image_url.split("/social-swag-2/");He[1]&&await q.storage.from("social-swag-2").remove([He[1]]);const{error:dt}=await q.from("social_swag_2").delete().eq("id",at.id);if(dt)throw dt},onSuccess:()=>{ae.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>ae.error("Failed to delete image")}),it=gt({mutationFn:async({id:at,postDate:He})=>{const{error:dt}=await q.from("social_swag_2").update({post_date:He}).eq("id",at);if(dt)throw dt},onSuccess:()=>{ae.success("Post date updated"),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})},onError:()=>ae.error("Failed to update post date")}),je=gt({mutationFn:async({month:at,link:He})=>{const{error:dt}=await q.from("social_swag_2_months").upsert({month:at,canva_link:He||null},{onConflict:"month"});if(dt)throw dt},onSuccess:()=>{ae.success("Canva link updated"),p(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>ae.error("Failed to update Canva link")}),Ge=at=>{var He;return((He=ve.find(dt=>dt.month===at))==null?void 0:He.canva_link)||""},Be=at=>ge.find(He=>He.month===at)||null,Ye=at=>{var dt;const He=(dt=at.target.files)==null?void 0:dt[0];He&&(z(He),W(URL.createObjectURL(He)))},We=()=>{V&&URL.revokeObjectURL(V),z(null),W(""),K(""),ne("")},rt=async()=>{if(!F){ae.error("Please select an image");return}he(!0);try{const at=F.name.split(".").pop(),He=`reels/${D}-${Date.now()}.${at}`,{error:dt}=await q.storage.from("social-swag-2").upload(He,F);if(dt)throw dt;const{data:{publicUrl:bt}}=q.storage.from("social-swag-2").getPublicUrl(He),{error:vt}=await q.from("social_swag_2_reels").upsert({month:D,image_url:bt,canva_link:J||null,caption:Y||null},{onConflict:"month"});if(vt)throw vt;ae.success("Reel uploaded successfully!"),y3e(`${Ce(D)} Reel`,"social-swag-2"),We(),L(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(at){console.error("Reel upload error:",at),ae.error("Failed to upload reel")}finally{he(!1)}},tt=gt({mutationFn:async at=>{const He=at.image_url.split("/social-swag-2/");He[1]&&await q.storage.from("social-swag-2").remove([He[1]]);const{error:dt}=await q.from("social_swag_2_reels").delete().eq("id",at.id);if(dt)throw dt},onSuccess:()=>{ae.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>ae.error("Failed to delete reel")});return e.jsxs(Ts,{title:"Admin - Social Swag 2.0",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Social Swag 2.0"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage monthly social media images and captions"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(bs,{open:r,onOpenChange:a,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(vs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Upload Social Swag Images"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Month"}),e.jsx(ye,{type:"month",value:i,onChange:at=>l(at.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:Fe,className:"hidden",id:"swag-upload",disabled:o.length>=16}),e.jsxs("label",{htmlFor:"swag-upload",className:"cursor-pointer",children:[e.jsx(Na,{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((at,He)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative aspect-[4/5] rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:at.preview,alt:`Upload ${He+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:()=>qe(He),children:e.jsx(Bn,{className:"h-3 w-3"})})]}),e.jsx(Es,{placeholder:"Caption...",value:at.caption,onChange:dt=>be(He,dt.target.value),className:"text-xs h-20"})]},He))}),e.jsx(B,{onClick:Ze,disabled:d||o.length===0,className:"w-full gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Na,{className:"h-4 w-4"}),"Upload ",o.length," Images"]})})]})]})]}),e.jsxs(bs,{open:T,onOpenChange:at=>{L(at),at||We()},children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"gap-2",children:[e.jsx(Ah,{className:"h-4 w-4"}),"Upload Reel"]})}),e.jsxs(vs,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Upload Monthly Reel"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Month"}),e.jsx(ye,{type:"month",value:D,onChange:at=>M(at.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Reel Preview Image"}),V?e.jsxs("div",{className:"relative aspect-[9/16] max-w-[120px] mx-auto rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:V,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(V),z(null),W("")},children:e.jsx(Bn,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:Ye,className:"hidden",id:"reel-upload"}),e.jsxs("label",{htmlFor:"reel-upload",className:"cursor-pointer",children:[e.jsx(Ah,{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:J,onChange:at=>ne(at.target.value),placeholder:"https://www.canva.com/..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Caption"}),e.jsx(Es,{value:Y,onChange:at=>K(at.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx(B,{onClick:rt,disabled:ie||!F,className:"w-full gap-2",children:ie?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Na,{className:"h-4 w-4"}),"Upload Reel"]})})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:pe.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:Te.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Br,{value:t,onValueChange:n,children:e.jsxs(Fr,{children:[e.jsx(Kt,{value:"all",children:"All"}),Te.map(at=>e.jsx(Kt,{value:at,children:Ce(at)},at))]})}),t!=="all"&&e.jsx(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Jo,{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 ",Ce(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:at=>p({...h,link:at.target.value}),placeholder:"https://www.canva.com/..."}),e.jsx(B,{size:"sm",onClick:()=>je.mutate(h),children:"Save"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>p(null),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-sm",children:Ge(t)||"No link set"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>p({month:t,link:Ge(t)}),children:"Edit"})]})]})]})})}),t!=="all"&&e.jsx(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Ah,{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 ",Ce(t)]}),(()=>{const at=Be(t);return at?e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsx("img",{src:at.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:at.caption||"No caption"}),at.canva_link&&e.jsx("a",{href:at.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:()=>tt.mutate(at),children:e.jsx(_n,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"No reel uploaded for this month"})})()]})]})})})]}),le?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):Me.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(nl,{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(Mve,{sensors:ce,collisionDetection:Sve,onDragEnd:Ie,children:e.jsx(Pve,{items:Me.map(at=>at.id),strategy:AU,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:Me.map(at=>e.jsx(tjs,{item:at,onEdit:Ae,onDelete:He=>Ne.mutate(He),onDateChange:(He,dt)=>it.mutate({id:He,postDate:dt})},at.id))})})})]}),e.jsx(bs,{open:!!f,onOpenChange:at=>{at||g(null)},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Edit Image"})}),f&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"aspect-[4/5] max-h-48 w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:f.image_url,alt:"Preview",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Caption"}),e.jsx(Es,{value:_,onChange:at=>v(at.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(el,{children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("flex-1 justify-start gap-2 font-normal",!j&&"text-muted-foreground"),children:[e.jsx(yr,{className:"h-4 w-4"}),j?Ss(new Date(j+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(Ho,{className:"w-auto p-0",align:"start",children:e.jsx(Kg,{mode:"single",selected:j?new Date(j+"T00:00:00"):void 0,onSelect:at=>b(at?Ss(at,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),j&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>b(null),children:e.jsx(Bn,{className:"h-4 w-4"})})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>g(null),children:"Cancel"}),e.jsx(B,{onClick:De,disabled:S,className:"gap-2",children:S?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})},njs=()=>{const{toast:s}=Ba(),t=Ht(),[n,r]=N.useState("categories"),[a,i]=N.useState(!1),[l,o]=N.useState(null),[c,d]=N.useState({name:"",description:"",icon:""}),[u,h]=N.useState(!1),[p,f]=N.useState(null),[g,_]=N.useState({name:"",description:"",icon:""}),[v,j]=N.useState(!1),[b,S]=N.useState(null),[A,T]=N.useState(""),{data:L=[],isLoading:D}=ct({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Ie,error:Fe}=await q.from("community_categories").select("*").order("sort_order");if(Fe)throw Fe;return Ie}}),{data:M=[],isLoading:F}=ct({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Ie,error:Fe}=await q.from("community_private_groups").select("*").order("sort_order");if(Fe)throw Fe;return Ie}}),{data:z=[]}=ct({queryKey:["admin-group-members",b==null?void 0:b.id],queryFn:async()=>{if(!b)return[];const{data:Ie,error:Fe}=await q.from("community_private_group_members").select("*").eq("group_id",b.id);if(Fe)throw Fe;return Ie},enabled:!!b}),{data:V=[]}=ct({queryKey:["admin-all-profiles"],queryFn:async()=>{let Fe=[],qe=0,be=!0;for(;be;){const{data:Ze,error:Ne}=await q.from("profiles").select("id, name, email, brokerage_id").order("name").range(qe,qe+1e3-1);if(Ne)throw Ne;Ze&&Ze.length>0?(Fe=[...Fe,...Ze],qe+=1e3,be=Ze.length===1e3):be=!1}return Fe}}),{data:W=[]}=ct({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Ie,error:Fe}=await q.from("brokerages").select("*").order("name");if(Fe)throw Fe;return Ie}}),Y=gt({mutationFn:async Ie=>{if(Ie.id){const{error:Fe}=await q.from("community_categories").update({name:Ie.name,description:Ie.description||null,icon:Ie.icon||null}).eq("id",Ie.id);if(Fe)throw Fe}else{const Fe=Math.max(...L.map(be=>be.sort_order),0),{error:qe}=await q.from("community_categories").insert({name:Ie.name,description:Ie.description||null,icon:Ie.icon||null,sort_order:Fe+1});if(qe)throw qe}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),i(!1),o(null),d({name:"",description:"",icon:""}),s({title:l?"Category updated!":"Category created!"})},onError:Ie=>{s({title:"Error",description:Ie.message,variant:"destructive"})}}),K=gt({mutationFn:async Ie=>{const{error:Fe}=await q.from("community_categories").delete().eq("id",Ie);if(Fe)throw Fe},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),J=gt({mutationFn:async({id:Ie,direction:Fe})=>{const qe=L.findIndex(be=>be.id===Ie);if(Fe==="up"&&qe>0){const be=L[qe-1],Ze=L[qe];await q.from("community_categories").update({sort_order:Ze.sort_order}).eq("id",be.id),await q.from("community_categories").update({sort_order:be.sort_order}).eq("id",Ze.id)}else if(Fe==="down"&&qet.invalidateQueries({queryKey:["admin-community-categories"]})}),ne=gt({mutationFn:async Ie=>{if(Ie.id){const{error:Fe}=await q.from("community_private_groups").update({name:Ie.name,description:Ie.description||null,icon:Ie.icon||null}).eq("id",Ie.id);if(Fe)throw Fe}else{const Fe=Math.max(...M.map(be=>be.sort_order),0),{error:qe}=await q.from("community_private_groups").insert({name:Ie.name,description:Ie.description||null,icon:Ie.icon||null,sort_order:Fe+1});if(qe)throw qe}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),h(!1),f(null),_({name:"",description:"",icon:""}),s({title:p?"Private group updated!":"Private group created!"})},onError:Ie=>{s({title:"Error",description:Ie.message,variant:"destructive"})}}),ie=gt({mutationFn:async Ie=>{const{error:Fe}=await q.from("community_private_groups").delete().eq("id",Ie);if(Fe)throw Fe},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),he=gt({mutationFn:async({id:Ie,direction:Fe})=>{const qe=M.findIndex(be=>be.id===Ie);if(Fe==="up"&&qe>0){const be=M[qe-1],Ze=M[qe];await q.from("community_private_groups").update({sort_order:Ze.sort_order}).eq("id",be.id),await q.from("community_private_groups").update({sort_order:be.sort_order}).eq("id",Ze.id)}else if(Fe==="down"&&qet.invalidateQueries({queryKey:["admin-private-groups"]})}),ce=gt({mutationFn:async({groupId:Ie,userId:Fe,isMember:qe})=>{if(qe){const{error:be}=await q.from("community_private_group_members").delete().eq("group_id",Ie).eq("user_id",Fe);if(be)throw be}else{const{error:be}=await q.from("community_private_group_members").insert({group_id:Ie,user_id:Fe});if(be)throw be}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",b==null?void 0:b.id]})}}),pe=gt({mutationFn:async({groupId:Ie,brokerageId:Fe,isMember:qe})=>{if(qe){const{error:be}=await q.from("community_private_group_members").delete().eq("group_id",Ie).eq("brokerage_id",Fe);if(be)throw be}else{const{error:be}=await q.from("community_private_group_members").insert({group_id:Ie,brokerage_id:Fe});if(be)throw be}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",b==null?void 0:b.id]})}}),le=Ie=>{o(Ie),d({name:Ie.name,description:Ie.description||"",icon:Ie.icon||""}),i(!0)},ve=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},ge=Ie=>{f(Ie),_({name:Ie.name,description:Ie.description||"",icon:Ie.icon||""}),h(!0)},Te=()=>{f(null),_({name:"",description:"",icon:""}),h(!0)},Me=Ie=>{S(Ie),T(""),j(!0)},Ce=Ie=>z.some(Fe=>Fe.user_id===Ie),Ae=Ie=>z.some(Fe=>Fe.brokerage_id===Ie),De=V.filter(Ie=>Ie.name.toLowerCase().includes(A.toLowerCase())||Ie.email.toLowerCase().includes(A.toLowerCase()));return e.jsx(Ts,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs(Br,{value:n,onValueChange:r,children:[e.jsxs(Fr,{children:[e.jsx(Kt,{value:"categories",children:"Public Categories"}),e.jsxs(Kt,{value:"private-groups",children:[e.jsx(Kc,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(is,{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:ve,children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{className:"w-[50px]",children:"Order"}),e.jsx(Ct,{className:"w-[80px]",children:"Icon"}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(ha,{children:D?e.jsx(Hs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):L.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):L.map((Ie,Fe)=>e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Fe===0,onClick:()=>J.mutate({id:Ie.id,direction:"up"}),children:"↑"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Fe===L.length-1,onClick:()=>J.mutate({id:Ie.id,direction:"down"}),children:"↓"})]})}),e.jsx(ut,{className:"text-2xl",children:Ie.icon||"📁"}),e.jsx(ut,{className:"font-medium",children:Ie.name}),e.jsx(ut,{className:"text-muted-foreground",children:Ie.description||"—"}),e.jsx(ut,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>le(Ie),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this category? Posts will be uncategorized.")&&K.mutate(Ie.id)},children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},Ie.id))})]})})})]}),e.jsxs(is,{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(Va,{className:"h-3 w-3"}),"Brokerage groups are created automatically and sync with brokerage names"]})]}),e.jsxs(B,{onClick:Te,children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{className:"w-[50px]",children:"Order"}),e.jsx(Ct,{className:"w-[80px]",children:"Icon"}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{className:"w-[120px]",children:"Members"}),e.jsx(Ct,{className:"w-[140px]",children:"Actions"})]})}),e.jsx(ha,{children:F?e.jsx(Hs,{children:e.jsx(ut,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):M.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No private groups yet. Create your first one!"})}):M.map((Ie,Fe)=>e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Fe===0,onClick:()=>he.mutate({id:Ie.id,direction:"up"}),children:"↑"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Fe===M.length-1,onClick:()=>he.mutate({id:Ie.id,direction:"down"}),children:"↓"})]})}),e.jsx(ut,{className:"text-2xl",children:Ie.icon||"🔒"}),e.jsx(ut,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Ie.name,Ie.brokerage_id?e.jsxs(ze,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[e.jsx(Va,{className:"h-3 w-3 mr-1"}),"Auto-managed"]}):e.jsxs(ze,{variant:"secondary",className:"text-xs",children:[e.jsx(Kc,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(ut,{className:"text-muted-foreground",children:Ie.description||"—"}),e.jsx(ut,{children:e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Me(Ie),children:[e.jsx(Nn,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex gap-1",children:[!Ie.brokerage_id&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ge(Ie),children:e.jsx(_a,{className:"h-4 w-4"})}),!Ie.brokerage_id&&e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this private group? All posts in this group will be deleted.")&&ie.mutate(Ie.id)},children:e.jsx(_n,{className:"h-4 w-4"})}),Ie.brokerage_id&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Managed via brokerage"})]})})]},Ie.id))})]})})})]})]}),e.jsx(bs,{open:a,onOpenChange:i,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:l?"Edit Category":"Create Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(ye,{value:c.icon,onChange:Ie=>d(Fe=>({...Fe,icon:Ie.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:Ie=>d(Fe=>({...Fe,name:Ie.target.value})),placeholder:"Category name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(Es,{value:c.description,onChange:Ie=>d(Fe=>({...Fe,description:Ie.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:()=>Y.mutate({...c,id:l==null?void 0:l.id}),disabled:!c.name.trim(),children:l?"Save Changes":"Create Category"})]})]})]})}),e.jsx(bs,{open:u,onOpenChange:h,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:p?"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:g.icon,onChange:Ie=>_(Fe=>({...Fe,icon:Ie.target.value})),placeholder:"🔒",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(ye,{value:g.name,onChange:Ie=>_(Fe=>({...Fe,name:Ie.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(Es,{value:g.description,onChange:Ie=>_(Fe=>({...Fe,description:Ie.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:()=>ne.mutate({...g,id:p==null?void 0:p.id}),disabled:!g.name.trim(),children:p?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(bs,{open:v,onOpenChange:j,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Manage Members: ",b==null?void 0:b.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Br,{defaultValue:"brokerages",children:[e.jsxs(Fr,{className:"w-full",children:[e.jsx(Kt,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),e.jsx(Kt,{value:"users",className:"flex-1",children:"Individual Users"})]}),e.jsxs(is,{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(hi,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[W.map(Ie=>e.jsxs("div",{className:"flex items-center justify-between p-2 hover:bg-muted rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ui,{checked:Ae(Ie.id),onCheckedChange:()=>{b&&pe.mutate({groupId:b.id,brokerageId:Ie.id,isMember:Ae(Ie.id)})}}),e.jsx("span",{className:"font-medium",children:Ie.name})]}),e.jsxs(ze,{variant:"secondary",children:[V.filter(Fe=>Fe.brokerage_id===Ie.id).length," agents"]})]},Ie.id)),W.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(is,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search users...",value:A,onChange:Ie=>T(Ie.target.value),className:"pl-9"})]}),e.jsx(hi,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[De.map(Ie=>e.jsx("div",{className:"flex items-center justify-between p-2 hover:bg-muted rounded-md",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ui,{checked:Ce(Ie.id),onCheckedChange:()=>{b&&ce.mutate({groupId:b.id,userId:Ie.id,isMember:Ce(Ie.id)})}}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ie.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Ie.email})]})]})},Ie.id)),De.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:()=>j(!1),children:"Done"})})]})]})})]})})},aGe=s=>{switch(s){case"academy_video":return e.jsx(Al,{className:"h-3 w-3"});case"template":return e.jsx(Nr,{className:"h-3 w-3"});case"toolbox":return e.jsx(Rc,{className:"h-3 w-3"});case"newsletter":return e.jsx(ay,{className:"h-3 w-3"});case"social_swag":return e.jsx(un,{className:"h-3 w-3"});default:return e.jsx(tr,{className:"h-3 w-3"})}},rjs=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}},ajs=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}},ijs=()=>{const{toast:s}=Ba(),[t,n]=N.useState([]),[r,a]=N.useState([]),[i,l]=N.useState([]),[o,c]=N.useState(!0),[d,u]=N.useState(""),[h,p]=N.useState(null),[f,g]=N.useState([]),[_,v]=N.useState([]);N.useEffect(()=>{j()},[]);const j=async()=>{try{c(!0);const{data:z,error:V}=await q.from("activity_logs").select(` id, user_id, app_name, launched_at, profiles ( name, email, brokerages ( name ) ) `).order("launched_at",{ascending:!1}).limit(5e3);if(V)throw V;const{data:W,error:Y}=await q.from("content_engagement_logs").select(` id, user_id, resource_type, resource_id, resource_title, action_type, created_at `).order("created_at",{ascending:!1}).limit(5e3);if(Y)throw Y;const K=[...new Set((W==null?void 0:W.map(le=>le.user_id))||[])],{data:J}=await q.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",K),ne=new Map((J==null?void 0:J.map(le=>[le.id,le]))||[]),ie=(z==null?void 0:z.map(le=>{var ve,ge,Te,Me;return{id:le.id,user_id:le.user_id,app_name:le.app_name,launched_at:le.launched_at,user_name:((ve=le.profiles)==null?void 0:ve.name)||"Unknown",user_email:((ge=le.profiles)==null?void 0:ge.email)||"Unknown",brokerage_name:((Me=(Te=le.profiles)==null?void 0:Te.brokerages)==null?void 0:Me.name)||null}}))||[],he=(W==null?void 0:W.map(le=>{var ge;const ve=ne.get(le.user_id);return{id:le.id,user_id:le.user_id,resource_type:le.resource_type,resource_id:le.resource_id,resource_title:le.resource_title,action_type:le.action_type,created_at:le.created_at,user_name:(ve==null?void 0:ve.name)||"Unknown",user_email:(ve==null?void 0:ve.email)||"Unknown",brokerage_name:((ge=ve==null?void 0:ve.brokerages)==null?void 0:ge.name)||null}}))||[];n(ie),a(he);const ce=new Map;ie.forEach(le=>{if(!ce.has(le.user_id))ce.set(le.user_id,{user_id:le.user_id,user_name:le.user_name,user_email:le.user_email,brokerage_name:le.brokerage_name,last_activity_type:"app",last_activity_name:le.app_name,last_activity_at:le.launched_at,total_app_launches:1,total_content_views:0});else{const ve=ce.get(le.user_id);ve.total_app_launches++,new Date(le.launched_at)>new Date(ve.last_activity_at)&&(ve.last_activity_type="app",ve.last_activity_name=le.app_name,ve.last_activity_at=le.launched_at)}}),he.forEach(le=>{if(!ce.has(le.user_id))ce.set(le.user_id,{user_id:le.user_id,user_name:le.user_name,user_email:le.user_email,brokerage_name:le.brokerage_name,last_activity_type:le.resource_type,last_activity_name:le.resource_title,last_activity_at:le.created_at,total_app_launches:0,total_content_views:1});else{const ve=ce.get(le.user_id);ve.total_content_views++,new Date(le.created_at)>new Date(ve.last_activity_at)&&(ve.last_activity_type=le.resource_type,ve.last_activity_name=le.resource_title,ve.last_activity_at=le.created_at)}});const pe=Array.from(ce.values()).sort((le,ve)=>new Date(ve.last_activity_at).getTime()-new Date(le.last_activity_at).getTime());l(pe)}catch(z){console.error("Error loading activity:",z),s({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{c(!1)}},b=z=>{p({id:z.user_id,name:z.user_name,email:z.user_email});const V=t.filter(Y=>Y.user_id===z.user_id),W=r.filter(Y=>Y.user_id===z.user_id);g(V),v(W)},S=()=>{p(null),g([]),v([])},{sortKey:A,sortDirection:T,handleSort:L,sortData:D}=kU("last_activity_at","desc"),M=i.filter(z=>{var W;if(!d)return!0;const V=d.toLowerCase();return z.user_name.toLowerCase().includes(V)||z.user_email.toLowerCase().includes(V)||((W=z.brokerage_name)==null?void 0:W.toLowerCase().includes(V))}),F=D(M,{user:z=>{var V;return((V=z.user_name)==null?void 0:V.toLowerCase())||""},brokerage:z=>{var V;return((V=z.brokerage_name)==null?void 0:V.toLowerCase())||""},last_activity_at:z=>new Date(z.last_activity_at).getTime(),apps:z=>z.total_app_launches,content:z=>z.total_content_views});return o?e.jsx(fe,{children:e.jsx(Ee,{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(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"User Activity"}),e.jsx(Vn,{children:"App launches and content engagement - click to see full history"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"mb-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, or brokerage...",value:d,onChange:z=>u(z.target.value),className:"pl-9"})]})}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ic,{sortKey:"user",currentSortKey:A,currentDirection:T,onSort:L,children:"User"}),e.jsx(Ic,{sortKey:"brokerage",currentSortKey:A,currentDirection:T,onSort:L,children:"Brokerage"}),e.jsx(Ct,{children:"Last Activity"}),e.jsx(Ic,{sortKey:"last_activity_at",currentSortKey:A,currentDirection:T,onSort:L,children:"Last Active"}),e.jsx(Ic,{sortKey:"apps",currentSortKey:A,currentDirection:T,onSort:L,className:"text-right",children:"Apps"}),e.jsx(Ic,{sortKey:"content",currentSortKey:A,currentDirection:T,onSort:L,className:"text-right",children:"Content"})]})}),e.jsx(ha,{children:F.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):F.map(z=>e.jsxs(Hs,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>b(z),children:[e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:z.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:z.user_email})]})}),e.jsx(ut,{children:z.brokerage_name?e.jsx(ze,{variant:"outline",children:z.brokerage_name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(ut,{children:e.jsx("div",{className:"flex items-center gap-2",children:z.last_activity_type==="app"?e.jsxs(ze,{variant:"secondary",children:[e.jsx(tr,{className:"h-3 w-3 mr-1"}),z.last_activity_name]}):e.jsxs(ze,{variant:"outline",className:"flex items-center gap-1",children:[aGe(z.last_activity_type),e.jsx("span",{className:"max-w-32 truncate",children:z.last_activity_name})]})})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:Vo(new Date(z.last_activity_at),{addSuffix:!0})}),e.jsx(ut,{className:"text-right",children:e.jsx(ze,{variant:"outline",children:z.total_app_launches})}),e.jsx(ut,{className:"text-right",children:e.jsx(ze,{variant:"outline",children:z.total_content_views})})]},z.user_id))})]})})]})]}),e.jsx(bs,{open:!!h,onOpenChange:z=>!z&&S(),children:e.jsxs(vs,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:[h==null?void 0:h.name,"'s Activity"]}),e.jsx(Qn,{children:h==null?void 0:h.email})]}),e.jsxs(Br,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Fr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Kt,{value:"content",children:["Content (",_.length,")"]}),e.jsxs(Kt,{value:"apps",children:["App Launches (",f.length,")"]})]}),e.jsx(is,{value:"content",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Type"}),e.jsx(Ct,{children:"Resource"}),e.jsx(Ct,{children:"Action"}),e.jsx(Ct,{children:"Time"})]})}),e.jsx(ha,{children:_.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):_.map(z=>e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsxs(ze,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[aGe(z.resource_type),rjs(z.resource_type)]})}),e.jsx(ut,{className:"max-w-48",children:e.jsx("span",{className:"truncate block",children:z.resource_title})}),e.jsx(ut,{children:e.jsx(ze,{variant:"secondary",children:ajs(z.action_type)})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:Vo(new Date(z.created_at),{addSuffix:!0})})]},z.id))})]})})}),e.jsx(is,{value:"apps",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"App"}),e.jsx(Ct,{children:"Time"})]})}),e.jsx(ha,{children:f.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):f.map(z=>e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsx(ze,{variant:"secondary",children:z.app_name})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:Vo(new Date(z.launched_at),{addSuffix:!0})})]},z.id))})]})})})]})]})})]})},ojs=()=>{const{toast:s}=Ba(),[t,n]=N.useState({totalUsers:0,activeUsers:0,pendingUsers:0,totalBrokerages:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0,uniqueActiveThisWeek:0}),[r,a]=N.useState(!0);N.useEffect(()=>{i()},[]);const i=async()=>{try{a(!0);const{count:l}=await q.from("profiles").select("*",{count:"exact",head:!0}),{count:o}=await q.from("profiles").select("*",{count:"exact",head:!0}).not("last_login","is",null),c=(l||0)-(o||0),{count:d}=await q.from("brokerages").select("*",{count:"exact",head:!0}),{count:u}=await q.from("activity_logs").select("*",{count:"exact",head:!0}),h=new Date;h.setDate(h.getDate()-7);const{count:p}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",h.toISOString()),f=new Date;f.setMonth(f.getMonth()-1);const{count:g}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",f.toISOString()),{data:_}=await q.from("activity_logs").select("user_id").gte("launched_at",h.toISOString()),v=new Set(_==null?void 0:_.map(j=>j.user_id)).size;n({totalUsers:l||0,activeUsers:o||0,pendingUsers:c,totalBrokerages:d||0,totalLaunches:u||0,launchesThisWeek:p||0,launchesThisMonth:g||0,uniqueActiveThisWeek:v})}catch(l){console.error("Error loading analytics:",l),s({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{a(!1)}};return r?e.jsx(fe,{children:e.jsx(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(Nn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Ri,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(gr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Brokerages"}),e.jsx(Va,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(nm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Launches This Week"}),e.jsx(nm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Launches This Month"}),e.jsx(nm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Active This Week"}),e.jsx(mo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.uniqueActiveThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique users"})]})]})]})},iGe={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},oGe={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 Myt({brokerageOnly:s=!1,brokerageId:t}){const[n,r]=N.useState([]),[a,i]=N.useState(!0),[l,o]=N.useState(""),[c,d]=N.useState("all");N.useEffect(()=>{u()},[t]);const u=async()=>{i(!0);try{let L=[];if(s&&t){const{data:K}=await q.from("profiles").select("id").eq("brokerage_id",t);if(L=(K==null?void 0:K.map(J=>J.id))||[],L.length===0){r([]),i(!1);return}}let D=q.from("resource_shares").select("*").order("created_at",{ascending:!1});s&&L.length>0&&(D=D.or(`sender_id.in.(${L.join(",")}),recipient_id.in.(${L.join(",")})`));const{data:M,error:F}=await D;if(F)throw F;const z=new Set;M==null||M.forEach(K=>{z.add(K.sender_id),z.add(K.recipient_id)});const{data:V}=await q.from("profiles").select("id, name, email").in("id",Array.from(z)),W=new Map((V==null?void 0:V.map(K=>[K.id,K]))||[]),Y=(M==null?void 0:M.map(K=>({...K,sender:W.get(K.sender_id),recipient:W.get(K.recipient_id)})))||[];r(Y)}catch(L){console.error("Error loading shares:",L)}finally{i(!1)}},{sortKey:h,sortDirection:p,handleSort:f,sortData:g}=kU("created_at","desc"),_=n.filter(L=>{var F,z;const D=l===""||L.resource_title.toLowerCase().includes(l.toLowerCase())||((F=L.sender)==null?void 0:F.name.toLowerCase().includes(l.toLowerCase()))||((z=L.recipient)==null?void 0:z.name.toLowerCase().includes(l.toLowerCase())),M=c==="all"||L.resource_type===c;return D&&M}),v=g(_,{resource:L=>{var D;return((D=L.resource_title)==null?void 0:D.toLowerCase())||""},type:L=>L.resource_type,sender:L=>{var D,M;return((M=(D=L.sender)==null?void 0:D.name)==null?void 0:M.toLowerCase())||""},recipient:L=>{var D,M;return((M=(D=L.recipient)==null?void 0:D.name)==null?void 0:M.toLowerCase())||""},status:L=>L.is_read?1:0,created_at:L=>new Date(L.created_at).getTime()}),j=n.length,b=new Set(n.map(L=>L.sender_id)).size,S=new Set(n.map(L=>L.recipient_id)).size,A=n.length>0?Math.round(n.filter(L=>L.is_read).length/n.length*100):0,T=n.reduce((L,D)=>(L[D.resource_type]=(L[D.resource_type]||0)+1,L),{});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((L,D)=>e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Ws,{className:"h-4 w-20"})}),e.jsx(Ee,{children:e.jsx(Ws,{className:"h-8 w-16"})})]},D))}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-6",children:e.jsx(Ws,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total Shares"}),e.jsx(Hl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:j})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Active Sharers"}),e.jsx(Nn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:b})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Recipients Reached"}),e.jsx(mo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:S})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Read Rate"}),e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ee,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[A,"%"]})})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-sm font-medium",children:"Shares by Resource Type"})}),e.jsx(Ee,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(T).map(([L,D])=>e.jsxs(ze,{variant:"secondary",className:oGe[L],children:[iGe[L],": ",D]},L)),Object.keys(T).length===0&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Share History"}),e.jsxs(Vn,{children:["All resource shares ",s?"in your brokerage":"across the platform"]})]}),e.jsxs(Ee,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by resource, sender, or recipient...",value:l,onChange:L=>o(L.target.value),className:"pl-9"})]}),e.jsxs(ds,{value:c,onValueChange:d,children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(us,{placeholder:"Resource type"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Types"}),e.jsx(Qe,{value:"event",children:"Events"}),e.jsx(Qe,{value:"template",children:"Templates"}),e.jsx(Qe,{value:"academy_video",children:"Academy Videos"}),e.jsx(Qe,{value:"resource_kit",children:"Resource Kits"}),e.jsx(Qe,{value:"newsletter",children:"Newsletters"}),e.jsx(Qe,{value:"social_swag",children:"Social Swag"})]})]})]}),e.jsx(hi,{className:"h-[400px]",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ic,{sortKey:"resource",currentSortKey:h,currentDirection:p,onSort:f,children:"Resource"}),e.jsx(Ic,{sortKey:"type",currentSortKey:h,currentDirection:p,onSort:f,children:"Type"}),e.jsx(Ic,{sortKey:"sender",currentSortKey:h,currentDirection:p,onSort:f,children:"Sender"}),e.jsx(Ic,{sortKey:"recipient",currentSortKey:h,currentDirection:p,onSort:f,children:"Recipient"}),e.jsx(Ic,{sortKey:"status",currentSortKey:h,currentDirection:p,onSort:f,children:"Status"}),e.jsx(Ic,{sortKey:"created_at",currentSortKey:h,currentDirection:p,onSort:f,children:"Date"})]})}),e.jsx(ha,{children:v.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):v.map(L=>{var D,M;return e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium max-w-[200px] truncate",children:L.resource_title}),e.jsx(ut,{children:e.jsx(ze,{variant:"secondary",className:oGe[L.resource_type],children:iGe[L.resource_type]})}),e.jsx(ut,{children:((D=L.sender)==null?void 0:D.name)||"Unknown"}),e.jsx(ut,{children:((M=L.recipient)==null?void 0:M.name)||"Unknown"}),e.jsx(ut,{children:e.jsx(ze,{variant:L.is_read?"default":"outline",children:L.is_read?"Read":"Unread"})}),e.jsx(ut,{className:"text-muted-foreground",children:Ss(new Date(L.created_at),"MMM d, yyyy")})]},L.id)})})]})})]})]})]})}const H2e={academy_video:{label:"Academy Videos",icon:br,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:Er},template:{label:"Templates",icon:T2,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:Om},toolbox:{label:"Toolkit",icon:_b,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:Pa},newsletter:{label:"Newsletters",icon:Vs,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:Om},social_swag:{label:"Social Swag",icon:fl,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:Om},event:{label:"Events",icon:yr,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:Om}};function lGe(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function ljs(s,t){return s==="toolbox"?t.downloads:t.clicks}function cjs(){var L;const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(null),l=N.useRef(null),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=kU("total_views","desc");N.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:D,error:M}=await q.rpc("get_admin_content_engagement");if(M)throw M;t(D||[])}catch(D){console.error("Error loading content engagement:",D)}finally{r(!1)}},p=D=>{i(M=>{const F=M===D?null:D;return requestAnimationFrame(()=>{var z;(z=l.current)==null||z.scrollIntoView({behavior:"smooth",block:"start"})}),F})};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((D,M)=>e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Ws,{className:"h-4 w-20"})}),e.jsx(Ee,{children:e.jsx(Ws,{className:"h-8 w-16"})})]},M))}),e.jsx(fe,{children:e.jsx(Ee,{className:"py-8",children:e.jsx(Ws,{className:"h-64 w-full"})})})]});const f=s.reduce((D,M)=>D+M.total_views,0),g=s.reduce((D,M)=>D+M.total_clicks,0),_=s.reduce((D,M)=>D+M.total_downloads,0),v=s.length,j=s.reduce((D,M)=>(D[M.resource_type]||(D[M.resource_type]={views:0,clicks:0,downloads:0,assets:0,uniqueUsers:0}),D[M.resource_type].views+=M.total_views,D[M.resource_type].clicks+=M.total_clicks,D[M.resource_type].downloads+=M.total_downloads,D[M.resource_type].assets+=1,D[M.resource_type].uniqueUsers+=M.unique_users,D),{}),b=a?s.filter(D=>D.resource_type===a):s,S=u(b,{asset:D=>{var M;return((M=D.resource_title)==null?void 0:M.toLowerCase())||""},type:D=>D.resource_type,views:D=>D.total_views,actions:D=>lGe(D),unique_users:D=>D.unique_users,last_activity:D=>D.last_engaged_at?new Date(D.last_engaged_at).getTime():0}),A=a?H2e[a]||{label:a,icon:Er,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:Om}:null,T=A==null?void 0:A.icon;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-5",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total Views"}),e.jsx(Er,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:f.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Across all content"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total Clicks"}),e.jsx(Om,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:g.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link & Canva clicks"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Downloads"}),e.jsx(Pa,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:_.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PDF downloads"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Assets Tracked"}),e.jsx(mo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique content items"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(Om,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[f>0?Math.round((g+_)/f*100):0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of views → actions"})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(Vn,{children:"Click a category to see individual asset performance"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-3",children:Object.entries(j).map(([D,M])=>{const F=H2e[D]||{label:D,icon:Er,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:Om},z=F.icon,V=a===D;return e.jsxs("button",{type:"button",onClick:()=>p(D),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors cursor-pointer ${V?"ring-2 ring-primary border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:`p-2 rounded-md ${F.color}`,children:e.jsx(z,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:F.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(Er,{className:"h-3 w-3"})," ",M.views]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(F.actionIcon,{className:"h-3 w-3"})," ",ljs(D,M)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"})," ",M.uniqueUsers]})]})]}),e.jsxs(ze,{variant:"secondary",className:"text-[10px]",children:[M.assets," items"]})]},D)})})})]}),e.jsx("div",{ref:l,children:e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{className:"text-sm font-medium flex items-center gap-2",children:A&&T?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"h-4 w-4"}),A.label," — Top Performers"]}):"Top Content by Engagement"}),e.jsx(Vn,{children:a?`${b.length} ${((L=A==null?void 0:A.label)==null?void 0:L.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(Hr,{className:"h-3.5 w-3.5"}),"Show All"]})]})}),e.jsx(Ee,{children:b.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No engagement data yet. As users view and click content, stats will appear here."}):e.jsx(hi,{className:"h-[400px]",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{className:"w-[40px]",children:"#"}),e.jsx(Ic,{sortKey:"asset",currentSortKey:o,currentDirection:c,onSort:d,children:"Asset"}),!a&&e.jsx(Ic,{sortKey:"type",currentSortKey:o,currentDirection:c,onSort:d,children:"Type"}),e.jsx(Ic,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Views"}),e.jsx(Ic,{sortKey:"actions",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:A?A.actionLabel:"Actions"}),e.jsx(Ic,{sortKey:"unique_users",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Unique Users"}),e.jsx(Ic,{sortKey:"last_activity",currentSortKey:o,currentDirection:c,onSort:d,children:"Last Activity"})]})}),e.jsx(ha,{children:S.map((D,M)=>{const F=H2e[D.resource_type]||{label:D.resource_type,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:Om};return e.jsxs(Hs,{children:[e.jsx(ut,{className:"text-muted-foreground text-xs",children:M+1}),e.jsx(ut,{children:e.jsx("p",{className:"font-medium text-sm truncate max-w-[250px]",children:D.resource_title})}),!a&&e.jsx(ut,{children:e.jsx(ze,{className:`text-[10px] ${F.color}`,children:F.label})}),e.jsx(ut,{className:"text-right font-medium",children:D.total_views}),e.jsx(ut,{className:"text-right font-medium",children:lGe(D)}),e.jsx(ut,{className:"text-right",children:D.unique_users}),e.jsx(ut,{className:"text-xs text-muted-foreground",children:D.last_engaged_at?Vo(new Date(D.last_engaged_at),{addSuffix:!0}):"—"})]},`${D.resource_type}-${D.resource_id}`)})})]})})})]})})]})}var djs=Array.isArray,o0=djs,ujs=typeof Eh=="object"&&Eh&&Eh.Object===Object&&Eh,Iyt=ujs,hjs=Iyt,mjs=typeof self=="object"&&self&&self.Object===Object&&self,pjs=hjs||mjs||Function("return this")(),Jw=pjs,fjs=Jw,xjs=fjs.Symbol,MU=xjs,cGe=MU,Pyt=Object.prototype,gjs=Pyt.hasOwnProperty,yjs=Pyt.toString,NF=cGe?cGe.toStringTag:void 0;function vjs(s){var t=gjs.call(s,NF),n=s[NF];try{s[NF]=void 0;var r=!0}catch{}var a=yjs.call(s);return r&&(t?s[NF]=n:delete s[NF]),a}var bjs=vjs,_js=Object.prototype,wjs=_js.toString;function jjs(s){return wjs.call(s)}var Njs=jjs,dGe=MU,kjs=bjs,Sjs=Njs,Cjs="[object Null]",Tjs="[object Undefined]",uGe=dGe?dGe.toStringTag:void 0;function Ejs(s){return s==null?s===void 0?Tjs:Cjs:uGe&&uGe in Object(s)?kjs(s):Sjs(s)}var EN=Ejs;function Ajs(s){return s!=null&&typeof s=="object"}var AN=Ajs,Mjs=EN,Ijs=AN,Pjs="[object Symbol]";function Ljs(s){return typeof s=="symbol"||Ijs(s)&&Mjs(s)==Pjs}var aR=Ljs,Djs=o0,Rjs=aR,Ojs=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Fjs=/^\w*$/;function zjs(s,t){if(Djs(s))return!1;var n=typeof s;return n=="number"||n=="symbol"||n=="boolean"||s==null||Rjs(s)?!0:Fjs.test(s)||!Ojs.test(s)||t!=null&&s in Object(t)}var nPe=zjs;function Bjs(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var dC=Bjs;const iR=wl(dC);var $js=EN,Ujs=dC,qjs="[object AsyncFunction]",Vjs="[object Function]",Hjs="[object GeneratorFunction]",Gjs="[object Proxy]";function Wjs(s){if(!Ujs(s))return!1;var t=$js(s);return t==Vjs||t==Hjs||t==qjs||t==Gjs}var rPe=Wjs;const ho=wl(rPe);var Kjs=Jw,Yjs=Kjs["__core-js_shared__"],Zjs=Yjs,G2e=Zjs,hGe=function(){var s=/[^.]+$/.exec(G2e&&G2e.keys&&G2e.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function Qjs(s){return!!hGe&&hGe in s}var Xjs=Qjs,Jjs=Function.prototype,e2s=Jjs.toString;function t2s(s){if(s!=null){try{return e2s.call(s)}catch{}try{return s+""}catch{}}return""}var Lyt=t2s,s2s=rPe,n2s=Xjs,r2s=dC,a2s=Lyt,i2s=/[\\^$.*+?()[\]{}|]/g,o2s=/^\[object .+?Constructor\]$/,l2s=Function.prototype,c2s=Object.prototype,d2s=l2s.toString,u2s=c2s.hasOwnProperty,h2s=RegExp("^"+d2s.call(u2s).replace(i2s,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function m2s(s){if(!r2s(s)||n2s(s))return!1;var t=s2s(s)?h2s:o2s;return t.test(a2s(s))}var p2s=m2s;function f2s(s,t){return s==null?void 0:s[t]}var x2s=f2s,g2s=p2s,y2s=x2s;function v2s(s,t){var n=y2s(s,t);return g2s(n)?n:void 0}var t6=v2s,b2s=t6,_2s=b2s(Object,"create"),Dve=_2s,mGe=Dve;function w2s(){this.__data__=mGe?mGe(null):{},this.size=0}var j2s=w2s;function N2s(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var k2s=N2s,S2s=Dve,C2s="__lodash_hash_undefined__",T2s=Object.prototype,E2s=T2s.hasOwnProperty;function A2s(s){var t=this.__data__;if(S2s){var n=t[s];return n===C2s?void 0:n}return E2s.call(t,s)?t[s]:void 0}var M2s=A2s,I2s=Dve,P2s=Object.prototype,L2s=P2s.hasOwnProperty;function D2s(s){var t=this.__data__;return I2s?t[s]!==void 0:L2s.call(t,s)}var R2s=D2s,O2s=Dve,F2s="__lodash_hash_undefined__";function z2s(s,t){var n=this.__data__;return this.size+=this.has(s)?0:1,n[s]=O2s&&t===void 0?F2s:t,this}var B2s=z2s,$2s=j2s,U2s=k2s,q2s=M2s,V2s=R2s,H2s=B2s;function oR(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t-1}var lNs=oNs,cNs=Rve;function dNs(s,t){var n=this.__data__,r=cNs(n,s);return r<0?(++this.size,n.push([s,t])):n[r][1]=t,this}var uNs=dNs,hNs=K2s,mNs=sNs,pNs=aNs,fNs=lNs,xNs=uNs;function lR(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t0?1:-1},tA=function(t){return EM(t)&&t.indexOf("%")===t.length-1},la=function(t){return Fks(t)&&!IU(t)},Uks=function(t){return No(t)},$m=function(t){return la(t)||EM(t)},qks=0,dR=function(t){var n=++qks;return"".concat(t||"").concat(n)},Xx=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)&&!EM(t))return r;var i;if(tA(t)){var l=t.indexOf("%");i=n*parseFloat(t.slice(0,l))/100}else i=+t;return IU(i)&&(i=r),a&&i>n&&(i=n),i},xS=function(t){if(!t)return null;var n=Object.keys(t);return n&&n.length?t[n[0]]:null},Vks=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 Qks(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 k3e(s){"@babel/helpers - typeof";return k3e=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},k3e(s)}var bGe={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"},sN=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},_Ge=null,K2e=null,pPe=function s(t){if(t===_Ge&&Array.isArray(K2e))return K2e;var n=[];return N.Children.forEach(t,function(r){No(r)||(Pks.isFragment(r)?n=n.concat(s(r.props.children)):n.push(r))}),K2e=n,_Ge=t,n};function fy(s,t){var n=[],r=[];return Array.isArray(t)?r=t.map(function(a){return sN(a)}):r=[sN(t)],pPe(s).forEach(function(a){var i=py(a,"type.displayName")||py(a,"type.name");r.indexOf(i)!==-1&&n.push(a)}),n}function q0(s,t){var n=fy(s,t);return n&&n[0]}var wGe=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)},Xks=["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"],Jks=function(t){return t&&t.type&&EM(t.type)&&Xks.indexOf(t.type)>=0},eSs=function(t){return t&&k3e(t)==="object"&&"clipDot"in t},tSs=function(t,n,r,a){var i,l=(i=W2e==null?void 0:W2e[a])!==null&&i!==void 0?i:[];return n.startsWith("data-")||!ho(t)&&(a&&l.includes(n)||Wks.includes(n))||r&&mPe.includes(n)},Wi=function(t,n,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(N.isValidElement(t)&&(a=t.props),!iR(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;tSs((o=a)===null||o===void 0?void 0:o[l],l,n,r)&&(i[l]=a[l])}),i},S3e=function s(t,n){if(t===n)return!0;var r=N.Children.count(t);if(r!==N.Children.count(n))return!1;if(r===0)return!0;if(r===1)return jGe(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 iSs(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 T3e(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=aSs(s,rSs),u=a||{width:n,height:r,x:0,y:0},h=So("recharts-surface",i);return St.createElement("svg",C3e({},Wi(d,!0,"svg"),{className:h,width:n,height:r,style:l,viewBox:"".concat(u.x," ").concat(u.y," ").concat(u.width," ").concat(u.height)}),St.createElement("title",null,o),St.createElement("desc",null,c),t)}var oSs=["children","className"];function E3e(){return E3e=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 cSs(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 Kl=St.forwardRef(function(s,t){var n=s.children,r=s.className,a=lSs(s,oSs),i=So("recharts-layer",r);return St.createElement("g",E3e({className:i},Wi(a,!0),{ref:t}),n)}),Nb=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:hSs(s,t,n)}var pSs=mSs,fSs="\\ud800-\\udfff",xSs="\\u0300-\\u036f",gSs="\\ufe20-\\ufe2f",ySs="\\u20d0-\\u20ff",vSs=xSs+gSs+ySs,bSs="\\ufe0e\\ufe0f",_Ss="\\u200d",wSs=RegExp("["+_Ss+fSs+vSs+bSs+"]");function jSs(s){return wSs.test(s)}var Vyt=jSs;function NSs(s){return s.split("")}var kSs=NSs,Hyt="\\ud800-\\udfff",SSs="\\u0300-\\u036f",CSs="\\ufe20-\\ufe2f",TSs="\\u20d0-\\u20ff",ESs=SSs+CSs+TSs,ASs="\\ufe0e\\ufe0f",MSs="["+Hyt+"]",A3e="["+ESs+"]",M3e="\\ud83c[\\udffb-\\udfff]",ISs="(?:"+A3e+"|"+M3e+")",Gyt="[^"+Hyt+"]",Wyt="(?:\\ud83c[\\udde6-\\uddff]){2}",Kyt="[\\ud800-\\udbff][\\udc00-\\udfff]",PSs="\\u200d",Yyt=ISs+"?",Zyt="["+ASs+"]?",LSs="(?:"+PSs+"(?:"+[Gyt,Wyt,Kyt].join("|")+")"+Zyt+Yyt+")*",DSs=Zyt+Yyt+LSs,RSs="(?:"+[Gyt+A3e+"?",A3e,Wyt,Kyt,MSs].join("|")+")",OSs=RegExp(M3e+"(?="+M3e+")|"+RSs+DSs,"g");function FSs(s){return s.match(OSs)||[]}var zSs=FSs,BSs=kSs,$Ss=Vyt,USs=zSs;function qSs(s){return $Ss(s)?USs(s):BSs(s)}var VSs=qSs,HSs=pSs,GSs=Vyt,WSs=VSs,KSs=Fyt;function YSs(s){return function(t){t=KSs(t);var n=GSs(t)?WSs(t):void 0,r=n?n[0]:t.charAt(0),a=n?HSs(n,1).join(""):t.slice(1);return r[s]()+a}}var ZSs=YSs,QSs=ZSs,XSs=QSs("toUpperCase"),JSs=XSs;const Zve=wl(JSs);function vd(s){return function(){return s}}const Qyt=Math.cos,Fxe=Math.sin,Fb=Math.sqrt,zxe=Math.PI,Qve=2*zxe,I3e=Math.PI,P3e=2*I3e,IE=1e-6,e4s=P3e-IE;function Xyt(s){this._+=s[0];for(let t=1,n=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return Xyt;const n=10**t;return function(r){this._+=r[0];for(let a=1,i=r.length;aIE)if(!(Math.abs(h*c-d*u)>IE)||!i)this._append`L${this._x1=t},${this._y1=n}`;else{let f=r-l,g=a-o,_=c*c+d*d,v=f*f+g*g,j=Math.sqrt(_),b=Math.sqrt(p),S=i*Math.tan((I3e-Math.acos((_+p-v)/(2*j*b)))/2),A=S/b,T=S/j;Math.abs(A-1)>IE&&this._append`L${t+A*u},${n+A*h}`,this._append`A${i},${i},0,0,${+(h*f>u*g)},${this._x1=t+T*c},${this._y1=n+T*d}`}}arc(t,n,r,a,i,l){if(t=+t,n=+n,r=+r,l=!!l,r<0)throw new Error(`negative radius: ${r}`);let o=r*Math.cos(a),c=r*Math.sin(a),d=t+o,u=n+c,h=1^l,p=l?a-i:i-a;this._x1===null?this._append`M${d},${u}`:(Math.abs(this._x1-d)>IE||Math.abs(this._y1-u)>IE)&&this._append`L${d},${u}`,r&&(p<0&&(p=p%P3e+P3e),p>e4s?this._append`A${r},${r},0,1,${h},${t-o},${n-c}A${r},${r},0,1,${h},${this._x1=d},${this._y1=u}`:p>IE&&this._append`A${r},${r},0,${+(p>=I3e)},${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 fPe(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 s4s(t)}function xPe(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function Jyt(s){this._context=s}Jyt.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 Xve(s){return new Jyt(s)}function evt(s){return s[0]}function tvt(s){return s[1]}function svt(s,t){var n=vd(!0),r=null,a=Xve,i=null,l=fPe(o);s=typeof s=="function"?s:s===void 0?evt:vd(s),t=typeof t=="function"?t:t===void 0?tvt:vd(t);function o(c){var d,u=(c=xPe(c)).length,h,p=!1,f;for(r==null&&(i=a(f=l())),d=0;d<=u;++d)!(d=f;--g)o.point(S[g],A[g]);o.lineEnd(),o.areaEnd()}j&&(S[p]=+s(v,p,h),A[p]=+t(v,p,h),o.point(r?+r(v,p,h):S[p],n?+n(v,p,h):A[p]))}if(b)return o=null,b+""||null}function u(){return svt().defined(a).curve(l).context(i)}return d.x=function(h){return arguments.length?(s=typeof h=="function"?h:vd(+h),r=null,d):s},d.x0=function(h){return arguments.length?(s=typeof h=="function"?h:vd(+h),d):s},d.x1=function(h){return arguments.length?(r=h==null?null:typeof h=="function"?h:vd(+h),d):r},d.y=function(h){return arguments.length?(t=typeof h=="function"?h:vd(+h),n=null,d):t},d.y0=function(h){return arguments.length?(t=typeof h=="function"?h:vd(+h),d):t},d.y1=function(h){return arguments.length?(n=h==null?null:typeof h=="function"?h:vd(+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:vd(!!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 nvt{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 n4s(s){return new nvt(s,!0)}function r4s(s){return new nvt(s,!1)}const gPe={draw(s,t){const n=Fb(t/zxe);s.moveTo(n,0),s.arc(0,0,n,0,Qve)}},a4s={draw(s,t){const n=Fb(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()}},rvt=Fb(1/3),i4s=rvt*2,o4s={draw(s,t){const n=Fb(t/i4s),r=n*rvt;s.moveTo(0,-n),s.lineTo(r,0),s.lineTo(0,n),s.lineTo(-r,0),s.closePath()}},l4s={draw(s,t){const n=Fb(t),r=-n/2;s.rect(r,r,n,n)}},c4s=.8908130915292852,avt=Fxe(zxe/10)/Fxe(7*zxe/10),d4s=Fxe(Qve/10)*avt,u4s=-Qyt(Qve/10)*avt,h4s={draw(s,t){const n=Fb(t*c4s),r=d4s*n,a=u4s*n;s.moveTo(0,-n),s.lineTo(r,a);for(let i=1;i<5;++i){const l=Qve*i/5,o=Qyt(l),c=Fxe(l);s.lineTo(c*n,-o*n),s.lineTo(o*r-c*a,c*r+o*a)}s.closePath()}},Y2e=Fb(3),m4s={draw(s,t){const n=-Fb(t/(Y2e*3));s.moveTo(0,n*2),s.lineTo(-Y2e*n,-n),s.lineTo(Y2e*n,-n),s.closePath()}},rv=-.5,av=Fb(3)/2,L3e=1/Fb(12),p4s=(L3e/2+1)*3,f4s={draw(s,t){const n=Fb(t/p4s),r=n/2,a=n*L3e,i=r,l=n*L3e+n,o=-i,c=l;s.moveTo(r,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(rv*r-av*a,av*r+rv*a),s.lineTo(rv*i-av*l,av*i+rv*l),s.lineTo(rv*o-av*c,av*o+rv*c),s.lineTo(rv*r+av*a,rv*a-av*r),s.lineTo(rv*i+av*l,rv*l-av*i),s.lineTo(rv*o+av*c,rv*c-av*o),s.closePath()}};function x4s(s,t){let n=null,r=fPe(a);s=typeof s=="function"?s:vd(s||gPe),t=typeof t=="function"?t:vd(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:vd(i),a):s},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:vd(+i),a):t},a.context=function(i){return arguments.length?(n=i??null,a):n},a}function Bxe(){}function $xe(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 ivt(s){this._context=s}ivt.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:$xe(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:$xe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function g4s(s){return new ivt(s)}function ovt(s){this._context=s}ovt.prototype={areaStart:Bxe,areaEnd:Bxe,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:$xe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function y4s(s){return new ovt(s)}function lvt(s){this._context=s}lvt.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:$xe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function v4s(s){return new lvt(s)}function cvt(s){this._context=s}cvt.prototype={areaStart:Bxe,areaEnd:Bxe,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 b4s(s){return new cvt(s)}function kGe(s){return s<0?-1:1}function SGe(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(kGe(i)+kGe(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function CGe(s,t){var n=s._x1-s._x0;return n?(3*(s._y1-s._y0)/n-t)/2:t}function Z2e(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 Uxe(s){this._context=s}Uxe.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:Z2e(this,this._t0,CGe(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,Z2e(this,CGe(this,n=SGe(this,s,t)),n);break;default:Z2e(this,this._t0,n=SGe(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=n}}};function dvt(s){this._context=new uvt(s)}(dvt.prototype=Object.create(Uxe.prototype)).point=function(s,t){Uxe.prototype.point.call(this,t,s)};function uvt(s){this._context=s}uvt.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 _4s(s){return new Uxe(s)}function w4s(s){return new dvt(s)}function hvt(s){this._context=s}hvt.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=TGe(s),a=TGe(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 N4s(s){return new Jve(s,.5)}function k4s(s){return new Jve(s,0)}function S4s(s){return new Jve(s,1)}function O8(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 C4s(s,t){return s[t]}function T4s(s){const t=[];return t.key=s,t}function E4s(){var s=vd([]),t=D3e,n=O8,r=C4s;function a(i){var l=Array.from(s.apply(this,arguments),T4s),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 F4s(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 mvt={symbolCircle:gPe,symbolCross:a4s,symbolDiamond:o4s,symbolSquare:l4s,symbolStar:h4s,symbolTriangle:m4s,symbolWye:f4s},z4s=Math.PI/180,B4s=function(t){var n="symbol".concat(Zve(t));return mvt[n]||gPe},$4s=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*z4s;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}},U4s=function(t,n){mvt["symbol".concat(Zve(t))]=n},yPe=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=O4s(t,P4s),d=AGe(AGe({},c),{},{type:r,size:i,sizeType:o}),u=function(){var v=B4s(r),j=x4s().type(v).size($4s(i,o,r));return j()},h=d.className,p=d.cx,f=d.cy,g=Wi(d,!0);return p===+p&&f===+f&&i===+i?St.createElement("path",R3e({},g,{className:So("recharts-symbols",h),transform:"translate(".concat(p,", ").concat(f,")"),d:u()})):null};yPe.registerSymbol=U4s;function F8(s){"@babel/helpers - typeof";return F8=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},F8(s)}function O3e(){return O3e=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var b=f.inactive?d:f.color;return St.createElement("li",O3e({className:v,style:h,key:"legend-item-".concat(g)},AM(r.props,f,g)),St.createElement(T3e,{width:l,height:l,viewBox:u,style:p},r.renderIcon(f)),St.createElement("span",{className:"recharts-legend-item-text",style:{color:b}},_?_(j,f,g):j))})}},{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 St.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(N.PureComponent);OB(vPe,"displayName","Legend");OB(vPe,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var X4s=Ove;function J4s(){this.__data__=new X4s,this.size=0}var eCs=J4s;function tCs(s){var t=this.__data__,n=t.delete(s);return this.size=t.size,n}var sCs=tCs;function nCs(s){return this.__data__.get(s)}var rCs=nCs;function aCs(s){return this.__data__.has(s)}var iCs=aCs,oCs=Ove,lCs=iPe,cCs=oPe,dCs=200;function uCs(s,t){var n=this.__data__;if(n instanceof oCs){var r=n.__data__;if(!lCs||r.lengtho))return!1;var d=i.get(s),u=i.get(t);if(d&&u)return d==t&&u==s;var h=-1,p=!0,f=n&PCs?new ECs:void 0;for(i.set(s,t),i.set(t,s);++h-1&&s%1==0&&s-1&&s%1==0&&s<=O3s}var jPe=F3s,z3s=EN,B3s=jPe,$3s=AN,U3s="[object Arguments]",q3s="[object Array]",V3s="[object Boolean]",H3s="[object Date]",G3s="[object Error]",W3s="[object Function]",K3s="[object Map]",Y3s="[object Number]",Z3s="[object Object]",Q3s="[object RegExp]",X3s="[object Set]",J3s="[object String]",e5s="[object WeakMap]",t5s="[object ArrayBuffer]",s5s="[object DataView]",n5s="[object Float32Array]",r5s="[object Float64Array]",a5s="[object Int8Array]",i5s="[object Int16Array]",o5s="[object Int32Array]",l5s="[object Uint8Array]",c5s="[object Uint8ClampedArray]",d5s="[object Uint16Array]",u5s="[object Uint32Array]",Ld={};Ld[n5s]=Ld[r5s]=Ld[a5s]=Ld[i5s]=Ld[o5s]=Ld[l5s]=Ld[c5s]=Ld[d5s]=Ld[u5s]=!0;Ld[U3s]=Ld[q3s]=Ld[t5s]=Ld[V3s]=Ld[s5s]=Ld[H3s]=Ld[G3s]=Ld[W3s]=Ld[K3s]=Ld[Y3s]=Ld[Z3s]=Ld[Q3s]=Ld[X3s]=Ld[J3s]=Ld[e5s]=!1;function h5s(s){return $3s(s)&&B3s(s.length)&&!!Ld[z3s(s)]}var m5s=h5s;function p5s(s){return function(t){return s(t)}}var Nvt=p5s,Gxe={exports:{}};Gxe.exports;(function(s,t){var n=Iyt,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})(Gxe,Gxe.exports);var f5s=Gxe.exports,x5s=m5s,g5s=Nvt,OGe=f5s,FGe=OGe&&OGe.isTypedArray,y5s=FGe?g5s(FGe):x5s,kvt=y5s,v5s=w3s,b5s=_Pe,_5s=o0,w5s=jvt,j5s=wPe,N5s=kvt,k5s=Object.prototype,S5s=k5s.hasOwnProperty;function C5s(s,t){var n=_5s(s),r=!n&&b5s(s),a=!n&&!r&&w5s(s),i=!n&&!r&&!a&&N5s(s),l=n||r||a||i,o=l?v5s(s.length,String):[],c=o.length;for(var d in s)(t||S5s.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||j5s(d,c)))&&o.push(d);return o}var T5s=C5s,E5s=Object.prototype;function A5s(s){var t=s&&s.constructor,n=typeof t=="function"&&t.prototype||E5s;return s===n}var M5s=A5s;function I5s(s,t){return function(n){return s(t(n))}}var Svt=I5s,P5s=Svt,L5s=P5s(Object.keys,Object),D5s=L5s,R5s=M5s,O5s=D5s,F5s=Object.prototype,z5s=F5s.hasOwnProperty;function B5s(s){if(!R5s(s))return O5s(s);var t=[];for(var n in Object(s))z5s.call(s,n)&&n!="constructor"&&t.push(n);return t}var $5s=B5s,U5s=rPe,q5s=jPe;function V5s(s){return s!=null&&q5s(s.length)&&!U5s(s)}var PU=V5s,H5s=T5s,G5s=$5s,W5s=PU;function K5s(s){return W5s(s)?H5s(s):G5s(s)}var e1e=K5s,Y5s=d3s,Z5s=b3s,Q5s=e1e;function X5s(s){return Y5s(s,Q5s,Z5s)}var J5s=X5s,zGe=J5s,eTs=1,tTs=Object.prototype,sTs=tTs.hasOwnProperty;function nTs(s,t,n,r,a,i){var l=n&eTs,o=zGe(s),c=o.length,d=zGe(t),u=d.length;if(c!=u&&!l)return!1;for(var h=c;h--;){var p=o[h];if(!(l?p in t:sTs.call(t,p)))return!1}var f=i.get(s),g=i.get(t);if(f&&g)return f==t&&g==s;var _=!0;i.set(s,t),i.set(t,s);for(var v=l;++h-1}var tAs=eAs;function sAs(s,t,n){for(var r=-1,a=s==null?0:s.length;++r=gAs){var d=t?null:fAs(s);if(d)return xAs(d);l=!1,a=pAs,c=new uAs}else c=t?[]:o;e:for(;++r=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function PAs(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 LAs(s){return s.value}function DAs(s,t){if(St.isValidElement(s))return St.cloneElement(s,t);if(typeof s=="function")return St.createElement(s,t);t.ref;var n=IAs(t,NAs);return St.createElement(vPe,n)}var tWe=1,XA=function(s){function t(){var n;kAs(this,t);for(var r=arguments.length,a=new Array(r),i=0;itWe||Math.abs(a.height-this.lastBoundingBox.height)>tWe)&&(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?l2({},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,p;if(!r||(r.left===void 0||r.left===null)&&(r.right===void 0||r.right===null))if(l==="center"&&i==="vertical"){var f=this.getBBoxSnapshot();h={left:((d||0)-f.width)/2}}else h=l==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!r||(r.top===void 0||r.top===null)&&(r.bottom===void 0||r.bottom===null))if(o==="middle"){var g=this.getBBoxSnapshot();p={top:((u||0)-g.height)/2}}else p=o==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return l2(l2({},h),p)}},{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=l2(l2({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return St.createElement("div",{className:"recharts-legend-wrapper",style:h,ref:function(f){r.wrapperNode=f}},DAs(i,l2(l2({},this.props),{},{payload:Pvt(u,d,LAs)})))}}],[{key:"getWithHeight",value:function(r,a){var i=l2(l2({},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}}])}(N.PureComponent);t1e(XA,"displayName","Legend");t1e(XA,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var sWe=MU,RAs=_Pe,OAs=o0,nWe=sWe?sWe.isConcatSpreadable:void 0;function FAs(s){return OAs(s)||RAs(s)||!!(nWe&&s&&s[nWe])}var zAs=FAs,BAs=_vt,$As=zAs;function Rvt(s,t,n,r,a){var i=-1,l=s.length;for(n||(n=$As),a||(a=[]);++i0&&n(o)?t>1?Rvt(o,t-1,n,r,a):BAs(a,o):r||(a[a.length]=o)}return a}var Ovt=Rvt;function UAs(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 qAs=UAs,VAs=qAs,HAs=VAs(),GAs=HAs,WAs=GAs,KAs=e1e;function YAs(s,t){return s&&WAs(s,t,KAs)}var Fvt=YAs,ZAs=PU;function QAs(s,t){return function(n,r){if(n==null)return n;if(!ZAs(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 uMs=dMs,eNe=cPe,hMs=dPe,mMs=ej,pMs=zvt,fMs=iMs,xMs=Nvt,gMs=uMs,yMs=mR,vMs=o0;function bMs(s,t,n){t.length?t=eNe(t,function(i){return vMs(i)?function(l){return hMs(l,i.length===1?i[0]:i)}:i}):t=[yMs];var r=-1;t=eNe(t,xMs(mMs));var a=pMs(s,function(i,l,o){var c=eNe(t,function(d){return d(i)});return{criteria:c,index:++r,value:i}});return fMs(a,function(i,l){return gMs(i,l,n)})}var _Ms=bMs;function wMs(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 jMs=wMs,NMs=jMs,aWe=Math.max;function kMs(s,t,n){return t=aWe(t===void 0?s.length-1:t,0),function(){for(var r=arguments,a=-1,i=aWe(r.length-t,0),l=Array(i);++a0){if(++t>=DMs)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var zMs=FMs,BMs=LMs,$Ms=zMs,UMs=$Ms(BMs),qMs=UMs,VMs=mR,HMs=SMs,GMs=qMs;function WMs(s,t){return GMs(HMs(s,t,VMs),s+"")}var KMs=WMs,YMs=aPe,ZMs=PU,QMs=wPe,XMs=dC;function JMs(s,t,n){if(!XMs(n))return!1;var r=typeof t;return(r=="number"?ZMs(n)&&QMs(t,n.length):r=="string"&&t in n)?YMs(n[t],s):!1}var s1e=JMs,e6s=Ovt,t6s=_Ms,s6s=KMs,oWe=s1e,n6s=s6s(function(s,t){if(s==null)return[];var n=t.length;return n>1&&oWe(s,t[0],t[1])?t=[]:n>2&&oWe(t[0],t[1],t[2])&&(t=[t[0]]),t6s(s,e6s(t,1),[])}),r6s=n6s;const SPe=wl(r6s);function FB(s){"@babel/helpers - typeof";return FB=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},FB(s)}function H3e(){return H3e=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(kF,"-left"),la(n)&&t&&la(t.x)&&n=t.y),"".concat(kF,"-top"),la(r)&&t&&la(t.y)&&r_?Math.max(u,c[r]):Math.max(h,c[r])}function v6s(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 b6s(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=dWe({allowEscapeViewBox:t,coordinate:n,key:"x",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),h=dWe({allowEscapeViewBox:t,coordinate:n,key:"y",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=v6s({translateX:u,translateY:h,useTranslate3d:o})):d=g6s,{cssProperties:d,cssClasses:y6s({translateX:u,translateY:h,coordinate:n})}}function B8(s){"@babel/helpers - typeof";return B8=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},B8(s)}function uWe(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 hWe(s){for(var t=1;tmWe||Math.abs(r.height-this.state.lastBoundingBox.height)>mWe)&&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,p=a.isAnimationActive,f=a.offset,g=a.position,_=a.reverseDirection,v=a.useTranslate3d,j=a.viewBox,b=a.wrapperStyle,S=b6s({allowEscapeViewBox:l,coordinate:u,offsetTopLeft:f,position:g,reverseDirection:_,tooltipBox:this.state.lastBoundingBox,useTranslate3d:v,viewBox:j}),A=S.cssClasses,T=S.cssProperties,L=hWe(hWe({transition:p&&i?"transform ".concat(o,"ms ").concat(c):void 0},T),{},{pointerEvents:"none",visibility:!this.state.dismissed&&i&&h?"visible":"hidden",position:"absolute",top:0,left:0},b);return St.createElement("div",{tabIndex:-1,className:A,style:L,ref:function(M){r.wrapperNode=M}},d)}}])}(N.PureComponent),A6s=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},Nw={isSsr:A6s(),get:function(t){return Nw[t]},set:function(t,n){if(typeof t=="string")Nw[t]=n;else{var r=Object.keys(t);r&&r.length&&r.forEach(function(a){Nw[a]=t[a]})}}};function $8(s){"@babel/helpers - typeof";return $8=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},$8(s)}function pWe(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 fWe(s){for(var t=1;t0;return St.createElement(E6s,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:p,active:i,coordinate:u,hasPayload:L,offset:f,position:v,reverseDirection:j,useTranslate3d:b,viewBox:S,wrapperStyle:A},B6s(d,fWe(fWe({},this.props),{},{payload:T})))}}])}(N.PureComponent);CPe(Np,"displayName","Tooltip");CPe(Np,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!Nw.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 $6s=Jw,U6s=function(){return $6s.Date.now()},q6s=U6s,V6s=/\s/;function H6s(s){for(var t=s.length;t--&&V6s.test(s.charAt(t)););return t}var G6s=H6s,W6s=G6s,K6s=/^\s+/;function Y6s(s){return s&&s.slice(0,W6s(s)+1).replace(K6s,"")}var Z6s=Y6s,Q6s=Z6s,xWe=dC,X6s=aR,gWe=NaN,J6s=/^[-+]0x[0-9a-f]+$/i,eIs=/^0b[01]+$/i,tIs=/^0o[0-7]+$/i,sIs=parseInt;function nIs(s){if(typeof s=="number")return s;if(X6s(s))return gWe;if(xWe(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=xWe(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=Q6s(s);var n=eIs.test(s);return n||tIs.test(s)?sIs(s.slice(2),n?2:8):J6s.test(s)?gWe:+s}var Hvt=nIs,rIs=dC,sNe=q6s,yWe=Hvt,aIs="Expected a function",iIs=Math.max,oIs=Math.min;function lIs(s,t,n){var r,a,i,l,o,c,d=0,u=!1,h=!1,p=!0;if(typeof s!="function")throw new TypeError(aIs);t=yWe(t)||0,rIs(n)&&(u=!!n.leading,h="maxWait"in n,i=h?iIs(yWe(n.maxWait)||0,t):i,p="trailing"in n?!!n.trailing:p);function f(L){var D=r,M=a;return r=a=void 0,d=L,l=s.apply(M,D),l}function g(L){return d=L,o=setTimeout(j,t),u?f(L):l}function _(L){var D=L-c,M=L-d,F=t-D;return h?oIs(F,i-M):F}function v(L){var D=L-c,M=L-d;return c===void 0||D>=t||D<0||h&&M>=i}function j(){var L=sNe();if(v(L))return b(L);o=setTimeout(j,_(L))}function b(L){return o=void 0,p&&r?f(L):(r=a=void 0,l)}function S(){o!==void 0&&clearTimeout(o),d=0,r=c=a=o=void 0}function A(){return o===void 0?l:b(sNe())}function T(){var L=sNe(),D=v(L);if(r=arguments,a=this,c=L,D){if(o===void 0)return g(c);if(h)return clearTimeout(o),o=setTimeout(j,t),f(c)}return o===void 0&&(o=setTimeout(j,t)),l}return T.cancel=S,T.flush=A,T}var cIs=lIs,dIs=cIs,uIs=dC,hIs="Expected a function";function mIs(s,t,n){var r=!0,a=!0;if(typeof s!="function")throw new TypeError(hIs);return uIs(n)&&(r="leading"in n?!!n.leading:r,a="trailing"in n?!!n.trailing:a),dIs(s,t,{leading:r,maxWait:t,trailing:a})}var pIs=mIs;const Gvt=wl(pIs);function BB(s){"@babel/helpers - typeof";return BB=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},BB(s)}function vWe(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 eG(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&(Y=Gvt(Y,_,{trailing:!0,leading:!1}));var K=new ResizeObserver(Y),J=T.current.getBoundingClientRect(),ne=J.width,ie=J.height;return V(ne,ie),K.observe(T.current),function(){K.disconnect()}},[V,_]);var W=N.useMemo(function(){var Y=F.containerWidth,K=F.containerHeight;if(Y<0||K<0)return null;Nb(tA(l)||tA(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),Nb(!n||n>0,"The aspect(%s) must be greater than zero.",n);var J=tA(l)?Y:l,ne=tA(c)?K:c;n&&n>0&&(J?ne=J/n:ne&&(J=ne*n),p&&ne>p&&(ne=p)),Nb(J>0||ne>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.`,J,ne,l,c,u,h,n);var ie=!Array.isArray(f)&&sN(f.type).endsWith("Chart");return St.Children.map(f,function(he){return St.isValidElement(he)?N.cloneElement(he,eG({width:J,height:ne},ie?{style:eG({height:"100%",width:"100%",maxHeight:ne,maxWidth:J},he.props.style)}:{})):he})},[n,f,c,p,h,u,F,l]);return St.createElement("div",{id:v?"".concat(v):void 0,className:So("recharts-responsive-container",j),style:eG(eG({},A),{},{width:l,height:c,minWidth:u,minHeight:h,maxHeight:p}),ref:T},W)}),pR=function(t){return null};pR.displayName="Cell";function $B(s){"@babel/helpers - typeof";return $B=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},$B(s)}function _We(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 Y3e(s){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||Nw.isSsr)return{width:0,height:0};var r=TIs(n),a=JSON.stringify({text:t,copyStyle:r});if(LI.widthCache[a])return LI.widthCache[a];try{var i=document.getElementById(wWe);i||(i=document.createElement("span"),i.setAttribute("id",wWe),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=Y3e(Y3e({},CIs),r);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return LI.widthCache[a]=c,++LI.cacheCount>SIs&&(LI.cacheCount=0,LI.widthCache={}),c}catch{return{width:0,height:0}}},EIs=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function UB(s){"@babel/helpers - typeof";return UB=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},UB(s)}function Zxe(s,t){return PIs(s)||IIs(s,t)||MIs(s,t)||AIs()}function AIs(){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 MIs(s,t){if(s){if(typeof s=="string")return jWe(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 jWe(s,t)}}function jWe(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 WIs(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 EWe(s,t){return QIs(s)||ZIs(s,t)||YIs(s,t)||KIs()}function KIs(){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 YIs(s,t){if(s){if(typeof s=="string")return AWe(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 AWe(s,t)}}function AWe(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 J.reduce(function(ne,ie){var he=ie.word,ce=ie.width,pe=ne[ne.length-1];if(pe&&(a==null||i||pe.width+ce+rie.width?ne:ie})};if(!u)return f;for(var _="…",v=function(J){var ne=h.slice(0,J),ie=Zvt({breakAll:d,style:c,children:ne+_}).wordsWithComputedWidth,he=p(ie),ce=he.length>l||g(he).width>Number(a);return[ce,he]},j=0,b=h.length-1,S=0,A;j<=b&&S<=h.length-1;){var T=Math.floor((j+b)/2),L=T-1,D=v(L),M=EWe(D,2),F=M[0],z=M[1],V=v(T),W=EWe(V,1),Y=W[0];if(!F&&!Y&&(j=T+1),F&&Y&&(b=T-1),!F&&Y){A=z;break}S++}return A||f},MWe=function(t){var n=No(t)?[]:t.toString().split(Yvt);return[{words:n}]},JIs=function(t){var n=t.width,r=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((n||r)&&!Nw.isSsr){var c,d,u=Zvt({breakAll:l,children:a,style:i});if(u){var h=u.wordsWithComputedWidth,p=u.spaceWidth;c=h,d=p}else return MWe(a);return XIs({breakAll:l,children:a,maxLines:o,style:i},c,d,n,r)}return MWe(a)},IWe="#808080",MM=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,p=t.textAnchor,f=p===void 0?"start":p,g=t.verticalAnchor,_=g===void 0?"end":g,v=t.fill,j=v===void 0?IWe:v,b=TWe(t,HIs),S=N.useMemo(function(){return JIs({breakAll:b.breakAll,children:b.children,maxLines:b.maxLines,scaleToFit:h,style:b.style,width:b.width})},[b.breakAll,b.children,b.maxLines,h,b.style,b.width]),A=b.dx,T=b.dy,L=b.angle,D=b.className,M=b.breakAll,F=TWe(b,GIs);if(!$m(r)||!$m(i))return null;var z=r+(la(A)?A:0),V=i+(la(T)?T:0),W;switch(_){case"start":W=nNe("calc(".concat(d,")"));break;case"middle":W=nNe("calc(".concat((S.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:W=nNe("calc(".concat(S.length-1," * -").concat(o,")"));break}var Y=[];if(h){var K=S[0].width,J=b.width;Y.push("scale(".concat((la(J)?J/K:1)/K,")"))}return L&&Y.push("rotate(".concat(L,", ").concat(z,", ").concat(V,")")),Y.length&&(F.transform=Y.join(" ")),St.createElement("text",Z3e({},Wi(F,!0),{x:z,y:V,className:So("recharts-text",D),textAnchor:f,fill:j.includes("url")?IWe:j}),S.map(function(ne,ie){var he=ne.words.join(M?"":" ");return St.createElement("tspan",{x:z,dy:ie===0?W:o,key:"".concat(he,"-").concat(ie)},he)}))};function _4(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function ePs(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function TPe(s){let t,n,r;s.length!==2?(t=_4,n=(o,c)=>_4(s(o),c),r=(o,c)=>s(o)-c):(t=s===_4||s===ePs?s:tPs,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 tPs(){return 0}function Qvt(s){return s===null?NaN:+s}function*sPs(s,t){for(let n of s)n!=null&&(n=+n)>=n&&(yield n)}const nPs=TPe(_4),LU=nPs.right;TPe(Qvt).center;class PWe extends Map{constructor(t,n=iPs){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(LWe(this,t))}has(t){return super.has(LWe(this,t))}set(t,n){return super.set(rPs(this,t),n)}delete(t){return super.delete(aPs(this,t))}}function LWe({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):n}function rPs({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):(s.set(r,n),n)}function aPs({_intern:s,_key:t},n){const r=t(n);return s.has(r)&&(n=s.get(r),s.delete(r)),n}function iPs(s){return s!==null&&typeof s=="object"?s.valueOf():s}function oPs(s=_4){if(s===_4)return Xvt;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 Xvt(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const lPs=Math.sqrt(50),cPs=Math.sqrt(10),dPs=Math.sqrt(2);function Qxe(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>=lPs?10:i>=cPs?5:i>=dPs?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 RWe(s,t){let n;for(const r of s)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function Jvt(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?Xvt:oPs(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),p=.5*Math.sqrt(u*h*(c-h)/c)*(d-c/2<0?-1:1),f=Math.max(n,Math.floor(t-d*h/c+p)),g=Math.min(r,Math.floor(t+(c-d)*h/c+p));Jvt(s,t,f,g,a)}const i=s[t];let l=n,o=r;for(SF(s,n,t),a(s[r],i)>0&&SF(s,n,r);l0;)--o}a(s[n],i)===0?SF(s,n,o):(++o,SF(s,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}return s}function SF(s,t,n){const r=s[t];s[t]=s[n],s[n]=r}function uPs(s,t,n){if(s=Float64Array.from(sPs(s)),!(!(r=s.length)||isNaN(t=+t))){if(t<=0||r<2)return RWe(s);if(t>=1)return DWe(s);var r,a=(r-1)*t,i=Math.floor(a),l=DWe(Jvt(s,i).subarray(0,i+1)),o=RWe(s.subarray(i+1));return l+(o-l)*(a-i)}}function hPs(s,t,n=Qvt){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 mPs(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?sG(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?sG(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=fPs.exec(s))?new Fg(t[1],t[2],t[3],1):(t=xPs.exec(s))?new Fg(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=gPs.exec(s))?sG(t[1],t[2],t[3],t[4]):(t=yPs.exec(s))?sG(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=vPs.exec(s))?qWe(t[1],t[2]/100,t[3]/100,1):(t=bPs.exec(s))?qWe(t[1],t[2]/100,t[3]/100,t[4]):OWe.hasOwnProperty(s)?BWe(OWe[s]):s==="transparent"?new Fg(NaN,NaN,NaN,0):null}function BWe(s){return new Fg(s>>16&255,s>>8&255,s&255,1)}function sG(s,t,n,r){return r<=0&&(s=t=n=NaN),new Fg(s,t,n,r)}function jPs(s){return s instanceof DU||(s=GB(s)),s?(s=s.rgb(),new Fg(s.r,s.g,s.b,s.opacity)):new Fg}function t5e(s,t,n,r){return arguments.length===1?jPs(s):new Fg(s,t,n,r??1)}function Fg(s,t,n,r){this.r=+s,this.g=+t,this.b=+n,this.opacity=+r}APe(Fg,t5e,t1t(DU,{brighter(s){return s=s==null?Xxe:Math.pow(Xxe,s),new Fg(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?VB:Math.pow(VB,s),new Fg(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new Fg(JA(this.r),JA(this.g),JA(this.b),Jxe(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:$We,formatHex:$We,formatHex8:NPs,formatRgb:UWe,toString:UWe}));function $We(){return`#${sA(this.r)}${sA(this.g)}${sA(this.b)}`}function NPs(){return`#${sA(this.r)}${sA(this.g)}${sA(this.b)}${sA((isNaN(this.opacity)?1:this.opacity)*255)}`}function UWe(){const s=Jxe(this.opacity);return`${s===1?"rgb(":"rgba("}${JA(this.r)}, ${JA(this.g)}, ${JA(this.b)}${s===1?")":`, ${s})`}`}function Jxe(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function JA(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function sA(s){return s=JA(s),(s<16?"0":"")+s.toString(16)}function qWe(s,t,n,r){return r<=0?s=t=n=NaN:n<=0||n>=1?s=t=NaN:t<=0&&(s=NaN),new ib(s,t,n,r)}function s1t(s){if(s instanceof ib)return new ib(s.h,s.s,s.l,s.opacity);if(s instanceof DU||(s=GB(s)),!s)return new ib;if(s instanceof ib)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 ib(l,o,c,s.opacity)}function kPs(s,t,n,r){return arguments.length===1?s1t(s):new ib(s,t,n,r??1)}function ib(s,t,n,r){this.h=+s,this.s=+t,this.l=+n,this.opacity=+r}APe(ib,kPs,t1t(DU,{brighter(s){return s=s==null?Xxe:Math.pow(Xxe,s),new ib(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?VB:Math.pow(VB,s),new ib(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 Fg(rNe(s>=240?s-240:s+120,a,r),rNe(s,a,r),rNe(s<120?s+240:s-120,a,r),this.opacity)},clamp(){return new ib(VWe(this.h),nG(this.s),nG(this.l),Jxe(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=Jxe(this.opacity);return`${s===1?"hsl(":"hsla("}${VWe(this.h)}, ${nG(this.s)*100}%, ${nG(this.l)*100}%${s===1?")":`, ${s})`}`}}));function VWe(s){return s=(s||0)%360,s<0?s+360:s}function nG(s){return Math.max(0,Math.min(1,s||0))}function rNe(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 MPe=s=>()=>s;function SPs(s,t){return function(n){return s+n*t}}function CPs(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 TPs(s){return(s=+s)==1?n1t:function(t,n){return n-t?CPs(t,n,s):MPe(isNaN(t)?n:t)}}function n1t(s,t){var n=t-s;return n?SPs(s,n):MPe(isNaN(s)?t:s)}const HWe=function s(t){var n=TPs(t);function r(a,i){var l=n((a=t5e(a)).r,(i=t5e(i)).r),o=n(a.g,i.g),c=n(a.b,i.b),d=n1t(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 EPs(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:ege(r,a)})),n=aNe.lastIndex;return nt&&(n=s,s=t,t=n),function(r){return Math.max(s,Math.min(t,r))}}function BPs(s,t,n){var r=s[0],a=s[1],i=t[0],l=t[1];return a2?$Ps:BPs,c=d=null,h}function h(p){return p==null||isNaN(p=+p)?i:(c||(c=o(s.map(r),t,n)))(r(l(p)))}return h.invert=function(p){return l(a((d||(d=o(t,s.map(r),ege)))(p)))},h.domain=function(p){return arguments.length?(s=Array.from(p,tge),u()):s.slice()},h.range=function(p){return arguments.length?(t=Array.from(p),u()):t.slice()},h.rangeRound=function(p){return t=Array.from(p),n=IPe,u()},h.clamp=function(p){return arguments.length?(l=p?!0:Jx,u()):l!==Jx},h.interpolate=function(p){return arguments.length?(n=p,u()):n},h.unknown=function(p){return arguments.length?(i=p,h):i},function(p,f){return r=p,a=f,u()}}function PPe(){return n1e()(Jx,Jx)}function UPs(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function sge(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 U8(s){return s=sge(Math.abs(s)),s?s[1]:NaN}function qPs(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 VPs(s){return function(t){return t.replace(/[0-9]/g,function(n){return s[+n]})}}var HPs=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function WB(s){if(!(t=HPs.exec(s)))throw new Error("invalid format: "+s);var t;return new LPe({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]})}WB.prototype=LPe.prototype;function LPe(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+""}LPe.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 GPs(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 r1t;function WPs(s,t){var n=sge(s,t);if(!n)return s+"";var r=n[0],a=n[1],i=a-(r1t=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")+sge(s,Math.max(0,t+i-1))[0]}function WWe(s,t){var n=sge(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 KWe={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:UPs,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)=>WWe(s*100,t),r:WWe,s:WPs,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function YWe(s){return s}var ZWe=Array.prototype.map,QWe=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function KPs(s){var t=s.grouping===void 0||s.thousands===void 0?YWe:qPs(ZWe.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?YWe:VPs(ZWe.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=WB(h);var p=h.fill,f=h.align,g=h.sign,_=h.symbol,v=h.zero,j=h.width,b=h.comma,S=h.precision,A=h.trim,T=h.type;T==="n"?(b=!0,T="g"):KWe[T]||(S===void 0&&(S=12),A=!0,T="g"),(v||p==="0"&&f==="=")&&(v=!0,p="0",f="=");var L=_==="$"?n:_==="#"&&/[boxX]/.test(T)?"0"+T.toLowerCase():"",D=_==="$"?r:/[%p]/.test(T)?l:"",M=KWe[T],F=/[defgprs%]/.test(T);S=S===void 0?6:/[gprs]/.test(T)?Math.max(1,Math.min(21,S)):Math.max(0,Math.min(20,S));function z(V){var W=L,Y=D,K,J,ne;if(T==="c")Y=M(V)+Y,V="";else{V=+V;var ie=V<0||1/V<0;if(V=isNaN(V)?c:M(Math.abs(V),S),A&&(V=GPs(V)),ie&&+V==0&&g!=="+"&&(ie=!1),W=(ie?g==="("?g:o:g==="-"||g==="("?"":g)+W,Y=(T==="s"?QWe[8+r1t/3]:"")+Y+(ie&&g==="("?")":""),F){for(K=-1,J=V.length;++Kne||ne>57){Y=(ne===46?a+V.slice(K+1):V.slice(K))+Y,V=V.slice(0,K);break}}}b&&!v&&(V=t(V,1/0));var he=W.length+V.length+Y.length,ce=he>1)+W+V+Y+ce.slice(he);break;default:V=ce+W+V+Y;break}return i(V)}return z.toString=function(){return h+""},z}function u(h,p){var f=d((h=WB(h),h.type="f",h)),g=Math.max(-8,Math.min(8,Math.floor(U8(p)/3)))*3,_=Math.pow(10,-g),v=QWe[8+g/3];return function(j){return f(_*j)+v}}return{format:d,formatPrefix:u}}var rG,DPe,a1t;YPs({thousands:",",grouping:[3],currency:["$",""]});function YPs(s){return rG=KPs(s),DPe=rG.format,a1t=rG.formatPrefix,rG}function ZPs(s){return Math.max(0,-U8(Math.abs(s)))}function QPs(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(U8(t)/3)))*3-U8(Math.abs(s)))}function XPs(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,U8(t)-U8(s))+1}function i1t(s,t,n,r){var a=J3e(s,t,n),i;switch(r=WB(r??",f"),r.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return r.precision==null&&!isNaN(i=QPs(a,l))&&(r.precision=i),a1t(r,l)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(i=XPs(a,Math.max(Math.abs(s),Math.abs(t))))&&(r.precision=i-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(i=ZPs(a))&&(r.precision=i-(r.type==="%")*2);break}}return DPe(r)}function uC(s){var t=s.domain;return s.ticks=function(n){var r=t();return Q3e(r[0],r[r.length-1],n??10)},s.tickFormat=function(n,r){var a=t();return i1t(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=X3e(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 nge(){var s=PPe();return s.copy=function(){return RU(s,nge())},e1.apply(s,arguments),uC(s)}function o1t(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,tge),n):s.slice()},n.unknown=function(r){return arguments.length?(t=r,n):t},n.copy=function(){return o1t(s).unknown(t)},s=arguments.length?Array.from(s,tge):[0,1],uC(n)}function l1t(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 nLs(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 eKe(s){return(t,n)=>-s(-t,n)}function RPe(s){const t=s(XWe,JWe),n=t.domain;let r=10,a,i;function l(){return a=nLs(r),i=sLs(r),n()[0]<0?(a=eKe(a),i=eKe(i),s(JPs,eLs)):s(XWe,JWe),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(;p<=f;++p)for(g=1;gu)break;j.push(_)}}else for(;p<=f;++p)for(g=r-1;g>=1;--g)if(_=p>0?g/i(-p):g*i(p),!(_u)break;j.push(_)}j.length*2{if(o==null&&(o=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=WB(c)).precision==null&&(c.trim=!0),c=DPe(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(l1t(n(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function c1t(){const s=RPe(n1e()).domain([1,10]);return s.copy=()=>RU(s,c1t()).base(s.base()),e1.apply(s,arguments),s}function tKe(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function sKe(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function OPe(s){var t=1,n=s(tKe(t),sKe(t));return n.constant=function(r){return arguments.length?s(tKe(t=+r),sKe(t)):t},uC(n)}function d1t(){var s=OPe(n1e());return s.copy=function(){return RU(s,d1t()).constant(s.constant())},e1.apply(s,arguments)}function nKe(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function rLs(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function aLs(s){return s<0?-s*s:s*s}function FPe(s){var t=s(Jx,Jx),n=1;function r(){return n===1?s(Jx,Jx):n===.5?s(rLs,aLs):s(nKe(n),nKe(1/n))}return t.exponent=function(a){return arguments.length?(n=+a,r()):n},uC(t)}function zPe(){var s=FPe(n1e());return s.copy=function(){return RU(s,zPe()).exponent(s.exponent())},e1.apply(s,arguments),s}function iLs(){return zPe.apply(null,arguments).exponent(.5)}function rKe(s){return Math.sign(s)*s*s}function oLs(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function u1t(){var s=PPe(),t=[0,1],n=!1,r;function a(i){var l=oLs(s(i));return isNaN(l)?r:n?Math.round(l):l}return a.invert=function(i){return s.invert(rKe(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,tge)).map(rKe)),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 u1t(s.domain(),t).round(n).clamp(s.clamp()).unknown(r)},e1.apply(a,arguments),uC(a)}function h1t(){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 m1t().domain([s,t]).range(a).unknown(i)},e1.apply(uC(l),arguments)}function p1t(){var s=[.5],t=[0,1],n,r=1;function a(i){return i!=null&&i<=i?t[LU(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 p1t().domain(s).range(t).unknown(n)},e1.apply(a,arguments)}const iNe=new Date,oNe=new Date;function Qm(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(dQm(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)=>(iNe.setTime(+i),oNe.setTime(+l),s(iNe),s(oNe),Math.floor(n(iNe,oNe))),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 rge=Qm(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);rge.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?Qm(t=>{t.setTime(Math.floor(t/s)*s)},(t,n)=>{t.setTime(+t+n*s)},(t,n)=>(n-t)/s):rge);rge.range;const B2=1e3,Mv=B2*60,$2=Mv*60,fN=$2*24,BPe=fN*7,aKe=fN*30,lNe=fN*365,nA=Qm(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*B2)},(s,t)=>(t-s)/B2,s=>s.getUTCSeconds());nA.range;const $Pe=Qm(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*B2)},(s,t)=>{s.setTime(+s+t*Mv)},(s,t)=>(t-s)/Mv,s=>s.getMinutes());$Pe.range;const UPe=Qm(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*Mv)},(s,t)=>(t-s)/Mv,s=>s.getUTCMinutes());UPe.range;const qPe=Qm(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*B2-s.getMinutes()*Mv)},(s,t)=>{s.setTime(+s+t*$2)},(s,t)=>(t-s)/$2,s=>s.getHours());qPe.range;const VPe=Qm(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*$2)},(s,t)=>(t-s)/$2,s=>s.getUTCHours());VPe.range;const OU=Qm(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*Mv)/fN,s=>s.getDate()-1);OU.range;const r1e=Qm(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/fN,s=>s.getUTCDate()-1);r1e.range;const f1t=Qm(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/fN,s=>Math.floor(s/fN));f1t.range;function s6(s){return Qm(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())*Mv)/BPe)}const a1e=s6(0),age=s6(1),lLs=s6(2),cLs=s6(3),q8=s6(4),dLs=s6(5),uLs=s6(6);a1e.range;age.range;lLs.range;cLs.range;q8.range;dLs.range;uLs.range;function n6(s){return Qm(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)/BPe)}const i1e=n6(0),ige=n6(1),hLs=n6(2),mLs=n6(3),V8=n6(4),pLs=n6(5),fLs=n6(6);i1e.range;ige.range;hLs.range;mLs.range;V8.range;pLs.range;fLs.range;const HPe=Qm(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());HPe.range;const GPe=Qm(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());GPe.range;const xN=Qm(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());xN.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:Qm(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)});xN.range;const gN=Qm(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());gN.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:Qm(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)});gN.range;function x1t(s,t,n,r,a,i){const l=[[nA,1,B2],[nA,5,5*B2],[nA,15,15*B2],[nA,30,30*B2],[i,1,Mv],[i,5,5*Mv],[i,15,15*Mv],[i,30,30*Mv],[a,1,$2],[a,3,3*$2],[a,6,6*$2],[a,12,12*$2],[r,1,fN],[r,2,2*fN],[n,1,BPe],[t,1,aKe],[t,3,3*aKe],[s,1,lNe]];function o(d,u,h){const p=uv).right(l,p);if(f===l.length)return s.every(J3e(d/lNe,u/lNe,h));if(f===0)return rge.every(Math.max(J3e(d,u,h),1));const[g,_]=l[p/l[f-1][2]53)return null;"w"in be||(be.w=1),"Z"in be?(Ne=dNe(CF(be.y,0,1)),it=Ne.getUTCDay(),Ne=it>4||it===0?ige.ceil(Ne):ige(Ne),Ne=r1e.offset(Ne,(be.V-1)*7),be.y=Ne.getUTCFullYear(),be.m=Ne.getUTCMonth(),be.d=Ne.getUTCDate()+(be.w+6)%7):(Ne=cNe(CF(be.y,0,1)),it=Ne.getDay(),Ne=it>4||it===0?age.ceil(Ne):age(Ne),Ne=OU.offset(Ne,(be.V-1)*7),be.y=Ne.getFullYear(),be.m=Ne.getMonth(),be.d=Ne.getDate()+(be.w+6)%7)}else("W"in be||"U"in be)&&("w"in be||(be.w="u"in be?be.u%7:"W"in be?1:0),it="Z"in be?dNe(CF(be.y,0,1)).getUTCDay():cNe(CF(be.y,0,1)).getDay(),be.m=0,be.d="W"in be?(be.w+6)%7+be.W*7-(it+5)%7:be.w+be.U*7-(it+6)%7);return"Z"in be?(be.H+=be.Z/100|0,be.M+=be.Z%100,dNe(be)):cNe(be)}}function M(Ie,Fe,qe,be){for(var Ze=0,Ne=Fe.length,it=qe.length,je,Ge;Ze=it)return-1;if(je=Fe.charCodeAt(Ze++),je===37){if(je=Fe.charAt(Ze++),Ge=T[je in iKe?Fe.charAt(Ze++):je],!Ge||(be=Ge(Ie,qe,be))<0)return-1}else if(je!=qe.charCodeAt(be++))return-1}return be}function F(Ie,Fe,qe){var be=d.exec(Fe.slice(qe));return be?(Ie.p=u.get(be[0].toLowerCase()),qe+be[0].length):-1}function z(Ie,Fe,qe){var be=f.exec(Fe.slice(qe));return be?(Ie.w=g.get(be[0].toLowerCase()),qe+be[0].length):-1}function V(Ie,Fe,qe){var be=h.exec(Fe.slice(qe));return be?(Ie.w=p.get(be[0].toLowerCase()),qe+be[0].length):-1}function W(Ie,Fe,qe){var be=j.exec(Fe.slice(qe));return be?(Ie.m=b.get(be[0].toLowerCase()),qe+be[0].length):-1}function Y(Ie,Fe,qe){var be=_.exec(Fe.slice(qe));return be?(Ie.m=v.get(be[0].toLowerCase()),qe+be[0].length):-1}function K(Ie,Fe,qe){return M(Ie,t,Fe,qe)}function J(Ie,Fe,qe){return M(Ie,n,Fe,qe)}function ne(Ie,Fe,qe){return M(Ie,r,Fe,qe)}function ie(Ie){return l[Ie.getDay()]}function he(Ie){return i[Ie.getDay()]}function ce(Ie){return c[Ie.getMonth()]}function pe(Ie){return o[Ie.getMonth()]}function le(Ie){return a[+(Ie.getHours()>=12)]}function ve(Ie){return 1+~~(Ie.getMonth()/3)}function ge(Ie){return l[Ie.getUTCDay()]}function Te(Ie){return i[Ie.getUTCDay()]}function Me(Ie){return c[Ie.getUTCMonth()]}function Ce(Ie){return o[Ie.getUTCMonth()]}function Ae(Ie){return a[+(Ie.getUTCHours()>=12)]}function De(Ie){return 1+~~(Ie.getUTCMonth()/3)}return{format:function(Ie){var Fe=L(Ie+="",S);return Fe.toString=function(){return Ie},Fe},parse:function(Ie){var Fe=D(Ie+="",!1);return Fe.toString=function(){return Ie},Fe},utcFormat:function(Ie){var Fe=L(Ie+="",A);return Fe.toString=function(){return Ie},Fe},utcParse:function(Ie){var Fe=D(Ie+="",!0);return Fe.toString=function(){return Ie},Fe}}}var iKe={"-":"",_:" ",0:"0"},Pp=/^\s*\d+/,_Ls=/^%/,wLs=/[\\^$*+?|[\]().{}]/g;function Xl(s,t,n){var r=s<0?"-":"",a=(r?-s:s)+"",i=a.length;return r+(i[t.toLowerCase(),n]))}function NLs(s,t,n){var r=Pp.exec(t.slice(n,n+1));return r?(s.w=+r[0],n+r[0].length):-1}function kLs(s,t,n){var r=Pp.exec(t.slice(n,n+1));return r?(s.u=+r[0],n+r[0].length):-1}function SLs(s,t,n){var r=Pp.exec(t.slice(n,n+2));return r?(s.U=+r[0],n+r[0].length):-1}function CLs(s,t,n){var r=Pp.exec(t.slice(n,n+2));return r?(s.V=+r[0],n+r[0].length):-1}function TLs(s,t,n){var r=Pp.exec(t.slice(n,n+2));return r?(s.W=+r[0],n+r[0].length):-1}function oKe(s,t,n){var r=Pp.exec(t.slice(n,n+4));return r?(s.y=+r[0],n+r[0].length):-1}function lKe(s,t,n){var r=Pp.exec(t.slice(n,n+2));return r?(s.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function ELs(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 ALs(s,t,n){var r=Pp.exec(t.slice(n,n+1));return r?(s.q=r[0]*3-3,n+r[0].length):-1}function MLs(s,t,n){var r=Pp.exec(t.slice(n,n+2));return r?(s.m=r[0]-1,n+r[0].length):-1}function cKe(s,t,n){var r=Pp.exec(t.slice(n,n+2));return r?(s.d=+r[0],n+r[0].length):-1}function ILs(s,t,n){var r=Pp.exec(t.slice(n,n+3));return r?(s.m=0,s.d=+r[0],n+r[0].length):-1}function dKe(s,t,n){var r=Pp.exec(t.slice(n,n+2));return r?(s.H=+r[0],n+r[0].length):-1}function PLs(s,t,n){var r=Pp.exec(t.slice(n,n+2));return r?(s.M=+r[0],n+r[0].length):-1}function LLs(s,t,n){var r=Pp.exec(t.slice(n,n+2));return r?(s.S=+r[0],n+r[0].length):-1}function DLs(s,t,n){var r=Pp.exec(t.slice(n,n+3));return r?(s.L=+r[0],n+r[0].length):-1}function RLs(s,t,n){var r=Pp.exec(t.slice(n,n+6));return r?(s.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function OLs(s,t,n){var r=_Ls.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function FLs(s,t,n){var r=Pp.exec(t.slice(n));return r?(s.Q=+r[0],n+r[0].length):-1}function zLs(s,t,n){var r=Pp.exec(t.slice(n));return r?(s.s=+r[0],n+r[0].length):-1}function uKe(s,t){return Xl(s.getDate(),t,2)}function BLs(s,t){return Xl(s.getHours(),t,2)}function $Ls(s,t){return Xl(s.getHours()%12||12,t,2)}function ULs(s,t){return Xl(1+OU.count(xN(s),s),t,3)}function g1t(s,t){return Xl(s.getMilliseconds(),t,3)}function qLs(s,t){return g1t(s,t)+"000"}function VLs(s,t){return Xl(s.getMonth()+1,t,2)}function HLs(s,t){return Xl(s.getMinutes(),t,2)}function GLs(s,t){return Xl(s.getSeconds(),t,2)}function WLs(s){var t=s.getDay();return t===0?7:t}function KLs(s,t){return Xl(a1e.count(xN(s)-1,s),t,2)}function y1t(s){var t=s.getDay();return t>=4||t===0?q8(s):q8.ceil(s)}function YLs(s,t){return s=y1t(s),Xl(q8.count(xN(s),s)+(xN(s).getDay()===4),t,2)}function ZLs(s){return s.getDay()}function QLs(s,t){return Xl(age.count(xN(s)-1,s),t,2)}function XLs(s,t){return Xl(s.getFullYear()%100,t,2)}function JLs(s,t){return s=y1t(s),Xl(s.getFullYear()%100,t,2)}function e8s(s,t){return Xl(s.getFullYear()%1e4,t,4)}function t8s(s,t){var n=s.getDay();return s=n>=4||n===0?q8(s):q8.ceil(s),Xl(s.getFullYear()%1e4,t,4)}function s8s(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+Xl(t/60|0,"0",2)+Xl(t%60,"0",2)}function hKe(s,t){return Xl(s.getUTCDate(),t,2)}function n8s(s,t){return Xl(s.getUTCHours(),t,2)}function r8s(s,t){return Xl(s.getUTCHours()%12||12,t,2)}function a8s(s,t){return Xl(1+r1e.count(gN(s),s),t,3)}function v1t(s,t){return Xl(s.getUTCMilliseconds(),t,3)}function i8s(s,t){return v1t(s,t)+"000"}function o8s(s,t){return Xl(s.getUTCMonth()+1,t,2)}function l8s(s,t){return Xl(s.getUTCMinutes(),t,2)}function c8s(s,t){return Xl(s.getUTCSeconds(),t,2)}function d8s(s){var t=s.getUTCDay();return t===0?7:t}function u8s(s,t){return Xl(i1e.count(gN(s)-1,s),t,2)}function b1t(s){var t=s.getUTCDay();return t>=4||t===0?V8(s):V8.ceil(s)}function h8s(s,t){return s=b1t(s),Xl(V8.count(gN(s),s)+(gN(s).getUTCDay()===4),t,2)}function m8s(s){return s.getUTCDay()}function p8s(s,t){return Xl(ige.count(gN(s)-1,s),t,2)}function f8s(s,t){return Xl(s.getUTCFullYear()%100,t,2)}function x8s(s,t){return s=b1t(s),Xl(s.getUTCFullYear()%100,t,2)}function g8s(s,t){return Xl(s.getUTCFullYear()%1e4,t,4)}function y8s(s,t){var n=s.getUTCDay();return s=n>=4||n===0?V8(s):V8.ceil(s),Xl(s.getUTCFullYear()%1e4,t,4)}function v8s(){return"+0000"}function mKe(){return"%"}function pKe(s){return+s}function fKe(s){return Math.floor(+s/1e3)}var DI,_1t,w1t;b8s({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 b8s(s){return DI=bLs(s),_1t=DI.format,DI.parse,w1t=DI.utcFormat,DI.utcParse,DI}function _8s(s){return new Date(s)}function w8s(s){return s instanceof Date?+s:+new Date(+s)}function WPe(s,t,n,r,a,i,l,o,c,d){var u=PPe(),h=u.invert,p=u.domain,f=d(".%L"),g=d(":%S"),_=d("%I:%M"),v=d("%I %p"),j=d("%a %d"),b=d("%b %d"),S=d("%B"),A=d("%Y");function T(L){return(c(L)t(a/(s.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(a,i)=>uPs(s,i/r))},n.copy=function(){return S1t(t).domain(s)},MN.apply(n,arguments)}function l1e(){var s=0,t=.5,n=1,r=1,a,i,l,o,c,d=Jx,u,h=!1,p;function f(_){return isNaN(_=+_)?p:(_=.5+((_=+u(_))-i)*(r*_t}var A1t=E8s,A8s=c1e,M8s=A1t,I8s=mR;function P8s(s){return s&&s.length?A8s(s,I8s,M8s):void 0}var L8s=P8s;const d1e=wl(L8s);function D8s(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};si.decimalPlaces=si.dp=function(){var s=this,t=s.d.length-1,n=(t-s.e)*Od;if(t=s.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n};si.dividedBy=si.div=function(s){return nN(this,new this.constructor(s))};si.dividedToIntegerBy=si.idiv=function(s){var t=this,n=t.constructor;return ad(nN(t,new n(s),0,1),n.precision)};si.equals=si.eq=function(s){return!this.cmp(s)};si.exponent=function(){return um(this)};si.greaterThan=si.gt=function(s){return this.cmp(s)>0};si.greaterThanOrEqualTo=si.gte=function(s){return this.cmp(s)>=0};si.isInteger=si.isint=function(){return this.e>this.d.length-2};si.isNegative=si.isneg=function(){return this.s<0};si.isPositive=si.ispos=function(){return this.s>0};si.isZero=function(){return this.s===0};si.lessThan=si.lt=function(s){return this.cmp(s)<0};si.lessThanOrEqualTo=si.lte=function(s){return this.cmp(s)<1};si.logarithm=si.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(J0))throw Error(Kv+"NaN");if(n.s<1)throw Error(Kv+(n.s?"NaN":"-Infinity"));return n.eq(J0)?new r(0):(lu=!1,t=nN(KB(n,i),KB(s,i),i),lu=!0,ad(t,a))};si.minus=si.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?D1t(t,s):P1t(t,(s.s=-s.s,s))};si.modulo=si.mod=function(s){var t,n=this,r=n.constructor,a=r.precision;if(s=new r(s),!s.s)throw Error(Kv+"NaN");return n.s?(lu=!1,t=nN(n,s,0,1).times(s),lu=!0,n.minus(t)):ad(new r(n),a)};si.naturalExponential=si.exp=function(){return L1t(this)};si.naturalLogarithm=si.ln=function(){return KB(this)};si.negated=si.neg=function(){var s=new this.constructor(this);return s.s=-s.s||0,s};si.plus=si.add=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?P1t(t,s):D1t(t,(s.s=-s.s,s))};si.precision=si.sd=function(s){var t,n,r,a=this;if(s!==void 0&&s!==!!s&&s!==1&&s!==0)throw Error(eM+s);if(t=um(a)+1,r=a.d.length-1,n=r*Od+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};si.squareRoot=si.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(Kv+"NaN")}for(s=um(o),lu=!1,a=Math.sqrt(+o),a==0||a==1/0?(t=iw(o.d),(t.length+s)%2==0&&(t+="0"),a=Math.sqrt(t),s=gR((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(nN(o,i,l+2)).times(.5),iw(i.d).slice(0,l)===(t=iw(r.d)).slice(0,l)){if(t=t.slice(l-3,l+1),a==l&&t=="4999"){if(ad(i,n+1,0),i.times(i).eq(o)){r=i;break}}else if(t!="9999")break;l+=4}return lu=!0,ad(r,n)};si.times=si.mul=function(s){var t,n,r,a,i,l,o,c,d,u=this,h=u.constructor,p=u.d,f=(s=new h(s)).d;if(!u.s||!s.s)return new h(0);for(s.s*=u.s,n=u.e+s.e,c=p.length,d=f.length,c=0;){for(t=0,a=c+r;a>r;)o=i[a]+f[r]*p[a-r-1]+t,i[a--]=o%vp|0,t=o/vp|0;i[a]=(i[a]+t)%vp|0}for(;!i[--l];)i.pop();return t?++n:i.shift(),s.d=i,s.e=n,lu?ad(s,h.precision):s};si.toDecimalPlaces=si.todp=function(s,t){var n=this,r=n.constructor;return n=new r(n),s===void 0?n:(Rw(s,0,xR),t===void 0?t=r.rounding:Rw(t,0,8),ad(n,s+um(n)+1,t))};si.toExponential=function(s,t){var n,r=this,a=r.constructor;return s===void 0?n=IM(r,!0):(Rw(s,0,xR),t===void 0?t=a.rounding:Rw(t,0,8),r=ad(new a(r),s+1,t),n=IM(r,!0,s+1)),n};si.toFixed=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?IM(a):(Rw(s,0,xR),t===void 0?t=i.rounding:Rw(t,0,8),r=ad(new i(a),s+um(a)+1,t),n=IM(r.abs(),!1,s+um(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};si.toInteger=si.toint=function(){var s=this,t=s.constructor;return ad(new t(s),um(s)+1,t.rounding)};si.toNumber=function(){return+this};si.toPower=si.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(J0);if(o=new c(o),!o.s){if(s.s<1)throw Error(Kv+"Infinity");return o}if(o.eq(J0))return o;if(r=c.precision,s.eq(J0))return ad(o,r);if(t=s.e,n=s.d.length-1,l=t>=n,i=o.s,l){if((n=u<0?-u:u)<=I1t){for(a=new c(J0),t=Math.ceil(r/Od+4),lu=!1;n%2&&(a=a.times(o),yKe(a.d,t)),n=gR(n/2),n!==0;)o=o.times(o),yKe(o.d,t);return lu=!0,s.s<0?new c(J0).div(a):ad(a,r)}}else if(i<0)throw Error(Kv+"NaN");return i=i<0&&s.d[Math.max(t,n)]&1?-1:1,o.s=1,lu=!1,a=s.times(KB(o,r+d)),lu=!0,a=L1t(a),a.s=i,a};si.toPrecision=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?(n=um(a),r=IM(a,n<=i.toExpNeg||n>=i.toExpPos)):(Rw(s,1,xR),t===void 0?t=i.rounding:Rw(t,0,8),a=ad(new i(a),s,t),n=um(a),r=IM(a,s<=n||n<=i.toExpNeg,s)),r};si.toSignificantDigits=si.tosd=function(s,t){var n=this,r=n.constructor;return s===void 0?(s=r.precision,t=r.rounding):(Rw(s,1,xR),t===void 0?t=r.rounding:Rw(t,0,8)),ad(new r(n),s,t)};si.toString=si.valueOf=si.val=si.toJSON=si[Symbol.for("nodejs.util.inspect.custom")]=function(){var s=this,t=um(s),n=s.constructor;return IM(s,t<=n.toExpNeg||t>=n.toExpPos)};function P1t(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)),lu?ad(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/Od),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)/vp|0,c[i]%=vp;for(n&&(c.unshift(n),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,lu?ad(t,h):t}function Rw(s,t,n){if(s!==~~s||sn)throw Error(eM+s)}function iw(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,p,f,g,_,v,j,b,S,A,T,L,D,M,F=r.constructor,z=r.s==a.s?1:-1,V=r.d,W=a.d;if(!r.s)return new F(r);if(!a.s)throw Error(Kv+"Division by zero");for(c=r.e-a.e,D=W.length,T=V.length,f=new F(z),g=f.d=[],d=0;W[d]==(V[d]||0);)++d;if(W[d]>(V[d]||0)&&--c,i==null?b=i=F.precision:l?b=i+(um(r)-um(a))+1:b=i,b<0)return new F(0);if(b=b/Od+2|0,d=0,D==1)for(u=0,W=W[0],b++;(d1&&(W=s(W,u),V=s(V,u),D=W.length,T=V.length),A=D,_=V.slice(0,D),v=_.length;v=vp/2&&++L;do u=0,o=t(W,_,D,v),o<0?(j=_[0],D!=v&&(j=j*vp+(_[1]||0)),u=j/L|0,u>1?(u>=vp&&(u=vp-1),h=s(W,u),p=h.length,v=_.length,o=t(h,_,p,v),o==1&&(u--,n(h,D16)throw Error(ZPe+um(s));if(!s.s)return new u(J0);for(t==null?(lu=!1,o=h):o=t,l=new u(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(r=Math.log(LE(2,d))/Math.LN10*2+5|0,o+=r,n=a=i=new u(J0),u.precision=o;;){if(a=ad(a.times(s),o),n=n.times(++c),l=i.plus(nN(a,n,o)),iw(l.d).slice(0,o)===iw(i.d).slice(0,o)){for(;d--;)i=ad(i.times(i),o);return u.precision=h,t==null?(lu=!0,ad(i,h)):i}i=l}}function um(s){for(var t=s.e*Od,n=s.d[0];n>=10;n/=10)t++;return t}function uNe(s,t,n){if(t>s.LN10.sd())throw lu=!0,n&&(s.precision=n),Error(Kv+"LN10 precision limit exceeded");return ad(new s(s.LN10),t)}function nS(s){for(var t="";s--;)t+="0";return t}function KB(s,t){var n,r,a,i,l,o,c,d,u,h=1,p=10,f=s,g=f.d,_=f.constructor,v=_.precision;if(f.s<1)throw Error(Kv+(f.s?"NaN":"-Infinity"));if(f.eq(J0))return new _(0);if(t==null?(lu=!1,d=v):d=t,f.eq(10))return t==null&&(lu=!0),uNe(_,d);if(d+=p,_.precision=d,n=iw(g),r=n.charAt(0),i=um(f),Math.abs(i)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)f=f.times(s),n=iw(f.d),r=n.charAt(0),h++;i=um(f),r>1?(f=new _("0."+n),i++):f=new _(r+"."+n.slice(1))}else return c=uNe(_,d+2,v).times(i+""),f=KB(new _(r+"."+n.slice(1)),d-p).plus(c),_.precision=v,t==null?(lu=!0,ad(f,v)):f;for(o=l=f=nN(f.minus(J0),f.plus(J0),d),u=ad(f.times(f),d),a=3;;){if(l=ad(l.times(u),d),c=o.plus(nN(l,new _(a),d)),iw(c.d).slice(0,d)===iw(o.d).slice(0,d))return o=o.times(2),i!==0&&(o=o.plus(uNe(_,d+2,v).times(i+""))),o=nN(o,new _(h),d),_.precision=v,t==null?(lu=!0,ad(o,v)):o;o=c,a+=2}}function gKe(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=gR(n/Od),s.d=[],r=(n+1)%Od,n<0&&(r+=Od),roge||s.e<-oge))throw Error(ZPe+n)}else s.s=0,s.e=0,s.d=[0];return s}function ad(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+=Od,a=t,d=h[u=0];else{if(u=Math.ceil((r+1)/Od),i=h.length,u>=i)return s;for(d=i=h[u],l=1;i>=10;i/=10)l++;r%=Od,a=r-Od+l}if(n!==void 0&&(i=LE(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/LE(10,l-a):0:h[u-1])%10&1||n==(s.s<0?8:7))),t<1||!h[0])return c?(i=um(s),h.length=1,t=t-i-1,h[0]=LE(10,(Od-t%Od)%Od),s.e=gR(-t/Od)||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=LE(10,Od-r),h[u]=a>0?(d/LE(10,l-a)%LE(10,a)|0)*i:0),c)for(;;)if(u==0){(h[0]+=i)==vp&&(h[0]=1,++s.e);break}else{if(h[u]+=i,h[u]!=vp)break;h[u--]=0,i=1}for(r=h.length;h[--r]===0;)h.pop();if(lu&&(s.e>oge||s.e<-oge))throw Error(ZPe+um(s));return s}function D1t(s,t){var n,r,a,i,l,o,c,d,u,h,p=s.constructor,f=p.precision;if(!s.s||!t.s)return t.s?t.s=-t.s:t=new p(s),lu?ad(t,f):t;if(c=s.d,h=t.d,r=t.e,d=s.e,c=c.slice(),l=d-r,l){for(u=l<0,u?(n=c,l=-l,o=h.length):(n=h,r=d,o=c.length),a=Math.max(Math.ceil(f/Od),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)+nS(r):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+nS(-a-1)+i,n&&(r=n-l)>0&&(i+=nS(r))):a>=l?(i+=nS(a+1-l),n&&(r=n-a-1)>0&&(i=i+"."+nS(r))):((r=a+1)0&&(a+1===l&&(i+="."),i+=nS(r))),s.s<0?"-"+i:i}function yKe(s,t){if(s.length>t)return s.length=t,!0}function R1t(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(eM+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 gKe(l,i.toString())}else if(typeof i!="string")throw Error(eM+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,sDs.test(i))gKe(l,i);else throw Error(eM+i)}if(a.prototype=si,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=R1t,a.config=a.set=nDs,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(eM+n+": "+r);if((r=s[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(eM+n+": "+r);return this}var QPe=R1t(tDs);J0=new QPe(1);const Vc=QPe;function rDs(s){return lDs(s)||oDs(s)||iDs(s)||aDs()}function aDs(){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 iDs(s,t){if(s){if(typeof s=="string")return r5e(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 r5e(s,t)}}function oDs(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function lDs(s){if(Array.isArray(s))return r5e(s)}function r5e(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,vKe(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 jDs(s){if(Array.isArray(s))return s}function $1t(s){var t=YB(s,2),n=t[0],r=t[1],a=n,i=r;return n>r&&(a=r,i=n),[a,i]}function U1t(s,t,n){if(s.lte(0))return new Vc(0);var r=m1e.getDigitCount(s.toNumber()),a=new Vc(10).pow(r),i=s.div(a),l=r!==1?.05:.1,o=new Vc(Math.ceil(i.div(l).toNumber())).add(n).mul(l),c=o.mul(a);return t?c:new Vc(Math.ceil(c))}function NDs(s,t,n){var r=1,a=new Vc(s);if(!a.isint()&&n){var i=Math.abs(s);i<1?(r=new Vc(10).pow(m1e.getDigitCount(s)-1),a=new Vc(Math.floor(a.div(r).toNumber())).mul(r)):i>1&&(a=new Vc(Math.floor(s)))}else s===0?a=new Vc(Math.floor((t-1)/2)):n||(a=new Vc(Math.floor(s)));var l=Math.floor((t-1)/2),o=hDs(uDs(function(c){return a.add(new Vc(c-l).mul(r)).toNumber()}),a5e);return o(0,t)}function q1t(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 Vc(0),tickMin:new Vc(0),tickMax:new Vc(0)};var i=U1t(new Vc(t).sub(s).div(n-1),r,a),l;s<=0&&t>=0?l=new Vc(0):(l=new Vc(s).add(t).div(2),l=l.sub(new Vc(l).mod(i)));var o=Math.ceil(l.sub(s).div(i).toNumber()),c=Math.ceil(new Vc(t).sub(l).div(i).toNumber()),d=o+c+1;return d>n?q1t(s,t,n,r,a+1):(d0?c+(n-d):c,o=t>0?o:o+(n-d)),{step:i,tickMin:l.sub(new Vc(o).mul(i)),tickMax:l.add(new Vc(c).mul(i))})}function kDs(s){var t=YB(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=$1t([n,r]),c=YB(o,2),d=c[0],u=c[1];if(d===-1/0||u===1/0){var h=u===1/0?[d].concat(o5e(a5e(0,a-1).map(function(){return 1/0}))):[].concat(o5e(a5e(0,a-1).map(function(){return-1/0})),[u]);return n>r?i5e(h):h}if(d===u)return NDs(d,a,i);var p=q1t(d,u,l,i),f=p.step,g=p.tickMin,_=p.tickMax,v=m1e.rangeStep(g,_.add(new Vc(.1).mul(f)),f);return n>r?i5e(v):v}function SDs(s,t){var n=YB(s,2),r=n[0],a=n[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=$1t([r,a]),o=YB(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=U1t(new Vc(d).sub(c).div(u-1),i,0),p=[].concat(o5e(m1e.rangeStep(new Vc(c),new Vc(d).sub(new Vc(.99).mul(h)),h)),[d]);return r>a?i5e(p):p}var CDs=z1t(kDs),TDs=z1t(SDs),EDs="Invariant failed";function PM(s,t){throw new Error(EDs)}var ADs=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function H8(s){"@babel/helpers - typeof";return H8=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},H8(s)}function lge(){return lge=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 ODs(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 FDs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function zDs(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,p=d>=o-1?a[0].coordinate:a[d+1].coordinate,f=void 0;if(Qx(h-u)!==Qx(p-h)){var g=[];if(Qx(p-h)===Qx(c[1]-c[0])){f=p;var _=h+c[1]-c[0];g[0]=Math.min(_,(_+u)/2),g[1]=Math.max(_,(_+u)/2)}else{f=u;var v=p+c[1]-c[0];g[0]=Math.min(h,(v+h)/2),g[1]=Math.max(h,(v+h)/2)}var j=[Math.min(h,(f+h)/2),Math.max(h,(f+h)/2)];if(t>j[0]&&t<=j[1]||t>=g[0]&&t<=g[1]){l=a[d].index;break}}else{var b=Math.min(u,p),S=Math.max(u,p);if(t>(b+h)/2&&t<=(S+h)/2){l=a[d].index;break}}}else for(var A=0;A0&&A(r[A].coordinate+r[A-1].coordinate)/2&&t<=(r[A].coordinate+r[A+1].coordinate)/2||A===o-1&&t>(r[A].coordinate+r[A-1].coordinate)/2){l=r[A].index;break}return l},XPe=function(t){var n,r=t,a=r.type.displayName,i=(n=t.type)!==null&&n!==void 0&&n.defaultProps?rh(rh({},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},sRs=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(j&&j.length){var b=j[0].type.defaultProps,S=b!==void 0?rh(rh({},b),j[0].props):j[0].props,A=S.barSize,T=S[v];l[T]||(l[T]=[]);var L=No(A)?n:A;l[T].push({item:j[0],stackList:j.slice(1),barSize:No(L)?void 0:Xx(L,r,0)})}}return l},nRs=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=Xx(n,a,0,!0),u,h=[];if(l[0].barSize===+l[0].barSize){var p=!1,f=a/c,g=l.reduce(function(A,T){return A+T.barSize||0},0);g+=(c-1)*d,g>=a&&(g-=(c-1)*d,d=0),g>=a&&f>0&&(p=!0,f*=.9,g=c*f);var _=(a-g)/2>>0,v={offset:_-d,size:0};u=l.reduce(function(A,T){var L={item:T.item,position:{offset:v.offset+v.size+d,size:p?f:T.barSize}},D=[].concat(wKe(A),[L]);return v=D[D.length-1].position,T.stackList&&T.stackList.length&&T.stackList.forEach(function(M){D.push({item:M,position:v})}),D},h)}else{var j=Xx(r,a,0,!0);a-2*j-(c-1)*d<=0&&(d=0);var b=(a-2*j-(c-1)*d)/c;b>1&&(b>>=0);var S=o===+o?Math.min(b,o):b;u=l.reduce(function(A,T,L){var D=[].concat(wKe(A),[{item:T.item,position:{offset:j+(b+d)*L+(b-S)/2,size:S}}]);return T.stackList&&T.stackList.length&&T.stackList.forEach(function(M){D.push({item:M,position:D[D.length-1].position})}),D},h)}return u},rRs=function(t,n,r,a){var i=r.children,l=r.width,o=r.margin,c=l-(o.left||0)-(o.right||0),d=W1t({children:i,legendWidth:c});if(d){var u=a||{},h=u.width,p=u.height,f=d.align,g=d.verticalAlign,_=d.layout;if((_==="vertical"||_==="horizontal"&&g==="middle")&&f!=="center"&&la(t[f]))return rh(rh({},t),{},UL({},f,t[f]+(h||0)));if((_==="horizontal"||_==="vertical"&&f==="center")&&g!=="middle"&&la(t[g]))return rh(rh({},t),{},UL({},g,t[g]+(p||0)))}return t},aRs=function(t,n,r){return No(n)?!0:t==="horizontal"?n==="yAxis":t==="vertical"||r==="x"?n==="xAxis":r==="y"?n==="yAxis":!0},K1t=function(t,n,r,a,i){var l=n.props.children,o=fy(l,zU).filter(function(d){return aRs(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=Fm(u,r);if(No(h))return d;var p=Array.isArray(h)?[u1e(h),d1e(h)]:[h,h],f=c.reduce(function(g,_){var v=Fm(u,_,0),j=p[0]-Math.abs(Array.isArray(v)?v[0]:v),b=p[1]+Math.abs(Array.isArray(v)?v[1]:v);return[Math.min(j,g[0]),Math.max(b,g[1])]},[1/0,-1/0]);return[Math.min(f[0],d[0]),Math.max(f[1],d[1])]},[1/0,-1/0])}return null},iRs=function(t,n,r,a,i){var l=n.map(function(o){return K1t(t,o,r,i,a)}).filter(function(o){return!No(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},Y1t=function(t,n,r,a,i){var l=n.map(function(c){var d=c.props.dataKey;return r==="number"&&d&&K1t(t,c,d,a)||jz(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?Qx(o[0]-o[1])*2*d:d,n&&(t.ticks||t.niceTicks)){var u=(t.ticks||t.niceTicks).map(function(h){var p=i?i.indexOf(h):h;return{coordinate:a(p)+d,value:h,offset:d}});return u.filter(function(h){return!IU(h.coordinate)})}return t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(h,p){return{coordinate:a(h)+d,value:h,index:p,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,p){return{coordinate:a(h)+d,value:i?i[h]:h,index:p,offset:d}})},hNe=new WeakMap,aG=function(t,n){if(typeof n!="function")return t;hNe.has(t)||hNe.set(t,new WeakMap);var r=hNe.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},X1t=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:qB(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:nge(),realScaleType:"linear"}:i==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!r)?{scale:wz(),realScaleType:"point"}:i==="category"?{scale:qB(),realScaleType:"band"}:{scale:nge(),realScaleType:"linear"};if(EM(a)){var c="scale".concat(Zve(a));return{scale:(xKe[c]||wz)(),realScaleType:xKe[c]?c:"point"}}return ho(a)?{scale:a}:{scale:wz(),realScaleType:"point"}},NKe=1e-4,J1t=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])-NKe,l=Math.max(a[0],a[1])+NKe,o=t(n[0]),c=t(n[r-1]);(ol||cl)&&t.domain([n[0],n[r-1]])}},oRs=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])}},dRs=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)}},uRs={sign:cRs,expand:A4s,none:O8,silhouette:M4s,wiggle:I4s,positive:dRs},hRs=function(t,n,r){var a=n.map(function(o){return o.props.dataKey}),i=uRs[r],l=E4s().keys(a).value(function(o,c){return+Fm(o,c,0)}).order(D3e).offset(i);return l(t)},mRs=function(t,n,r,a,i,l){if(!t)return null;var o=l?n.reverse():n,c={},d=o.reduce(function(h,p){var f,g=(f=p.type)!==null&&f!==void 0&&f.defaultProps?rh(rh({},p.type.defaultProps),p.props):p.props,_=g.stackId,v=g.hide;if(v)return h;var j=g[r],b=h[j]||{hasStack:!1,stackGroups:{}};if($m(_)){var S=b.stackGroups[_]||{numericAxisId:r,cateAxisId:a,items:[]};S.items.push(p),b.hasStack=!0,b.stackGroups[_]=S}else b.stackGroups[dR("_stackId_")]={numericAxisId:r,cateAxisId:a,items:[p]};return rh(rh({},h),{},UL({},j,b))},c),u={};return Object.keys(d).reduce(function(h,p){var f=d[p];if(f.hasStack){var g={};f.stackGroups=Object.keys(f.stackGroups).reduce(function(_,v){var j=f.stackGroups[v];return rh(rh({},_),{},UL({},v,{numericAxisId:r,cateAxisId:a,items:j.items,stackedData:hRs(t,j.items,i)}))},g)}return rh(rh({},h),{},UL({},p,f))},u)},ebt=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=CDs(d,i,o);return t.domain([u1e(u),d1e(u)]),{niceTicks:u}}if(i&&a==="number"){var h=t.domain(),p=TDs(h,i,o);return{niceTicks:p}}return null};function kKe(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&&!No(a[t.dataKey])){var o=Rxe(n,"value",a[t.dataKey]);if(o)return o.coordinate+r/2}return n[i]?n[i].coordinate+r/2:null}var c=Fm(a,No(l)?t.dataKey:l);return No(c)?null:t.scale(c)}var SKe=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=Fm(l,n.dataKey,n.domain[o]);return No(c)?null:n.scale(c)-i/2+a},pRs=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]},fRs=function(t,n){var r,a=(r=t.type)!==null&&r!==void 0&&r.defaultProps?rh(rh({},t.type.defaultProps),t.props):t.props,i=a.stackId;if($m(i)){var l=n[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},xRs=function(t){return t.reduce(function(n,r){return[u1e(r.concat([n[0]]).filter(la)),d1e(r.concat([n[1]]).filter(la))]},[1/0,-1/0])},tbt=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=xRs(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})},CKe=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,TKe=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,u5e=function(t,n,r){if(ho(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(CKe.test(t[0])){var i=+CKe.exec(t[0])[1];a[0]=n[0]-i}else ho(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(TKe.test(t[1])){var l=+TKe.exec(t[1])[1];a[1]=n[1]+l}else ho(t[1])?a[1]=t[1](n[1]):a[1]=n[1];return a},dge=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=SPe(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},kRs=function(t,n,r,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,u=Xx(t.cx,l,l/2),h=Xx(t.cy,o,o/2),p=rbt(l,o,r),f=Xx(t.innerRadius,p,0),g=Xx(t.outerRadius,p,p*.8),_=Object.keys(n);return _.reduce(function(v,j){var b=n[j],S=b.domain,A=b.reversed,T;if(No(b.range))a==="angleAxis"?T=[c,d]:a==="radiusAxis"&&(T=[f,g]),A&&(T=[T[1],T[0]]);else{T=b.range;var L=T,D=vRs(L,2);c=D[0],d=D[1]}var M=X1t(b,i),F=M.realScaleType,z=M.scale;z.domain(S).range(T),J1t(z);var V=ebt(z,j2(j2({},b),{},{realScaleType:F})),W=j2(j2(j2({},b),V),{},{range:T,radius:g,realScaleType:F,scale:z,cx:u,cy:h,innerRadius:f,outerRadius:g,startAngle:c,endAngle:d});return j2(j2({},v),{},nbt({},j,W))},{})},SRs=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))},CRs=function(t,n){var r=t.x,a=t.y,i=n.cx,l=n.cy,o=SRs({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:NRs(d),angleInRadian:d}},TRs=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}},ERs=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},IKe=function(t,n){var r=t.x,a=t.y,i=CRs({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=TRs(n),h=u.startAngle,p=u.endAngle,f=o,g;if(h<=p){for(;f>p;)f-=360;for(;f=h&&f<=p}else{for(;f>h;)f-=360;for(;f=p&&f<=h}return g?j2(j2({},n),{},{radius:l,angle:ERs(f,n)}):null},abt=function(t){return!N.isValidElement(t)&&!ho(t)&&typeof t!="boolean"?t.className:""};function JB(s){"@babel/helpers - typeof";return JB=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},JB(s)}var ARs=["offset"];function MRs(s){return DRs(s)||LRs(s)||PRs(s)||IRs()}function IRs(){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 PRs(s,t){if(s){if(typeof s=="string")return h5e(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 h5e(s,t)}}function LRs(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function DRs(s){if(Array.isArray(s))return h5e(s)}function h5e(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 ORs(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 PKe(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 Cm(s){for(var t=1;t=0?1:-1,S,A;a==="insideStart"?(S=f+b*l,A=_):a==="insideEnd"?(S=g-b*l,A=!_):a==="end"&&(S=g+b*l,A=_),A=j<=0?A:!A;var T=wd(d,u,v,S),L=wd(d,u,v,S+(A?1:-1)*359),D="M".concat(T.x,",").concat(T.y,` A`).concat(v,",").concat(v,",0,1,").concat(A?0:1,`, `).concat(L.x,",").concat(L.y),M=No(t.id)?dR("recharts-radial-line-"):t.id;return St.createElement("text",e$({},r,{dominantBaseline:"central",className:So("recharts-radial-bar-label",o)}),St.createElement("defs",null,St.createElement("path",{id:M,d:D})),St.createElement("textPath",{xlinkHref:"#".concat(M)},n))},VRs=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,p=(u+h)/2;if(a==="outside"){var f=wd(l,o,d+r,p),g=f.x,_=f.y;return{x:g,y:_,textAnchor:g>=l?"start":"end",verticalAnchor:"middle"}}if(a==="center")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"middle"};if(a==="centerTop")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"start"};if(a==="centerBottom")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"end"};var v=(c+d)/2,j=wd(l,o,v,p),b=j.x,S=j.y;return{x:b,y:S,textAnchor:"middle",verticalAnchor:"middle"}},HRs=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,p=h*a,f=h>0?"end":"start",g=h>0?"start":"end",_=d>=0?1:-1,v=_*a,j=_>0?"end":"start",b=_>0?"start":"end";if(i==="top"){var S={x:o+d/2,y:c-h*a,textAnchor:"middle",verticalAnchor:f};return Cm(Cm({},S),r?{height:Math.max(c-r.y,0),width:d}:{})}if(i==="bottom"){var A={x:o+d/2,y:c+u+p,textAnchor:"middle",verticalAnchor:g};return Cm(Cm({},A),r?{height:Math.max(r.y+r.height-(c+u),0),width:d}:{})}if(i==="left"){var T={x:o-v,y:c+u/2,textAnchor:j,verticalAnchor:"middle"};return Cm(Cm({},T),r?{width:Math.max(T.x-r.x,0),height:u}:{})}if(i==="right"){var L={x:o+d+v,y:c+u/2,textAnchor:b,verticalAnchor:"middle"};return Cm(Cm({},L),r?{width:Math.max(r.x+r.width-L.x,0),height:u}:{})}var D=r?{width:d,height:u}:{};return i==="insideLeft"?Cm({x:o+v,y:c+u/2,textAnchor:b,verticalAnchor:"middle"},D):i==="insideRight"?Cm({x:o+d-v,y:c+u/2,textAnchor:j,verticalAnchor:"middle"},D):i==="insideTop"?Cm({x:o+d/2,y:c+p,textAnchor:"middle",verticalAnchor:g},D):i==="insideBottom"?Cm({x:o+d/2,y:c+u-p,textAnchor:"middle",verticalAnchor:f},D):i==="insideTopLeft"?Cm({x:o+v,y:c+p,textAnchor:b,verticalAnchor:g},D):i==="insideTopRight"?Cm({x:o+d-v,y:c+p,textAnchor:j,verticalAnchor:g},D):i==="insideBottomLeft"?Cm({x:o+v,y:c+u-p,textAnchor:b,verticalAnchor:f},D):i==="insideBottomRight"?Cm({x:o+d-v,y:c+u-p,textAnchor:j,verticalAnchor:f},D):iR(i)&&(la(i.x)||tA(i.x))&&(la(i.y)||tA(i.y))?Cm({x:o+Xx(i.x,d),y:c+Xx(i.y,u),textAnchor:"end",verticalAnchor:"end"},D):Cm({x:o+d/2,y:c+u/2,textAnchor:"middle",verticalAnchor:"middle"},D)},GRs=function(t){return"cx"in t&&la(t.cx)};function kp(s){var t=s.offset,n=t===void 0?5:t,r=RRs(s,ARs),a=Cm({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,p=a.textBreakAll;if(!i||No(o)&&No(c)&&!N.isValidElement(d)&&!ho(d))return null;if(N.isValidElement(d))return N.cloneElement(d,a);var f;if(ho(d)){if(f=N.createElement(d,a),N.isValidElement(f))return f}else f=$Rs(a);var g=GRs(i),_=Wi(a,!0);if(g&&(l==="insideStart"||l==="insideEnd"||l==="end"))return qRs(a,f,_);var v=g?VRs(a):HRs(a);return St.createElement(MM,e$({className:So("recharts-label",h)},_,v,{breakAll:p}),f)}kp.displayName="Label";var ibt=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,p=t.y,f=t.top,g=t.left,_=t.width,v=t.height,j=t.clockWise,b=t.labelViewBox;if(b)return b;if(la(_)&&la(v)){if(la(h)&&la(p))return{x:h,y:p,width:_,height:v};if(la(f)&&la(g))return{x:f,y:g,width:_,height:v}}return la(h)&&la(p)?{x:h,y:p,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:j}:t.viewBox?t.viewBox:{}},WRs=function(t,n){return t?t===!0?St.createElement(kp,{key:"label-implicit",viewBox:n}):$m(t)?St.createElement(kp,{key:"label-implicit",viewBox:n,value:t}):N.isValidElement(t)?t.type===kp?N.cloneElement(t,{key:"label-implicit",viewBox:n}):St.createElement(kp,{key:"label-implicit",content:t,viewBox:n}):ho(t)?St.createElement(kp,{key:"label-implicit",content:t,viewBox:n}):iR(t)?St.createElement(kp,e$({viewBox:n},t,{key:"label-implicit"})):null:null},KRs=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=ibt(t),l=fy(a,kp).map(function(c,d){return N.cloneElement(c,{viewBox:n||i,key:"label-".concat(d)})});if(!r)return l;var o=WRs(t.label,n||i);return[o].concat(MRs(l))};kp.parseViewBox=ibt;kp.renderCallByParent=KRs;function YRs(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var ZRs=YRs;const QRs=wl(ZRs);function t$(s){"@babel/helpers - typeof";return t$=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},t$(s)}var XRs=["valueAccessor"],JRs=["data","dataKey","clockWise","id","textBreakAll"];function eOs(s){return rOs(s)||nOs(s)||sOs(s)||tOs()}function tOs(){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 sOs(s,t){if(s){if(typeof s=="string")return m5e(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 m5e(s,t)}}function nOs(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function rOs(s){if(Array.isArray(s))return m5e(s)}function m5e(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 lOs(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 cOs=function(t){return Array.isArray(t.value)?QRs(t.value):t.value};function rN(s){var t=s.valueAccessor,n=t===void 0?cOs:t,r=RKe(s,XRs),a=r.data,i=r.dataKey,l=r.clockWise,o=r.id,c=r.textBreakAll,d=RKe(r,JRs);return!a||!a.length?null:St.createElement(Kl,{className:"recharts-label-list"},a.map(function(u,h){var p=No(i)?n(u,h):Fm(u&&u.payload,i),f=No(o)?{}:{id:"".concat(o,"-").concat(h)};return St.createElement(kp,hge({},Wi(u,!0),d,f,{parentViewBox:u.parentViewBox,value:p,textBreakAll:c,viewBox:kp.parseViewBox(No(l)?u:DKe(DKe({},u),{},{clockWise:l})),key:"label-".concat(h),index:h}))}))}rN.displayName="LabelList";function dOs(s,t){return s?s===!0?St.createElement(rN,{key:"labelList-implicit",data:t}):St.isValidElement(s)||ho(s)?St.createElement(rN,{key:"labelList-implicit",data:t,content:s}):iR(s)?St.createElement(rN,hge({data:t},s,{key:"labelList-implicit"})):null:null}function uOs(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=fy(r,rN).map(function(l,o){return N.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!n)return a;var i=dOs(s.label,t);return[i].concat(eOs(a))}rN.renderCallByParent=uOs;function s$(s){"@babel/helpers - typeof";return s$=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},s$(s)}function p5e(){return p5e=Object.assign?Object.assign.bind():function(s){for(var t=1;t180),",").concat(+(l>d),`, `).concat(h.x,",").concat(h.y,` `);if(a>0){var f=wd(n,r,a,l),g=wd(n,r,a,d);p+="L ".concat(g.x,",").concat(g.y,` A `).concat(a,",").concat(a,`,0, `).concat(+(Math.abs(c)>180),",").concat(+(l<=d),`, `).concat(f.x,",").concat(f.y," Z")}else p+="L ".concat(n,",").concat(r," Z");return p},xOs=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=Qx(u-d),p=iG({cx:n,cy:r,radius:i,angle:d,sign:h,cornerRadius:l,cornerIsExternal:c}),f=p.circleTangency,g=p.lineTangency,_=p.theta,v=iG({cx:n,cy:r,radius:i,angle:u,sign:-h,cornerRadius:l,cornerIsExternal:c}),j=v.circleTangency,b=v.lineTangency,S=v.theta,A=c?Math.abs(d-u):Math.abs(d-u)-_-S;if(A<0)return o?"M ".concat(g.x,",").concat(g.y,` a`).concat(l,",").concat(l,",0,0,1,").concat(l*2,`,0 a`).concat(l,",").concat(l,",0,0,1,").concat(-l*2,`,0 `):obt({cx:n,cy:r,innerRadius:a,outerRadius:i,startAngle:d,endAngle:u});var T="M ".concat(g.x,",").concat(g.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(f.x,",").concat(f.y,` A`).concat(i,",").concat(i,",0,").concat(+(A>180),",").concat(+(h<0),",").concat(j.x,",").concat(j.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(b.x,",").concat(b.y,` `);if(a>0){var L=iG({cx:n,cy:r,radius:a,angle:d,sign:h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),D=L.circleTangency,M=L.lineTangency,F=L.theta,z=iG({cx:n,cy:r,radius:a,angle:u,sign:-h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),V=z.circleTangency,W=z.lineTangency,Y=z.theta,K=c?Math.abs(d-u):Math.abs(d-u)-F-Y;if(K<0&&l===0)return"".concat(T,"L").concat(n,",").concat(r,"Z");T+="L".concat(W.x,",").concat(W.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(V.x,",").concat(V.y,` A`).concat(a,",").concat(a,",0,").concat(+(K>180),",").concat(+(h>0),",").concat(D.x,",").concat(D.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(M.x,",").concat(M.y,"Z")}else T+="L".concat(n,",").concat(r,"Z");return T},gOs={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},lbt=function(t){var n=FKe(FKe({},gOs),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,p=n.className;if(l0&&Math.abs(u-h)<360?v=xOs({cx:r,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(_,g/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:u,endAngle:h}):v=obt({cx:r,cy:a,innerRadius:i,outerRadius:l,startAngle:u,endAngle:h}),St.createElement("path",p5e({},Wi(n,!0),{className:f,d:v,role:"img"}))};function n$(s){"@babel/helpers - typeof";return n$=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},n$(s)}function f5e(){return f5e=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 IOs(s,t){return yR(s.getTime(),t.getTime())}function GKe(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,p=h[0],f=h[1],g=o.value,_=g[0],v=g[1];!d&&!r[u]&&(d=n.equals(p,_,i,u,s,t,n)&&n.equals(f,v,p,_,s,t,n))&&(r[u]=!0),u++}if(!d)return!1;i++}return!0}function POs(s,t,n){var r=HKe(s),a=r.length;if(HKe(t).length!==a)return!1;for(var i;a-- >0;)if(i=r[a],i===mbt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!hbt(t,i)||!n.equals(s[i],t[i],i,i,s,t,n))return!1;return!0}function IF(s,t,n){var r=qKe(s),a=r.length;if(qKe(t).length!==a)return!1;for(var i,l,o;a-- >0;)if(i=r[a],i===mbt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!hbt(t,i)||!n.equals(s[i],t[i],i,i,s,t,n)||(l=VKe(s,i),o=VKe(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function LOs(s,t){return yR(s.valueOf(),t.valueOf())}function DOs(s,t){return s.source===t.source&&s.flags===t.flags}function WKe(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 ROs(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 OOs="[object Arguments]",FOs="[object Boolean]",zOs="[object Date]",BOs="[object Map]",$Os="[object Number]",UOs="[object Object]",qOs="[object RegExp]",VOs="[object Set]",HOs="[object String]",GOs=Array.isArray,KKe=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,YKe=Object.assign,WOs=Object.prototype.toString.call.bind(Object.prototype.toString);function KOs(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,p){if(u===h)return!0;if(u==null||h==null||typeof u!="object"||typeof h!="object")return u!==u&&h!==h;var f=u.constructor;if(f!==h.constructor)return!1;if(f===Object)return a(u,h,p);if(GOs(u))return t(u,h,p);if(KKe!=null&&KKe(u))return c(u,h,p);if(f===Date)return n(u,h,p);if(f===RegExp)return l(u,h,p);if(f===Map)return r(u,h,p);if(f===Set)return o(u,h,p);var g=WOs(u);return g===zOs?n(u,h,p):g===qOs?l(u,h,p):g===BOs?r(u,h,p):g===VOs?o(u,h,p):g===UOs?typeof u.then!="function"&&typeof h.then!="function"&&a(u,h,p):g===OOs?a(u,h,p):g===FOs||g===$Os||g===HOs?i(u,h,p):!1}}function YOs(s){var t=s.circular,n=s.createCustomConfig,r=s.strict,a={areArraysEqual:r?IF:MOs,areDatesEqual:IOs,areMapsEqual:r?UKe(GKe,IF):GKe,areObjectsEqual:r?IF:POs,arePrimitiveWrappersEqual:LOs,areRegExpsEqual:DOs,areSetsEqual:r?UKe(WKe,IF):WKe,areTypedArraysEqual:r?IF:ROs};if(n&&(a=YKe({},a,n(a))),t){var i=lG(a.areArraysEqual),l=lG(a.areMapsEqual),o=lG(a.areObjectsEqual),c=lG(a.areSetsEqual);a=YKe({},a,{areArraysEqual:i,areMapsEqual:l,areObjectsEqual:o,areSetsEqual:c})}return a}function ZOs(s){return function(t,n,r,a,i,l,o){return s(t,n,o)}}function QOs(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,p=h===void 0?t?new WeakMap:void 0:h,f=u.meta;return n(c,d,{cache:p,equals:a,meta:f,strict:i})};if(t)return function(c,d){return n(c,d,{cache:new WeakMap,equals:a,meta:void 0,strict:i})};var l={cache:void 0,equals:a,meta:void 0,strict:i};return function(c,d){return n(c,d,l)}}var XOs=mC();mC({strict:!0});mC({circular:!0});mC({circular:!0,strict:!0});mC({createInternalComparator:function(){return yR}});mC({strict:!0,createInternalComparator:function(){return yR}});mC({circular:!0,createInternalComparator:function(){return yR}});mC({circular:!0,createInternalComparator:function(){return yR},strict:!0});function mC(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=YOs(s),c=KOs(o),d=r?r(c):ZOs(c);return QOs({circular:n,comparator:c,createState:a,equals:d,strict:l})}function JOs(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function ZKe(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):JOs(a)};requestAnimationFrame(r)}function x5e(s){"@babel/helpers - typeof";return x5e=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},x5e(s)}function eFs(s){return rFs(s)||nFs(s)||sFs(s)||tFs()}function tFs(){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 sFs(s,t){if(s){if(typeof s=="string")return QKe(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 QKe(s,t)}}function QKe(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:j<0?0:j},_=function(j){for(var b=j>1?1:j,S=b,A=0;A<8;++A){var T=h(S)-b,L=f(S);if(Math.abs(T-b)0&&arguments[0]!==void 0?arguments[0]:{},n=t.stiff,r=n===void 0?100:n,a=t.damping,i=a===void 0?8:a,l=t.dt,o=l===void 0?17:l,c=function(u,h,p){var f=-(u-h)*r,g=p*i,_=p+(f-g)*o/1e3,v=p*o/1e3+u;return Math.abs(v-h)s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function DFs(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 mNe(s){return zFs(s)||FFs(s)||OFs(s)||RFs()}function RFs(){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 OFs(s,t){if(s){if(typeof s=="string")return _5e(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 _5e(s,t)}}function FFs(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function zFs(s){if(Array.isArray(s))return _5e(s)}function _5e(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 xge(s){return xge=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},xge(s)}var Ow=function(s){VFs(n,s);var t=HFs(n);function n(r,a){var i;BFs(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,p=l.children,f=l.duration;if(i.handleStyleChange=i.handleStyleChange.bind(N5e(i)),i.changeStyle=i.changeStyle.bind(N5e(i)),!o||f<=0)return i.state={style:{}},typeof p=="function"&&(i.state={style:u}),j5e(i);if(h&&h.length)i.state={style:h[0].style};else if(d){if(typeof p=="function")return i.state={style:d},j5e(i);i.state={style:c?k7({},c,d):d}}else i.state={style:{}};return i}return UFs(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,p=this.state.style;if(o){if(!l){var f={style:c?k7({},c,u):u};this.state&&p&&(c&&p[c]!==u||!c&&p!==u)&&this.setState(f);return}if(!(XOs(a.to,u)&&a.canBegin&&a.isActive)){var g=!a.canBegin||!a.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var _=g||d?h:a.to;if(this.state&&p){var v={style:c?k7({},c,_):_};(c&&p[c]!==_||!c&&p!==_)&&this.setState(v)}this.runAnimation(z1(z1({},this.props),{},{from:_,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,p=a.onAnimationStart,f=IFs(l,o,_Fs(d),c,this.changeStyle),g=function(){i.stopJSAnimation=f()};this.manager.start([p,u,g,c,h])}},{key:"runStepAnimation",value:function(a){var i=this,l=a.steps,o=a.begin,c=a.onAnimationStart,d=l[0],u=d.style,h=d.duration,p=h===void 0?0:h,f=function(_,v,j){if(j===0)return _;var b=v.duration,S=v.easing,A=S===void 0?"ease":S,T=v.style,L=v.properties,D=v.onAnimationEnd,M=j>0?l[j-1]:v,F=L||Object.keys(T);if(typeof A=="function"||A==="spring")return[].concat(mNe(_),[i.runJSAnimation.bind(i,{from:M.style,to:T,duration:b,easing:A}),b]);var z=eYe(F,b,A),V=z1(z1(z1({},M.style),T),{},{transition:z});return[].concat(mNe(_),[V,b,D]).filter(cFs)};return this.manager.start([c].concat(mNe(l.reduce(f,[u,Math.max(p,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=aFs());var i=a.begin,l=a.duration,o=a.attributeName,c=a.to,d=a.easing,u=a.onAnimationStart,h=a.onAnimationEnd,p=a.steps,f=a.children,g=this.manager;if(this.unSubscribe=g.subscribe(this.handleStyleChange),typeof d=="function"||typeof f=="function"||d==="spring"){this.runJSAnimation(a);return}if(p.length>1){this.runStepAnimation(a);return}var _=o?k7({},o,c):c,v=eYe(Object.keys(_),l,d);g.start([u,i,z1(z1({},_),{},{transition:v}),l,h])}},{key:"render",value:function(){var a=this.props,i=a.children;a.begin;var l=a.duration;a.attributeName,a.easing;var o=a.isActive;a.steps,a.from,a.to,a.canBegin,a.onAnimationEnd,a.shouldReAnimate,a.onAnimationReStart;var c=LFs(a,PFs),d=N.Children.count(i),u=this.state.style;if(typeof i=="function")return i(u);if(!o||d===0||l<=0)return i;var h=function(f){var g=f.props,_=g.style,v=_===void 0?{}:_,j=g.className,b=N.cloneElement(f,z1(z1({},c),{},{style:z1(z1({},v),u),className:j}));return b};return d===1?h(N.Children.only(i)):St.createElement("div",null,N.Children.map(i,function(p){return h(p)}))}}]),n}(N.PureComponent);Ow.displayName="Animate";Ow.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};Ow.propTypes={from:gc.oneOfType([gc.object,gc.string]),to:gc.oneOfType([gc.object,gc.string]),attributeName:gc.string,duration:gc.number,begin:gc.number,easing:gc.oneOfType([gc.string,gc.func]),steps:gc.arrayOf(gc.shape({duration:gc.number.isRequired,style:gc.object.isRequired,easing:gc.oneOfType([gc.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),gc.func]),properties:gc.arrayOf("string"),onAnimationEnd:gc.func})),children:gc.oneOfType([gc.node,gc.func]),isActive:gc.bool,canBegin:gc.bool,onAnimationEnd:gc.func,shouldReAnimate:gc.bool,onAnimationStart:gc.func,onAnimationReStart:gc.func};function i$(s){"@babel/helpers - typeof";return i$=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},i$(s)}function gge(){return gge=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],p=0,f=4;pl?l:i[p];u="M".concat(t,",").concat(n+o*h[0]),h[0]>0&&(u+="A ".concat(h[0],",").concat(h[0],",0,0,").concat(d,",").concat(t+c*h[0],",").concat(n)),u+="L ".concat(t+r-c*h[1],",").concat(n),h[1]>0&&(u+="A ".concat(h[1],",").concat(h[1],",0,0,").concat(d,`, `).concat(t+r,",").concat(n+o*h[1])),u+="L ".concat(t+r,",").concat(n+a-o*h[2]),h[2]>0&&(u+="A ".concat(h[2],",").concat(h[2],",0,0,").concat(d,`, `).concat(t+r-c*h[2],",").concat(n+a)),u+="L ".concat(t+c*h[3],",").concat(n+a),h[3]>0&&(u+="A ".concat(h[3],",").concat(h[3],",0,0,").concat(d,`, `).concat(t,",").concat(n+a-o*h[3])),u+="Z"}else if(l>0&&i===+i&&i>0){var g=Math.min(l,i);u="M ".concat(t,",").concat(n+o*g,` A `).concat(g,",").concat(g,",0,0,").concat(d,",").concat(t+c*g,",").concat(n,` L `).concat(t+r-c*g,",").concat(n,` A `).concat(g,",").concat(g,",0,0,").concat(d,",").concat(t+r,",").concat(n+o*g,` L `).concat(t+r,",").concat(n+a-o*g,` A `).concat(g,",").concat(g,",0,0,").concat(d,",").concat(t+r-c*g,",").concat(n+a,` L `).concat(t+c*g,",").concat(n+a,` A `).concat(g,",").concat(g,",0,0,").concat(d,",").concat(t,",").concat(n+a-o*g," Z")}else u="M ".concat(t,",").concat(n," h ").concat(r," v ").concat(a," h ").concat(-r," Z");return u},t7s=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),p=Math.max(l,l+c);return r>=d&&r<=u&&a>=h&&a<=p}return!1},s7s={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},JPe=function(t){var n=lYe(lYe({},s7s),t),r=N.useRef(),a=N.useState(-1),i=WFs(a,2),l=i[0],o=i[1];N.useEffect(function(){if(r.current&&r.current.getTotalLength)try{var A=r.current.getTotalLength();A&&o(A)}catch{}},[]);var c=n.x,d=n.y,u=n.width,h=n.height,p=n.radius,f=n.className,g=n.animationEasing,_=n.animationDuration,v=n.animationBegin,j=n.isAnimationActive,b=n.isUpdateAnimationActive;if(c!==+c||d!==+d||u!==+u||h!==+h||u===0||h===0)return null;var S=So("recharts-rectangle",f);return b?St.createElement(Ow,{canBegin:l>0,from:{width:u,height:h,x:c,y:d},to:{width:u,height:h,x:c,y:d},duration:_,animationEasing:g,isActive:b},function(A){var T=A.width,L=A.height,D=A.x,M=A.y;return St.createElement(Ow,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:v,duration:_,isActive:j,easing:g},St.createElement("path",gge({},Wi(n,!0),{className:S,d:cYe(D,M,T,L,p),ref:r})))}):St.createElement("path",gge({},Wi(n,!0),{className:S,d:cYe(c,d,u,h,p)}))},n7s=["points","className","baseLinePoints","connectNulls"];function DP(){return DP=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 a7s(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 dYe(s){return c7s(s)||l7s(s)||o7s(s)||i7s()}function i7s(){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 o7s(s,t){if(s){if(typeof s=="string")return k5e(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 k5e(s,t)}}function l7s(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function c7s(s){if(Array.isArray(s))return k5e(s)}function k5e(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){uYe(r)?n[n.length-1].push(r):n[n.length-1].length>0&&n.push([])}),uYe(t[0])&&n[n.length-1].push(t[0]),n[n.length-1].length<=0&&(n=n.slice(0,-1)),n},kz=function(t,n){var r=d7s(t);n&&(r=[r.reduce(function(i,l){return[].concat(dYe(i),dYe(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},u7s=function(t,n,r){var a=kz(t,r);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(kz(n.reverse(),r).slice(1))},h7s=function(t){var n=t.points,r=t.className,a=t.baseLinePoints,i=t.connectNulls,l=r7s(t,n7s);if(!n||!n.length)return null;var o=So("recharts-polygon",r);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=u7s(n,a,i);return St.createElement("g",{className:o},St.createElement("path",DP({},Wi(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?St.createElement("path",DP({},Wi(l,!0),{fill:"none",d:kz(n,i)})):null,c?St.createElement("path",DP({},Wi(l,!0),{fill:"none",d:kz(a,i)})):null)}var u=kz(n,i);return St.createElement("path",DP({},Wi(l,!0),{fill:u.slice(-1)==="Z"?l.fill:"none",className:o,d:u}))};function S5e(){return S5e=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 v7s(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 b7s=function(t,n,r,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(n,"h").concat(r)},_7s=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,p=t.height,f=p===void 0?0:p,g=t.className,_=y7s(t,m7s),v=p7s({x:r,y:i,top:o,left:d,width:h,height:f},_);return!la(r)||!la(i)||!la(h)||!la(f)||!la(o)||!la(d)?null:St.createElement("path",C5e({},Wi(v,!0),{className:So("recharts-cross",g),d:b7s(r,i,h,f,o,d)}))},w7s=c1e,j7s=A1t,N7s=ej;function k7s(s,t){return s&&s.length?w7s(s,N7s(t),j7s):void 0}var S7s=k7s;const C7s=wl(S7s);var T7s=c1e,E7s=ej,A7s=M1t;function M7s(s,t){return s&&s.length?T7s(s,E7s(t),A7s):void 0}var I7s=M7s;const P7s=wl(I7s);var L7s=["cx","cy","angle","ticks","axisLine"],D7s=["ticks","tick","angle","tickFormatter","stroke"];function W8(s){"@babel/helpers - typeof";return W8=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},W8(s)}function Sz(){return Sz=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 R7s(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 O7s(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function fYe(s,t){for(var n=0;nyYe?l=a==="outer"?"start":"end":i<-yYe?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=f3(f3({},Wi(this.props,!1)),{},{fill:"none"},Wi(o,!1));if(c==="circle")return St.createElement(p1e,UE({className:"recharts-polar-angle-axis-line"},d,{cx:a,cy:i,r:l}));var u=this.props.ticks,h=u.map(function(p){return wd(a,i,l,p.coordinate)});return St.createElement(h7s,UE({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=Wi(this.props,!1),h=Wi(l,!1),p=f3(f3({},u),{},{fill:"none"},Wi(o,!1)),f=i.map(function(g,_){var v=r.getTickLineCoord(g),j=r.getTickTextAnchor(g),b=f3(f3(f3({textAnchor:j},u),{},{stroke:"none",fill:d},h),{},{index:_,payload:g,x:v.x2,y:v.y2});return St.createElement(Kl,UE({className:So("recharts-polar-angle-axis-tick",abt(l)),key:"tick-".concat(g.coordinate)},AM(r.props,g,_)),o&&St.createElement("line",UE({className:"recharts-polar-angle-axis-tick-line"},p,v)),l&&t.renderTickItem(l,b,c?c(g.value,_):g.value))});return St.createElement(Kl,{className:"recharts-polar-angle-axis-ticks"},f)}},{key:"render",value:function(){var r=this.props,a=r.ticks,i=r.radius,l=r.axisLine;return i<=0||!a||!a.length?null:St.createElement(Kl,{className:So("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(r,a,i){var l;return St.isValidElement(r)?l=St.cloneElement(r,a):ho(r)?l=r(a):l=St.createElement(MM,UE({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(N.PureComponent);g1e(y1e,"displayName","PolarAngleAxis");g1e(y1e,"axisType","angleAxis");g1e(y1e,"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 X7s=Svt,J7s=X7s(Object.getPrototypeOf,Object),e9s=J7s,t9s=EN,s9s=e9s,n9s=AN,r9s="[object Object]",a9s=Function.prototype,i9s=Object.prototype,Nbt=a9s.toString,o9s=i9s.hasOwnProperty,l9s=Nbt.call(Object);function c9s(s){if(!n9s(s)||t9s(s)!=r9s)return!1;var t=s9s(s);if(t===null)return!0;var n=o9s.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&Nbt.call(n)==l9s}var d9s=c9s;const u9s=wl(d9s);var h9s=EN,m9s=AN,p9s="[object Boolean]";function f9s(s){return s===!0||s===!1||m9s(s)&&h9s(s)==p9s}var x9s=f9s;const g9s=wl(x9s);function l$(s){"@babel/helpers - typeof";return l$=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},l$(s)}function bge(){return bge=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:p,x:c,y:d},to:{upperWidth:u,lowerWidth:h,height:p,x:c,y:d},duration:_,animationEasing:g,isActive:j},function(S){var A=S.upperWidth,T=S.lowerWidth,L=S.height,D=S.x,M=S.y;return St.createElement(Ow,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:v,duration:_,easing:g},St.createElement("path",bge({},Wi(n,!0),{className:b,d:wYe(D,M,A,T,L),ref:r})))}):St.createElement("g",null,St.createElement("path",bge({},Wi(n,!0),{className:b,d:wYe(c,d,u,h,p)})))},T9s=["option","shapeType","propTransformer","activeClassName","isActive"];function c$(s){"@babel/helpers - typeof";return c$=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},c$(s)}function E9s(s,t){if(s==null)return{};var n=A9s(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 A9s(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 jYe(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 _ge(s){for(var t=1;t0?py(S,"paddingAngle",0):0;if(T){var D=K0(T.endAngle-T.startAngle,S.endAngle-S.startAngle),M=yd(yd({},S),{},{startAngle:b+L,endAngle:b+D(_)+L});v.push(M),b=M.endAngle}else{var F=S.endAngle,z=S.startAngle,V=K0(0,F-z),W=V(_),Y=yd(yd({},S),{},{startAngle:b+L,endAngle:b+W+L});v.push(Y),b=Y.endAngle}}),St.createElement(Kl,null,r.renderSectorsStatically(v))})}},{key:"attachKeyboardHandlers",value:function(r){var a=this;r.onkeydown=function(i){if(!i.altKey)switch(i.key){case"ArrowLeft":{var l=++a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[l].focus(),a.setState({sectorToFocus:l});break}case"ArrowRight":{var o=--a.state.sectorToFocus<0?a.sectorRefs.length-1:a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[o].focus(),a.setState({sectorToFocus:o});break}case"Escape":{a.sectorRefs[a.state.sectorToFocus].blur(),a.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var r=this.props,a=r.sectors,i=r.isAnimationActive,l=this.state.prevSectors;return i&&a&&a.length&&(!l||!FU(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,p=a.outerRadius,f=a.isAnimationActive,g=this.state.isAnimationFinished;if(i||!l||!l.length||!la(d)||!la(u)||!la(h)||!la(p))return null;var _=So("recharts-pie",o);return St.createElement(Kl,{tabIndex:this.props.rootTabIndex,className:_,ref:function(j){r.pieRef=j}},this.renderSectors(),c&&this.renderLabels(l),kp.renderCallByParent(this.props,null,!1),(!f||g)&&rN.renderCallByParent(this.props,l,!1))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return a.prevIsAnimationActive!==r.isAnimationActive?{prevIsAnimationActive:r.isAnimationActive,prevAnimationId:r.animationId,curSectors:r.sectors,prevSectors:[],isAnimationFinished:!0}:r.isAnimationActive&&r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curSectors:r.sectors,prevSectors:a.curSectors,isAnimationFinished:!0}:r.sectors!==a.curSectors?{curSectors:r.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(r,a){return r>a?"start":r=360?b:b-1)*c,A=v-b*f-S,T=a.reduce(function(M,F){var z=Fm(F,j,0);return M+(la(z)?z:0)},0),L;if(T>0){var D;L=a.map(function(M,F){var z=Fm(M,j,0),V=Fm(M,u,F),W=(la(z)?z:0)/T,Y;F?Y=D.endAngle+Qx(_)*c*(z!==0?1:0):Y=l;var K=Y+Qx(_)*((z!==0?f:0)+W*A),J=(Y+K)/2,ne=(g.innerRadius+g.outerRadius)/2,ie=[{name:V,value:z,payload:M,dataKey:j,type:p}],he=wd(g.cx,g.cy,ne,J);return D=yd(yd(yd({percent:W,cornerRadius:i,name:V,tooltipPayload:ie,midAngle:J,middleRadius:ne,tooltipPosition:he},M),g),{},{value:Fm(M,j),startAngle:Y,endAngle:K,payload:M,paddingAngle:Qx(_)*c}),D})}return yd(yd({},g),{},{sectors:L,data:a})});var Q9s=Math.ceil,X9s=Math.max;function J9s(s,t,n,r){for(var a=-1,i=X9s(Q9s((t-s)/(n||1)),0),l=Array(i);i--;)l[r?i:++a]=s,s+=n;return l}var ezs=J9s,tzs=Hvt,CYe=1/0,szs=17976931348623157e292;function nzs(s){if(!s)return s===0?s:0;if(s=tzs(s),s===CYe||s===-CYe){var t=s<0?-1:1;return t*szs}return s===s?s:0}var Tbt=nzs,rzs=ezs,azs=s1e,pNe=Tbt;function izs(s){return function(t,n,r){return r&&typeof r!="number"&&azs(t,n,r)&&(n=r=void 0),t=pNe(t),n===void 0?(n=t,t=0):n=pNe(n),r=r===void 0?t0&&r.handleDrag(a.changedTouches[0])}),z0(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()}),z0(r,"handleLeaveWrapper",function(){(r.state.isTravellerMoving||r.state.isSlideMoving)&&(r.leaveTimer=window.setTimeout(r.handleDragEnd,r.props.leaveTimeOut))}),z0(r,"handleEnterSlideOrTraveller",function(){r.setState({isTextActive:!0})}),z0(r,"handleLeaveSlideOrTraveller",function(){r.setState({isTextActive:!1})}),z0(r,"handleSlideDragStart",function(a){var i=IYe(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 bzs(t,s),xzs(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),p=Math.max(a,i),f=t.getIndexInRange(l,h),g=t.getIndexInRange(l,p);return{startIndex:f-f%c,endIndex:g===u?u:g-g%c}}},{key:"getTextOfTick",value:function(r){var a=this.props,i=a.data,l=a.tickFormatter,o=a.dataKey,c=Fm(i[r],o,r);return ho(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,p=c.startIndex,f=c.endIndex,g=c.onChange,_=r.pageX-i;_>0?_=Math.min(_,d+u-h-o,d+u-h-l):_<0&&(_=Math.max(_,d-l,d-o));var v=this.getIndex({startX:l+_,endX:o+_});(v.startIndex!==p||v.endIndex!==f)&&g&&g(v),this.setState({startX:l+_,endX:o+_,slideMoveStartX:r.pageX})}},{key:"handleTravellerDragStart",value:function(r,a){var i=IYe(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,p=u.width,f=u.travellerWidth,g=u.onChange,_=u.gap,v=u.data,j={startX:this.state.startX,endX:this.state.endX},b=r.pageX-i;b>0?b=Math.min(b,h+p-f-d):b<0&&(b=Math.max(b,h-d)),j[l]=d+b;var S=this.getIndex(j),A=S.startIndex,T=S.endIndex,L=function(){var M=v.length-1;return l==="startX"&&(o>c?A%_===0:T%_===0)||oc?T%_===0:A%_===0)||o>c&&T===M};this.setState(z0(z0({},l,d+b),"brushMoveStartX",r.pageX),function(){g&&L()&&g(S)})}},{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 p=h+r;if(!(p===-1||p>=o.length)){var f=o[p];a==="startX"&&f>=d||a==="endX"&&f<=c||this.setState(z0({},a,f),function(){i.props.onChange(i.getIndex({startX:i.state.startX,endX:i.state.endX}))})}}}},{key:"renderBackground",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.fill,d=r.stroke;return St.createElement("rect",{stroke:d,fill:c,x:a,y:i,width:l,height:o})}},{key:"renderPanorama",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.data,d=r.children,u=r.padding,h=N.Children.only(d);return h?St.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,p=c.traveller,f=c.ariaLabel,g=c.data,_=c.startIndex,v=c.endIndex,j=Math.max(r,this.props.x),b=fNe(fNe({},Wi(this.props,!1)),{},{x:j,y:d,width:u,height:h}),S=f||"Min value: ".concat((i=g[_])===null||i===void 0?void 0:i.name,", Max value: ").concat((l=g[v])===null||l===void 0?void 0:l.name);return St.createElement(Kl,{tabIndex:0,role:"slider","aria-label":S,"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(p,b))}},{key:"renderSlide",value:function(r,a){var i=this.props,l=i.y,o=i.height,c=i.stroke,d=i.travellerWidth,u=Math.min(r,a)+d,h=Math.max(Math.abs(a-r)-d,0);return St.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,p=u.endX,f=5,g={pointerEvents:"none",fill:d};return St.createElement(Kl,{className:"recharts-brush-texts"},St.createElement(MM,Nge({textAnchor:"end",verticalAnchor:"middle",x:Math.min(h,p)-f,y:l+o/2},g),this.getTextOfTick(a)),St.createElement(MM,Nge({textAnchor:"start",verticalAnchor:"middle",x:Math.max(h,p)+c+f,y:l+o/2},g),this.getTextOfTick(i)))}},{key:"render",value:function(){var r=this.props,a=r.data,i=r.className,l=r.children,o=r.x,c=r.y,d=r.width,u=r.height,h=r.alwaysShowText,p=this.state,f=p.startX,g=p.endX,_=p.isTextActive,v=p.isSlideMoving,j=p.isTravellerMoving,b=p.isTravellerFocused;if(!a||!a.length||!la(o)||!la(c)||!la(d)||!la(u)||d<=0||u<=0)return null;var S=So("recharts-brush",i),A=St.Children.count(l)===1,T=pzs("userSelect","none");return St.createElement(Kl,{className:S,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:T},this.renderBackground(),A&&this.renderPanorama(),this.renderSlide(f,g),this.renderTravellerLayer(f,"startX"),this.renderTravellerLayer(g,"endX"),(_||v||j||b||h)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(r){var a=r.x,i=r.y,l=r.width,o=r.height,c=r.stroke,d=Math.floor(i+o/2)-1;return St.createElement(St.Fragment,null,St.createElement("rect",{x:a,y:i,width:l,height:o,fill:c,stroke:"none"}),St.createElement("line",{x1:a+1,y1:d,x2:a+l-1,y2:d,fill:"none",stroke:"#fff"}),St.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 St.isValidElement(r)?i=St.cloneElement(r,a):ho(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 fNe({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?wzs({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 p=a.scale.domain().map(function(f){return a.scale(f)});return{prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l,startX:a.scale(r.startIndex),endX:a.scale(r.endIndex),scaleValues:p}}return null}},{key:"getIndexInRange",value:function(r,a){for(var i=r.length,l=0,o=i-1;o-l>1;){var c=Math.floor((l+o)/2);r[c]>a?o=c:l=c}return a>=r[o]?o:l}}])}(N.PureComponent);z0(Q8,"displayName","Brush");z0(Q8,"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 jzs=kPe;function Nzs(s,t){var n;return jzs(s,function(r,a,i){return n=t(r,a,i),!n}),!!n}var kzs=Nzs,Szs=yvt,Czs=ej,Tzs=kzs,Ezs=o0,Azs=s1e;function Mzs(s,t,n){var r=Ezs(s)?Szs:Tzs;return n&&Azs(s,t,n)&&(t=void 0),r(s,Czs(t))}var Izs=Mzs;const Pzs=wl(Izs);var Cw=function(t,n){var r=t.alwaysShow,a=t.ifOverflow;return r&&(a="extendDomain"),a===n},PYe=Bvt;function Lzs(s,t,n){t=="__proto__"&&PYe?PYe(s,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[t]=n}var Dzs=Lzs,Rzs=Dzs,Ozs=Fvt,Fzs=ej;function zzs(s,t){var n={};return t=Fzs(t),Ozs(s,function(r,a,i){Rzs(n,a,t(r,a,i))}),n}var Bzs=zzs;const $zs=wl(Bzs);function Uzs(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 aBs(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 iBs(s,t){var n=s.x,r=s.y,a=rBs(s,eBs),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),p=parseInt(h,10);return PF(PF(PF(PF(PF({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:u,width:p,name:t.name,radius:t.radius})}function DYe(s){return St.createElement(kbt,I5e({shapeType:"rectangle",propTransformer:iBs,activeClassName:"recharts-active-bar"},s))}var oBs=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)||Uks(r);return i?t(r,a):(i||PM(),n)}},lBs=["value","background"],Pbt;function X8(s){"@babel/helpers - typeof";return X8=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},X8(s)}function cBs(s,t){if(s==null)return{};var n=dBs(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 dBs(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 Sge(){return Sge=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(J)0&&Math.abs(K)0&&(Y=Math.min((Te||0)-(K[Me-1]||0),Y))}),Number.isFinite(Y)){var J=Y/W,ne=_.layout==="vertical"?r.height:r.width;if(_.padding==="gap"&&(D=J*ne/2),_.padding==="no-gap"){var ie=Xx(t.barCategoryGap,J*ne),he=J*ne/2;D=he-ie-(he-ie)/ne*ie}}}a==="xAxis"?M=[r.left+(S.left||0)+(D||0),r.left+r.width-(S.right||0)-(D||0)]:a==="yAxis"?M=c==="horizontal"?[r.top+r.height-(S.bottom||0),r.top+(S.top||0)]:[r.top+(S.top||0)+(D||0),r.top+r.height-(S.bottom||0)-(D||0)]:M=_.range,T&&(M=[M[1],M[0]]);var ce=X1t(_,i,p),pe=ce.scale,le=ce.realScaleType;pe.domain(j).range(M),J1t(pe);var ve=ebt(pe,Q1(Q1({},_),{},{realScaleType:le}));a==="xAxis"?(V=v==="top"&&!A||v==="bottom"&&A,F=r.left,z=h[L]-V*_.height):a==="yAxis"&&(V=v==="left"&&!A||v==="right"&&A,F=h[L]-V*_.width,z=r.top);var ge=Q1(Q1(Q1({},_),ve),{},{realScaleType:le,x:F,y:z,scale:pe,width:a==="xAxis"?r.width:_.width,height:a==="yAxis"?r.height:_.height});return ge.bandSize=dge(ge,ve),!_.hide&&a==="xAxis"?h[L]+=(V?-1:1)*ge.height:_.hide||(h[L]+=(V?-1:1)*ge.width),Q1(Q1({},f),{},_1e({},g,ge))},{})},Fbt=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)}},_Bs=function(t){var n=t.x1,r=t.y1,a=t.x2,i=t.y2;return Fbt({x:n,y:r},{x:a,y:i})},zbt=function(){function s(t){yBs(this,s),this.scale=t}return vBs(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)}}])}();_1e(zbt,"EPS",1e-4);var eLe=function(t){var n=Object.keys(t).reduce(function(r,a){return Q1(Q1({},r),{},_1e({},a,zbt.create(t[a])))},{});return Q1(Q1({},n),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return $zs(a,function(c,d){return n[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return Ibt(a,function(i,l){return n[l].isInRange(i)})}})};function wBs(s){return(s%180+180)%180}var jBs=function(t){var n=t.width,r=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=wBs(a),l=i*Math.PI/180,o=Math.atan(r/n),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var TBs=CBs,EBs=Tbt;function ABs(s){var t=EBs(s),n=t%1;return t===t?n?t-n:t:0}var MBs=ABs,IBs=Ivt,PBs=ej,LBs=MBs,DBs=Math.max;function RBs(s,t,n){var r=s==null?0:s.length;if(!r)return-1;var a=n==null?0:LBs(n);return a<0&&(a=DBs(r+a,0)),IBs(s,PBs(t),a)}var OBs=RBs,FBs=TBs,zBs=OBs,BBs=FBs(zBs),$Bs=BBs;const UBs=wl($Bs);var qBs=GNs(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("")}),tLe=N.createContext(void 0),sLe=N.createContext(void 0),Bbt=N.createContext(void 0),$bt=N.createContext({}),Ubt=N.createContext(void 0),qbt=N.createContext(0),Vbt=N.createContext(0),BYe=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=qBs(i);return St.createElement(tLe.Provider,{value:r},St.createElement(sLe.Provider,{value:a},St.createElement($bt.Provider,{value:i},St.createElement(Bbt.Provider,{value:u},St.createElement(Ubt.Provider,{value:l},St.createElement(qbt.Provider,{value:d},St.createElement(Vbt.Provider,{value:c},o)))))))},VBs=function(){return N.useContext(Ubt)},Hbt=function(t){var n=N.useContext(tLe);n==null&&PM();var r=n[t];return r==null&&PM(),r},HBs=function(){var t=N.useContext(tLe);return xS(t)},GBs=function(){var t=N.useContext(sLe),n=UBs(t,function(r){return Ibt(r.domain,Number.isFinite)});return n||xS(t)},Gbt=function(t){var n=N.useContext(sLe);n==null&&PM();var r=n[t];return r==null&&PM(),r},WBs=function(){var t=N.useContext(Bbt);return t},KBs=function(){return N.useContext($bt)},nLe=function(){return N.useContext(Vbt)},rLe=function(){return N.useContext(qbt)};function J8(s){"@babel/helpers - typeof";return J8=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},J8(s)}function YBs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function ZBs(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 M$s(s,t){return Jbt(s,t+1)}function I$s(s,t,n,r,a){for(var i=(r||[]).slice(),l=t.start,o=t.end,c=0,d=1,u=l,h=function(){var g=r==null?void 0:r[c];if(g===void 0)return{v:Jbt(r,d)};var _=c,v,j=function(){return v===void 0&&(v=n(g,_)),v},b=g.coordinate,S=c===0||Mge(s,b,j,u,o);S||(c=0,u=l,d+=1),S&&(u=b+s*(j()/2+a),c+=d)},p;d<=i.length;)if(p=h(),p)return p.v;return[]}function p$(s){"@babel/helpers - typeof";return p$=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},p$(s)}function KYe(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 Kf(s){for(var t=1;t0?f.coordinate-v*s:f.coordinate})}else i[p]=f=Kf(Kf({},f),{},{tickCoord:f.coordinate});var j=Mge(s,f.tickCoord,_,o,c);j&&(c=f.tickCoord-s*(_()/2+a),i[p]=Kf(Kf({},f),{},{isShow:!0}))},u=l-1;u>=0;u--)d(u);return i}function O$s(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),p=s*(u.coordinate+s*h/2-d);l[o-1]=u=Kf(Kf({},u),{},{tickCoord:p>0?u.coordinate-p*s:u.coordinate});var f=Mge(s,u.tickCoord,function(){return h},c,d);f&&(d=u.tickCoord-s*(h/2+a),l[o-1]=Kf(Kf({},u),{},{isShow:!0}))}for(var g=i?o-1:o,_=function(b){var S=l[b],A,T=function(){return A===void 0&&(A=n(S,b)),A};if(b===0){var L=s*(S.coordinate-s*T()/2-c);l[b]=S=Kf(Kf({},S),{},{tickCoord:L<0?S.coordinate-L*s:S.coordinate})}else l[b]=S=Kf(Kf({},S),{},{tickCoord:S.coordinate});var D=Mge(s,S.tickCoord,T,c,d);D&&(c=S.tickCoord+s*(T()/2+a),l[b]=Kf(Kf({},S),{},{isShow:!0}))},v=0;v=2?Qx(a[1].coordinate-a[0].coordinate):1,j=A$s(i,v,f);return c==="equidistantPreserveStart"?I$s(v,j,_,a,l):(c==="preserveStart"||c==="preserveStartEnd"?p=O$s(v,j,_,a,l,c==="preserveStartEnd"):p=R$s(v,j,_,a,l),p.filter(function(b){return b.isShow}))}var F$s=["viewBox"],z$s=["viewBox"],B$s=["ticks"];function sD(s){"@babel/helpers - typeof";return sD=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},sD(s)}function OP(){return OP=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 $$s(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 U$s(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function ZYe(s,t){for(var n=0;n0?c(this.props):c(f)),l<=0||o<=0||!g||!g.length?null:St.createElement(Kl,{className:So("recharts-cartesian-axis",d),ref:function(v){r.layerReference=v}},i&&this.renderAxisLine(),this.renderTicks(g,this.state.fontSize,this.state.letterSpacing),kp.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(r,a,i){var l,o=So(a.className,"recharts-cartesian-axis-tick-value");return St.isValidElement(r)?l=St.cloneElement(r,Sm(Sm({},a),{},{className:o})):ho(r)?l=r(Sm(Sm({},a),{},{className:o})):l=St.createElement(MM,OP({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(N.Component);lLe(vR,"displayName","CartesianAxis");lLe(vR,"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 Y$s=["x1","y1","x2","y2","key"],Z$s=["offset"];function LM(s){"@babel/helpers - typeof";return LM=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},LM(s)}function QYe(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 Xf(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function eUs(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 tUs=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 St.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:n,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function s_t(s,t){var n;if(St.isValidElement(s))n=St.cloneElement(s,t);else if(ho(s))n=s(t);else{var r=t.x1,a=t.y1,i=t.x2,l=t.y2,o=t.key,c=XYe(t,Y$s),d=Wi(c,!1);d.offset;var u=XYe(d,Z$s);n=St.createElement("line",rA({},u,{x1:r,y1:a,x2:i,y2:l,fill:"none",key:o}))}return n}function sUs(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=Xf(Xf({},s),{},{x1:t,y1:o,x2:t+n,y2:o,key:"line-".concat(c),index:c});return s_t(a,d)});return St.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function nUs(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=Xf(Xf({},s),{},{x1:o,y1:t,x2:o,y2:t+n,key:"line-".concat(c),index:c});return s_t(a,d)});return St.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function rUs(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(p){return Math.round(p+a-a)}).sort(function(p,f){return p-f});a!==u[0]&&u.unshift(0);var h=u.map(function(p,f){var g=!u[f+1],_=g?a+l-p:u[f+1]-p;if(_<=0)return null;var v=f%t.length;return St.createElement("rect",{key:"react-".concat(f),y:p,x:r,height:_,width:i,stroke:"none",fill:t[v],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return St.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},h)}function aUs(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(p){return Math.round(p+i-i)}).sort(function(p,f){return p-f});i!==u[0]&&u.unshift(0);var h=u.map(function(p,f){var g=!u[f+1],_=g?i+o-p:u[f+1]-p;if(_<=0)return null;var v=f%r.length;return St.createElement("rect",{key:"react-".concat(f),x:p,y:l,width:_,height:c,stroke:"none",fill:r[v],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return St.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},h)}var iUs=function(t,n){var r=t.xAxis,a=t.width,i=t.height,l=t.offset;return Q1t(oLe(Xf(Xf(Xf({},vR.defaultProps),r),{},{ticks:U2(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,n)},oUs=function(t,n){var r=t.yAxis,a=t.width,i=t.height,l=t.offset;return Q1t(oLe(Xf(Xf(Xf({},vR.defaultProps),r),{},{ticks:U2(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,n)},RI={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function cLe(s){var t,n,r,a,i,l,o=nLe(),c=rLe(),d=KBs(),u=Xf(Xf({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:RI.stroke,fill:(n=s.fill)!==null&&n!==void 0?n:RI.fill,horizontal:(r=s.horizontal)!==null&&r!==void 0?r:RI.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:RI.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:RI.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:RI.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,p=u.y,f=u.width,g=u.height,_=u.syncWithTicks,v=u.horizontalValues,j=u.verticalValues,b=HBs(),S=GBs();if(!la(f)||f<=0||!la(g)||g<=0||!la(h)||h!==+h||!la(p)||p!==+p)return null;var A=u.verticalCoordinatesGenerator||iUs,T=u.horizontalCoordinatesGenerator||oUs,L=u.horizontalPoints,D=u.verticalPoints;if((!L||!L.length)&&ho(T)){var M=v&&v.length,F=T({yAxis:S?Xf(Xf({},S),{},{ticks:M?v:S.ticks}):void 0,width:o,height:c,offset:d},M?!0:_);Nb(Array.isArray(F),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(LM(F),"]")),Array.isArray(F)&&(L=F)}if((!D||!D.length)&&ho(A)){var z=j&&j.length,V=A({xAxis:b?Xf(Xf({},b),{},{ticks:z?j:b.ticks}):void 0,width:o,height:c,offset:d},z?!0:_);Nb(Array.isArray(V),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(LM(V),"]")),Array.isArray(V)&&(D=V)}return St.createElement("g",{className:"recharts-cartesian-grid"},St.createElement(tUs,{fill:u.fill,fillOpacity:u.fillOpacity,x:u.x,y:u.y,width:u.width,height:u.height,ry:u.ry}),St.createElement(sUs,rA({},u,{offset:d,horizontalPoints:L,xAxis:b,yAxis:S})),St.createElement(nUs,rA({},u,{offset:d,verticalPoints:D,xAxis:b,yAxis:S})),St.createElement(rUs,rA({},u,{horizontalPoints:L})),St.createElement(aUs,rA({},u,{verticalPoints:D})))}cLe.displayName="CartesianGrid";var lUs=["type","layout","connectNulls","ref"],cUs=["key"];function nD(s){"@babel/helpers - typeof";return nD=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},nD(s)}function JYe(s,t){if(s==null)return{};var n=dUs(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 dUs(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 Cz(){return Cz=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);nh){f=[].concat(OI(c.slice(0,g)),[h-_]);break}var v=f.length%2===0?[0,p]:[p];return[].concat(OI(t.repeat(c,u)),OI(f),v).map(function(j){return"".concat(j,"px")}).join(", ")}),X1(n,"id",dR("recharts-line-")),X1(n,"pathRef",function(l){n.mainCurve=l}),X1(n,"handleAnimationEnd",function(){n.setState({isAnimationFinished:!0}),n.props.onAnimationEnd&&n.props.onAnimationEnd()}),X1(n,"handleAnimationStart",function(){n.setState({isAnimationFinished:!1}),n.props.onAnimationStart&&n.props.onAnimationStart()}),n}return bUs(t,s),xUs(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=fy(u,zU);if(!h)return null;var p=function(_,v){return{x:_.x,y:_.y,value:_.value,errorVal:Fm(_.payload,v)}},f={clipPath:r?"url(#clipPath-".concat(a,")"):null};return St.createElement(Kl,f,h.map(function(g){return St.cloneElement(g,{key:"bar-".concat(g.props.dataKey),data:l,xAxis:o,yAxis:c,layout:d,dataPointFormatter:p})}))}},{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=Wi(this.props,!1),p=Wi(c,!0),f=d.map(function(_,v){var j=R0(R0(R0({key:"dot-".concat(v),r:3},h),p),{},{index:v,cx:_.x,cy:_.y,value:_.value,dataKey:u,payload:_.payload,points:d});return t.renderDotItem(c,j)}),g={clipPath:r?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return St.createElement(Kl,Cz({className:"recharts-line-dots",key:"dots"},g),f)}},{key:"renderCurveStatically",value:function(r,a,i,l){var o=this.props,c=o.type,d=o.layout,u=o.connectNulls;o.ref;var h=JYe(o,lUs),p=R0(R0(R0({},Wi(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 St.createElement(mge,Cz({},p,{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,p=l.animationEasing,f=l.animationId,g=l.animateNewValues,_=l.width,v=l.height,j=this.state,b=j.prevPoints,S=j.totalLength;return St.createElement(Ow,{begin:u,duration:h,isActive:d,easing:p,from:{t:0},to:{t:1},key:"line-".concat(f),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(A){var T=A.t;if(b){var L=b.length/o.length,D=o.map(function(W,Y){var K=Math.floor(Y*L);if(b[K]){var J=b[K],ne=K0(J.x,W.x),ie=K0(J.y,W.y);return R0(R0({},W),{},{x:ne(T),y:ie(T)})}if(g){var he=K0(_*2,W.x),ce=K0(v/2,W.y);return R0(R0({},W),{},{x:he(T),y:ce(T)})}return R0(R0({},W),{},{x:W.x,y:W.y})});return i.renderCurveStatically(D,r,a)}var M=K0(0,S),F=M(T),z;if(c){var V="".concat(c).split(/[,\s]+/gim).map(function(W){return parseFloat(W)});z=i.getStrokeDasharray(F,S,V)}else z=i.generateSimpleStrokeDasharray(S,F);return i.renderCurveStatically(o,r,a,{strokeDasharray:z})})}},{key:"renderCurve",value:function(r,a){var i=this.props,l=i.points,o=i.isAnimationActive,c=this.state,d=c.prevPoints,u=c.totalLength;return o&&l&&l.length&&(!d&&u>0||!FU(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,p=a.left,f=a.width,g=a.height,_=a.isAnimationActive,v=a.id;if(i||!o||!o.length)return null;var j=this.state.isAnimationFinished,b=o.length===1,S=So("recharts-line",c),A=d&&d.allowDataOverflow,T=u&&u.allowDataOverflow,L=A||T,D=No(v)?this.id:v,M=(r=Wi(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},F=M.r,z=F===void 0?3:F,V=M.strokeWidth,W=V===void 0?2:V,Y=eSs(l)?l:{},K=Y.clipDot,J=K===void 0?!0:K,ne=z*2+W;return St.createElement(Kl,{className:S},A||T?St.createElement("defs",null,St.createElement("clipPath",{id:"clipPath-".concat(D)},St.createElement("rect",{x:A?p:p-f/2,y:T?h:h-g/2,width:A?f:f*2,height:T?g:g*2})),!J&&St.createElement("clipPath",{id:"clipPath-dots-".concat(D)},St.createElement("rect",{x:p-ne/2,y:h-ne/2,width:f+ne,height:g+ne}))):null,!b&&this.renderCurve(L,D),this.renderErrorBar(L,D),(b||l)&&this.renderDots(L,J,D),(!_||j)&&rN.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(OI(r),[0]):r,l=[],o=0;os.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function cqs(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 dqs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function uqs(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 y_t(s){return s==="number"?[0,"auto"]:void 0}var Q5e=function(t,n,r,a){var i=t.graphicalItems,l=t.tooltipAxis,o=S1e(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 p;if(l.dataKey&&!l.allowDuplicatedCategory){var f=h===void 0?o:h;p=Rxe(f,l.dataKey,a)}else p=h&&h[r]||o[r];return p?[].concat(oD(c),[sbt(d,p)]):c},[])},oZe=function(t,n,r,a){var i=a||{x:t.chartX,y:t.chartY},l=jqs(i,r),o=t.orderedTooltipTicks,c=t.tooltipAxis,d=t.tooltipTicks,u=tRs(l,o,d,c);if(u>=0&&d){var h=d[u]&&d[u].value,p=Q5e(t,n,u,h),f=Nqs(r,o,u,i);return{activeTooltipIndex:u,activeLabel:h,activePayload:p,activeCoordinate:f}}return null},kqs=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,p=t.stackOffset,f=Z1t(u,i);return r.reduce(function(g,_){var v,j=_.type.defaultProps!==void 0?lr(lr({},_.type.defaultProps),_.props):_.props,b=j.type,S=j.dataKey,A=j.allowDataOverflow,T=j.allowDuplicatedCategory,L=j.scale,D=j.ticks,M=j.includeHidden,F=j[l];if(g[F])return g;var z=S1e(t.data,{graphicalItems:a.filter(function(ve){var ge,Te=l in ve.props?ve.props[l]:(ge=ve.type.defaultProps)===null||ge===void 0?void 0:ge[l];return Te===F}),dataStartIndex:c,dataEndIndex:d}),V=z.length,W,Y,K;QUs(j.domain,A,b)&&(W=u5e(j.domain,null,A),f&&(b==="number"||L!=="auto")&&(K=jz(z,S,"category")));var J=y_t(b);if(!W||W.length===0){var ne,ie=(ne=j.domain)!==null&&ne!==void 0?ne:J;if(S){if(W=jz(z,S,b),b==="category"&&f){var he=Vks(W);T&&he?(Y=W,W=jge(0,V)):T||(W=EKe(ie,W,_).reduce(function(ve,ge){return ve.indexOf(ge)>=0?ve:[].concat(oD(ve),[ge])},[]))}else if(b==="category")T?W=W.filter(function(ve){return ve!==""&&!No(ve)}):W=EKe(ie,W,_).reduce(function(ve,ge){return ve.indexOf(ge)>=0||ge===""||No(ge)?ve:[].concat(oD(ve),[ge])},[]);else if(b==="number"){var ce=iRs(z,a.filter(function(ve){var ge,Te,Me=l in ve.props?ve.props[l]:(ge=ve.type.defaultProps)===null||ge===void 0?void 0:ge[l],Ce="hide"in ve.props?ve.props.hide:(Te=ve.type.defaultProps)===null||Te===void 0?void 0:Te.hide;return Me===F&&(M||!Ce)}),S,i,u);ce&&(W=ce)}f&&(b==="number"||L!=="auto")&&(K=jz(z,S,"category"))}else f?W=jge(0,V):o&&o[F]&&o[F].hasStack&&b==="number"?W=p==="expand"?[0,1]:tbt(o[F].stackGroups,c,d):W=Y1t(z,a.filter(function(ve){var ge=l in ve.props?ve.props[l]:ve.type.defaultProps[l],Te="hide"in ve.props?ve.props.hide:ve.type.defaultProps.hide;return ge===F&&(M||!Te)}),b,u,!0);if(b==="number")W=K5e(h,W,F,i,D),ie&&(W=u5e(ie,W,A));else if(b==="category"&&ie){var pe=ie,le=W.every(function(ve){return pe.indexOf(ve)>=0});le&&(W=pe)}}return lr(lr({},g),{},eo({},F,lr(lr({},j),{},{axisType:i,domain:W,categoricalDomain:K,duplicateDomain:Y,originalDomain:(v=j.domain)!==null&&v!==void 0?v:J,isCategorical:f,layout:u})))},{})},Sqs=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,p=S1e(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:d}),f=p.length,g=Z1t(u,i),_=-1;return r.reduce(function(v,j){var b=j.type.defaultProps!==void 0?lr(lr({},j.type.defaultProps),j.props):j.props,S=b[l],A=y_t("number");if(!v[S]){_++;var T;return g?T=jge(0,f):o&&o[S]&&o[S].hasStack?(T=tbt(o[S].stackGroups,c,d),T=K5e(h,T,S,i)):(T=u5e(A,Y1t(p,r.filter(function(L){var D,M,F=l in L.props?L.props[l]:(D=L.type.defaultProps)===null||D===void 0?void 0:D[l],z="hide"in L.props?L.props.hide:(M=L.type.defaultProps)===null||M===void 0?void 0:M.hide;return F===S&&!z}),"number",u),a.defaultProps.allowDataOverflow),T=K5e(h,T,S,i)),lr(lr({},v),{},eo({},S,lr(lr({axisType:i},a.defaultProps),{},{hide:!0,orientation:py(_qs,"".concat(i,".").concat(_%2),null),domain:T,originalDomain:A,isCategorical:g,layout:u})))}return v},{})},Cqs=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"),p=fy(u,i),f={};return p&&p.length?f=kqs(t,{axes:p,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(f=Sqs(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),f},Tqs=function(t){var n=xS(t),r=U2(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:SPe(r,function(a){return a.coordinate}),tooltipAxis:n,tooltipAxisBandSize:dge(n,r)}},lZe=function(t){var n=t.children,r=t.defaultShowTooltip,a=q0(n,Q8),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}},Eqs=function(t){return!t||!t.length?!1:t.some(function(n){var r=sN(n&&n.type);return r&&r.indexOf("Bar")>=0})},cZe=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"}},Aqs=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,p=r.margin||{},f=q0(h,Q8),g=q0(h,XA),_=Object.keys(c).reduce(function(T,L){var D=c[L],M=D.orientation;return!D.mirror&&!D.hide?lr(lr({},T),{},eo({},M,T[M]+D.width)):T},{left:p.left||0,right:p.right||0}),v=Object.keys(l).reduce(function(T,L){var D=l[L],M=D.orientation;return!D.mirror&&!D.hide?lr(lr({},T),{},eo({},M,py(T,"".concat(M))+D.height)):T},{top:p.top||0,bottom:p.bottom||0}),j=lr(lr({},v),_),b=j.bottom;f&&(j.bottom+=f.props.height||Q8.defaultProps.height),g&&n&&(j=rRs(j,a,r,n));var S=d-j.left-j.right,A=u-j.top-j.bottom;return lr(lr({brushBottom:b},j),{},{width:Math.max(S,0),height:Math.max(A,0)})},Mqs=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},dLe=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,p=function(j,b){var S=b.graphicalItems,A=b.stackGroups,T=b.offset,L=b.updateId,D=b.dataStartIndex,M=b.dataEndIndex,F=j.barSize,z=j.layout,V=j.barGap,W=j.barCategoryGap,Y=j.maxBarSize,K=cZe(z),J=K.numericAxisName,ne=K.cateAxisName,ie=Eqs(S),he=[];return S.forEach(function(ce,pe){var le=S1e(j.data,{graphicalItems:[ce],dataStartIndex:D,dataEndIndex:M}),ve=ce.type.defaultProps!==void 0?lr(lr({},ce.type.defaultProps),ce.props):ce.props,ge=ve.dataKey,Te=ve.maxBarSize,Me=ve["".concat(J,"Id")],Ce=ve["".concat(ne,"Id")],Ae={},De=c.reduce(function(rt,tt){var at=b["".concat(tt.axisType,"Map")],He=ve["".concat(tt.axisType,"Id")];at&&at[He]||tt.axisType==="zAxis"||PM();var dt=at[He];return lr(lr({},rt),{},eo(eo({},tt.axisType,dt),"".concat(tt.axisType,"Ticks"),U2(dt)))},Ae),Ie=De[ne],Fe=De["".concat(ne,"Ticks")],qe=A&&A[Me]&&A[Me].hasStack&&fRs(ce,A[Me].stackGroups),be=sN(ce.type).indexOf("Bar")>=0,Ze=dge(Ie,Fe),Ne=[],it=ie&&sRs({barSize:F,stackGroups:A,totalSize:Mqs(De,ne)});if(be){var je,Ge,Be=No(Te)?Y:Te,Ye=(je=(Ge=dge(Ie,Fe,!0))!==null&&Ge!==void 0?Ge:Be)!==null&&je!==void 0?je:0;Ne=nRs({barGap:V,barCategoryGap:W,bandSize:Ye!==Ze?Ye:Ze,sizeList:it[Ce],maxBarSize:Be}),Ye!==Ze&&(Ne=Ne.map(function(rt){return lr(lr({},rt),{},{position:lr(lr({},rt.position),{},{offset:rt.position.offset-Ye/2})})}))}var We=ce&&ce.type&&ce.type.getComposedData;We&&he.push({props:lr(lr({},We(lr(lr({},De),{},{displayedData:le,props:j,dataKey:ge,item:ce,bandSize:Ze,barPosition:Ne,offset:T,stackedData:qe,layout:z,dataStartIndex:D,dataEndIndex:M}))),{},eo(eo(eo({key:ce.key||"item-".concat(pe)},J,De[J]),ne,De[ne]),"animationId",L)),childIndex:nSs(ce,j.children),item:ce})}),he},f=function(j,b){var S=j.props,A=j.dataStartIndex,T=j.dataEndIndex,L=j.updateId;if(!wGe({props:S}))return null;var D=S.children,M=S.layout,F=S.stackOffset,z=S.data,V=S.reverseStackOrder,W=cZe(M),Y=W.numericAxisName,K=W.cateAxisName,J=fy(D,r),ne=mRs(z,J,"".concat(Y,"Id"),"".concat(K,"Id"),F,V),ie=c.reduce(function(ve,ge){var Te="".concat(ge.axisType,"Map");return lr(lr({},ve),{},eo({},Te,Cqs(S,lr(lr({},ge),{},{graphicalItems:J,stackGroups:ge.axisType===Y&&ne,dataStartIndex:A,dataEndIndex:T}))))},{}),he=Aqs(lr(lr({},ie),{},{props:S,graphicalItems:J}),b==null?void 0:b.legendBBox);Object.keys(ie).forEach(function(ve){ie[ve]=u(S,ie[ve],he,ve.replace("Map",""),n)});var ce=ie["".concat(K,"Map")],pe=Tqs(ce),le=p(S,lr(lr({},ie),{},{dataStartIndex:A,dataEndIndex:T,updateId:L,graphicalItems:J,stackGroups:ne,offset:he}));return lr(lr({formattedGraphicalItems:le,graphicalItems:J,offset:he,stackGroups:ne},pe),ie)},g=function(v){function j(b){var S,A,T;return dqs(this,j),T=mqs(this,j,[b]),eo(T,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),eo(T,"accessibilityManager",new ZUs),eo(T,"handleLegendBBoxUpdate",function(L){if(L){var D=T.state,M=D.dataStartIndex,F=D.dataEndIndex,z=D.updateId;T.setState(lr({legendBBox:L},f({props:T.props,dataStartIndex:M,dataEndIndex:F,updateId:z},lr(lr({},T.state),{},{legendBBox:L}))))}}),eo(T,"handleReceiveSyncEvent",function(L,D,M){if(T.props.syncId===L){if(M===T.eventEmitterSymbol&&typeof T.props.syncMethod!="function")return;T.applySyncEvent(D)}}),eo(T,"handleBrushChange",function(L){var D=L.startIndex,M=L.endIndex;if(D!==T.state.dataStartIndex||M!==T.state.dataEndIndex){var F=T.state.updateId;T.setState(function(){return lr({dataStartIndex:D,dataEndIndex:M},f({props:T.props,dataStartIndex:D,dataEndIndex:M,updateId:F},T.state))}),T.triggerSyncEvent({dataStartIndex:D,dataEndIndex:M})}}),eo(T,"handleMouseEnter",function(L){var D=T.getMouseInfo(L);if(D){var M=lr(lr({},D),{},{isTooltipActive:!0});T.setState(M),T.triggerSyncEvent(M);var F=T.props.onMouseEnter;ho(F)&&F(M,L)}}),eo(T,"triggeredAfterMouseMove",function(L){var D=T.getMouseInfo(L),M=D?lr(lr({},D),{},{isTooltipActive:!0}):{isTooltipActive:!1};T.setState(M),T.triggerSyncEvent(M);var F=T.props.onMouseMove;ho(F)&&F(M,L)}),eo(T,"handleItemMouseEnter",function(L){T.setState(function(){return{isTooltipActive:!0,activeItem:L,activePayload:L.tooltipPayload,activeCoordinate:L.tooltipPosition||{x:L.cx,y:L.cy}}})}),eo(T,"handleItemMouseLeave",function(){T.setState(function(){return{isTooltipActive:!1}})}),eo(T,"handleMouseMove",function(L){L.persist(),T.throttleTriggeredAfterMouseMove(L)}),eo(T,"handleMouseLeave",function(L){T.throttleTriggeredAfterMouseMove.cancel();var D={isTooltipActive:!1};T.setState(D),T.triggerSyncEvent(D);var M=T.props.onMouseLeave;ho(M)&&M(D,L)}),eo(T,"handleOuterEvent",function(L){var D=sSs(L),M=py(T.props,"".concat(D));if(D&&ho(M)){var F,z;/.*touch.*/i.test(D)?z=T.getMouseInfo(L.changedTouches[0]):z=T.getMouseInfo(L),M((F=z)!==null&&F!==void 0?F:{},L)}}),eo(T,"handleClick",function(L){var D=T.getMouseInfo(L);if(D){var M=lr(lr({},D),{},{isTooltipActive:!0});T.setState(M),T.triggerSyncEvent(M);var F=T.props.onClick;ho(F)&&F(M,L)}}),eo(T,"handleMouseDown",function(L){var D=T.props.onMouseDown;if(ho(D)){var M=T.getMouseInfo(L);D(M,L)}}),eo(T,"handleMouseUp",function(L){var D=T.props.onMouseUp;if(ho(D)){var M=T.getMouseInfo(L);D(M,L)}}),eo(T,"handleTouchMove",function(L){L.changedTouches!=null&&L.changedTouches.length>0&&T.throttleTriggeredAfterMouseMove(L.changedTouches[0])}),eo(T,"handleTouchStart",function(L){L.changedTouches!=null&&L.changedTouches.length>0&&T.handleMouseDown(L.changedTouches[0])}),eo(T,"handleTouchEnd",function(L){L.changedTouches!=null&&L.changedTouches.length>0&&T.handleMouseUp(L.changedTouches[0])}),eo(T,"handleDoubleClick",function(L){var D=T.props.onDoubleClick;if(ho(D)){var M=T.getMouseInfo(L);D(M,L)}}),eo(T,"handleContextMenu",function(L){var D=T.props.onContextMenu;if(ho(D)){var M=T.getMouseInfo(L);D(M,L)}}),eo(T,"triggerSyncEvent",function(L){T.props.syncId!==void 0&&gNe.emit(yNe,T.props.syncId,L,T.eventEmitterSymbol)}),eo(T,"applySyncEvent",function(L){var D=T.props,M=D.layout,F=D.syncMethod,z=T.state.updateId,V=L.dataStartIndex,W=L.dataEndIndex;if(L.dataStartIndex!==void 0||L.dataEndIndex!==void 0)T.setState(lr({dataStartIndex:V,dataEndIndex:W},f({props:T.props,dataStartIndex:V,dataEndIndex:W,updateId:z},T.state)));else if(L.activeTooltipIndex!==void 0){var Y=L.chartX,K=L.chartY,J=L.activeTooltipIndex,ne=T.state,ie=ne.offset,he=ne.tooltipTicks;if(!ie)return;if(typeof F=="function")J=F(he,L);else if(F==="value"){J=-1;for(var ce=0;ce=0){var qe,be;if(Y.dataKey&&!Y.allowDuplicatedCategory){var Ze=typeof Y.dataKey=="function"?Fe:"payload.".concat(Y.dataKey.toString());qe=Rxe(ce,Ze,J),be=pe&&le&&Rxe(le,Ze,J)}else qe=ce==null?void 0:ce[K],be=pe&&le&&le[K];if(Ce||Me){var Ne=L.props.activeIndex!==void 0?L.props.activeIndex:K;return[N.cloneElement(L,lr(lr(lr({},F.props),De),{},{activeIndex:Ne})),null,null]}if(!No(qe))return[Ie].concat(oD(T.renderActivePoints({item:F,activePoint:qe,basePoint:be,childIndex:K,isRange:pe})))}else{var it,je=(it=T.getItemByXY(T.state.activeCoordinate))!==null&&it!==void 0?it:{graphicalItem:Ie},Ge=je.graphicalItem,Be=Ge.item,Ye=Be===void 0?L:Be,We=Ge.childIndex,rt=lr(lr(lr({},F.props),De),{},{activeIndex:We});return[N.cloneElement(Ye,rt),null,null]}return pe?[Ie,null,null]:[Ie,null]}),eo(T,"renderCustomized",function(L,D,M){return N.cloneElement(L,lr(lr({key:"recharts-customized-".concat(M)},T.props),T.state))}),eo(T,"renderMap",{CartesianGrid:{handler:dG,once:!0},ReferenceArea:{handler:T.renderReferenceElement},ReferenceLine:{handler:dG},ReferenceDot:{handler:T.renderReferenceElement},XAxis:{handler:dG},YAxis:{handler:dG},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((S=b.id)!==null&&S!==void 0?S:dR("recharts"),"-clip"),T.throttleTriggeredAfterMouseMove=Gvt(T.triggeredAfterMouseMove,(A=b.throttleDelay)!==null&&A!==void 0?A:1e3/60),T.state={},T}return xqs(j,v),hqs(j,[{key:"componentDidMount",value:function(){var S,A;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(S=this.props.margin.left)!==null&&S!==void 0?S:0,top:(A=this.props.margin.top)!==null&&A!==void 0?A:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var S=this.props,A=S.children,T=S.data,L=S.height,D=S.layout,M=q0(A,Np);if(M){var F=M.props.defaultIndex;if(!(typeof F!="number"||F<0||F>this.state.tooltipTicks.length-1)){var z=this.state.tooltipTicks[F]&&this.state.tooltipTicks[F].value,V=Q5e(this.state,T,F,z),W=this.state.tooltipTicks[F].coordinate,Y=(this.state.offset.top+L)/2,K=D==="horizontal",J=K?{x:W,y:Y}:{y:W,x:Y},ne=this.state.formattedGraphicalItems.find(function(he){var ce=he.item;return ce.type.name==="Scatter"});ne&&(J=lr(lr({},J),ne.props.points[F].tooltipPosition),V=ne.props.points[F].tooltipPayload);var ie={activeTooltipIndex:F,isTooltipActive:!0,activeLabel:z,activePayload:V,activeCoordinate:J};this.setState(ie),this.renderCursor(M),this.accessibilityManager.setIndex(F)}}}},{key:"getSnapshotBeforeUpdate",value:function(S,A){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==A.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==S.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==S.margin){var T,L;this.accessibilityManager.setDetails({offset:{left:(T=this.props.margin.left)!==null&&T!==void 0?T:0,top:(L=this.props.margin.top)!==null&&L!==void 0?L:0}})}return null}},{key:"componentDidUpdate",value:function(S){S3e([q0(S.children,Np)],[q0(this.props.children,Np)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var S=q0(this.props.children,Np);if(S&&typeof S.props.shared=="boolean"){var A=S.props.shared?"axis":"item";return o.indexOf(A)>=0?A:i}return i}},{key:"getMouseInfo",value:function(S){if(!this.container)return null;var A=this.container,T=A.getBoundingClientRect(),L=EIs(T),D={chartX:Math.round(S.pageX-L.left),chartY:Math.round(S.pageY-L.top)},M=T.width/A.offsetWidth||1,F=this.inRange(D.chartX,D.chartY,M);if(!F)return null;var z=this.state,V=z.xAxisMap,W=z.yAxisMap,Y=this.getTooltipEventType(),K=oZe(this.state,this.props.data,this.props.layout,F);if(Y!=="axis"&&V&&W){var J=xS(V).scale,ne=xS(W).scale,ie=J&&J.invert?J.invert(D.chartX):null,he=ne&&ne.invert?ne.invert(D.chartY):null;return lr(lr({},D),{},{xValue:ie,yValue:he},K)}return K?lr(lr({},D),K):null}},{key:"inRange",value:function(S,A){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,L=this.props.layout,D=S/T,M=A/T;if(L==="horizontal"||L==="vertical"){var F=this.state.offset,z=D>=F.left&&D<=F.left+F.width&&M>=F.top&&M<=F.top+F.height;return z?{x:D,y:M}:null}var V=this.state,W=V.angleAxisMap,Y=V.radiusAxisMap;if(W&&Y){var K=xS(W);return IKe({x:D,y:M},K)}return null}},{key:"parseEventsOfWrapper",value:function(){var S=this.props.children,A=this.getTooltipEventType(),T=q0(S,Np),L={};T&&A==="axis"&&(T.props.trigger==="click"?L={onClick:this.handleClick}:L={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 D=Oxe(this.props,this.handleOuterEvent);return lr(lr({},D),L)}},{key:"addListener",value:function(){gNe.on(yNe,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){gNe.removeListener(yNe,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(S,A,T){for(var L=this.state.formattedGraphicalItems,D=0,M=L.length;D{const{data:b,error:S}=await q.from("email_campaigns").select("*").eq("status","sent").order("sent_at",{ascending:!0});if(S)throw S;return b}}),{data:r}=ct({queryKey:["campaign-agent-profiles"],queryFn:async()=>{const{data:b,error:S}=await q.from("profiles").select("id, name, email");if(S)throw S;return b}});if(n)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading analytics..."});const a=t||[],i=new Map((r||[]).map(b=>[b.id,b])),l=a.reduce((b,S)=>b+(S.sent_count||0),0),o=a.reduce((b,S)=>b+(S.open_count||0),0),c=a.reduce((b,S)=>b+(S.click_count||0),0),d=a.reduce((b,S)=>b+(S.bounce_count||0),0),u=a.reduce((b,S)=>b+(S.complaint_count||0),0),h=l>0?(o/l*100).toFixed(1):"0.0",p=l>0?(c/l*100).toFixed(1):"0.0",f=[{label:"Campaigns Sent",value:a.length,icon:cr,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:Nn,color:"text-green-600"},{label:"Avg Open Rate",value:`${h}%`,icon:Er,color:"text-blue-600"},{label:"Avg Click Rate",value:`${p}%`,icon:Om,color:"text-purple-600"},{label:"Total Bounces",value:d,icon:$l,color:"text-orange-600"},{label:"Complaints",value:u,icon:mo,color:"text-destructive"}],g=new Map;a.forEach(b=>{var T,L;const S=b.user_id,A=g.get(S)||{name:((T=i.get(S))==null?void 0:T.name)||((L=i.get(S))==null?void 0:L.email)||"Unknown",campaigns:0,sent:0,opens:0,clicks:0};A.campaigns++,A.sent+=b.sent_count||0,A.opens+=b.open_count||0,A.clicks+=b.click_count||0,g.set(S,A)});const _=[...g.entries()].map(([b,S])=>({id:b,...S,openRate:S.sent>0?+(S.opens/S.sent*100).toFixed(1):0})).sort((b,S)=>S.sent-b.sent),v=_.slice(0,6).map(b=>({name:b.name,value:b.sent})),j=a.map(b=>{var S;return{name:b.name.length>20?b.name.slice(0,20)+"…":b.name,agent:((S=i.get(b.user_id))==null?void 0:S.name)||"Unknown",openRate:b.sent_count>0?+(b.open_count/b.sent_count*100).toFixed(1):0,clickRate:b.sent_count>0?+(b.click_count/b.sent_count*100).toFixed(1):0,sent:b.sent_count,date:b.sent_at?Ss(new Date(b.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(cr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No campaigns sent yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Campaign analytics will appear here after the first send."})]})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:f.map(b=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 text-center",children:[e.jsx(b.icon,{className:`h-5 w-5 mx-auto mb-1 ${b.color}`}),e.jsx("p",{className:"text-2xl font-bold",children:b.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b.label})]})},b.label))}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(Ee,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(kw,{width:"100%",height:"100%",children:e.jsxs(hLe,{data:j,children:[e.jsx(zw,{dataKey:"date",fontSize:11}),e.jsx(Bw,{fontSize:11,unit:"%"}),e.jsx(Np,{formatter:b=>`${b}%`}),e.jsx(Fw,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(Fw,{dataKey:"clickRate",fill:"hsl(270, 70%, 50%)",name:"Click Rate",radius:[2,2,0,0]})]})})})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Send Volume by Agent"})}),e.jsx(Ee,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(kw,{width:"100%",height:"100%",children:e.jsxs(mLe,{children:[e.jsx(zb,{data:v,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:b,percent:S})=>`${b} (${(S*100).toFixed(0)}%)`,fontSize:11,children:v.map((b,S)=>e.jsx(pR,{fill:dZe[S%dZe.length]},S))}),e.jsx(Np,{})]})})})})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(Ee,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(kw,{width:"100%",height:"100%",children:e.jsxs(uLe,{data:j,children:[e.jsx(zw,{dataKey:"date",fontSize:11}),e.jsx(Bw,{fontSize:11}),e.jsx(Np,{}),e.jsx(r6,{type:"monotone",dataKey:"sent",stroke:"hsl(142, 71%, 45%)",strokeWidth:2,name:"Emails Sent",dot:{r:4}})]})})})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Agent Performance"})}),e.jsx(Ee,{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:_.map(b=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2.5 font-medium",children:b.name}),e.jsx("td",{className:"py-2.5 text-center",children:b.campaigns}),e.jsx("td",{className:"py-2.5 text-center",children:b.sent}),e.jsx("td",{className:"py-2.5 text-center",children:b.opens}),e.jsx("td",{className:"py-2.5 text-center",children:b.clicks}),e.jsx("td",{className:"py-2.5 text-center",children:e.jsxs(ze,{variant:"outline",children:[b.openRate,"%"]})})]},b.id))})]})})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Campaign Leaderboard"})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-2",children:[...a].sort((b,S)=>{const A=b.sent_count>0?b.open_count/b.sent_count:0;return(S.sent_count>0?S.open_count/S.sent_count:0)-A}).slice(0,10).map((b,S)=>{const A=b.sent_count>0?(b.open_count/b.sent_count*100).toFixed(1):"0.0",T=b.sent_count>0?(b.click_count/b.sent_count*100).toFixed(1):"0.0",L=i.get(b.user_id);return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted/30 cursor-pointer",onClick:()=>s(`/admin/email-campaigns/${b.id}`),children:[e.jsxs("span",{className:"text-lg font-bold text-muted-foreground w-6",children:["#",S+1]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:b.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(L==null?void 0:L.name)||"Unknown"," · ",b.sent_at?Ss(new Date(b.sent_at),"MMM d, yyyy"):""," · ",b.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Er,{className:"h-3 w-3"})," ",A,"%"]}),e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Om,{className:"h-3 w-3"})," ",T,"%"]})]})]},b.id)})})})]})]})})}const Pqs=()=>{const{toast:s}=Ba(),[t,n]=N.useState(!0),[r,a]=N.useState([]),[i,l]=N.useState([]),[o,c]=N.useState({installs:0,activeAgents:0,impressions30d:0,leads30d:0});N.useEffect(()=>{d()},[]);const d=async()=>{try{n(!0);const u=new Date;u.setDate(u.getDate()-30);const h=u.toISOString(),{data:p}=await q.from("website_apps").select("slug, name").order("sort_order"),f=[];let g=0;for(;;){const{data:T,error:L}=await q.from("agent_website_app_installs").select("user_id, app_slug, enabled").range(g,g+999);if(L)throw L;if(f.push(...T||[]),!T||T.length<1e3)break;g+=1e3}const _=[];for(g=0;;){const{data:T,error:L}=await q.from("widget_events").select("user_id, app_slug, event_type, created_at").gte("created_at",h).order("created_at",{ascending:!1}).range(g,g+999);if(L)throw L;if(_.push(...T||[]),!T||T.length<1e3||(g+=1e3,g>2e4))break}const v=new Map;for(const T of p||[])v.set(T.slug,{app_slug:T.slug,app_name:T.name,installs:0,enabled:0,impressions:0,expands:0,cta_clicks:0,lead_captures:0});for(const T of f){const L=v.get(T.app_slug);L&&(L.installs+=1,T.enabled&&(L.enabled+=1))}for(const T of _){const L=v.get(T.app_slug);L&&(T.event_type==="impression"?L.impressions+=1:T.event_type==="expand"?L.expands+=1:T.event_type==="cta_click"?L.cta_clicks+=1:T.event_type==="lead_capture"&&(L.lead_captures+=1))}const j=new Map;for(const T of f){if(!T.enabled)continue;const L=j.get(T.user_id)||{user_id:T.user_id,name:null,email:null,apps_enabled:[],events_30d:0,leads_30d:0};L.apps_enabled.includes(T.app_slug)||L.apps_enabled.push(T.app_slug),j.set(T.user_id,L)}for(const T of _){const L=j.get(T.user_id);L&&(L.events_30d+=1,T.event_type==="lead_capture"&&(L.leads_30d+=1))}const b=Array.from(j.keys());if(b.length>0){const{data:T}=await q.from("profiles").select("id, name, email").in("id",b);for(const L of T||[]){const D=j.get(L.id);D&&(D.name=L.name,D.email=L.email)}}const S=Array.from(v.values()),A=Array.from(j.values()).sort((T,L)=>L.events_30d-T.events_30d);a(S),l(A),c({installs:S.reduce((T,L)=>T+L.enabled,0),activeAgents:A.length,impressions30d:S.reduce((T,L)=>T+L.impressions,0),leads30d:S.reduce((T,L)=>T+L.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(fe,{children:e.jsx(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Active Installs"}),e.jsx(lc,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Agents Using Apps"}),e.jsx(Nn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Impressions (30d)"}),e.jsx(Er,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Leads Captured (30d)"}),e.jsx(Vs,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"App Performance (last 30 days)"})}),e.jsx(Ee,{children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"App"}),e.jsx(Ct,{className:"text-right",children:"Installs"}),e.jsx(Ct,{className:"text-right",children:"Enabled"}),e.jsx(Ct,{className:"text-right",children:"Impressions"}),e.jsx(Ct,{className:"text-right",children:"Expands"}),e.jsx(Ct,{className:"text-right",children:"CTA Clicks"}),e.jsx(Ct,{className:"text-right",children:"Leads"}),e.jsx(Ct,{className:"text-right",children:"Conv. Rate"})]})}),e.jsxs(ha,{children:[r.map(u=>{const h=u.impressions>0?(u.lead_captures/u.impressions*100).toFixed(1):"—";return e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:u.app_name}),e.jsx(ut,{className:"text-right",children:u.installs}),e.jsx(ut,{className:"text-right",children:u.enabled}),e.jsx(ut,{className:"text-right",children:u.impressions}),e.jsx(ut,{className:"text-right",children:u.expands}),e.jsx(ut,{className:"text-right",children:u.cta_clicks}),e.jsx(ut,{className:"text-right font-semibold",children:u.lead_captures}),e.jsx(ut,{className:"text-right text-muted-foreground",children:h==="—"?"—":`${h}%`})]},u.app_slug)}),r.length===0&&e.jsx(Hs,{children:e.jsx(ut,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data yet"})})]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"Agent Usage (last 30 days)"})}),e.jsxs(Ee,{children:[e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Apps Enabled"}),e.jsx(Ct,{className:"text-right",children:"Events (30d)"}),e.jsx(Ct,{className:"text-right",children:"Leads (30d)"})]})}),e.jsxs(ha,{children:[i.slice(0,100).map(u=>e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:u.name||"—"}),e.jsx(ut,{className:"text-muted-foreground",children:u.email||"—"}),e.jsx(ut,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:u.apps_enabled.map(h=>e.jsx(ze,{variant:"secondary",className:"text-xs",children:h},h))})}),e.jsx(ut,{className:"text-right",children:u.events_30d}),e.jsx(ut,{className:"text-right font-semibold",children:u.leads_30d})]},u.user_id)),i.length===0&&e.jsx(Hs,{children:e.jsx(ut,{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."]})]})]})]})},Lqs=()=>{const[s,t]=N.useState([]),[n,r]=N.useState([]),[a,i]=N.useState({}),[l,o]=N.useState(!0);N.useEffect(()=>{c()},[]);const c=async()=>{o(!0);try{const[{data:h},{data:p}]=await Promise.all([q.rpc("get_extension_usage_summary"),q.from("extension_usage_events").select("id, user_id, action, metadata, created_at").order("created_at",{ascending:!1}).limit(50)]),f=h||[],g=p||[];t(f),r(g);const _=Array.from(new Set(g.map(v=>v.user_id)));if(_.length){const{data:v}=await q.from("profiles").select("id, name, email").in("id",_),j={};(v||[]).forEach(b=>{j[b.id]={name:b.name,email:b.email}}),i(j)}}finally{o(!1)}},d=s.reduce((h,p)=>({users:h.users+1,contacts:h.contacts+Number(p.contacts_saved||0),listings:h.listings+Number(p.listings_imported||0),activities:h.activities+Number(p.activities_logged||0),events:h.events+Number(p.total_events||0)}),{users:0,contacts:0,listings:0,activities:0,events:0});if(l)return e.jsx(fe,{children:e.jsx(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Nn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total Actions"}),e.jsx(NA,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Contacts Saved"}),e.jsx(Fo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.contacts})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Listings Imported"}),e.jsx(Or,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.listings})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Activities Logged"}),e.jsx(Ei,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.activities})})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"Users by Extension Activity"})}),e.jsx(Ee,{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(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"User"}),e.jsx(Ct,{className:"text-right",children:"Total"}),e.jsx(Ct,{className:"text-right",children:"Contacts"}),e.jsx(Ct,{className:"text-right",children:"Listings"}),e.jsx(Ct,{className:"text-right",children:"Activities"}),e.jsx(Ct,{children:"First Used"}),e.jsx(Ct,{children:"Last Used"})]})}),e.jsx(ha,{children:s.map(h=>e.jsxs(Hs,{children:[e.jsxs(ut,{children:[e.jsx("div",{className:"font-medium",children:h.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.email})]}),e.jsx(ut,{className:"text-right font-medium",children:h.total_events}),e.jsx(ut,{className:"text-right",children:h.contacts_saved}),e.jsx(ut,{className:"text-right",children:h.listings_imported}),e.jsx(ut,{className:"text-right",children:h.activities_logged}),e.jsx(ut,{className:"text-xs text-muted-foreground",children:h.first_event_at?Ss(new Date(h.first_event_at),"MMM d, yyyy"):"—"}),e.jsx(ut,{className:"text-xs text-muted-foreground",children:h.last_event_at?Ss(new Date(h.last_event_at),"MMM d, h:mm a"):"—"})]},h.user_id))})]})})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"Recent Activity"})}),e.jsx(Ee,{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 p=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(ze,{variant:"secondary",children:u(h.action)}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:(p==null?void 0:p.name)||(p==null?void 0:p.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:Ss(new Date(h.created_at),"MMM d, h:mm a")})]},h.id)})})})]})]})},Dqs=()=>e.jsx(Ts,{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(Br,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(Fr,{children:[e.jsx(Kt,{value:"analytics",children:"Analytics"}),e.jsx(Kt,{value:"website-apps",children:"Website Apps"}),e.jsx(Kt,{value:"extension",children:"Chrome Extension"}),e.jsx(Kt,{value:"content",children:"Content"}),e.jsx(Kt,{value:"email-campaigns",children:"Email Campaigns"}),e.jsx(Kt,{value:"activity",children:"Activity"}),e.jsx(Kt,{value:"shares",children:"Shares"})]}),e.jsx(is,{value:"analytics",className:"space-y-4",children:e.jsx(ojs,{})}),e.jsx(is,{value:"website-apps",className:"space-y-4",children:e.jsx(Pqs,{})}),e.jsx(is,{value:"extension",className:"space-y-4",children:e.jsx(Lqs,{})}),e.jsx(is,{value:"content",className:"space-y-4",children:e.jsx(cjs,{})}),e.jsx(is,{value:"email-campaigns",className:"space-y-4",children:e.jsx(Iqs,{})}),e.jsx(is,{value:"activity",className:"space-y-4",children:e.jsx(ijs,{})}),e.jsx(is,{value:"shares",className:"space-y-4",children:e.jsx(Myt,{})})]})]})});function Rqs(){const s=Ht(),[t,n]=N.useState(!1),[r,a]=N.useState(null),[i,l]=N.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),[o,c]=N.useState(null),[d,u]=N.useState(""),[h,p]=N.useState([]),[f,g]=N.useState([]),[_,v]=N.useState([]),[j,b]=N.useState(!1),[S,A]=N.useState(null),[T,L]=N.useState(""),{data:D,isLoading:M}=ct({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:be,error:Ze}=await q.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(Ze)throw Ze;return be}}),{data:F}=ct({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:be,error:Ze}=await q.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(Ze)throw Ze;return be}}),{data:z}=ct({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:be,error:Ze}=await q.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(Ze)throw Ze;return be}}),{data:V}=ct({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:be,error:Ze}=await q.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(Ze)throw Ze;return be}}),{data:W,isLoading:Y}=ct({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:be,error:Ze}=await q.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(Ze)throw Ze;return be}}),K=()=>{l({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),c(null),u(""),p([]),g([]),v([]),a(null),L("")},J=be=>{a(be),l({title:be.title,description:be.description||"",publish_date:be.publish_date.split("T")[0],is_published:be.is_published,category_id:be.category_id||""}),u(be.preview_image_url||""),L("");const Ze=(F==null?void 0:F.filter(je=>je.resource_id===be.id))||[];p(Ze.map(je=>({id:je.id,name:je.name,file_url:je.file_url,file_size:je.file_size,sort_order:je.sort_order})));const Ne=(z==null?void 0:z.filter(je=>je.resource_id===be.id))||[];g(Ne.map(je=>({id:je.id,title:je.title,video_url:je.video_url,sort_order:je.sort_order})));const it=(V==null?void 0:V.filter(je=>je.resource_id===be.id))||[];v(it.map(je=>({id:je.id,title:je.title,canva_share_link:je.canva_share_link,sort_order:je.sort_order}))),n(!0)},ne=be=>{var Ne;const Ze=(Ne=be.target.files)==null?void 0:Ne[0];Ze&&(c(Ze),u(URL.createObjectURL(Ze)))},ie=()=>{p([...h,{name:"",file_url:"",sort_order:h.length}])},he=be=>{p(h.filter((Ze,Ne)=>Ne!==be))},ce=(be,Ze,Ne)=>{const it=[...h];if(Ze==="file"&&Ne instanceof File){const je=Ne.name.replace(/\.[^/.]+$/,"");it[be]={...it[be],file:Ne,file_size:Ne.size,name:it[be].name||je}}else it[be]={...it[be],[Ze]:Ne};p(it)},pe=()=>{g([...f,{title:"",video_url:"",sort_order:f.length}])},le=be=>{g(f.filter((Ze,Ne)=>Ne!==be))},ve=(be,Ze,Ne)=>{const it=[...f];Ze==="file"&&Ne instanceof File?it[be]={...it[be],file:Ne}:it[be]={...it[be],[Ze]:Ne},g(it)},ge=()=>{v([..._,{title:"",canva_share_link:"",sort_order:_.length}])},Te=be=>{v(_.filter((Ze,Ne)=>Ne!==be))},Me=(be,Ze,Ne)=>{const it=[..._];it[be]={...it[be],[Ze]:Ne},v(it)},Ce=async(be,Ze)=>{try{const Ne=await q.functions.invoke("bunny-upload",{body:{action:"create",title:be.name}});if(Ne.error)throw Ne.error;const{videoId:it,uploadUrl:je,libraryId:Ge}=Ne.data,Be=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:it,libraryId:Ge}});if(Be.error)throw Be.error;const{uploadUrl:Ye,apiKey:We}=Be.data,rt=new XMLHttpRequest;return rt.open("PUT",Ye,!0),rt.setRequestHeader("AccessKey",We),rt.upload.onprogress=tt=>{if(tt.lengthComputable){const at=Math.round(tt.loaded/tt.total*100),He=[...f];He[Ze]={...He[Ze],uploadProgress:at},g(He)}},await new Promise((tt,at)=>{rt.onload=()=>rt.status>=200&&rt.status<300?tt():at(new Error("Upload failed")),rt.onerror=()=>at(new Error("Upload failed")),rt.send(be)}),`https://iframe.mediadelivery.net/embed/${Ge}/${it}`}catch(Ne){throw console.error("Bunny upload error:",Ne),Ne}},Ae=gt({mutationFn:async be=>{const{data:Ze,error:Ne}=await q.from("brokerage_resource_categories").insert({name:be,sort_order:(W==null?void 0:W.length)||0}).select().single();if(Ne)throw Ne;return Ze},onSuccess:be=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:be.id}),L(""),ae.success("Category created")},onError:be=>{ae.error("Failed to create category: "+be.message)}}),De=gt({mutationFn:async()=>{b(!0);let be=(r==null?void 0:r.preview_image_url)||null;if(o){const it=o.name.split(".").pop(),je=`${Date.now()}.${it}`,{error:Ge}=await q.storage.from("brokerage-resources").upload(`previews/${je}`,o);if(Ge)throw Ge;const{data:Be}=q.storage.from("brokerage-resources").getPublicUrl(`previews/${je}`);be=Be.publicUrl}const Ze={title:i.title,description:i.description||null,preview_image_url:be,publish_date:i.publish_date,is_published:i.is_published,category_id:i.category_id||null};let Ne;if(r){const{error:it}=await q.from("brokerage_resources").update(Ze).eq("id",r.id);if(it)throw it;Ne=r.id;const je=(F==null?void 0:F.filter(dt=>dt.resource_id===r.id).map(dt=>dt.id))||[],Ge=h.filter(dt=>dt.id).map(dt=>dt.id),Be=je.filter(dt=>!Ge.includes(dt));Be.length>0&&await q.from("brokerage_resource_pdfs").delete().in("id",Be);const Ye=(z==null?void 0:z.filter(dt=>dt.resource_id===r.id).map(dt=>dt.id))||[],We=f.filter(dt=>dt.id).map(dt=>dt.id),rt=Ye.filter(dt=>!We.includes(dt));rt.length>0&&await q.from("brokerage_resource_videos").delete().in("id",rt);const tt=(V==null?void 0:V.filter(dt=>dt.resource_id===r.id).map(dt=>dt.id))||[],at=_.filter(dt=>dt.id).map(dt=>dt.id),He=tt.filter(dt=>!at.includes(dt));He.length>0&&await q.from("brokerage_resource_links").delete().in("id",He)}else{const{data:it,error:je}=await q.from("brokerage_resources").insert(Ze).select().single();if(je)throw je;Ne=it.id}for(let it=0;it{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ae.success(r?"Resource updated":"Resource created"),n(!1),K(),b(!1)},onError:be=>{ae.error("Failed to save resource: "+be.message),b(!1)}}),Ie=gt({mutationFn:async be=>{const{error:Ze}=await q.from("brokerage_resources").delete().eq("id",be);if(Ze)throw Ze},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ae.success("Resource deleted")},onError:be=>{ae.error("Failed to delete: "+be.message)}}),Fe=be=>{if(be.preventDefault(),!i.title){ae.error("Please enter a title");return}De.mutate()},qe=be=>{const Ze=(F==null?void 0:F.filter(je=>je.resource_id===be).length)||0,Ne=(z==null?void 0:z.filter(je=>je.resource_id===be).length)||0,it=(V==null?void 0:V.filter(je=>je.resource_id===be).length)||0;return{pdfCount:Ze,videoCount:Ne,linkCount:it}};return e.jsx(Ts,{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(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:(D==null?void 0:D.length)||0})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:(D==null?void 0:D.filter(be=>be.is_published).length)||0})})]})]}),e.jsxs(B,{onClick:()=>{K(),n(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Category"}),e.jsx(Ct,{children:"Content"}),e.jsx(Ct,{children:"Publish Date"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:M?e.jsx(Hs,{children:e.jsx(ut,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(D==null?void 0:D.length)===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No brokerage resources yet. Create your first one!"})}):D==null?void 0:D.map(be=>{const{pdfCount:Ze,videoCount:Ne,linkCount:it}=qe(be.id),je=W==null?void 0:W.find(Ge=>Ge.id===be.category_id);return e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[be.preview_image_url?e.jsx("img",{src:be.preview_image_url,alt:be.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(qm,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:be.title}),be.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:be.description})]})]})}),e.jsx(ut,{children:je?e.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted",children:je.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ut,{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(Nr,{className:"h-3.5 w-3.5"}),Ze]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(br,{className:"h-3.5 w-3.5"}),Ne]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jo,{className:"h-3.5 w-3.5"}),it]})]})}),e.jsx(ut,{children:Ss(new Date(be.publish_date),"MMM d, yyyy")}),e.jsx(ut,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${be.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:be.is_published?"Published":"Draft"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{const Ge=(F==null?void 0:F.filter(We=>We.resource_id===be.id))||[],Be=(z==null?void 0:z.filter(We=>We.resource_id===be.id))||[],Ye=(V==null?void 0:V.filter(We=>We.resource_id===be.id))||[];A({...be,pdfs:Ge,videos:Be,links:Ye})},children:e.jsx(Er,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>J(be),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource?")&&Ie.mutate(be.id)},children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},be.id)})})]})})}),e.jsx(bs,{open:t,onOpenChange:n,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:r?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:Fe,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(qm,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(ye,{type:"file",accept:"image/*",onChange:ne})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",value:i.title,onChange:be=>l({...i,title:be.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(uh,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ds,{value:i.category_id,onValueChange:be=>l({...i,category_id:be}),children:[e.jsx(ls,{className:"flex-1",children:e.jsx(us,{placeholder:"Select a category"})}),e.jsx(cs,{children:W==null?void 0:W.map(be=>e.jsx(Qe,{value:be.id,children:be.name},be.id))})]}),i.category_id&&e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>l({...i,category_id:""}),children:e.jsx(Bn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"Or create new category...",value:T,onChange:be=>L(be.target.value),className:"flex-1"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",disabled:!T.trim()||Ae.isPending,onClick:()=>Ae.mutate(T.trim()),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Lb,{content:i.description,onChange:be=>l({...i,description:be}),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:be=>l({...i,publish_date:be.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(bn,{checked:i.is_published,onCheckedChange:be=>l({...i,is_published:be})}),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(Nr,{className:"h-4 w-4"}),"PDF Documents (",h.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:ie,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),h.map((be,Ze)=>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:be.name,onChange:Ne=>ce(Ze,"name",Ne.target.value),className:"flex-1"}),e.jsx(ye,{type:"file",accept:".pdf",onChange:Ne=>{var je;const it=(je=Ne.target.files)==null?void 0:je[0];it&&ce(Ze,"file",it)},className:"flex-1"}),be.file_url&&!be.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>he(Ze),children:e.jsx(Bn,{className:"h-4 w-4"})})]},Ze))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(br,{className:"h-4 w-4"}),"Videos (",f.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:pe,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),f.map((be,Ze)=>e.jsxs("div",{className:"space-y-2 p-3 border rounded-lg bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{placeholder:"Video Title",value:be.title,onChange:Ne=>ve(Ze,"title",Ne.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>le(Ze),children:e.jsx(Bn,{className:"h-4 w-4"})})]}),e.jsx(ye,{type:"file",accept:"video/*",onChange:Ne=>{var je;const it=(je=Ne.target.files)==null?void 0:je[0];it&&ve(Ze,"file",it)}}),be.uploadProgress!==void 0&&be.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:`${be.uploadProgress}%`}})}),be.video_url&&!be.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Video uploaded"})]},Ze))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(Jo,{className:"h-4 w-4"}),"Canva Links (",_.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:ge,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),_.map((be,Ze)=>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:be.title,onChange:Ne=>Me(Ze,"title",Ne.target.value),className:"flex-1"}),e.jsx(ye,{placeholder:"Canva Share Link",value:be.canva_share_link,onChange:Ne=>Me(Ze,"canva_share_link",Ne.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>Te(Ze),children:e.jsx(Bn,{className:"h-4 w-4"})})]},Ze))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:De.isPending||j,children:De.isPending||j?"Saving...":r?"Update":"Create"})]})]})]})}),e.jsx(bs,{open:!!S,onOpenChange:()=>A(null),children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:S==null?void 0:S.title})}),S&&e.jsxs("div",{className:"space-y-4",children:[S.preview_image_url&&e.jsx("img",{src:S.preview_image_url,alt:S.title,className:"w-full h-48 object-cover rounded-lg"}),S.description&&e.jsx("p",{className:"text-muted-foreground",children:S.description}),S.pdfs&&S.pdfs.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Nr,{className:"h-4 w-4"}),"PDF Documents (",S.pdfs.length,")"]}),e.jsx("div",{className:"space-y-1",children:S.pdfs.map(be=>e.jsx("a",{href:be.file_url,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:be.name},be.id))})]}),S.videos&&S.videos.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(br,{className:"h-4 w-4"}),"Videos (",S.videos.length,")"]}),e.jsx("div",{className:"space-y-2",children:S.videos.map(be=>e.jsx("div",{className:"p-2 border rounded",children:e.jsx("p",{className:"font-medium text-sm",children:be.title})},be.id))})]}),S.links&&S.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Jo,{className:"h-4 w-4"}),"Canva Links (",S.links.length,")"]}),e.jsx("div",{className:"space-y-1",children:S.links.map(be=>e.jsx("a",{href:be.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:be.title},be.id))})]})]})]})})]})})}const v_t=[{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 Oqs(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(null),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[g,_]=N.useState(""),[v,j]=N.useState(""),[b,S]=N.useState(""),[A,T]=N.useState(""),[L,D]=N.useState("Learn More"),[M,F]=N.useState("top"),[z,V]=N.useState(""),[W,Y]=N.useState(!0),[K,J]=N.useState(""),[ne,ie]=N.useState("");N.useEffect(()=>{he()},[]);const he=async()=>{try{const{data:Ae,error:De}=await q.from("dashboard_banners").select("*").order("placement").order("sort_order");if(De)throw De;t(Ae||[])}catch(Ae){ae.error("Failed to load banners: "+Ae.message)}finally{r(!1)}},ce=()=>{_(""),j(""),S(""),T(""),D("Learn More"),F("top"),V(""),Y(!0),J(""),ie(""),d(null)},pe=Ae=>{d(Ae),_(Ae.title),j(Ae.description||""),S(Ae.image_url),T(Ae.link_url||""),D(Ae.link_text||"Learn More"),F(Ae.placement),V(Ae.section_after||""),Y(Ae.is_active),J(Ae.start_date?Ss(new Date(Ae.start_date),"yyyy-MM-dd'T'HH:mm"):""),ie(Ae.end_date?Ss(new Date(Ae.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},le=async Ae=>{var Ie;const De=(Ie=Ae.target.files)==null?void 0:Ie[0];if(De){h(!0);try{const Fe=De.name.split(".").pop(),qe=`${Date.now()}.${Fe}`,{error:be}=await q.storage.from("banner-images").upload(qe,De);if(be)throw be;const{data:{publicUrl:Ze}}=q.storage.from("banner-images").getPublicUrl(qe);S(Ze),ae.success("Image uploaded successfully")}catch(Fe){ae.error("Failed to upload image: "+Fe.message)}finally{h(!1)}}},ve=async()=>{if(!g.trim()||!b){ae.error("Please fill in required fields (title and image)");return}f(!0);try{const Ae={title:g.trim(),description:v.trim()||null,image_url:b,link_url:A.trim()||null,link_text:L.trim()||"Learn More",placement:M,section_after:M==="between"?z:null,is_active:W,start_date:K?new Date(K).toISOString():null,end_date:ne?new Date(ne).toISOString():null};if(c){const{error:De}=await q.from("dashboard_banners").update(Ae).eq("id",c.id);if(De)throw De;ae.success("Banner updated successfully")}else{const De=s.filter(Fe=>Fe.placement===M).length,{error:Ie}=await q.from("dashboard_banners").insert({...Ae,sort_order:De});if(Ie)throw Ie;ae.success("Banner created successfully")}i(!1),ce(),he()}catch(Ae){ae.error("Failed to save banner: "+Ae.message)}finally{f(!1)}},ge=async()=>{if(c)try{const{error:Ae}=await q.from("dashboard_banners").delete().eq("id",c.id);if(Ae)throw Ae;ae.success("Banner deleted successfully"),o(!1),d(null),he()}catch(Ae){ae.error("Failed to delete banner: "+Ae.message)}},Te=async Ae=>{try{const{error:De}=await q.from("dashboard_banners").update({is_active:!Ae.is_active}).eq("id",Ae.id);if(De)throw De;ae.success(Ae.is_active?"Banner deactivated":"Banner activated"),he()}catch(De){ae.error("Failed to update banner: "+De.message)}},Me=s.filter(Ae=>Ae.placement==="top"),Ce=s.filter(Ae=>Ae.placement==="between");return n?e.jsx(Ts,{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(Ts,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(nl,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),e.jsx(Vn,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(bs,{open:a&&M==="top",onOpenChange:Ae=>{Ae||ce(),i(Ae),Ae&&F("top")},children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{onClick:()=>{ce(),F("top")},children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(Qn,{children:"Configure the banner's content and display settings"})]}),e.jsx(uZe,{title:g,setTitle:_,description:v,setDescription:j,imageUrl:b,linkUrl:A,setLinkUrl:T,linkText:L,setLinkText:D,placement:M,setPlacement:F,sectionAfter:z,setSectionAfter:V,isActive:W,setIsActive:Y,startDate:K,setStartDate:J,endDate:ne,setEndDate:ie,handleImageUpload:le,uploading:u,showPlacementOptions:!1}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>{i(!1),ce()},children:"Cancel"}),e.jsx(B,{onClick:ve,disabled:p,children:p?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Ee,{children:Me.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No hero banners yet. Add your first banner above."}):e.jsx("div",{className:"space-y-3",children:Me.map(Ae=>e.jsx(hZe,{banner:Ae,onEdit:()=>pe(Ae),onDelete:()=>{d(Ae),o(!0)},onToggleActive:()=>Te(Ae)},Ae.id))})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(nl,{className:"h-5 w-5"}),"Section Banners"]}),e.jsx(Vn,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(bs,{open:a&&M==="between",onOpenChange:Ae=>{Ae||ce(),i(Ae),Ae&&F("between")},children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{onClick:()=>{ce(),F("between")},children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(Qn,{children:"Configure where this banner appears between sections"})]}),e.jsx(uZe,{title:g,setTitle:_,description:v,setDescription:j,imageUrl:b,linkUrl:A,setLinkUrl:T,linkText:L,setLinkText:D,placement:M,setPlacement:F,sectionAfter:z,setSectionAfter:V,isActive:W,setIsActive:Y,startDate:K,setStartDate:J,endDate:ne,setEndDate:ie,handleImageUpload:le,uploading:u,showPlacementOptions:!0}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>{i(!1),ce()},children:"Cancel"}),e.jsx(B,{onClick:ve,disabled:p,children:p?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Ee,{children:Ce.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:Ce.map(Ae=>e.jsx(hZe,{banner:Ae,onEdit:()=>pe(Ae),onDelete:()=>{d(Ae),o(!0)},onToggleActive:()=>Te(Ae),showSection:!0},Ae.id))})})]})]}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Delete Banner"}),e.jsxs(Qn,{children:['Are you sure you want to delete "',c==null?void 0:c.title,'"? This action cannot be undone.']})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:ge,children:"Delete"})]})]})})]})}function uZe({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:p,isActive:f,setIsActive:g,startDate:_,setStartDate:v,endDate:j,setEndDate:b,handleImageUpload:S,uploading:A,showPlacementOptions:T}){return e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",placeholder:"Banner headline...",value:s,onChange:L=>t(L.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Es,{id:"description",placeholder:"Optional banner description...",value:n,onChange:L=>r(L.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:S,disabled:A,className:"flex-1"}),A&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),a&&e.jsx("div",{className:"mt-2 relative rounded-lg overflow-hidden border",children:e.jsx("img",{src:a,alt:"Preview",className:"w-full h-40 object-cover"})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"linkUrl",children:"Link URL (optional)"}),e.jsx(ye,{id:"linkUrl",placeholder:"https://...",value:i,onChange:L=>l(L.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:L=>c(L.target.value)})]})]}),T&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Placement"}),e.jsxs(ds,{value:h,onValueChange:p,children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select section placement..."})}),e.jsx(cs,{children:v_t.map(L=>e.jsx(Qe,{value:L.value,children:L.label},L.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(yr,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(ye,{id:"startDate",type:"datetime-local",value:_,onChange:L=>v(L.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"endDate",className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(ye,{id:"endDate",type:"datetime-local",value:j,onChange:L=>b(L.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(bn,{id:"isActive",checked:f,onCheckedChange:g}),e.jsx(se,{htmlFor:"isActive",children:"Active"})]})})]})}function hZe({banner:s,onEdit:t,onDelete:n,onToggleActive:r,showSection:a=!1}){var c;const i=(c=v_t.find(d=>d.value===s.section_after))==null?void 0:c.label,[l,o]=N.useState(null);return N.useEffect(()=>{(async()=>{const{count:u}=await q.from("content_engagement_logs").select("*",{count:"exact",head:!0}).eq("resource_id",s.id).eq("action_type","click_link");o(u??0)})()},[s.id]),e.jsxs("div",{className:"flex items-center gap-4 p-3 border rounded-lg bg-card hover:bg-accent/50 transition-colors",children:[e.jsx(Fu,{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(ze,{variant:"secondary",children:"Inactive"}),s.start_date&&new Date(s.start_date)>new Date&&e.jsx(ze,{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(oc,{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(Er,{className:"h-4 w-4"}):e.jsx(xf,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})]})}const uG={open:{label:"Open",icon:gr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Ql,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Ri,color:"bg-green-500"},closed:{label:"Closed",icon:Hc,color:"bg-muted-foreground"}},mZe={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function Fqs(){var M,F;const{user:s}=ys(),t=Ht(),[n,r]=N.useState(null),[a,i]=N.useState(""),[l,o]=N.useState([]),[c,d]=N.useState("all"),[u,h]=N.useState("all"),[p,f]=N.useState(!1),{data:g=[],isLoading:_}=ct({queryKey:["admin-support-tickets",c,u],queryFn:async()=>{let z=q.from("support_tickets").select("*, profiles!support_tickets_user_id_fkey(name, email)").order("created_at",{ascending:!1});c!=="all"&&(z=z.eq("status",c)),u!=="all"&&(z=z.eq("category",u));const{data:V,error:W}=await z;if(W)throw W;return V}}),{data:v=[]}=ct({queryKey:["admin-users-notifications"],queryFn:async()=>{const{data:z,error:V}=await q.from("user_roles").select("user_id").eq("role","admin");if(V)throw V;const W=z.map(he=>he.user_id),{data:Y,error:K}=await q.from("profiles").select("id, name, email").in("id",W);if(K)throw K;const{data:J,error:ne}=await q.from("support_notification_settings").select("user_id, receive_notifications");if(ne)throw ne;const ie=new Map((J==null?void 0:J.map(he=>[he.user_id,he.receive_notifications]))||[]);return Y.map(he=>({...he,receives_notifications:ie.get(he.id)||!1}))}}),{data:j=[]}=ct({queryKey:["admin-ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:z,error:V}=await q.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(V)throw V;return z},enabled:!!n}),b=gt({mutationFn:async({userId:z,enabled:V})=>{const{data:W}=await q.from("support_notification_settings").select("id").eq("user_id",z).maybeSingle();if(W){const{error:Y}=await q.from("support_notification_settings").update({receive_notifications:V}).eq("user_id",z);if(Y)throw Y}else{const{error:Y}=await q.from("support_notification_settings").insert({user_id:z,receive_notifications:V});if(Y)throw Y}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-users-notifications"]}),ae.success("Notification settings updated")},onError:()=>{ae.error("Failed to update settings")}}),S=gt({mutationFn:async({ticketId:z,status:V})=>{const{error:W}=await q.from("support_tickets").update({status:V}).eq("id",z);if(W)throw W},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),n&&r({...n,status:n.status}),ae.success("Status updated")},onError:()=>{ae.error("Failed to update status")}}),A=gt({mutationFn:async({ticketId:z,assignedTo:V})=>{const{error:W}=await q.from("support_tickets").update({assigned_to:V}).eq("id",z);if(W)throw W},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),ae.success("Ticket assigned")},onError:()=>{ae.error("Failed to assign ticket")}}),T=gt({mutationFn:async({content:z,attachments:V})=>{var Y,K;if(!n||!s)throw new Error("Missing data");const{error:W}=await q.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:z,is_admin_reply:!0,attachments:V});if(W)throw W;try{await q.functions.invoke("support-reply-notify",{body:{ticketId:n.id,ticketSubject:n.subject,replyContent:z,userEmail:(Y=n.profiles)==null?void 0:Y.email,userName:(K=n.profiles)==null?void 0:K.name}})}catch(J){console.error("Failed to send reply notification:",J)}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-ticket-replies",n==null?void 0:n.id]}),i(""),o([]),ae.success("Reply sent!")},onError:()=>{ae.error("Failed to send reply")}}),L=()=>{!a.trim()&&l.length===0||T.mutate({content:a,attachments:l})};N.useEffect(()=>{const z=q.channel("admin-tickets").on("postgres_changes",{event:"*",schema:"public",table:"support_tickets"},()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]})}).subscribe();return()=>{q.removeChannel(z)}},[t]);const D=g.filter(z=>z.status==="open").length;return n?(uG[n.status].icon,e.jsx(Ts,{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(Hr,{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(ze,{variant:"secondary",children:mZe[n.category]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["from ",((M=n.profiles)==null?void 0:M.name)||"Unknown"," (",(F=n.profiles)==null?void 0:F.email,")"]})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm",children:"Status"})}),e.jsx(Ee,{children:e.jsxs(ds,{value:n.status,onValueChange:z=>{S.mutate({ticketId:n.id,status:z}),r({...n,status:z})},children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"open",children:"Open"}),e.jsx(Qe,{value:"in_progress",children:"In Progress"}),e.jsx(Qe,{value:"resolved",children:"Resolved"}),e.jsx(Qe,{value:"closed",children:"Closed"})]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm",children:"Assigned To"})}),e.jsx(Ee,{children:e.jsxs(ds,{value:n.assigned_to||"unassigned",onValueChange:z=>{const V=z==="unassigned"?null:z;A.mutate({ticketId:n.id,assignedTo:V}),r({...n,assigned_to:V})},children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Unassigned"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"unassigned",children:"Unassigned"}),v.map(z=>e.jsx(Qe,{value:z.id,children:z.name},z.id))]})]})})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(Vn,{children:["Created on ",Ss(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Ee,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-lg",children:"Conversation"})}),e.jsxs(Ee,{children:[e.jsx(hi,{className:"h-[300px] pr-4",children:j.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:j.map(z=>{var V,W;return e.jsxs("div",{className:`p-4 rounded-lg ${z.is_admin_reply?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsx("span",{className:"font-medium text-sm",children:z.is_admin_reply?`${((V=z.profiles)==null?void 0:V.name)||"Admin"} (Support)`:((W=z.profiles)==null?void 0:W.name)||"User"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date(z.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:z.content}),z.attachments&&z.attachments.length>0&&e.jsx(J0t,{attachments:z.attachments})]},z.id)})})}),e.jsx(ll,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Es,{placeholder:"Type your reply...",value:a,onChange:z=>i(z.target.value),className:"min-h-[80px]"}),e.jsx(B,{onClick:L,disabled:!a.trim()&&l.length===0||T.isPending,className:"self-end",children:e.jsx(cr,{className:"h-4 w-4"})})]}),e.jsx(X0t,{value:l,onChange:o,disabled:T.isPending})]})]})]})]})})):e.jsx(Ts,{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",D>0&&e.jsxs(ze,{variant:"destructive",className:"ml-2",children:[D," open"]})]})]}),e.jsxs(bs,{open:p,onOpenChange:f,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(Xo,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Email Notification Settings"}),e.jsx(Qn,{children:"Choose which admins receive email notifications for new support tickets."})]}),e.jsx("div",{className:"space-y-4 mt-4",children:v.map(z=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Xi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:z.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:z.email})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[z.receives_notifications?e.jsx(im,{className:"h-4 w-4 text-primary"}):e.jsx(pw,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(bn,{checked:z.receives_notifications,onCheckedChange:V=>b.mutate({userId:z.id,enabled:V})})]})]},z.id))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsx(Br,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(Fr,{children:[e.jsx(Kt,{value:"all",children:"All"}),e.jsx(Kt,{value:"open",children:"Open"}),e.jsx(Kt,{value:"in_progress",children:"In Progress"}),e.jsx(Kt,{value:"resolved",children:"Resolved"}),e.jsx(Kt,{value:"closed",children:"Closed"})]})}),e.jsxs(ds,{value:u,onValueChange:h,children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(us,{placeholder:"All Categories"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Categories"}),e.jsx(Qe,{value:"general",children:"General Support"}),e.jsx(Qe,{value:"technology",children:"Technology Support"}),e.jsx(Qe,{value:"crm",children:"CRM Support"}),e.jsx(Qe,{value:"marketing",children:"Marketing Support"})]})]})]}),e.jsx("div",{className:"mt-4",children:_?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):g.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"text-center py-12",children:[e.jsx(Ql,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets found"}),e.jsx("p",{className:"text-muted-foreground",children:"No support tickets match the current filters."})]})}):e.jsx("div",{className:"space-y-3",children:g.map(z=>{var W,Y;const V=uG[z.status].icon;return e.jsx(fe,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(z),children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:z.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx(ze,{variant:"outline",className:"text-xs",children:mZe[z.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(W=z.profiles)==null?void 0:W.name," • ",Ss(new Date(z.created_at),"MMM d, yyyy")]}),z.assigned_to&&e.jsxs(ze,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(Xi,{className:"h-3 w-3"}),((Y=v.find(K=>K.id===z.assigned_to))==null?void 0:Y.name)||"Assigned"]})]})]}),e.jsxs(ze,{className:uG[z.status].color,children:[e.jsx(V,{className:"h-3 w-3 mr-1"}),uG[z.status].label]})]})})},z.id)})})})]})]})})}const b_t=Cf.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 zqs({content:s,onChange:t,variables:n}){const r=Z6e({extensions:[X6e,lIe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),cIe.configure({types:["heading","paragraph"]}),dIe,b_t],content:s,onUpdate:({editor:l})=>{t(l.getHTML())}});N.useEffect(()=>{r&&s!==r.getHTML()&&r.commands.setContent(s)},[s,r]);const a=l=>{r&&r.chain().focus().insertContent(`{{${l.key}}}`).run()},i=()=>{if(!r)return;const l=r.getAttributes("link").href,o=window.prompt("URL",l);if(o!==null){if(o===""){r.chain().focus().extendMarkRange("link").unsetLink().run();return}r.chain().focus().extendMarkRange("link").setLink({href:o}).run()}};return r?e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1 p-2 border-b bg-muted/30",children:[e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBold().run(),className:r.isActive("bold")?"bg-muted":"",children:e.jsx(KS,{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(JS,{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(Tp,{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(Ov,{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(_A,{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(bA,{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(wA,{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(Jo,{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(kA,{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(d4,{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(o4,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),n.length>0&&e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(wL,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(cc,{align:"end",className:"w-64",children:n.map(l=>e.jsxs(Qr,{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(K6e,{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(ze,{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 Bqs(){const s=Ht(),[t,n]=N.useState(null),[r,a]=N.useState(null),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(!0),[f,g]=N.useState("visual"),{data:_,isLoading:v}=ct({queryKey:["email-templates"],queryFn:async()=>{const{data:T,error:L}=await q.from("email_templates").select("*").order("name");if(L)throw L;return T.map(D=>({...D,available_variables:D.available_variables||[]}))}}),j=gt({mutationFn:async T=>{const{error:L}=await q.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(L)throw L},onSuccess:()=>{s.invalidateQueries({queryKey:["email-templates"]}),ae.success("Email template updated successfully"),n(null)},onError:T=>{ae.error("Failed to update template: "+T.message)}}),b=T=>{n(T),l(T.subject),c(T.body_html),u(T.description||""),p(T.is_active),g("visual")},S=()=>{t&&j.mutate({id:t.id,subject:i,body_html:o,description:d,is_active:h})},A=(T,L)=>{let D=T;return L.forEach(M=>{const F=`{{${M.key}}}`,z=`[${M.label}]`;D=D.replace(new RegExp(F.replace(/[{}]/g,"\\$&"),"g"),z)}),D};return t?e.jsxs(Ts,{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(Hr,{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(Er,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(B,{onClick:S,disabled:j.isPending,children:[e.jsx(qo,{className:"h-4 w-4 mr-2"}),j.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5"}),t.name]}),e.jsxs(Vn,{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(bn,{id:"active-toggle",checked:h,onCheckedChange:p})]})]})}),e.jsxs(Ee,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Es,{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(Br,{value:f,onValueChange:T=>g(T),children:e.jsxs(Fr,{className:"h-8",children:[e.jsxs(Kt,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(xb,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Kt,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx(kA,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),f==="visual"?e.jsx(zqs,{content:o,onChange:c,variables:t.available_variables}):e.jsx(Es,{value:o,onChange:T=>c(T.target.value),className:"font-mono text-sm min-h-[400px]",placeholder:"HTML email body"})]})]})]})]}),e.jsx(bs,{open:!!r,onOpenChange:()=>a(null),children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Email Preview"}),e.jsxs(Qn,{children:["Subject: ",i.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:A(o,t.available_variables)}})})]})})]}):e.jsx(Ts,{title:"Email Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Email Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage and customize system email templates"})]}),v?e.jsx("div",{className:"grid gap-4",children:[...Array(4)].map((T,L)=>e.jsx(fe,{children:e.jsxs(Mt,{children:[e.jsx(Ws,{className:"h-5 w-48"}),e.jsx(Ws,{className:"h-4 w-96"})]})},L))}):e.jsx("div",{className:"grid gap-4",children:_==null?void 0:_.map(T=>e.jsxs(fe,{className:"hover:shadow-md transition-shadow",children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(It,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Vs,{className:"h-5 w-5 text-muted-foreground"}),T.name,!T.is_active&&e.jsx(ze,{variant:"secondary",children:"Inactive"})]}),e.jsx(Vn,{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(Er,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(B,{size:"sm",onClick:()=>b(T),children:[e.jsx(ku,{className:"h-4 w-4 mr-2"}),"Edit"]})]})]})}),e.jsx(Ee,{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(L=>e.jsx(ze,{variant:"outline",className:"font-mono text-xs",children:`{{${L.key}}}`},L.key))})]})]})})]},T.id))}),e.jsx(bs,{open:!!r&&!t,onOpenChange:()=>a(null),children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:["Email Preview: ",r==null?void 0:r.name]}),e.jsxs(Qn,{children:["Subject: ",r==null?void 0:r.subject.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),r&&e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:A(r.body_html,r.available_variables)}})})]})})]})})}function $qs(){const s=Ht(),[t,n]=N.useState("templates"),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),[f,g]=N.useState({name:"",description:"",icon:"📧"}),{data:_=[]}=ct({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:z,error:V}=await q.from("email_template_categories").select("*").order("sort_order");if(V)throw V;return z}}),{data:v=[],isLoading:j}=ct({queryKey:["agent-email-templates-admin"],queryFn:async()=>{const{data:z,error:V}=await q.from("agent_email_templates").select("*, category:email_template_categories(*)").order("sort_order");if(V)throw V;return z}}),b=gt({mutationFn:async z=>{const V={title:z.title,subject:z.subject,body:z.body,description:z.description||null,tone:z.tone||null,category_id:z.category_id||null,is_active:z.is_active};if(z.id){const{error:W}=await q.from("agent_email_templates").update(V).eq("id",z.id);if(W)throw W}else{const{error:W}=await q.from("agent_email_templates").insert(V);if(W)throw W}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),c(!1),ae.success(r?"Template updated":"Template created")},onError:()=>ae.error("Failed to save template")}),S=gt({mutationFn:async z=>{const{error:V}=await q.from("agent_email_templates").delete().eq("id",z);if(V)throw V},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),ae.success("Template deleted")}}),A=gt({mutationFn:async z=>{const V={name:z.name,description:z.description||null,icon:z.icon};if(z.id){const{error:W}=await q.from("email_template_categories").update(V).eq("id",z.id);if(W)throw W}else{const W=_.length>0?Math.max(..._.map(K=>K.sort_order))+1:0,{error:Y}=await q.from("email_template_categories").insert({...V,sort_order:W});if(Y)throw Y}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),u(!1),ae.success(i?"Category updated":"Category created")},onError:()=>ae.error("Failed to save category")}),T=gt({mutationFn:async z=>{const{error:V}=await q.from("email_template_categories").delete().eq("id",z);if(V)throw V},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),ae.success("Category deleted")}}),L=()=>{a(null),p({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),c(!0)},D=z=>{a(z),p({title:z.title,subject:z.subject,body:z.body,description:z.description||"",tone:z.tone||"",category_id:z.category_id||"",is_active:z.is_active}),c(!0)},M=()=>{l(null),g({name:"",description:"",icon:"📧"}),u(!0)},F=z=>{l(z),g({name:z.name,description:z.description||"",icon:z.icon}),u(!0)};return e.jsx(Ts,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx(Ud,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs(Br,{value:t,onValueChange:n,children:[e.jsxs(Fr,{children:[e.jsxs(Kt,{value:"templates",className:"gap-2",children:[e.jsx(Vs,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Kt,{value:"categories",className:"gap-2",children:[e.jsx(gf,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(is,{value:"templates",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:L,className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Template"}),e.jsx(Ct,{className:"hidden md:table-cell",children:"Category"}),e.jsx(Ct,{className:"hidden md:table-cell",children:"Tone"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:j?e.jsx(Hs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8",children:e.jsx(ts,{className:"h-6 w-6 animate-spin mx-auto"})})}):v.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):v.map(z=>e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:z.title}),e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[300px]",children:z.subject})]})}),e.jsx(ut,{className:"hidden md:table-cell",children:z.category?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[z.category.icon," ",z.category.name]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ut,{className:"hidden md:table-cell",children:z.tone?e.jsx(ze,{variant:"secondary",children:z.tone}):"—"}),e.jsx(ut,{children:e.jsx(ze,{variant:z.is_active?"default":"secondary",children:z.is_active?"Active":"Inactive"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>D(z),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&S.mutate(z.id)},children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},z.id))})]})})})]}),e.jsxs(is,{value:"categories",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:M,className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"})," Add Category"]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:_.map(z=>e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:z.icon})," ",z.name]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>F(z),children:e.jsx(_a,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>{confirm("Delete this category?")&&T.mutate(z.id)},children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Ee,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:z.description||"No description"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[v.filter(V=>V.category_id===z.id).length," templates"]})]})]},z.id))})]})]}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:r?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:h.title,onChange:z=>p(V=>({...V,title:z.target.value})),placeholder:"e.g. Quick Check-in"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Category"}),e.jsxs(ds,{value:h.category_id,onValueChange:z=>p(V=>({...V,category_id:z})),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select category"})}),e.jsx(cs,{children:_.map(z=>e.jsxs(Qe,{value:z.id,children:[z.icon," ",z.name]},z.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Subject Line"}),e.jsx(ye,{value:h.subject,onChange:z=>p(V=>({...V,subject:z.target.value})),placeholder:"e.g. Hey {{first_name}}, just checking in!"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{{first_name}}",", ","{{last_name}}",", ","{{full_name}}"," for merge variables"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Email Body"}),e.jsx(Es,{value:h.body,onChange:z=>p(V=>({...V,body:z.target.value})),rows:12,placeholder:"Write your email template...",className:"resize-y"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description (internal)"}),e.jsx(ye,{value:h.description,onChange:z=>p(V=>({...V,description:z.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:z=>p(V=>({...V,tone:z.target.value})),placeholder:"e.g. Warm & Casual"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bn,{checked:h.is_active,onCheckedChange:z=>p(V=>({...V,is_active:z}))}),e.jsx(se,{children:"Active"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>b.mutate({...h,id:r==null?void 0:r.id}),disabled:b.isPending||!h.title||!h.subject||!h.body,children:[b.isPending&&e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Save Changes":"Create Template"]})]})]})}),e.jsx(bs,{open:d,onOpenChange:u,children:e.jsxs(vs,{className:"sm:max-w-[450px]",children:[e.jsx(ws,{children:e.jsx(_s,{children:i?"Edit Category":"New Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-[60px_1fr] gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Icon"}),e.jsx(ye,{value:f.icon,onChange:z=>g(V=>({...V,icon:z.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:f.name,onChange:z=>g(V=>({...V,name:z.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:f.description,onChange:z=>g(V=>({...V,description:z.target.value})),placeholder:"Brief description of this category"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>A.mutate({...f,id:i==null?void 0:i.id}),disabled:A.isPending||!f.name,children:[A.isPending&&e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),i?"Save Changes":"Create Category"]})]})]})})]})})}const Uqs=({brokerageId:s})=>{var $r,ss;const{toast:t}=Ba(),n=Mn(),[r,a]=N.useState([]),[i,l]=N.useState(!0),[o,c]=N.useState(""),[d,u]=N.useState("all"),[h,p]=N.useState(new Set),[f,g]=N.useState(!1),[_,v]=N.useState({}),[j,b]=N.useState(!1),[S,A]=N.useState(!1),[T,L]=N.useState({email:"",name:"",password:"",phone:""}),[D,M]=N.useState(!1),[F,z]=N.useState(null),[V,W]=N.useState(!1),[Y,K]=N.useState(!1),[J,ne]=N.useState(!1),[ie,he]=N.useState(""),[ce,pe]=N.useState(!1),[le,ve]=N.useState([]),[ge,Te]=N.useState(!1),[Me,Ce]=N.useState(!1),[Ae,De]=N.useState(null),[Ie,Fe]=N.useState({name:"",phone:"",email:""}),[qe,be]=N.useState(!1),[Ze,Ne]=N.useState(!1),[it,je]=N.useState(null),[Ge,Be]=N.useState("asc"),[Ye,We]=N.useState(!1),[rt,tt]=N.useState(null),[at,He]=N.useState(!1),[dt,bt]=N.useState(null),[vt,Bt]=N.useState(""),[Zt,Fs]=N.useState(!1),[Rs,ms]=N.useState(null);N.useEffect(()=>{Jt(),Pt()},[s]);const Pt=async()=>{try{const{data:Oe,error:Xe}=await q.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(Xe)throw Xe;ve((Oe==null?void 0:Oe.map(ot=>ot.user_id))||[])}catch(Oe){console.error("Error loading brokerage managers:",Oe)}},Jt=async()=>{try{l(!0);const{data:Oe,error:Xe}=await q.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(Xe)throw Xe;const ot=Oe.agents||[];if(a(ot),ot.length>0){const Nt=ot.map(qt=>qt.id),{data:Rt}=await q.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",Nt);if(Rt&&Rt.length>0){const qt=Rt.map(ks=>ks.assistant_id),{data:xs}=await q.from("profiles").select("id, name, email").in("id",qt),rs={};for(const ks of Rt){const ln=xs==null?void 0:xs.find(Gs=>Gs.id===ks.assistant_id);ln&&(rs[ks.agent_id]={name:ln.name||"",email:ln.email||""})}v(rs)}else v({})}}catch(Oe){console.error("Error loading agents:",Oe),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},ft=async()=>{if(!T.email||!T.name||!T.password){t({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}A(!0);try{const{data:{session:Oe}}=await q.auth.getSession(),Xe=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Oe==null?void 0:Oe.access_token}`},body:JSON.stringify({...T,brokerageId:s})}),ot=await Xe.json();if(!Xe.ok)throw new Error(ot.error||"Failed to create agent");t({title:"Success",description:`Agent ${T.email} created successfully`}),L({email:"",name:"",password:"",phone:""}),b(!1),Jt()}catch(Oe){console.error("Error creating agent:",Oe),t({title:"Error",description:Oe.message||"Failed to create agent",variant:"destructive"})}finally{A(!1)}},Vt=async Oe=>{try{const{data:{session:Xe}}=await q.auth.getSession(),ot=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Xe==null?void 0:Xe.access_token}`},body:JSON.stringify({userId:Oe})}),Nt=await ot.json();if(!ot.ok)throw new Error(Nt.error||"Failed to resend welcome email");t({title:"Success",description:"Welcome email sent successfully"})}catch(Xe){console.error("Error resending welcome email:",Xe),t({title:"Error",description:Xe.message||"Failed to resend welcome email",variant:"destructive"})}},Ms=async(Oe,Xe)=>{try{const{error:ot}=await q.functions.invoke("send-password-reset",{body:{email:Oe,redirectTo:window.location.origin}});if(ot)throw ot;t({title:"Password Reset Sent",description:`Password reset email sent to ${Xe}`})}catch(ot){console.error("Error sending password reset:",ot),t({title:"Error",description:ot.message||"Failed to send password reset email",variant:"destructive"})}},Xt=Oe=>{z(Oe),M(!0)},Js=Oe=>{De(Oe),Fe({name:Oe.name,phone:Oe.phone||"",email:Oe.email}),Ce(!0)},Cs=async()=>{if(!Ae)return;if(!Ie.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const Oe=Ie.email.trim().toLowerCase()!==Ae.email.toLowerCase();be(!0);try{if(Oe){if(!Ie.email.trim())throw new Error("Email is required");Ne(!0);const{data:{session:ot}}=await q.auth.getSession(),Nt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ot==null?void 0:ot.access_token}`},body:JSON.stringify({agentId:Ae.id,newEmail:Ie.email.trim(),brokerageId:s})}),Rt=await Nt.json();if(Ne(!1),!Nt.ok)throw new Error(Rt.error||"Failed to update email")}const{error:Xe}=await q.from("profiles").update({name:Ie.name.trim(),phone:Ie.phone.trim()||null}).eq("id",Ae.id);if(Xe)throw Xe;t({title:"Success",description:"Agent profile updated successfully"}),Ce(!1),De(null),Jt()}catch(Xe){console.error("Error updating agent:",Xe),t({title:"Error",description:Xe.message||"Failed to update agent",variant:"destructive"})}finally{be(!1),Ne(!1)}},As=async()=>{if(!ie){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}pe(!0);try{const{data:{session:Oe}}=await q.auth.getSession(),Xe=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Oe==null?void 0:Oe.access_token}`},body:JSON.stringify({userId:ie,role:"brokerage_manager",action:"add",brokerageId:s})}),ot=await Xe.json();if(!Xe.ok)throw new Error(ot.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),ne(!1),he(""),Pt()}catch(Oe){console.error("Error adding brokerage manager:",Oe),t({title:"Error",description:Oe.message||"Failed to add brokerage manager",variant:"destructive"})}finally{pe(!1)}},rn=async Oe=>{try{const{data:{session:Xe}}=await q.auth.getSession(),ot=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Xe==null?void 0:Xe.access_token}`},body:JSON.stringify({userId:Oe,role:"brokerage_manager",action:"remove",brokerageId:s})}),Nt=await ot.json();if(!ot.ok)throw new Error(Nt.error||"Failed to remove brokerage manager");t({title:"Success",description:"Brokerage manager role removed"}),Pt()}catch(Xe){console.error("Error removing brokerage manager:",Xe),t({title:"Error",description:Xe.message||"Failed to remove brokerage manager",variant:"destructive"})}},tn=Oe=>le.includes(Oe),er=Oe=>{bt(Oe),Bt(""),He(!0)},gn=async()=>{if(!(!dt||!vt)){if(vt.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}Fs(!0);try{const{data:{session:Oe}}=await q.auth.getSession(),Xe=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Oe==null?void 0:Oe.access_token}`},body:JSON.stringify({agentId:dt.id,brokerageId:s,action:"set_password",newPassword:vt})}),ot=await Xe.json();if(!Xe.ok)throw new Error(ot.error||"Failed to set password");t({title:"Success",description:`Password set for ${dt.name}`}),He(!1),bt(null),Bt("")}catch(Oe){console.error("Error setting password:",Oe),t({title:"Error",description:Oe.message||"Failed to set password",variant:"destructive"})}finally{Fs(!1)}}},In=async Oe=>{ms(Oe.id);try{const{data:{session:Xe}}=await q.auth.getSession(),ot=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Xe==null?void 0:Xe.access_token}`},body:JSON.stringify({agentId:Oe.id,brokerageId:s,action:"claim_account"})}),Nt=await ot.json();if(!ot.ok)throw new Error(Nt.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${Oe.name}`}),Jt()}catch(Xe){console.error("Error claiming account:",Xe),t({title:"Error",description:Xe.message||"Failed to claim account",variant:"destructive"})}finally{ms(null)}},Zn=async()=>{if(F){W(!0);try{const{data:{session:Oe}}=await q.auth.getSession(),Xe=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Oe==null?void 0:Oe.access_token}`},body:JSON.stringify({userId:F.id,brokerageId:s})}),ot=await Xe.json();if(!Xe.ok)throw new Error(ot.error||"Failed to remove agent");t({title:"Success",description:`${F.name} has been removed from your brokerage`}),M(!1),z(null),Jt()}catch(Oe){console.error("Error removing agent:",Oe),t({title:"Error",description:Oe.message||"Failed to remove agent",variant:"destructive"})}finally{W(!1)}}},ea=Oe=>{const Xe=Oe.trim().split(" ");return Xe.length>1?Xe[Xe.length-1].toLowerCase():Oe.toLowerCase()},vi=Oe=>{it===Oe?Be(Ge==="asc"?"desc":"asc"):(je(Oe),Be("asc"))},Ls=Oe=>it!==Oe?e.jsx(em,{className:"ml-1 h-4 w-4"}):Ge==="asc"?e.jsx(Ru,{className:"ml-1 h-4 w-4"}):e.jsx(am,{className:"ml-1 h-4 w-4"}),fi=r.filter(Oe=>{if(d==="active"&&!Oe.claimed||d==="pending"&&Oe.claimed)return!1;if(!o)return!0;const Xe=o.toLowerCase();return Oe.name.toLowerCase().includes(Xe)||Oe.email.toLowerCase().includes(Xe)}),Lr=[...fi].sort((Oe,Xe)=>{if(!it)return 0;let ot=0;return it==="name"?ot=ea(Oe.name).localeCompare(ea(Xe.name)):it==="status"&&(ot=Oe.claimed===Xe.claimed?0:Oe.claimed?-1:1),Ge==="asc"?ot:-ot});fi.filter(Oe=>Oe.claimed&&!tn(Oe.id));const Jn=Oe=>{p(Xe=>{const ot=new Set(Xe);return ot.has(Oe)?ot.delete(Oe):ot.add(Oe),ot})},js=()=>{h.size===Lr.length?p(new Set):p(new Set(Lr.map(Oe=>Oe.id)))},Dn=()=>{p(new Set)},wr=async()=>{const Oe=Array.from(h);if(Oe.length===0)return;g(!0);let Xe=0,ot=0;try{const{data:{session:Nt}}=await q.auth.getSession();for(const Rt of Oe)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Nt==null?void 0:Nt.access_token}`},body:JSON.stringify({userId:Rt})})).ok?Xe++:ot++}catch{ot++}Xe>0?t({title:"Success",description:`Welcome emails sent to ${Xe} agent${Xe>1?"s":""}${ot>0?` (${ot} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),Dn()}catch(Nt){console.error("Error bulk sending welcome emails:",Nt),t({title:"Error",description:Nt.message||"Failed to send welcome emails",variant:"destructive"})}finally{g(!1)}};return i?e.jsx(fe,{children:e.jsx(Ee,{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(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Agents"}),e.jsx(Vn,{children:"Manage your brokerage's agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>ne(!0),children:[e.jsx(dh,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs(B,{variant:"outline",onClick:()=>K(!0),children:[e.jsx(gw,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs(B,{onClick:()=>b(!0),children:[e.jsx(Fo,{className:"mr-2 h-4 w-4"}),"Add Agent"]})]})]})}),e.jsxs(Ee,{children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-4 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents...",value:o,onChange:Oe=>c(Oe.target.value),className:"pl-9"})]}),e.jsxs(ds,{value:d,onValueChange:Oe=>u(Oe),children:[e.jsx(ls,{className:"w-[160px]",children:e.jsx(us,{placeholder:"Filter by status"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Agents"}),e.jsx(Qe,{value:"active",children:"Active"}),e.jsx(Qe,{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 Xe=r.filter(ot=>h.has(ot.id)&&ot.email).map(ot=>({email:ot.email,name:ot.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(Xe)),n("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:Xe}})},disabled:f,children:[e.jsx($d,{className:"mr-2 h-4 w-4"}),"Email Agents (",h.size,")"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:wr,disabled:f,children:[e.jsx(Vs,{className:"mr-2 h-4 w-4"}),f?"Sending...":"Resend Welcome Email"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:Dn,children:"Clear"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{className:"w-[40px]",children:e.jsx(ui,{checked:Lr.length>0&&h.size===Lr.length,onCheckedChange:js,"aria-label":"Select all"})}),e.jsx(Ct,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>vi("name"),children:["Name (Last)",Ls("name")]})}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>vi("status"),children:["Status",Ls("status")]})}),e.jsx(Ct,{children:"Actions"})]})}),e.jsx(ha,{children:Lr.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):Lr.map(Oe=>e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsx(ui,{checked:h.has(Oe.id),onCheckedChange:()=>Jn(Oe.id),"aria-label":`Select ${Oe.name}`})}),e.jsx(ut,{className:"font-medium",children:Oe.name}),e.jsx(ut,{children:Oe.email}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Oe.claimed?e.jsx(ze,{variant:"default",children:"Active"}):e.jsx(ze,{variant:"secondary",children:"Pending"}),tn(Oe.id)&&e.jsxs(ze,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(sg,{className:"mr-1 h-3 w-3"}),"Manager"]}),_[Oe.id]&&e.jsxs(ze,{variant:"outline",className:"text-xs",children:[e.jsx(Nn,{className:"mr-1 h-3 w-3"}),"Asst: ",_[Oe.id].name||_[Oe.id].email]})]})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{tt(Oe),We(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(ch,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Js(Oe),title:"Edit agent",children:e.jsx(_a,{className:"h-4 w-4"})}),!Oe.claimed&&e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Vt(Oe.id),title:"Resend welcome email",children:e.jsx(Vs,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>In(Oe),title:"Claim account for agent",disabled:Rs===Oe.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(bb,{className:"h-4 w-4"})})]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>er(Oe),title:"Set password",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50",children:e.jsx(Kc,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Ms(Oe.email,Oe.name),title:"Send password reset email",children:e.jsx(IA,{className:"h-4 w-4"})}),tn(Oe.id)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>rn(Oe.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:e.jsx(dh,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Xt(Oe),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},Oe.id))})]})})]})]}),e.jsx(bs,{open:j,onOpenChange:b,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Add New Agent"}),e.jsx(Qn,{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:Oe=>L({...T,name:Oe.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:Oe=>L({...T,email:Oe.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:Oe=>L({...T,phone:Oe.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:Oe=>L({...T,password:Oe.target.value}),placeholder:"Temporary password"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(B,{onClick:ft,disabled:S,children:S?"Creating...":"Create Agent"})]})]})}),e.jsx(bs,{open:D,onOpenChange:M,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Remove Agent"}),e.jsxs(Qn,{children:["Are you sure you want to remove ",e.jsx("strong",{children:F==null?void 0:F.name})," from your brokerage? This will revoke their access to the dashboard."]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>M(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Zn,disabled:V,children:V?"Removing...":"Remove Agent"})]})]})}),e.jsx(eyt,{open:Y,onOpenChange:K,fixedBrokerageId:s,onSuccess:Jt}),e.jsx(bs,{open:J,onOpenChange:ne,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Add Brokerage Manager"}),e.jsx(Qn,{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(el,{open:ge,onOpenChange:Te,children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":ge,className:"w-full justify-between",children:[ie?(($r=r.find(Oe=>Oe.id===ie))==null?void 0:$r.name)+" ("+((ss=r.find(Oe=>Oe.id===ie))==null?void 0:ss.email)+")":"Select an agent to promote...",e.jsx(qg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ho,{className:"w-full p-0",align:"start",children:e.jsxs(Qg,{children:[e.jsx(Xg,{placeholder:"Search by name or email..."}),e.jsxs(Jg,{className:"max-h-[200px]",children:[e.jsx(e0,{children:"No eligible agents found."}),e.jsx(t0,{children:r.filter(Oe=>!tn(Oe.id)).map(Oe=>e.jsxs(Jf,{value:`${Oe.name} ${Oe.email}`,onSelect:()=>{he(Oe.id),Te(!1)},children:[e.jsx(Ir,{className:`mr-2 h-4 w-4 ${ie===Oe.id?"opacity-100":"opacity-0"}`}),Oe.name," (",Oe.email,")"]},Oe.id))})]})]})})]}),r.filter(Oe=>!tn(Oe.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>ne(!1),children:"Cancel"}),e.jsx(B,{onClick:As,disabled:ce||!ie,children:ce?"Adding...":"Add as Manager"})]})]})}),e.jsx(bs,{open:Me,onOpenChange:Ce,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Edit Agent"}),e.jsxs(Qn,{children:["Update profile information for ",Ae==null?void 0:Ae.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:Ie.name,onChange:Oe=>Fe({...Ie,name:Oe.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:Ie.email,onChange:Oe=>Fe({...Ie,email:Oe.target.value}),placeholder:"agent@example.com"}),Ie.email.trim().toLowerCase()!==(Ae==null?void 0:Ae.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:Ie.phone,onChange:Oe=>Fe({...Ie,phone:Oe.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Ce(!1),children:"Cancel"}),e.jsx(B,{onClick:Cs,disabled:qe||Ze,children:Ze?"Updating email...":qe?"Saving...":"Save Changes"})]})]})}),rt&&e.jsx(tyt,{open:Ye,onOpenChange:Oe=>{We(Oe),Oe||tt(null)},userId:rt.id,userName:rt.name}),e.jsx(bs,{open:at,onOpenChange:He,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Set Password"}),e.jsxs(Qn,{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:vt,onChange:Oe=>Bt(Oe.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(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>He(!1),children:"Cancel"}),e.jsx(B,{onClick:gn,disabled:Zt||!vt||vt.length<6,children:Zt?"Setting...":"Set Password"})]})]})})]})},qqs={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},Vqs={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},Hqs=s=>{switch(s){case"academy_video":return e.jsx(br,{className:"h-4 w-4"});case"template":return e.jsx(Nr,{className:"h-4 w-4"});case"toolbox":return e.jsx(Nr,{className:"h-4 w-4"});case"newsletter":return e.jsx(ay,{className:"h-4 w-4"});case"social_swag":return e.jsx(un,{className:"h-4 w-4"});case"event":return e.jsx(yr,{className:"h-4 w-4"});default:return e.jsx(tr,{className:"h-4 w-4"})}},Gqs=({brokerageId:s})=>{const{toast:t}=Ba(),[n,r]=N.useState([]),[a,i]=N.useState([]),[l,o]=N.useState([]),[c,d]=N.useState(!0),[u,h]=N.useState(null);N.useEffect(()=>{p()},[s]);const p=async()=>{try{d(!0);const{data:_,error:v}=await q.from("profiles").select("id, name, email").eq("brokerage_id",s);if(v)throw v;const j=_.map(V=>V.id),b=new Map(_.map(V=>[V.id,V]));if(j.length===0){r([]),i([]),o([]);return}const{data:S,error:A}=await q.from("activity_logs").select("*").in("user_id",j).order("launched_at",{ascending:!1});if(A)throw A;const T=S.map(V=>{var W,Y;return{id:V.id,user_id:V.user_id,app_name:V.app_name,launched_at:V.launched_at,user_name:((W=b.get(V.user_id))==null?void 0:W.name)||"Unknown",user_email:((Y=b.get(V.user_id))==null?void 0:Y.email)||"Unknown"}});r(T);const{data:L,error:D}=await q.from("content_engagement_logs").select("*").in("user_id",j).order("created_at",{ascending:!1});if(D)throw D;const M=(L||[]).map(V=>{var W,Y;return{id:V.id,user_id:V.user_id,resource_type:V.resource_type,resource_id:V.resource_id,resource_title:V.resource_title,action_type:V.action_type,created_at:V.created_at,user_name:((W=b.get(V.user_id))==null?void 0:W.name)||"Unknown",user_email:((Y=b.get(V.user_id))==null?void 0:Y.email)||"Unknown"}});i(M);const F=new Map;_.forEach(V=>{F.set(V.id,{user_id:V.id,user_name:V.name,user_email:V.email,app_launches:0,content_views:0,last_activity:""})}),T.forEach(V=>{const W=F.get(V.user_id);W&&(W.app_launches++,(!W.last_activity||new Date(V.launched_at)>new Date(W.last_activity))&&(W.last_activity=V.launched_at))}),M.forEach(V=>{const W=F.get(V.user_id);W&&(W.content_views++,(!W.last_activity||new Date(V.created_at)>new Date(W.last_activity))&&(W.last_activity=V.created_at))});const z=Array.from(F.values()).filter(V=>V.app_launches>0||V.content_views>0).sort((V,W)=>new Date(W.last_activity).getTime()-new Date(V.last_activity).getTime());o(z)}catch(_){console.error("Error loading activity:",_),t({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{d(!1)}},f=_=>n.filter(v=>v.user_id===_),g=_=>a.filter(v=>v.user_id===_);return c?e.jsx(fe,{children:e.jsx(Ee,{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(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Agent Activity"}),e.jsx(Vn,{children:"Track app usage and content engagement - click an agent for details"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{className:"text-center",children:"App Launches"}),e.jsx(Ct,{className:"text-center",children:"Content Views"}),e.jsx(Ct,{children:"Last Active"})]})}),e.jsx(ha,{children:l.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):l.map(_=>e.jsxs(Hs,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>h({id:_.user_id,name:_.user_name,email:_.user_email}),children:[e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:_.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:_.user_email})]})}),e.jsx(ut,{className:"text-center",children:e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Al,{className:"h-3 w-3"}),_.app_launches]})}),e.jsx(ut,{className:"text-center",children:e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Nr,{className:"h-3 w-3"}),_.content_views]})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:_.last_activity&&Vo(new Date(_.last_activity),{addSuffix:!0})})]},_.user_id))})]})})})]}),e.jsx(bs,{open:!!u,onOpenChange:_=>!_&&h(null),children:e.jsxs(vs,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:[u==null?void 0:u.name,"'s Activity"]}),e.jsx(Qn,{children:u==null?void 0:u.email})]}),e.jsxs(Br,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Fr,{className:"grid w-full grid-cols-2",children:[e.jsx(Kt,{value:"content",children:"Content Engagement"}),e.jsx(Kt,{value:"apps",children:"App Launches"})]}),e.jsx(is,{value:"content",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Resource"}),e.jsx(Ct,{children:"Type"}),e.jsx(Ct,{children:"Action"}),e.jsx(Ct,{children:"Time"})]})}),e.jsx(ha,{children:u&&g(u.id).length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):u&&g(u.id).map(_=>e.jsxs(Hs,{children:[e.jsx(ut,{className:"max-w-[200px] truncate font-medium",children:_.resource_title}),e.jsx(ut,{children:e.jsxs(ze,{variant:"outline",className:"gap-1",children:[Hqs(_.resource_type),qqs[_.resource_type]||_.resource_type]})}),e.jsx(ut,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Vqs[_.action_type]||_.action_type})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:Vo(new Date(_.created_at),{addSuffix:!0})})]},_.id))})]})})}),e.jsx(is,{value:"apps",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"App"}),e.jsx(Ct,{children:"Time"})]})}),e.jsx(ha,{children:u&&f(u.id).length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):u&&f(u.id).map(_=>e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsx(ze,{variant:"outline",children:_.app_name})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:Vo(new Date(_.launched_at),{addSuffix:!0})})]},_.id))})]})})})]})]})})]})},Wqs=({brokerageId:s})=>{const{toast:t}=Ba(),[n,r]=N.useState({totalAgents:0,activeAgents:0,pendingAgents:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0}),[a,i]=N.useState(!0);N.useEffect(()=>{l()},[s]);const l=async()=>{try{i(!0);const{data:o,error:c}=await q.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:p}=await q.from("profiles").select("id, email").in("id",d);if(p)throw p;const{count:f}=await q.from("profiles").select("*",{count:"exact",head:!0}).eq("brokerage_id",s).not("last_login","is",null),g=f||0,_=u-g,{count:v}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d),j=new Date;j.setDate(j.getDate()-7);const{count:b}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",j.toISOString()),S=new Date;S.setMonth(S.getMonth()-1);const{count:A}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",S.toISOString());r({totalAgents:u,activeAgents:g,pendingAgents:_,totalLaunches:v||0,launchesThisWeek:b||0,launchesThisMonth:A||0})}catch(o){console.error("Error loading analytics:",o),t({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{i(!1)}};return a?e.jsx(fe,{children:e.jsx(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total Agents"}),e.jsx(Nn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Active Agents"}),e.jsx(Ri,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(gr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(nm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"This Week"}),e.jsx(nm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"This Month"}),e.jsx(nm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{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"})]})]})]})},Kqs=({brokerageId:s})=>{const[t,n]=N.useState([]),[r,a]=N.useState(!0),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState({description:"",maxUses:""});N.useEffect(()=>{h()},[s]);const h=async()=>{try{const{data:j,error:b}=await q.from("invite_codes").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(b)throw b;n(j||[])}catch(j){console.error("Error loading invite codes:",j),ae.error("Failed to load invite links")}finally{a(!1)}},p=()=>Math.random().toString(36).substring(2,8).toUpperCase(),f=async()=>{l(!0);try{const j=p(),{error:b}=await q.from("invite_codes").insert({code:j,description:d.description||null,max_uses:d.maxUses?parseInt(d.maxUses):null,brokerage_id:s,is_active:!0});if(b)throw b;ae.success("Invite link created!"),c(!1),u({description:"",maxUses:""}),h()}catch(j){console.error("Error creating invite code:",j),ae.error("Failed to create invite link")}finally{l(!1)}},g=async j=>{try{const{error:b}=await q.from("invite_codes").delete().eq("id",j);if(b)throw b;ae.success("Invite link deleted"),n(t.filter(S=>S.id!==j))}catch(b){console.error("Error deleting invite code:",b),ae.error("Failed to delete invite link")}},_=async(j,b)=>{try{const{error:S}=await q.from("invite_codes").update({is_active:!b}).eq("id",j);if(S)throw S;n(t.map(A=>A.id===j?{...A,is_active:!b}:A)),ae.success(`Invite link ${b?"deactivated":"activated"}`)}catch(S){console.error("Error toggling invite code:",S),ae.error("Failed to update invite link")}},v=j=>{const b=`${window.location.origin}/join?code=${j}`;navigator.clipboard.writeText(b),ae.success("Link copied to clipboard!")};return r?e.jsx(fe,{children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Jo,{className:"h-5 w-5"}),"Agent Invite Links"]}),e.jsx(Vn,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(bs,{open:o,onOpenChange:c,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create Invite Link"}),e.jsx(Qn,{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:j=>u({...d,description:j.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:j=>u({...d,maxUses:j.target.value})})]}),e.jsx(B,{onClick:f,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Invite Link"})]})]})]})]}),e.jsx(Ee,{children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Jo,{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(j=>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:j.code}),e.jsx(ze,{variant:j.is_active?"default":"secondary",children:j.is_active?"Active":"Inactive"})]}),j.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:j.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[j.uses_count," uses",j.max_uses&&` / ${j.max_uses} max`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>v(j.code),title:"Copy link",children:e.jsx(Xr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>_(j.id,j.is_active),title:j.is_active?"Deactivate":"Activate",children:j.is_active?"Disable":"Enable"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>g(j.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(_n,{className:"h-4 w-4"})})]})]},j.id))})})]})},Yqs=({open:s,onOpenChange:t,referralCode:n,brokerageId:r,senderName:a,brokerageName:i,onInvitesSent:l})=>{const[o,c]=N.useState(""),[d,u]=N.useState([]),[h,p]=N.useState(""),[f,g]=N.useState(!1),_=A=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A),v=()=>{const A=o.trim().toLowerCase();if(A&&_(A)&&!d.includes(A)){if(d.length>=10){ae.error("Maximum 10 emails per invite");return}u([...d,A]),c("")}else A&&!_(A)?ae.error("Please enter a valid email address"):d.includes(A)&&ae.error("Email already added")},j=A=>{u(d.filter(T=>T!==A))},b=A=>{(A.key==="Enter"||A.key===",")&&(A.preventDefault(),v())},S=async()=>{if(d.length===0){ae.error("Please add at least one email address");return}g(!0);try{const{data:A,error:T}=await q.functions.invoke("send-referral-invite",{body:{emails:d,personalMessage:h.trim()||void 0,referralCode:n,brokerageId:r,senderName:a,brokerageName:i}});if(T)throw T;A.successCount===A.totalCount?ae.success(`${A.successCount} invite${A.successCount>1?"s":""} sent successfully!`):ae.warning(`${A.successCount} of ${A.totalCount} invites sent. Some failed.`),u([]),p(""),t(!1),l==null||l()}catch(A){console.error("Error sending invites:",A),ae.error("Failed to send invites. Please try again.")}finally{g(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[550px]",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5 text-primary"}),"Invite Broker Friends"]}),e.jsx(Qn,{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(Oi,{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:A=>c(A.target.value),onKeyDown:b,onBlur:v}),e.jsx(B,{type:"button",variant:"secondary",onClick:v,children:"Add"})]}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.map(A=>e.jsxs(ze,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[A,e.jsx("button",{type:"button",onClick:()=>j(A),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx(Bn,{className:"h-3 w-3"})})]},A))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"message",children:"Personal Message (optional)"}),e.jsx(Es,{id:"message",placeholder:"Add a personal note that will appear at the top of the email...",value:h,onChange:A=>p(A.target.value),rows:3,maxLength:500}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[h.length,"/500 characters"]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),"What they'll receive:"]}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Beautiful branded email from you"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Your personal message (if added)"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Key LevelUp features for brokerages"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Direct signup link with your referral code"]})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:S,disabled:d.length===0||f,children:f?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent mr-2"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},Zqs=({brokerageId:s,refreshTrigger:t})=>{const[n,r]=N.useState([]),[a,i]=N.useState(!0);N.useEffect(()=>{l()},[s,t]);const l=async()=>{try{const{data:c,error:d}=await q.from("referral_invites").select("*").eq("referrer_brokerage_id",s).order("sent_at",{ascending:!1}).limit(20);if(d)throw d;r(c||[])}catch(c){console.error("Error fetching invites:",c)}finally{i(!1)}},o=c=>{switch(c){case"signed_up":return e.jsxs(ze,{className:"bg-green-100 text-green-800 gap-1",children:[e.jsx(Ri,{className:"h-3 w-3"}),"Signed Up"]});case"expired":return e.jsxs(ze,{variant:"outline",className:"text-muted-foreground gap-1",children:[e.jsx(Hc,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),"Pending"]})}};return a?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):n.length===0?e.jsxs("div",{className:"text-center py-6 text-muted-foreground",children:[e.jsx(Vs,{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 ",Ss(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},Qqs=()=>{const{brokerageId:s,user:t}=ys(),[n,r]=N.useState(null),[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState([]),[u,h]=N.useState(!0),[p,f]=N.useState(!1),[g,_]=N.useState(0);N.useEffect(()=>{s&&v()},[s]);const v=async()=>{try{const[L,D]=await Promise.all([q.from("brokerages").select("name").eq("id",s).single(),t?q.from("profiles").select("name").eq("id",t.id).single():Promise.resolve({data:null})]);L.data&&i(L.data.name),D.data&&o(D.data.name||"A LevelUp Member");const{data:M}=await q.from("referral_codes").select("code").eq("brokerage_id",s).single();if(M)r(M.code);else{const z=`REF${s==null?void 0:s.slice(0,8).toUpperCase()}`;await q.from("referral_codes").insert({brokerage_id:s,code:z}),r(z)}const{data:F}=await q.from("referrals").select(` *, referred_user:profiles!referred_user_id(name, email), referred_brokerage:brokerages!referred_brokerage_id(name) `).eq("referrer_brokerage_id",s).order("created_at",{ascending:!1});d(F||[])}catch(L){console.error("Error fetching referral data:",L)}finally{h(!1)}},j=()=>{const L=`https://dashboard.relevelup.com/?ref=${n}`;navigator.clipboard.writeText(L),ae.success("Referral link copied to clipboard!")},b=c.filter(L=>L.status==="qualified").length,S=c.filter(L=>L.status==="pending").length,A=b*25,T=Math.max(0,Math.ceil((299-A)/25));return u?null:e.jsxs(e.Fragment,{children:[e.jsxs(fe,{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(Oi,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold",children:"Referral Rewards Program"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Earn $25/month off your membership for every broker you refer"})]})]}),e.jsx("div",{className:"mt-4 bg-background/80 rounded-lg p-4 border",children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"text-3xl font-bold text-primary",children:["$",A]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Savings"})]}),A>0&&e.jsxs("div",{className:"flex items-center gap-1 text-green-600",children:[e.jsx(Ri,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Active"})]})]}),T>0&&A<299&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Refer ",T," more = ",e.jsx("span",{className:"text-primary",children:"FREE membership!"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your membership could cost $0/month"})]}),A>=299&&e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(un,{className:"h-5 w-5"}),e.jsx("span",{className:"font-bold",children:"FREE Membership Unlocked!"})]})]})})]})}),e.jsxs(Ee,{className:"pt-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs(B,{onClick:()=>f(!0),className:"w-full",size:"lg",children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs(B,{onClick:j,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(Xr,{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(Zl,{className:"h-5 w-5 mx-auto text-green-600 mb-1"}),e.jsxs("p",{className:"text-2xl font-bold text-green-700 dark:text-green-400",children:["$",A]}),e.jsx("p",{className:"text-xs text-green-600 dark:text-green-500",children:"Monthly Savings"})]}),e.jsxs("div",{className:"text-center p-4 bg-primary/5 rounded-lg border border-primary/20",children:[e.jsx(Nn,{className:"h-5 w-5 mx-auto text-primary mb-1"}),e.jsx("p",{className:"text-2xl font-bold",children:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified Referrals"})]}),e.jsxs("div",{className:"text-center p-4 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-900",children:[e.jsx(gr,{className:"h-5 w-5 mx-auto text-amber-600 mb-1"}),e.jsx("p",{className:"text-2xl font-bold text-amber-700 dark:text-amber-400",children:S}),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(Zqs,{brokerageId:s,refreshTrigger:g}),c.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Your Referrals"}),c.slice(0,5).map(L=>{var D,M;return e.jsxs("div",{className:"flex items-center justify-between p-2.5 bg-muted/30 rounded-lg",children:[e.jsx("span",{className:"text-sm truncate",children:((D=L.referred_brokerage)==null?void 0:D.name)||((M=L.referred_user)==null?void 0:M.email)||"Pending setup"}),e.jsxs(ze,{variant:L.status==="qualified"?"default":L.status==="pending"?"secondary":"destructive",className:L.status==="qualified"?"bg-green-600":"",children:[L.status==="qualified"&&e.jsx(Ri,{className:"h-3 w-3 mr-1"}),L.status]})]},L.id)})]})]})]}),e.jsx(Yqs,{open:p,onOpenChange:f,referralCode:n||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>_(L=>L+1)})]})},Xqs=({brokerageId:s})=>{const t=Mn(),{teams:n,isLoading:r}=e6(s),{data:a,isLoading:i}=ct({queryKey:["team-aggregate-stats",s,n.map(u=>u.id)],queryFn:async()=>{if(n.length===0)return[];const u=n.map(L=>L.id),{data:h}=await q.from("team_members").select("team_id, user_id, role").in("team_id",u);if(!h||h.length===0)return n.map(L=>({team_id:L.id,team_name:L.name,member_count:0,leader_name:null,leader_avatar:null,total_contacts:0,total_deals:0,total_videos:0}));const p=h.map(L=>L.user_id),f=h.filter(L=>L.role==="team_leader").map(L=>L.user_id),{data:g}=await q.from("profiles").select("id, name, avatar_url").in("id",f),_=new Map((g||[]).map(L=>[L.id,L])),{data:v}=await q.from("innercircle_contacts").select("owner_user_id").in("owner_user_id",p),{data:j}=await q.from("deal_pipeline").select("owner_user_id").in("owner_user_id",p),{data:b}=await q.from("agent_videos").select("owner_user_id").in("owner_user_id",p).eq("is_deleted",!1),S=new Map;(v||[]).forEach(L=>{S.set(L.owner_user_id,(S.get(L.owner_user_id)||0)+1)});const A=new Map;(j||[]).forEach(L=>{A.set(L.owner_user_id,(A.get(L.owner_user_id)||0)+1)});const T=new Map;return(b||[]).forEach(L=>{T.set(L.owner_user_id,(T.get(L.owner_user_id)||0)+1)}),n.map(L=>{const D=h.filter(K=>K.team_id===L.id),M=D.find(K=>K.role==="team_leader"),F=M?_.get(M.user_id):null,z=D.map(K=>K.user_id),V=z.reduce((K,J)=>K+(S.get(J)||0),0),W=z.reduce((K,J)=>K+(A.get(J)||0),0),Y=z.reduce((K,J)=>K+(T.get(J)||0),0);return{team_id:L.id,team_name:L.name,member_count:D.length,leader_name:(F==null?void 0:F.name)||null,leader_avatar:(F==null?void 0:F.avatar_url)||null,total_contacts:V,total_deals:W,total_videos:Y}})},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(fe,{children:[e.jsx(Mt,{children:e.jsx(Ws,{className:"h-5 w-32"})}),e.jsx(Ee,{children:e.jsx(Ws,{className:"h-24 w-full"})})]},u))});if(n.length===0)return e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Nn,{className:"h-12 w-12 text-muted-foreground mb-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(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Nn,{className:"h-4 w-4"})," Teams"]}),e.jsx("p",{className:"text-2xl font-bold",children:n.length})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Nn,{className:"h-4 w-4"})," Total Members"]}),e.jsx("p",{className:"text-2xl font-bold",children:o})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(SA,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(qm,{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(fe,{className:"hover:shadow-md transition-shadow",children:[e.jsxs(Mt,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(It,{className:"text-lg",children:u.team_name}),e.jsxs(ze,{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(ni,{src:u.leader_avatar||""}),e.jsx(aa,{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(ff,{className:"h-3 w-3 text-amber-500"}),u.leader_name]})]})]}),e.jsx(Ee,{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 →"})})]})},Jqs=()=>{const{user:s,isBrokerageManager:t,brokerageId:n,isAdmin:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=ys(),o=Mn(),{toast:c}=Ba(),[d,u]=N.useState(""),[h,p]=N.useState(!0),f=i||(a.length>0?a[0].id:n);N.useEffect(()=>{if(!s||!t&&!r){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),f?g():a.length===0&&!n&&p(!1)},[s,t,r,f,o,a,i]);const g=async()=>{if(!f){p(!1);return}try{const{data:_,error:v}=await q.from("brokerages").select("name").eq("id",f).single();if(v)throw v;u(_.name)}catch(_){console.error("Error loading brokerage info:",_),c({title:"Error",description:"Failed to load brokerage information",variant:"destructive"})}finally{p(!1)}};return h?e.jsx(Ts,{title:"Manage Brokerages",description:"Loading brokerage information...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):f?e.jsx(Ts,{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(ds,{value:i||"",onValueChange:l,children:[e.jsxs(ls,{className:"w-[280px]",children:[e.jsx(Va,{className:"mr-2 h-4 w-4"}),e.jsx(us,{placeholder:"Select brokerage"})]}),e.jsx(cs,{children:a.map(_=>e.jsx(Qe,{value:_.id,children:_.name},_.id))})]})]}),e.jsxs(Br,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(Fr,{className:"grid w-full grid-cols-4 md:grid-cols-8",children:[e.jsx(Kt,{value:"agents",children:"Agents"}),e.jsx(Kt,{value:"teams",children:"Teams"}),e.jsx(Kt,{value:"invite",children:"Invite Links"}),e.jsx(Kt,{value:"referrals",children:"Referrals"}),e.jsx(Kt,{value:"leaderboard",children:"Leaderboard"}),e.jsx(Kt,{value:"activity",children:"Activity"}),e.jsx(Kt,{value:"analytics",children:"Analytics"}),e.jsx(Kt,{value:"shares",children:"Shares"})]}),e.jsx(is,{value:"agents",className:"space-y-4",children:e.jsx(Uqs,{brokerageId:f})}),e.jsx(is,{value:"teams",className:"space-y-4",children:e.jsx(Xqs,{brokerageId:f})}),e.jsx(is,{value:"invite",className:"space-y-4",children:e.jsx(Kqs,{brokerageId:f})}),e.jsx(is,{value:"referrals",className:"space-y-4",children:e.jsx(Qqs,{})}),e.jsx(is,{value:"leaderboard",className:"space-y-4",children:e.jsx(qxt,{brokerageId:f,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(is,{value:"activity",className:"space-y-4",children:e.jsx(Gqs,{brokerageId:f})}),e.jsx(is,{value:"analytics",className:"space-y-4",children:e.jsx(Wqs,{brokerageId:f})}),e.jsx(is,{value:"shares",className:"space-y-4",children:e.jsx(Myt,{brokerageOnly:!0,brokerageId:f})})]})]})}):e.jsx(Ts,{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(Va,{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 eVs({brokerageId:s,canManage:t}){const{user:n}=ys(),[r,a]=N.useState([]),[i,l]=N.useState(!0),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(null),[f,g]=N.useState(!1),[_,v]=N.useState(""),[j,b]=N.useState(""),[S,A]=N.useState(!1),T=async()=>{try{const{data:z,error:V}=await q.from("brokerage_announcements").select("*").eq("brokerage_id",s).order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1});if(V)throw V;const W=z;if(W&&W.length>0){const Y=[...new Set(W.map(ie=>ie.created_by))],{data:K}=await q.from("profiles").select("id, name, avatar_url").in("id",Y),J=new Map((K==null?void 0:K.map(ie=>[ie.id,ie]))||[]),ne=W.map(ie=>({...ie,author:J.get(ie.created_by)||{name:"Unknown",avatar_url:null}}));a(ne)}else a([])}catch(z){console.error("Error fetching announcements:",z)}finally{l(!1)}};N.useEffect(()=>{T()},[s]);const L=()=>{v(""),b(""),A(!1),u(null)},D=z=>{z?(u(z),v(z.title),b(z.content),A(z.is_pinned)):L(),c(!0)},M=async()=>{if(!_.trim()||!j.trim()){ae.error("Please fill in all fields");return}g(!0);try{if(d){const{error:z}=await q.from("brokerage_announcements").update({title:_.trim(),content:j.trim(),is_pinned:S,pinned_at:S?new Date().toISOString():null}).eq("id",d.id);if(z)throw z;ae.success("Announcement updated")}else{const{error:z}=await q.from("brokerage_announcements").insert({brokerage_id:s,created_by:n==null?void 0:n.id,title:_.trim(),content:j.trim(),is_pinned:S,pinned_at:S?new Date().toISOString():null});if(z)throw z;ae.success("Announcement created")}c(!1),L(),T()}catch(z){console.error("Error saving announcement:",z),ae.error("Failed to save announcement")}finally{g(!1)}},F=async()=>{if(h)try{const{error:z}=await q.from("brokerage_announcements").delete().eq("id",h);if(z)throw z;ae.success("Announcement deleted"),T()}catch(z){console.error("Error deleting announcement:",z),ae.error("Failed to delete announcement")}finally{p(null)}};return i?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx($d,{className:"h-5 w-5"}),"Announcements"]})}),e.jsx(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx($d,{className:"h-5 w-5 text-primary"}),"Announcements"]}),t&&e.jsxs(B,{size:"sm",onClick:()=>D(),className:"gap-1",children:[e.jsx(Is,{className:"h-4 w-4"}),"New"]})]}),e.jsx(Ee,{children:r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No announcements yet"}):e.jsx("div",{className:"space-y-4",children:r.map(z=>{var V,W,Y,K;return e.jsx("div",{className:`p-4 rounded-lg border ${z.is_pinned?"bg-primary/5 border-primary/20":"bg-muted/30"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[z.is_pinned&&e.jsx(i4,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("h4",{className:"font-semibold truncate",children:z.title})]}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:z.content}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 text-xs text-muted-foreground",children:[e.jsxs(ra,{className:"h-5 w-5",children:[e.jsx(ni,{src:((V=z.author)==null?void 0:V.avatar_url)||void 0}),e.jsx(aa,{className:"text-[10px]",children:((Y=(W=z.author)==null?void 0:W.name)==null?void 0:Y.charAt(0))||"?"})]}),e.jsx("span",{children:(K=z.author)==null?void 0:K.name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Ss(new Date(z.created_at),"MMM d, yyyy")})]})]}),t&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>D(z),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>p(z.id),children:e.jsx(_n,{className:"h-4 w-4"})})]})]})},z.id)})})})]}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:d?"Edit Announcement":"New Announcement"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title"}),e.jsx(ye,{id:"title",value:_,onChange:z=>v(z.target.value),placeholder:"Announcement title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"content",children:"Content"}),e.jsx(Es,{id:"content",value:j,onChange:z=>b(z.target.value),placeholder:"Write your announcement...",rows:4})]}),e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bn,{id:"pinned",checked:S,onCheckedChange:A}),e.jsxs(se,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(i4,{className:"h-4 w-4"}),"Pin to top"]})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{onClick:M,disabled:f,children:f?"Saving...":d?"Update":"Create"})]})]})]})}),e.jsx(Oo,{open:!!h,onOpenChange:()=>p(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Announcement"}),e.jsx(Mo,{children:"Are you sure you want to delete this announcement? This action cannot be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:F,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function tVs({brokerageId:s,canManage:t=!1}){const{startImpersonation:n,isLoading:r}=H0e(),{user:a}=ys(),[i,l]=N.useState([]),[o,c]=N.useState(!0),[d,u]=N.useState(""),[h,p]=N.useState(new Set);N.useEffect(()=>{(async()=>{try{const{data:_,error:v}=await q.from("profiles").select("id, name, email, phone, avatar_url, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("brokerage_id",s).order("name");if(v)throw v;if(l(_||[]),_&&_.length>0){const j=_.map(S=>S.id),{data:b}=await q.from("agent_assistant_assignments").select("agent_id").in("agent_id",j);b&&p(new Set(b.map(S=>S.agent_id)))}}catch(_){console.error("Error fetching agents:",_)}finally{c(!1)}})()},[s]);const f=i.filter(g=>{var _,v;return g.name.toLowerCase().includes(d.toLowerCase())||g.email.toLowerCase().includes(d.toLowerCase())||((_=g.title)==null?void 0:_.toLowerCase().includes(d.toLowerCase()))||((v=g.areas_served)==null?void 0:v.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5"}),"Agent Roster"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:[1,2,3,4].map(g=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-48 bg-muted rounded-lg"})},g))})})]}):e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5 text-primary"}),"Agent Roster",e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:["(",i.length,")"]})]}),e.jsxs("div",{className:"relative w-full sm:w-64",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents...",value:d,onChange:g=>u(g.target.value),className:"pl-9"})]})]}),e.jsx(Ee,{children:f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:d?"No agents match your search":"No agents in this brokerage yet"}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:f.map(g=>e.jsx(sVs,{agent:g,hasAssistant:h.has(g.id),canImpersonate:t&&g.id!==(a==null?void 0:a.id),onImpersonate:()=>n(g.id,"/my-brokerage"),impersonationLoading:r},g.id))})})]})}function sVs({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(ni,{src:s.avatar_url||void 0,alt:s.name}),e.jsx(aa,{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(ze,{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(ka,{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(Ec,{children:[e.jsx(Ac,{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(PA,{className:"h-4 w-4"})})}),e.jsxs(vc,{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(Ar,{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(Vs,{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(vf,{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(du,{className:"h-4 w-4"})})})]})]})}function nVs({brokerageId:s}){const[t,n]=N.useState([]),[r,a]=N.useState(!0);if(N.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await q.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){n([]),a(!1);return}const u=c.map(_=>_.id),{data:h,error:p}=await q.from("agent_attendance_stats").select("user_id, total_points").in("user_id",u).order("total_points",{ascending:!1});if(p)throw p;const f=new Map(c.map(_=>[_.id,_])),g=(h||[]).filter(_=>_.total_points>0).map(_=>{const v=f.get(_.user_id);return{user_id:_.user_id,total_points:_.total_points,name:(v==null?void 0:v.name)||"Unknown",avatar_url:(v==null?void 0:v.avatar_url)||null}});n(g)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),r)return e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(vo,{className:"h-5 w-5"}),"Team Leaderboard"]})}),e.jsx(Ee,{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(Q2,{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(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(vo,{className:"h-5 w-5 text-primary"}),"Team Leaderboard"]})}),e.jsx(Ee,{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(ni,{src:o.avatar_url||void 0}),e.jsx(aa,{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 rVs({brokerageId:s}){const t=Mn(),[n,r]=N.useState([]),[a,i]=N.useState(!0);N.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await q.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){r([]),i(!1);return}const u=c.map(_=>_.id),h=new Map(c.map(_=>[_.id,_])),{data:p,error:f}=await q.from("listings").select(` id, slug, property_address, city, price, property_type, agent_id, listing_photos(photo_url) `).in("agent_id",u).eq("status","active").order("created_at",{ascending:!1}).limit(6);if(f)throw f;const g=(p||[]).map(_=>({id:_.id,slug:_.slug,property_address:_.property_address,city:_.city,price:_.price,property_type:_.property_type,agent_id:_.agent_id,agent:h.get(_.agent_id)||null,photos:_.listing_photos||[]}));r(g)}catch(c){console.error("Error fetching listings:",c)}finally{i(!1)}})()},[s]);const l=o=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(o);return a?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Or,{className:"h-5 w-5"}),"Brokerage Listings"]})}),e.jsx(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Or,{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(Is,{className:"h-4 w-4"}),"Add Listing"]})]}),e.jsxs(Ee,{children:[n.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Or,{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(Is,{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(Or,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute top-2 left-2",children:e.jsx("span",{className:"text-[10px] font-medium bg-primary text-primary-foreground px-1.5 py-0.5 rounded uppercase",children:o.property_type.replace("_"," ")})})]}),e.jsxs("div",{className:"p-2.5",children:[e.jsx("p",{className:"font-semibold text-sm text-primary",children:l(o.price)}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:o.property_address||"Address not available"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:o.city}),o.agent&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 truncate",children:["Listed by ",o.agent.name]})]})]},o.id))}),n.length>0&&e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>t("/mission-control/listings"),children:["View All Listings",e.jsx(tr,{className:"h-3 w-3 ml-1"})]})]})]})}function aVs(){const{user:s,isAdmin:t,isBrokerageManager:n}=ys(),r=Mn(),[a,i]=N.useState(!0),[l,o]=N.useState(null),[c,d]=N.useState(""),[u,h]=N.useState(0),[p,f]=N.useState(!1),[g,_]=N.useState(!1);return N.useEffect(()=>{(async()=>{if(s)try{const{data:j}=await q.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(j!=null&&j.brokerage_id)){i(!1);return}o(j.brokerage_id);const{data:b}=await q.from("brokerages").select("name").eq("id",j.brokerage_id).maybeSingle();b&&d(b.name);const{count:S}=await q.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",j.brokerage_id);if(h(S||0),t)f(!0),_(!0);else if(n){const{data:A}=await q.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",j.brokerage_id).maybeSingle();f(!!A),_(!!A)}}catch(j){console.error("Error fetching brokerage info:",j)}finally{i(!1)}})()},[s,t,n]),a?e.jsx(Ts,{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(Ts,{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(Nn,{className:"h-5 w-5 text-primary"}),e.jsxs("span",{className:"font-medium",children:[u," ",u===1?"Agent":"Agents"]})]}),g&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>r("/brokerage-content"),children:[e.jsx(Ou,{className:"h-4 w-4 mr-2"}),"Brokerage Content"]}),e.jsxs(B,{onClick:()=>r(`/mission-control/listings/new?brokerage=${l}`),children:[e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})]}),e.jsx(eVs,{brokerageId:l,canManage:p}),e.jsx(tVs,{brokerageId:l,canManage:p}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(nVs,{brokerageId:l}),e.jsx(rVs,{brokerageId:l})]})]})}):e.jsx(Ts,{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(Va,{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 iVs(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 oVs(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 pZe={video:{icon:Al,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Nr,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:El,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:yr,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:fl,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function lVs({item:s,canManage:t}){const[n,r]=N.useState(!1),[a,i]=N.useState(null),l=prs(),o=Mn(),c=pZe[s.content_type]||pZe.link,d=c.icon,u=N.useMemo(()=>s.thumbnail_url?s.thumbnail_url:s.content_type==="graphic"&&s.file_url?s.file_url:s.content_type==="video"?iVs(s.url):null,[s]);N.useEffect(()=>{u||!s.url||s.content_type!=="video"||!oVs(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(g=>g.ok?g.json():null).then(g=>{g!=null&&g.thumbnail_url&&i(g.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,u]);const h=u||a,p=()=>{o(`/brokerage-content/${s.id}`)},f=async()=>{try{await l.mutateAsync(s.id),ae.success("Content deleted")}catch{ae.error("Failed to delete")}r(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"group overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30 cursor-pointer",onClick:p,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(Ee,{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(ze,{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(ze,{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:["📅 ",Ss(new Date(s.event_date),"MMM d, yyyy · h:mm a")]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Added ",Ss(new Date(s.created_at),"MMM d, yyyy")]})]}),t&&e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,onClick:g=>g.stopPropagation(),children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(Ig,{className:"h-4 w-4"})})}),e.jsx(cc,{align:"end",children:e.jsxs(Qr,{onClick:g=>{g.stopPropagation(),r(!0)},className:"text-destructive",children:[e.jsx(_n,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})})]}),e.jsx(Oo,{open:n,onOpenChange:r,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Content"}),e.jsxs(Mo,{children:['Are you sure you want to delete "',s.title,'"? This cannot be undone.']})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:f,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function cVs(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 fZe=[{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 dVs({brokerageId:s,categories:t}){var ve;const{user:n}=ys(),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(""),[d,u]=N.useState("📁"),[h,p]=N.useState(!1);N.useRef(null);const[f,g]=N.useState("video"),[_,v]=N.useState(""),[j,b]=N.useState(""),[S,A]=N.useState(""),[T,L]=N.useState(""),[D,M]=N.useState(""),[F,z]=N.useState(""),[V,W]=N.useState(""),Y=mrs(),K=frs(s),J=xrs(),ne=grs(s),ie=()=>{g("video"),v(""),b(""),A(""),L(""),M(""),z(""),W("")},he=async(ge,Te)=>{var Ce;const Me=(Ce=ge.target.files)==null?void 0:Ce[0];if(Me){p(!0);try{const Ae=Me.name.split(".").pop(),De=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${Ae}`,{error:Ie}=await q.storage.from("brokerage-content").upload(De,Me);if(Ie)throw Ie;const{data:{publicUrl:Fe}}=q.storage.from("brokerage-content").getPublicUrl(De);Te==="file"?(L(Fe),f==="graphic"&&!D&&M(Fe)):M(Fe),ae.success("File uploaded")}catch(Ae){ae.error(Ae.message||"Upload failed")}finally{p(!1)}}},ce=async()=>{if(!_.trim()){ae.error("Title is required");return}if(n)try{await Y.mutateAsync({brokerage_id:s,category_id:V||null,content_type:f,title:_.trim(),description:j.trim()||null,url:S.trim()||null,file_url:T.trim()||null,thumbnail_url:D.trim()||null,event_date:F?new Date(F).toISOString():null,created_by:n.id}),ae.success("Content added!"),ie(),a(!1)}catch(ge){ae.error(ge.message||"Failed to add content")}},pe=async()=>{if(o.trim())try{await K.mutateAsync({name:o.trim(),icon:d,sort_order:t.length}),c(""),u("📁"),ae.success("Category created")}catch(ge){ae.error(ge.message||"Failed to create category")}},le=async()=>{try{await ne.mutateAsync(),ae.success("Default categories created")}catch{ae.error("Failed to create defaults")}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(bs,{open:r,onOpenChange:a,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Content"]})}),e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Add Brokerage Content"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Content Type"}),e.jsxs(ds,{value:f,onValueChange:g,children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:fZe.map(ge=>e.jsx(Qe,{value:ge.value,children:ge.label},ge.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(ve=fZe.find(ge=>ge.value===f))==null?void 0:ve.hint})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Category"}),e.jsxs(ds,{value:V,onValueChange:W,children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select category (optional)"})}),e.jsx(cs,{children:t.map(ge=>e.jsxs(Qe,{value:ge.id,children:[ge.icon," ",ge.name]},ge.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Title *"}),e.jsx(ye,{value:_,onChange:ge=>v(ge.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description"}),e.jsx(Es,{value:j,onChange:ge=>b(ge.target.value),placeholder:"Brief description...",rows:2})]}),["video","link","graphic","event"].includes(f)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:f==="video"?"Video URL":f==="graphic"?"Canva / Image URL":f==="event"?"Event Link (Zoom, etc.)":"URL"}),e.jsx(ye,{value:S,onChange:ge=>{const Te=ge.target.value;if(A(Te),f==="video"&&!D){const Me=cVs(Te);Me&&M(Me)}},placeholder:"https://..."})]}),["pdf","graphic"].includes(f)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:f==="pdf"?"Upload PDF":"Upload Image"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"file",accept:f==="pdf"?".pdf,.doc,.docx":"image/*",onChange:ge=>he(ge,"file"),disabled:h}),h&&e.jsx(ts,{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:ge=>he(ge,"thumbnail"),disabled:h}),D&&e.jsxs("div",{className:"relative w-20 h-20 rounded overflow-hidden",children:[e.jsx("img",{src:D,className:"w-full h-full object-cover",alt:"thumb"}),e.jsx("button",{onClick:()=>M(""),className:"absolute top-0 right-0 bg-background/80 rounded-bl p-0.5",children:e.jsx(Bn,{className:"h-3 w-3"})})]})]}),f==="event"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Event Date & Time"}),e.jsx(ye,{type:"datetime-local",value:F,onChange:ge=>z(ge.target.value)})]}),e.jsxs(B,{onClick:ce,disabled:Y.isPending||!_.trim(),className:"w-full",children:[Y.isPending?e.jsx(ts,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(bs,{open:i,onOpenChange:l,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",children:[e.jsx(Xo,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Manage Categories"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[t.length===0&&e.jsxs("div",{className:"text-center py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No categories yet"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:le,disabled:ne.isPending,children:[ne.isPending?e.jsx(ts,{className:"h-4 w-4 animate-spin mr-2"}):null,"Create Default Categories"]})]}),t.map(ge=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg border",children:[e.jsxs("span",{className:"text-sm",children:[ge.icon," ",ge.name]}),!ge.is_default&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:async()=>{await J.mutateAsync(ge.id),ae.success("Category deleted")},children:e.jsx(Bn,{className:"h-4 w-4"})})]},ge.id)),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(ye,{value:d,onChange:ge=>u(ge.target.value),className:"w-14 text-center",maxLength:2}),e.jsx(ye,{value:o,onChange:ge=>c(ge.target.value),placeholder:"New category name",className:"flex-1",onKeyDown:ge=>ge.key==="Enter"&&pe()}),e.jsx(B,{size:"sm",onClick:pe,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function uVs(){const{user:s,isAdmin:t,isBrokerageManager:n}=ys(),[r,a]=N.useState(!0),[i,l]=N.useState(null),[o,c]=N.useState(""),[d,u]=N.useState(!1),[h,p]=N.useState(null),[f,g]=N.useState("");N.useEffect(()=>{(async()=>{if(s)try{const{data:A}=await q.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(A!=null&&A.brokerage_id)){a(!1);return}l(A.brokerage_id);const{data:T}=await q.from("brokerages").select("name").eq("id",A.brokerage_id).maybeSingle();if(T&&c(T.name),t)u(!0);else if(n){const{data:L}=await q.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",A.brokerage_id).maybeSingle();u(!!L)}}catch(A){console.error("Error fetching brokerage info:",A)}finally{a(!1)}})()},[s,t,n]);const{data:_=[]}=drs(i),{data:v=[],isLoading:j}=urs(i,h),b=N.useMemo(()=>{if(!f.trim())return v;const S=f.toLowerCase();return v.filter(A=>{var T;return A.title.toLowerCase().includes(S)||((T=A.description)==null?void 0:T.toLowerCase().includes(S))||A.content_type.toLowerCase().includes(S)})},[v,f]);return r?e.jsx(Ts,{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(Ts,{title:`${o} Content`,description:"Brokerage Content Hub",children:e.jsxs("div",{className:"space-y-6",children:[d&&i&&e.jsx(dVs,{brokerageId:i,categories:_}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search content...",value:f,onChange:S=>g(S.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:()=>p(null),children:"All"}),_.map(S=>e.jsxs(B,{variant:h===S.id?"default":"outline",size:"sm",onClick:()=>p(S.id),children:[e.jsx("span",{className:"mr-1",children:S.icon}),S.name]},S.id))]})]}),j?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):b.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(gf,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:f.trim()?"No matching content found":"No content yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:f.trim()?"Try a different search term or category.":d?"Add your first piece of content above.":"Your brokerage hasn't added content yet."})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b.map(S=>e.jsx(lVs,{item:S,canManage:d},S.id))})]})}):e.jsx(Ts,{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(Va,{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 xZe={video:{icon:Al,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Nr,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:El,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:yr,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:fl,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function hVs(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 mVs(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function pVs(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function fVs(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function xVs(){const{contentId:s}=bi(),{data:t,isLoading:n}=ct({queryKey:["brokerage-content-detail",s],queryFn:async()=>{const{data:d,error:u}=await q.from("brokerage_content").select(` *, category:brokerage_content_categories(*) `).eq("id",s).single();if(u)throw u;return d},enabled:!!s});if(n)return e.jsx(Ts,{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(Ts,{title:"Brokerage Content",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Va,{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(Ln,{to:"/brokerage-content",children:"Back to Content"})})]})});const r=xZe[t.content_type]||xZe.link,a=r.icon,i=t.url||t.file_url,l=i&&mVs(i)?hVs(i):null,o=i&&pVs(i)?fVs(i):null,c=l||o;return e.jsx(Ts,{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(Ln,{to:"/brokerage-content",children:[e.jsx(Hr,{className:"h-4 w-4"}),"Back to Content"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ze,{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(ze,{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 ",Ss(new Date(t.created_at),"MMMM d, yyyy")]})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),c&&e.jsx(fe,{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(fe,{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(fe,{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(fe,{children:e.jsx(Ee,{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(fe,{children:e.jsxs(Ee,{className:"pt-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(yr,{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:Ss(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(Pa,{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 Oge={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 gVs(s="open"){const{user:t}=ys();return ct({queryKey:["brokerage-help-requests",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];let n=q.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, avatar_url)").order("created_at",{ascending:!1});if(s==="open")n=n.eq("status","open");else if(s==="mine")n=n.eq("requester_user_id",t.id);else if(s==="filled")n=n.in("status",["filled","completed"]);else if(s==="my_claims"){const{data:i}=await q.from("brokerage_help_claims").select("request_id").eq("claimant_user_id",t.id),l=(i||[]).map(o=>o.request_id);if(l.length===0)return[];n=n.in("id",l)}const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})}function yVs(s){return ct({queryKey:["brokerage-help-request",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, phone, avatar_url)").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function vVs(s){return ct({queryKey:["brokerage-help-claims",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("brokerage_help_claims").select("*, claimant:profiles!brokerage_help_claims_claimant_user_id_fkey(name, email, phone, avatar_url)").eq("request_id",s).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function bVs(){const s=Ht(),{user:t,brokerageId:n}=ys();return gt({mutationFn:async r=>{if(!t||!n)throw new Error("You must be in a brokerage to post.");const{data:a,error:i}=await q.from("brokerage_help_requests").insert({...r,brokerage_id:n,requester_user_id:t.id}).select().single();if(i)throw i;try{await q.functions.invoke("brokerage-help-notify",{body:{request_id:a.id}})}catch(l){console.warn("notify failed (non-blocking):",l)}return a},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function _Vs(){const s=Ht(),{user:t}=ys();return gt({mutationFn:async({request_id:n,note:r})=>{if(!t)throw new Error("Not signed in");const{data:a,error:i}=await q.from("brokerage_help_claims").insert({request_id:n,claimant_user_id:t.id,note:r}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",r.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function wVs(){const s=Ht();return gt({mutationFn:async({claim_id:t,request_id:n,claimant_user_id:r})=>{const{error:a}=await q.from("brokerage_help_claims").update({status:"accepted",responded_at:new Date().toISOString()}).eq("id",t);if(a)throw a;const{error:i}=await q.from("brokerage_help_requests").update({status:"filled",assigned_user_id:r}).eq("id",n);if(i)throw i;try{await q.functions.invoke("brokerage-help-claim-decision",{body:{claim_id:t}})}catch(l){console.warn("claim decision notify failed:",l)}},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-request",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function jVs(){const s=Ht();return gt({mutationFn:async({claim_id:t})=>{const{error:n}=await q.from("brokerage_help_claims").update({status:"declined",responded_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]})}})}function NVs(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("brokerage_help_requests").update({status:"cancelled"}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",n]})}})}function kVs(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("brokerage_help_requests").update({status:"completed"}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",n]})}})}function SVs(){const{user:s,brokerageId:t}=ys(),n=Ht(),r=ct({queryKey:["brokerage-help-prefs",s==null?void 0:s.id,t],queryFn:async()=>{if(!s||!t)return null;const{data:i,error:l}=await q.from("brokerage_help_notification_prefs").select("*").eq("user_id",s.id).eq("brokerage_id",t).maybeSingle();if(l)throw l;return i},enabled:!!s&&!!t}),a=gt({mutationFn:async i=>{if(!s||!t)throw new Error("No user/brokerage");const{error:l}=await q.from("brokerage_help_notification_prefs").upsert({user_id:s.id,brokerage_id:t,email_enabled:i},{onConflict:"user_id,brokerage_id"});if(l)throw l},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-help-prefs"]})}});return{...r,setEmailEnabled:a.mutate,isSaving:a.isPending}}function CVs(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 TVs(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 EVs({req:s,onClick:t}){var i;const n=Oge[s.request_type],r=CVs(s.event_start_at,s.event_end_at),a=[s.address,s.city,s.state].filter(Boolean).join(", ");return e.jsx(fe,{className:"cursor-pointer hover:shadow-md transition group",onClick:t,children:e.jsxs(Ee,{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(ze,{variant:"secondary",className:"text-xs",children:[n.emoji," ",n.label]}),s.status!=="open"&&e.jsx(ze,{variant:"outline",className:"text-xs capitalize",children:s.status})]}),e.jsx(xa,{className:"h-4 w-4 text-muted-foreground group-hover:translate-x-0.5 transition"})]}),e.jsx("h3",{className:"font-semibold text-base mb-2 line-clamp-2",children:s.title}),e.jsxs("div",{className:"space-y-1.5 text-sm text-muted-foreground",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gr,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:r})]}),a&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ka,{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(Zl,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:TVs(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 AVs(){var c;const s=Mn(),{brokerageId:t}=ys(),[n,r]=N.useState("open"),{data:a=[],isLoading:i}=gVs(n),l=SVs(),o=((c=l.data)==null?void 0:c.email_enabled)??!0;return t?e.jsx(Ts,{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(Br,{value:n,onValueChange:d=>r(d),children:e.jsxs(Fr,{children:[e.jsx(Kt,{value:"open",children:"Open"}),e.jsx(Kt,{value:"mine",children:"My Posts"}),e.jsx(Kt,{value:"my_claims",children:"My Claims"}),e.jsx(Kt,{value:"filled",children:"Filled"})]})}),e.jsxs(B,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ee,{className:"flex items-center justify-between py-3 px-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[o?e.jsx(im,{className:"h-4 w-4 text-primary"}):e.jsx(pw,{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(bn,{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(fe,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(tb,{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(EVs,{req:d,onClick:()=>s(`/brokerage/help-board/${d.id}`)},d.id))})]})}):e.jsx(Ts,{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(tb,{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 MVs(){const s=Mn(),{toast:t}=Ba(),n=bVs(),[r,a]=N.useState("open_house"),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(""),[_,v]=N.useState(""),[j,b]=N.useState(""),[S,A]=N.useState(""),[T,L]=N.useState(""),[D,M]=N.useState(""),[F,z]=N.useState("goodwill"),[V,W]=N.useState(""),[Y,K]=N.useState(""),J=r==="open_house"||r==="showing_coverage",ne=r!=="general",ie=(ce,pe)=>!ce||!pe?null:`${ce}T${pe}:00`,he=async ce=>{if(ce.preventDefault(),!i.trim()){t({title:"Add a title",description:"Tell teammates what you need help with.",variant:"destructive"});return}try{const pe=ie(d,h),le=ie(d,f);await n.mutateAsync({request_type:r,title:i.trim(),description:o.trim()||null,event_start_at:pe,event_end_at:le,address:J&&_.trim()||null,city:J&&j.trim()||null,state:J&&S.trim()||null,zip:J&&T.trim()||null,mls_number:D.trim()||null,compensation_type:F,compensation_amount:V?Number(V):null,compensation_notes:Y.trim()||null}),t({title:"Posted!",description:"Your teammates have been notified."}),s("/brokerage/help-board")}catch(pe){t({title:"Could not post",description:(pe==null?void 0:pe.message)??"Something went wrong.",variant:"destructive"})}};return e.jsx(Ts,{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(Hr,{className:"h-4 w-4"})," Back to board"]}),e.jsx("form",{onSubmit:he,children:e.jsx(fe,{children:e.jsxs(Ee,{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(Oge).map(ce=>{const pe=Oge[ce],le=ce===r;return e.jsxs("button",{type:"button",onClick:()=>a(ce),className:`text-left p-3 rounded-lg border-2 transition ${le?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"text-lg",children:pe.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:pe.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:pe.description})]},ce)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",value:i,onChange:ce=>l(ce.target.value),placeholder:r==="open_house"?"Open house at 123 Oak St — Sat 1-3pm":"Quick description",maxLength:120,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Details"}),e.jsx(Es,{id:"description",value:o,onChange:ce=>c(ce.target.value),placeholder:"Any context — lockbox code instructions later, what to expect, etc.",rows:3,maxLength:1e3})]}),ne&&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:ce=>u(ce.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:ce=>p(ce.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:f,onChange:ce=>g(ce.target.value)})]})]}),J&&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:_,onChange:ce=>v(ce.target.value),placeholder:"123 Oak St"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(se,{htmlFor:"city",children:"City"}),e.jsx(ye,{id:"city",value:j,onChange:ce=>b(ce.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"state",children:"State"}),e.jsx(ye,{id:"state",value:S,onChange:ce=>A(ce.target.value.toUpperCase()),maxLength:2})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"zip",children:"Zip"}),e.jsx(ye,{id:"zip",value:T,onChange:ce=>L(ce.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:D,onChange:ce=>M(ce.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(ce=>{const pe=F===ce.val;return e.jsxs("button",{type:"button",onClick:()=>z(ce.val),className:`text-left p-3 rounded-lg border-2 transition ${pe?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children:ce.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ce.sub})]},ce.val)})}),F!=="goodwill"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"amount",children:F==="flat_fee"?"Amount ($)":"Percent (%)"}),e.jsx(ye,{id:"amount",type:"number",min:"0",step:F==="referral_percent"?"1":"5",value:V,onChange:ce=>W(ce.target.value),placeholder:F==="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:Y,onChange:ce=>K(ce.target.value),placeholder:"e.g. Venmo same day, or split any leads",maxLength:200})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{type:"button",variant:"ghost",onClick:()=>s("/brokerage/help-board"),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:n.isPending,className:"gap-2",children:[n.isPending&&e.jsx(ts,{className:"h-4 w-4 animate-spin"}),"Post & Notify Brokerage"]})]})]})})})]})})}function IVs(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 bNe(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function PVs(){var D,M,F,z,V,W,Y,K;const{id:s}=bi(),t=Mn(),{user:n}=ys(),{toast:r}=Ba(),{data:a,isLoading:i}=yVs(s),{data:l=[]}=vVs(s),o=_Vs(),c=wVs(),d=jVs(),u=NVs(),h=kVs(),[p,f]=N.useState("");if(i)return e.jsx(Ts,{title:"Loading...",description:"",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(ts,{className:"h-8 w-8 animate-spin text-primary"})})});if(!a)return e.jsxs(Ts,{title:"Not Found",description:"",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(Hr,{className:"h-4 w-4"})," Back to board"]}),e.jsx("p",{className:"mt-4 text-muted-foreground",children:"Request not found or you don't have access."})]});const g=Oge[a.request_type],_=IVs(a.event_start_at,a.event_end_at),v=[a.address,a.city,a.state,a.zip].filter(Boolean).join(", "),j=(n==null?void 0:n.id)===a.requester_user_id,b=l.find(J=>J.claimant_user_id===(n==null?void 0:n.id)),S=l.find(J=>J.status==="accepted"),A=a.status==="open",T=a.compensation_type==="flat_fee"?a.compensation_amount?`$${Number(a.compensation_amount).toFixed(0)} flat fee`:"Flat fee":a.compensation_type==="referral_percent"?a.compensation_amount?`${a.compensation_amount}% referral`:"Referral percentage":"Goodwill (paying it forward)",L=async()=>{if(!p.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:p.trim()}),r({title:"You're in!",description:"The requester will review and pick someone."}),f("")}catch(J){r({title:"Could not submit",description:J==null?void 0:J.message,variant:"destructive"})}};return e.jsx(Ts,{title:a.title,description:`${g.emoji} ${g.label}`,children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-4",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(Hr,{className:"h-4 w-4"})," Back to board"]}),e.jsx(fe,{children:e.jsxs(Ee,{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(ze,{variant:"secondary",children:[g.emoji," ",g.label]}),e.jsx(ze,{variant:A?"default":"outline",className:"capitalize",children:a.status})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs(ra,{className:"h-7 w-7",children:[e.jsx(ni,{src:((D=a.requester)==null?void 0:D.avatar_url)||void 0}),e.jsx(aa,{children:bNe((M=a.requester)==null?void 0:M.name)})]}),e.jsx("span",{children:((F=a.requester)==null?void 0:F.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:[_&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(gr,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"When"}),e.jsx("div",{children:_})]})]}),v&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ka,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Where"}),e.jsx("div",{children:v})]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Zl,{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(XS,{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]})]})}),!j&&A&&!b&&e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Offer to cover this"}),e.jsx(Es,{placeholder:"Quick note — e.g. 'I'm 10 min away and free that day'",value:p,onChange:J=>f(J.target.value),rows:3,maxLength:400}),e.jsxs(B,{onClick:L,disabled:o.isPending,className:"gap-2",children:[o.isPending&&e.jsx(ts,{className:"h-4 w-4 animate-spin"}),"I can cover this"]})]})}),!j&&b&&e.jsx(fe,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx(Ir,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium capitalize",children:["Your offer: ",b.status]}),e.jsxs("div",{className:"text-muted-foreground",children:[b.status==="pending"&&"Waiting for the requester to pick.",b.status==="accepted"&&"You're confirmed — see contact info below.",b.status==="declined"&&"They went with someone else this time."]})]})]})}),S&&(j||S.claimant_user_id===(n==null?void 0:n.id))&&e.jsx(fe,{className:"border-primary/30",children:e.jsxs(Ee,{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(ni,{src:((z=S.claimant)==null?void 0:z.avatar_url)||void 0}),e.jsx(aa,{children:bNe((V=S.claimant)==null?void 0:V.name)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:(W=S.claimant)==null?void 0:W.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:[((Y=S.claimant)==null?void 0:Y.email)&&e.jsxs("a",{href:`mailto:${S.claimant.email}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Vs,{className:"h-4 w-4"})," ",S.claimant.email]}),((K=S.claimant)==null?void 0:K.phone)&&e.jsxs("a",{href:`tel:${S.claimant.phone}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Ar,{className:"h-4 w-4"})," ",S.claimant.phone]})]})]})}),j&&e.jsx(fe,{children:e.jsxs(Ee,{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(J=>{var ne,ie,he,ce,pe;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(ni,{src:((ne=J.claimant)==null?void 0:ne.avatar_url)||void 0}),e.jsx(aa,{children:bNe((ie=J.claimant)==null?void 0:ie.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:((he=J.claimant)==null?void 0:he.name)||"Teammate"}),e.jsx(ze,{variant:"outline",className:"capitalize text-xs",children:J.status})]}),J.note&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['"',J.note,'"']}),J.status==="pending"&&A&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(B,{size:"sm",onClick:()=>c.mutate({claim_id:J.id,request_id:a.id,claimant_user_id:J.claimant_user_id}),disabled:c.isPending,className:"gap-1",children:[e.jsx(Ir,{className:"h-3.5 w-3.5"})," Pick ",((pe=(ce=J.claimant)==null?void 0:ce.name)==null?void 0:pe.split(" ")[0])||"them"]}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>d.mutate({claim_id:J.id,request_id:a.id}),disabled:d.isPending,className:"gap-1",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},J.id)}),j&&A&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>u.mutate(a.id),disabled:u.isPending,children:"Cancel request"})}),j&&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 __t({onSelect:s,maxHeight:t="460px"}){const[n,r]=N.useState(""),[a,i]=N.useState("all"),{data:l=[],isLoading:o}=ct({queryKey:["newsletter-graphics-picker"],queryFn:async()=>{const{data:u,error:h}=await q.from("newsletter_graphics").select("*").eq("is_active",!0).order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0}).order("created_at",{ascending:!1});if(h)throw h;return u||[]}}),c=N.useMemo(()=>{const u=new Set;return l.forEach(h=>u.add(h.category||"general")),["all",...Array.from(u).sort()]},[l]),d=N.useMemo(()=>{const u=n.trim().toLowerCase();return l.filter(h=>a!=="all"&&h.category!==a?!1:u?h.title.toLowerCase().includes(u)||(h.description||"").toLowerCase().includes(u)||(h.tags||[]).some(p=>p.toLowerCase().includes(u)):!0)},[l,n,a]);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(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(hi,{style:{maxHeight:t},className:"rounded-md border",children:o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ts,{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(nl,{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(ze,{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(ca,{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 LVs=[{key:"search",label:"Search for Properties",icon:vr,defaultText:"Search for Properties",placeholder:"https://your-website.com/search",helper:"Link to your home search page"},{key:"call",label:"Call Agent",icon:Ar,defaultText:"Call Me",hrefPrefix:"tel:",placeholder:"+15555551234",helper:"Your phone number"},{key:"email",label:"Email Agent",icon:Vs,defaultText:"Email Me",hrefPrefix:"mailto:",placeholder:"you@email.com",helper:"Your email address"},{key:"schedule",label:"Schedule a Call",icon:yr,defaultText:"Schedule a Call",placeholder:"https://calendly.com/you",helper:"Link to your booking page"},{key:"listings",label:"View My Listings",icon:Or,defaultText:"View My Listings",placeholder:"https://your-website.com/listings",helper:"Link to your listings page"},{key:"valuation",label:"Get Home Value",icon:Zl,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:ka,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:Hl,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:oc,defaultText:"Learn More",placeholder:"https://...",helper:"Any link you want"}];function gZe(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function DVs(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function w_t({html:s,onChange:t}){const{user:n}=ys(),r=N.useRef(null),a=N.useRef(""),i=N.useRef(t);i.current=t;const[l,o]=N.useState("desktop"),c=N.useRef(null),[d,u]=N.useState(!1),[h,p]=N.useState(""),[f,g]=N.useState(""),_=N.useRef(null),v=()=>{var ft;const Pt=(ft=r.current)==null?void 0:ft.contentDocument,Jt=Pt==null?void 0:Pt.getSelection();Jt&&Jt.rangeCount>0&&(Pt!=null&&Pt.body.contains(Jt.anchorNode))&&(_.current=Jt.getRangeAt(0).cloneRange())},j=()=>{var Xt;const Pt=c.current,Jt=(Xt=r.current)==null?void 0:Xt.contentDocument;if(!Pt||!Jt)return;let ft=h.trim();ft&&!/^(https?:|mailto:|tel:|#|\/)/i.test(ft)&&(ft="https://"+ft),Pt.setAttribute("href",ft),Pt.setAttribute("target","_blank");const Vt=f.trim();Vt&&Vt!==(Pt.textContent||"").trim()&&(Pt.textContent=Vt);const Ms=` `+Jt.documentElement.outerHTML;a.current=Ms,i.current(Ms),u(!1)};N.useEffect(()=>{var ft,Vt;const Pt=r.current;if(!Pt||a.current===s)return;const Jt=()=>{const Ms=Pt.contentDocument;if(!Ms)return;Ms.open(),Ms.write(s||""),Ms.close(),a.current=s;const Xt=Ms.body;if(!Xt)return;Xt.setAttribute("contenteditable","true"),Xt.style.outline="none",Xt.style.minHeight="400px",Xt.style.cursor="text";const Js=()=>{const As=` `+Ms.documentElement.outerHTML;a.current=As,i.current(As)};Xt.addEventListener("input",Js),Xt.addEventListener("blur",Js),Xt.addEventListener("mouseup",v),Xt.addEventListener("keyup",v),Ms.addEventListener("selectionchange",v);const Cs=As=>{var Zn;const rn=As.target,tn=rn==null?void 0:rn.closest("a");if(tn){if(As.metaKey||As.ctrlKey||As.shiftKey)return;As.preventDefault(),As.stopPropagation(),c.current=tn,p(tn.getAttribute("href")||""),g((tn.textContent||"").trim()),u(!0);return}const er=Ms.getSelection();if(!er)return;const gn=(Zn=Ms.caretRangeFromPoint)==null?void 0:Zn.call(Ms,As.clientX,As.clientY),In=gn==null?void 0:gn.startContainer;if(In&&In.nodeType===Node.TEXT_NODE){const ea=In.textContent||"",vi=gn.startOffset,Ls=ea.lastIndexOf("[",vi),fi=ea.indexOf("]",vi);if(Ls!==-1&&fi!==-1&&fi>Ls){const Lr=Ms.createRange();Lr.setStart(In,Ls),Lr.setEnd(In,fi+1),er.removeAllRanges(),er.addRange(Lr),_.current=Lr.cloneRange()}}};Xt.addEventListener("click",Cs,!0)};((ft=Pt.contentDocument)==null?void 0:ft.readyState)==="complete"||(Vt=Pt.contentDocument)!=null&&Vt.body?Jt():Pt.addEventListener("load",Jt,{once:!0})},[s]);const b=(Pt,Jt)=>{var Ms;const ft=(Ms=r.current)==null?void 0:Ms.contentDocument;if(!ft)return;ft.body.focus(),ft.execCommand(Pt,!1,Jt);const Vt=` `+ft.documentElement.outerHTML;a.current=Vt,i.current(Vt)},S=()=>{const Pt=window.prompt("Enter URL (https://...)");Pt&&b("createLink",Pt)},A=(Pt,Jt)=>{var Ms;const ft=(Ms=r.current)==null?void 0:Ms.contentDocument;if(!ft)return;if(ft.body.focus(),Jt==="cursor"&&_.current&&ft.body.contains(_.current.startContainer)){const Xt=ft.getSelection();if(Xt){Xt.removeAllRanges(),Xt.addRange(_.current),ft.execCommand("insertHTML",!1,Pt);const Js=` `+ft.documentElement.outerHTML;a.current=Js,i.current(Js);return}}Jt==="top"?ft.body.insertAdjacentHTML("afterbegin",Pt):ft.body.insertAdjacentHTML("beforeend",Pt);const Vt=` `+ft.documentElement.outerHTML;a.current=Vt,i.current(Vt)},[T,L]=N.useState(!1),[D,M]=N.useState(null),[F,z]=N.useState(""),[V,W]=N.useState(""),[Y,K]=N.useState("#406E71"),[J,ne]=N.useState("cursor"),ie=Pt=>{M(Pt),z(Pt.defaultText),W(""),L(!0)},he=()=>{if(!D)return;const Pt=V.trim();if(!D.isForward&&!Pt)return;let Jt=Pt;if(D.isForward){const Xt=Pt||"",Js=encodeURIComponent("You should see this newsletter"),Cs=encodeURIComponent(Xt?`I thought you'd like this — take a look: ${Xt} `:`I thought you'd like this newsletter — take a look! `);Jt=`mailto:?subject=${Js}&body=${Cs}`}else D.hrefPrefix==="tel:"?Jt="tel:"+Pt.replace(/[^0-9+]/g,""):D.hrefPrefix==="mailto:"?Jt="mailto:"+Pt:/^https?:\/\//i.test(Pt)||(Jt="https://"+Pt);const ft=(F||D.defaultText).replace(/[<>]/g,""),Vt=Y||"#406E71",Ms=`
${ft}

 

`;A(Ms,J),L(!1)},[ce,pe]=N.useState(!1),[le,ve]=N.useState(""),[ge,Te]=N.useState(""),[Me,Ce]=N.useState(""),[Ae,De]=N.useState("cursor"),Ie=(()=>{if(ge.trim())return ge.trim();const Pt=gZe(le);return Pt?`https://i.ytimg.com/vi/${Pt}/hqdefault.jpg`:""})(),Fe=()=>{ve(""),Te(""),Ce(""),pe(!0)},qe=()=>{const Pt=le.trim();if(!Pt)return;let Jt=Pt;/^https?:\/\//i.test(Jt)||(Jt="https://"+Jt);const ft=gZe(Jt),Vt=ft?null:DVs(Jt);let Ms=ge.trim();!Ms&&ft&&(Ms=`https://i.ytimg.com/vi/${ft}/hqdefault.jpg`),!Ms&&Vt&&(Ms=`https://vumbnail.com/${Vt}.jpg`),Ms||(Ms="https://placehold.co/600x340/406E71/ffffff?text=Watch+Video");const Xt=(Me||"Watch the video").replace(/[<>]/g,""),Js=`
${Xt}
▶ ${Xt}

 

`.trim();A(Js,Ae),pe(!1)},[be,Ze]=N.useState(!1),[Ne,it]=N.useState(""),[je,Ge]=N.useState(""),[Be,Ye]=N.useState("full"),[We,rt]=N.useState("cursor"),[tt,at]=N.useState(!1),He=N.useRef(null),dt=()=>{it(""),Ge(""),Ye("full"),Ze(!0)},bt=async Pt=>{var Jt;if(!n){ae.error("You must be signed in to upload images");return}if(Pt.size>10*1024*1024){ae.error("Image must be under 10MB");return}at(!0);try{const ft=((Jt=Pt.name.split(".").pop())==null?void 0:Jt.toLowerCase())||"png",Vt=`${n.id}/newsletters/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${ft}`,{error:Ms}=await q.storage.from("email-assets").upload(Vt,Pt,{cacheControl:"3600",upsert:!1,contentType:Pt.type});if(Ms)throw Ms;const{data:Xt}=q.storage.from("email-assets").getPublicUrl(Vt);it(Xt.publicUrl),ae.success("Image uploaded")}catch(ft){ae.error(ft.message||"Upload failed")}finally{at(!1)}},vt=()=>{if(!Ne.trim())return;const Pt=(je||"").replace(/[<>"]/g,""),Jt=Be==="half"?280:560,ft=`
${Pt}

 

`.trim();A(ft,We),Ze(!1)},{data:Bt,isLoading:Zt}=ct({queryKey:["newsletter-editor-videos",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&ce,queryFn:async()=>{const{data:Pt,error:Jt}=await q.from("agent_videos").select("id, title, thumbnail_url, share_token, duration_seconds, created_at").eq("owner_user_id",n.id).eq("is_deleted",!1).eq("status","ready").not("share_token","is",null).order("created_at",{ascending:!1}).limit(50);if(Jt)throw Jt;return Pt||[]}}),Fs=Pt=>{Pt.share_token&&(ve(`https://video.relevelup.com/share/video/${Pt.share_token}`),Te(`https://video.relevelup.com/thumb/${Pt.share_token}`),Ce(Pt.title||"Watch the video"))},Rs=l==="mobile"?390:"100%",ms=l==="mobile"?390:void 0;return e.jsxs("div",{className:"rounded-md border overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b bg-muted/40 px-2 py-1.5 flex-wrap",children:[e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("bold"),title:"Bold",children:e.jsx(KS,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("italic"),title:"Italic",children:e.jsx(JS,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("underline"),title:"Underline",children:e.jsx(_L,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("insertUnorderedList"),title:"Bullet list",children:e.jsx(Tp,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("insertOrderedList"),title:"Numbered list",children:e.jsx(Ov,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:S,title:"Insert link",children:e.jsx(Jo,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("undo"),title:"Undo",children:e.jsx(d4,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("redo"),title:"Redo",children:e.jsx(o4,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs(wc,{children:[e.jsx(jc,{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(oc,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"CTA Button"})]})}),e.jsxs(cc,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(M4,{children:"Insert a call-to-action"}),e.jsx(Zg,{}),LVs.map(Pt=>{const Jt=Pt.icon;return e.jsxs(Qr,{onClick:()=>ie(Pt),children:[e.jsx(Jt,{className:"h-4 w-4 mr-2"}),Pt.label]},Pt.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(nl,{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:Fe,children:[e.jsx(br,{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(FL,{type:"single",value:l,onValueChange:Pt=>Pt&&o(Pt),size:"sm",className:"h-7",children:[e.jsx(QA,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(xb,{className:"h-3.5 w-3.5"})}),e.jsx(QA,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx(ng,{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(oc,{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:Rs,maxWidth:ms,height:480,border:l==="mobile"?"1px solid hsl(var(--border))":"none",borderRadius:l==="mobile"?12:0,boxShadow:l==="mobile"?"0 4px 12px rgba(0,0,0,0.08)":"none"}})}),e.jsx(bs,{open:d,onOpenChange:u,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Edit link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"link-edit-text",children:"Button / link text"}),e.jsx(ye,{id:"link-edit-text",value:f,onChange:Pt=>g(Pt.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:Pt=>p(Pt.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(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:j,disabled:!h.trim(),children:"Save link"})]})]})}),e.jsx(bs,{open:T,onOpenChange:L,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Insert ",(D==null?void 0:D.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:F,onChange:Pt=>z(Pt.target.value),placeholder:D==null?void 0:D.defaultText})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"cta-value",children:D==null?void 0:D.helper}),e.jsx(ye,{id:"cta-value",value:V,onChange:Pt=>W(Pt.target.value),placeholder:D==null?void 0:D.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:Y,onChange:Pt=>K(Pt.target.value),className:"h-9 w-16 p-1 cursor-pointer"}),e.jsx(ye,{value:Y,onChange:Pt=>K(Pt.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Position"}),e.jsxs(cb,{value:J,onValueChange:Pt=>ne(Pt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Rd,{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(oc,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Rd,{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(Ru,{className:"h-3.5 w-3.5"}),"Top of newsletter"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Rd,{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(am,{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:Y,color:"#ffffff",borderRadius:6,padding:"14px 28px",fontFamily:"Arial, sans-serif",fontWeight:600,fontSize:16},children:F||(D==null?void 0:D.defaultText)})})]}),e.jsxs(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>L(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:he,disabled:!(D!=null&&D.isForward)&&!V.trim(),children:"Insert Button"})]})]})}),e.jsx(bs,{open:ce,onOpenChange:pe,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Insert Video Block"})}),e.jsxs(Br,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(Fr,{className:"grid w-full grid-cols-3",children:[e.jsx(Kt,{value:"library",children:"My Library"}),e.jsx(Kt,{value:"url",children:"From URL"}),e.jsx(Kt,{value:"record",children:"Record New"})]}),e.jsxs(is,{value:"library",className:"space-y-3 mt-2",children:[Zt?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:[e.jsx(ts,{className:"h-5 w-5 animate-spin mx-auto mb-2"}),"Loading your videos..."]}):!Bt||Bt.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[e.jsx(br,{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:Bt.map(Pt=>{const Jt=le.includes(Pt.share_token||"___"),ft=Pt.share_token?`https://video.relevelup.com/thumb/${Pt.share_token}`:Pt.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>Fs(Pt),className:`group text-left rounded-md border-2 overflow-hidden transition-all ${Jt?"border-primary ring-2 ring-primary/30":"border-transparent hover:border-primary/40"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[ft?e.jsx("img",{src:ft,alt:Pt.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(br,{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(Al,{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:Pt.title||"Untitled"})})]},Pt.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:Me,onChange:Pt=>Ce(Pt.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(is,{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:le,onChange:Pt=>ve(Pt.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:Me,onChange:Pt=>Ce(Pt.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:ge,onChange:Pt=>Te(Pt.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(is,{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(br,{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(cb,{value:Ae,onValueChange:Pt=>De(Pt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Rd,{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(oc,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Rd,{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(Ru,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Rd,{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(am,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]}),Ie&&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:Ie,alt:"thumbnail",className:"w-full rounded-md",style:{maxHeight:180,objectFit:"cover"},onError:Pt=>{Pt.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(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>pe(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:qe,disabled:!le.trim(),children:"Insert Video"})]})]})}),e.jsx(bs,{open:be,onOpenChange:Ze,children:e.jsxs(vs,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Insert Image"})}),e.jsxs(Br,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(Fr,{className:"grid w-full grid-cols-3",children:[e.jsx(Kt,{value:"library",children:"Library"}),e.jsx(Kt,{value:"upload",children:"Upload"}),e.jsx(Kt,{value:"url",children:"From URL"})]}),e.jsx(is,{value:"library",className:"mt-2",children:e.jsx(__t,{maxHeight:"380px",onSelect:Pt=>{it(Pt.image_url),je||Ge(Pt.title)}})}),e.jsxs(is,{value:"upload",className:"space-y-3 mt-2",children:[e.jsx("input",{ref:He,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:Pt=>{var ft;const Jt=(ft=Pt.target.files)==null?void 0:ft[0];Jt&&bt(Jt),Pt.target.value=""}}),Ne?e.jsxs("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:[e.jsx("img",{src:Ne,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:()=>it(""),children:"Replace"})]})]}):e.jsx("button",{type:"button",onClick:()=>{var Pt;return(Pt=He.current)==null?void 0:Pt.click()},disabled:tt,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:tt?e.jsxs(e.Fragment,{children:[e.jsx(ts,{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(Na,{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(is,{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:Ne,onChange:Pt=>it(Pt.target.value),placeholder:"https://..."})]}),Ne&&/^https?:\/\//i.test(Ne)&&e.jsx("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:e.jsx("img",{src:Ne,alt:"Preview",className:"w-full max-h-48 object-contain",onError:Pt=>{Pt.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:je,onChange:Pt=>Ge(Pt.target.value),placeholder:"Describe the image"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Size"}),e.jsxs(cb,{value:Be,onValueChange:Pt=>Ye(Pt),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Rd,{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(Rd,{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(cb,{value:We,onValueChange:Pt=>rt(Pt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Rd,{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(oc,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Rd,{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(Ru,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Rd,{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(am,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>Ze(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:vt,disabled:!Ne.trim()||tt,children:"Insert Image"})]})]})})]})}const yZe="newsletter-content",RVs="inline-images";function OVs(s,t){const n=atob(s),r=new Array(n.length);for(let a=0;a{const{data:M}=await q.from("team_members").select("team_id, role").eq("user_id",a.id).maybeSingle();return M}}),T=(A==null?void 0:A.role)==="team_leader",L=(A==null?void 0:A.team_id)??null;N.useEffect(()=>{s&&(d((n==null?void 0:n.title)??""),h((n==null?void 0:n.description)??""),f((n==null?void 0:n.html_content)??BVs()),_((n==null?void 0:n.is_template)??!1),j((n==null?void 0:n.share_scope)??"private"))},[s,n]);const D=async()=>{if(a){if(!c.trim()){ae.error("Please enter a title");return}if(!p.trim()){ae.error("Newsletter content is empty");return}S(!0);try{const M=await FVs(p);M!==p&&f(M);const F={user_id:a.id,title:c.trim(),description:u.trim()||null,html_content:M,is_template:g,share_scope:v,shared_team_id:v==="team"?L:null,shared_brokerage_id:v==="brokerage"?o:null};if(v==="team"&&!L){ae.error("You must be a team leader to share with a team"),S(!1);return}if(v==="brokerage"&&!l){ae.error("Only brokerage managers can share to a brokerage"),S(!1);return}if(v==="global"&&!i){ae.error("Only admins can publish global starter templates"),S(!1);return}let z;if(n!=null&&n.id?{error:z}=await q.from("agent_custom_newsletters").update(F).eq("id",n.id):{error:z}=await q.from("agent_custom_newsletters").insert(F),z)throw z;ae.success(n!=null&&n.id?"Saved":"Newsletter created"),r==null||r(),t(!1)}catch(M){ae.error(M.message||"Failed to save")}finally{S(!1)}}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-6xl h-[92vh] flex flex-col p-0",children:[e.jsx(ws,{className:"px-6 pt-6 pb-3 border-b",children:e.jsx(_s,{children:n!=null&&n.id?"Edit Newsletter":"Create Newsletter"})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"acn-title",children:"Title *"}),e.jsx(ye,{id:"acn-title",value:c,onChange:M=>d(M.target.value),placeholder:"e.g. June Market Update"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"acn-desc",children:"Description (optional)"}),e.jsx(ye,{id:"acn-desc",value:u,onChange:M=>h(M.target.value),placeholder:"Short summary"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border bg-muted/30 px-4 py-3",children:[e.jsx(bn,{id:"acn-template",checked:g,onCheckedChange:_}),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(cb,{value:v,onValueChange:M=>j(M),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Rd,{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(Rd,{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(Rd,{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(Rd,{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(w_t,{html:p,onChange:f})]})]}),e.jsxs(Xn,{className:"px-6 py-3 border-t",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsxs(B,{onClick:D,disabled:b,children:[b?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(qo,{className:"h-4 w-4 mr-2"}),n!=null&&n.id?"Save Changes":"Create"]})]})]})})}function BVs(){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}}

`}function bR(){var a;const{user:s}=ys(),{data:t,isLoading:n}=ct({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{var d,u,h,p;const[i,l]=await Promise.all([q.from("mass_email_settings").select("reply_to_email, display_name").eq("user_id",s.id).maybeSingle(),q.from("profiles").select("email, name").eq("id",s.id).maybeSingle()]),o=i.data,c=l.data;return{reply_to_email:((d=o==null?void 0:o.reply_to_email)==null?void 0:d.trim())||((u=c==null?void 0:c.email)==null?void 0:u.trim())||s.email||null,display_name:((h=o==null?void 0:o.display_name)==null?void 0:h.trim())||((p=c==null?void 0:c.name)==null?void 0:p.trim())||null}}});return{isReady:!!((a=t==null?void 0:t.reply_to_email)!=null&&a.trim()),isLoading:n,settings:t}}function C1e(){const{user:s}=ys();return ct({queryKey:["verified-sender-check",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{const[t,n]=await Promise.all([q.from("user_verified_senders").select("id, email, status").eq("user_id",s.id),q.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]),r=t.data||[],a=r.filter(l=>l.status==="verified"),i=r.filter(l=>l.status==="pending");return{hasVerifiedSes:a.length>0,hasPendingSes:i.length>0,hasAnySender:r.length>0,hasGmail:!!n.data,verifiedEmails:a.map(l=>l.email),pendingEmails:i.map(l=>l.email)}}})}function T1e({open:s,onOpenChange:t,hasPending:n,pendingEmails:r}){const a=Mn();return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{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(Gi,{className:"h-5 w-5"})}),e.jsx(_s,{children:"Verify your sending email first"})]}),e.jsx(Qn,{className:"pt-2",children:`Before you can send emails through Amazon, your "from" address needs to be verified so inboxes trust it and it doesn't land in spam.`})]}),n&&r&&r.length>0?e.jsxs("div",{className:"rounded-lg border bg-amber-500/5 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-amber-700",children:[e.jsx(gr,{className:"h-4 w-4"})," Waiting for you to click Amazon's link"]}),r.map(i=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Vs,{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(Xn,{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 _R(){const s=ma();return ct({queryKey:["custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_custom_tags").select("*").eq("owner_user_id",s).order("name");if(n)throw n;return t},enabled:!!s})}function $Vs(s){return ct({queryKey:["contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_custom_tag_assignments").select("*, tag:contact_custom_tags(*)").eq("contact_id",s);if(n)throw n;return t},enabled:!!s})}function pLe(){const s=Ht(),t=ma();return gt({mutationFn:async({name:n,color:r})=>{const{data:a,error:i}=await q.from("contact_custom_tags").insert({owner_user_id:t,name:n.trim(),color:r||"#6366F1"}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]})}})}function UVs(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("contact_custom_tags").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function qVs(){const s=Ht();return gt({mutationFn:async({id:t,name:n,color:r})=>{const a={};n!==void 0&&(a.name=n.trim()),r!==void 0&&(a.color=r);const{error:i}=await q.from("contact_custom_tags").update(a).eq("id",t);if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function j_t(){const s=Ht();return gt({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await q.from("contact_custom_tag_assignments").insert({contact_id:t,tag_id:n});if(r)throw r},onSuccess:(t,{contactId:n})=>{s.invalidateQueries({queryKey:["contact-custom-tags",n]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function VVs(){const s=Ht();return gt({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await q.from("contact_custom_tag_assignments").delete().eq("contact_id",t).eq("tag_id",n);if(r)throw r},onSuccess:(t,{contactId:n})=>{s.invalidateQueries({queryKey:["contact-custom-tags",n]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function E1e(){const s=ma();return ct({queryKey:["all-contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_custom_tag_assignments").select("contact_id, tag_id, tag:contact_custom_tags(id, name, color)");if(n)throw n;return t},enabled:!!s})}function fLe(){const{user:s}=ys();return ct({queryKey:["contact-smart-lists",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_smart_lists").select("*").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function N_t(){const s=Ht(),{user:t}=ys();return gt({mutationFn:async({name:n,filters:r,sort_by:a})=>{const{data:i,error:l}=await q.from("contact_smart_lists").insert({owner_user_id:t.id,name:n,filters:r,sort_by:a}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),Pr({title:"Smart filter saved"})},onError:n=>{Pr({title:"Error saving smart filter",description:n.message,variant:"destructive"})}})}function k_t(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("contact_smart_lists").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),Pr({title:"Smart filter deleted"})}})}const vZe=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function bZe(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={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:(n==null?void 0:n.name)||"",agent_email:(n==null?void 0:n.email)||"",agent_phone:(n==null?void 0:n.phone)||"",agent_title:(n==null?void 0:n.title)||"",brokerage:r||"",current_date:l,current_year:o};return s.replace(/\{\{\s*(\w+)\s*\}\}/g,(d,u)=>c[u]??`{{${u}}}`)}function HVs(s,t,n,r){const a=t.trim()?`
${vZe(t).replace(/\n/g,"
")}
`:"",i=n.trim()?`
${vZe(n).replace(/\n/g,"
")}
`:"",l=r?`
${r}
`:"";return`${a} ${s} ${i} ${l}`}function GVs(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 WVs=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function KVs(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=WVs.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 xLe({open:s,onOpenChange:t,newsletterId:n,newsletterTitle:r,htmlCode:a}){const{user:i}=ys();Oh();const{isReady:l,settings:o}=bR(),{data:c}=C1e(),[d,u]=N.useState(!1),h=ma(),{data:p}=ct({queryKey:["agent-profile-for-newsletter-send",i==null?void 0:i.id],enabled:!!i&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!i)return null;const{data:js}=await q.from("profiles").select("name, email, phone, avatar_url, title, email_signature, use_email_signature").eq("id",i.id).maybeSingle();return js}}),[f,g]=N.useState("visual"),[_,v]=N.useState("all"),[j,b]=N.useState(""),[S,A]=N.useState(""),[T,L]=N.useState(""),[D,M]=N.useState(""),[F,z]=N.useState(!0),[V,W]=N.useState([]),[Y,K]=N.useState(null),[J,ne]=N.useState(new Set),[ie,he]=N.useState(""),[ce,pe]=N.useState(!1),[le,ve]=N.useState(!1),[ge,Te]=N.useState(!1),[Me,Ce]=N.useState({sent:0,failed:0,total:0,currentName:""}),[Ae,De]=N.useState(!0),[Ie,Fe]=N.useState(!1),[qe,be]=N.useState([]),[Ze,Ne]=N.useState(!1),[it,je]=N.useState(new Set),[Ge,Be]=N.useState("now"),[Ye,We]=N.useState(""),{data:rt=[]}=_R(),{data:tt=[]}=E1e(),{data:at=[]}=fLe(),{data:He=[],isLoading:dt}=ct({queryKey:["newsletter-send-contacts",h],enabled:!!h&&s,queryFn:async()=>{const js=[];let Dn=0;const wr=1e3;for(;;){const{data:$r,error:ss}=await q.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(Dn,Dn+wr-1);if(ss)throw ss;if(!$r||$r.length===0||(js.push(...$r),$r.length{const{data:js}=await q.from("ses_suppressed_emails").select("email");return(js||[]).map(Dn=>Dn.email.toLowerCase())}}),{data:vt}=ct({queryKey:["newsletter-brokerage-info",i==null?void 0:i.id],enabled:!!i&&s,staleTime:10*60*1e3,queryFn:async()=>{if(!i)return null;const{data:js}=await q.from("profiles").select("brokerage_id").eq("id",i.id).maybeSingle();if(!(js!=null&&js.brokerage_id))return null;const{data:Dn}=await q.from("brokerages").select("name, city, state").eq("id",js.brokerage_id).maybeSingle();return Dn}}),{data:Bt}=ct({queryKey:["newsletter-active-lead-site",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!h)return null;const{data:js}=await q.from("lead_sites").select("id, subdomain_slug, mls_provider_id, mls_agent_id, mls_agent_key, is_active").eq("agent_id",h).eq("is_active",!0).not("mls_provider_id","is",null).order("created_at",{ascending:!0}).limit(1).maybeSingle();return js}}),Zt=!!(Bt!=null&&Bt.mls_provider_id),Fs=(Bt==null?void 0:Bt.mls_agent_id)||(Bt==null?void 0:Bt.mls_agent_key)||null,{data:Rs=[],isLoading:ms}=ct({queryKey:["newsletter-agent-listings",h,Fs],enabled:!!h&&!!Fs&&Ze,staleTime:60*1e3,queryFn:async()=>{if(!Fs)return[];const{data:js}=await q.from("mlsgrid_listings").select("listing_key, address, city, state, list_price, bedrooms, bathrooms_total, living_area, photos, standard_status, modification_timestamp").eq("list_agent_mls_id",Fs).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return js||[]}}),{data:Pt=[],isLoading:Jt}=ct({queryKey:["newsletter-exchange-listings",h],enabled:!!h&&Ze,staleTime:60*1e3,queryFn:async()=>{const{data:js}=await q.from("listings").select("id, slug, property_address, city, state, price, bedrooms, bathrooms, square_footage, status, created_at").eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]).order("created_at",{ascending:!1}).limit(30),Dn=js||[];if(Dn.length===0)return[];const wr=Dn.map(Xe=>Xe.id),{data:$r}=await q.from("listing_photos").select("listing_id, photo_url, is_primary, sort_order").in("listing_id",wr),ss=new Map,Oe=new Map;for(const Xe of $r||[])Xe.is_primary&&!ss.has(Xe.listing_id)&&ss.set(Xe.listing_id,Xe.photo_url),Oe.has(Xe.listing_id)||Oe.set(Xe.listing_id,Xe.photo_url);return Dn.map(Xe=>({...Xe,_photo:ss.get(Xe.id)||Oe.get(Xe.id)||""}))}}),{data:ft=!1}=ct({queryKey:["newsletter-exchange-listings-exists",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{const{count:js}=await q.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]);return(js||0)>0}}),Vt=N.useMemo(()=>{const js=new Set(bt);return He.filter(Dn=>Dn.email&&Dn.email.includes("@")&&!js.has(Dn.email.toLowerCase()))},[He,bt]),Ms=N.useMemo(()=>{if(V.length===0)return null;const js=new Set;for(const Dn of tt)V.includes(Dn.tag_id)&&js.add(Dn.contact_id);return js},[tt,V]),Xt=N.useMemo(()=>at.find(js=>js.id===Y)||null,[at,Y]),Js=N.useMemo(()=>{var js;if(_==="all")return Vt;if(_==="tags")return Ms?Vt.filter(Dn=>Ms.has(Dn.id)):[];if(_==="smartlists"){if(!Xt)return[];const Dn=(((js=Xt.filters)==null?void 0:js.search)||"").toLowerCase().trim();return Dn?Vt.filter(wr=>`${wr.first_name||""} ${wr.last_name||""}`.toLowerCase().includes(Dn)||(wr.email||"").toLowerCase().includes(Dn)):Vt}return Vt.filter(Dn=>J.has(Dn.id))},[_,Vt,Ms,Xt,J]),Cs=N.useMemo(()=>{if(!ie.trim())return Vt;const js=ie.toLowerCase();return Vt.filter(Dn=>`${Dn.first_name||""} ${Dn.last_name||""}`.toLowerCase().includes(js))},[Vt,ie]);N.useEffect(()=>{s&&(b(""),A(`Hi {{first_name}}, Sharing this month's update — hope you find something useful!`),L(`As always, reach out anytime if I can help. Talk soon!`),M(a||""),g("light"),v("all"),W([]),K(null),ne(new Set),he(""),pe(!1),z(!0),De(!0),be([]),Be("now"),We(""),Ce({sent:0,failed:0,total:0,currentName:""}))},[s,r,a]);const As=l,rn=!!(j.trim()&&As&&Js.length>0&&!le),tn=js=>{const Dn=f==="advanced"||f==="visual"?D:a,wr=F&&(p!=null&&p.email_signature)?p.email_signature:null;let $r;return f==="light"?$r=HVs(Dn,S,T,wr):$r=wr?`${Dn}
${wr}
`:Dn,Ae&&($r+=GVs(p??null,vt??null,js.email)),bZe($r,js,p??null,(vt==null?void 0:vt.name)??null)},er=N.useMemo(()=>tn({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[f,S,T,D,a,F,p,Ae,vt]),gn=N.useMemo(()=>KVs(j,f==="advanced"||f==="visual"?D:a),[j,f,D,a]),In=async()=>{Fe(!0),be([]);try{const js=f==="advanced"||f==="visual"?D:a,{data:Dn,error:wr}=await q.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:r,bodyHtml:js,currentSubject:j}});if(wr)throw wr;const $r=Dn==null?void 0:Dn.subjects;if(!Array.isArray($r)||$r.length===0)throw new Error("No subjects returned");be($r)}catch(js){const Dn=(js==null?void 0:js.message)||"Failed to generate subjects";Dn.includes("credits exhausted")||Dn.includes("402")?ae.error("AI credits exhausted. Please add credits to your workspace."):Dn.includes("Rate limit")||Dn.includes("429")?ae.error("Rate limit hit — try again in a moment."):ae.error(Dn)}finally{Fe(!1)}},Zn=js=>js?"$"+Number(js).toLocaleString("en-US"):"",ea=()=>{var Oe,Xe;if(it.size===0){ae.error("Pick at least one listing first.");return}const js=(Bt==null?void 0:Bt.subdomain_slug)||"",Dn=js?`https://${js}.relevelup.com`:"https://relevelup.com",wr=[];for(const ot of Rs){const Nt=`mls:${ot.listing_key}`;if(!it.has(Nt))continue;const Rt=Array.isArray(ot.photos)&&ot.photos.length>0?typeof ot.photos[0]=="string"?ot.photos[0]:((Oe=ot.photos[0])==null?void 0:Oe.MediaURL)||((Xe=ot.photos[0])==null?void 0:Xe.url)||"":"",qt=ot.bedrooms?`${ot.bedrooms} bd`:"",xs=ot.bathrooms_total?`${ot.bathrooms_total} ba`:"",rs=ot.living_area?`${Number(ot.living_area).toLocaleString()} sqft`:"";wr.push({url:`${Dn}/listings/${ot.listing_key}`,photo:Rt,price:Zn(ot.list_price),addr:`${ot.address||""}${ot.city?", "+ot.city:""}`,stats:[qt,xs,rs].filter(Boolean).join(" • ")})}for(const ot of Pt){const Nt=`ex:${ot.id}`;if(!it.has(Nt))continue;const Rt=ot.bedrooms?`${ot.bedrooms} bd`:"",qt=ot.bathrooms?`${ot.bathrooms} ba`:"",xs=ot.square_footage?`${Number(ot.square_footage).toLocaleString()} sqft`:"";wr.push({url:`https://listings.relevelup.com/${ot.slug||ot.id}`,photo:ot._photo||"",price:Zn(ot.price),addr:`${ot.property_address||""}${ot.city?", "+ot.city:""}`,stats:[Rt,qt,xs].filter(Boolean).join(" • ")})}const ss=`

Featured Listings

${wr.map(ot=>`
${ot.photo?`${ot.addr}`:""}
${ot.price}
${ot.addr}
${ot.stats}
`.trim()).join(` `)}
`.trim();M(ot=>(ot||a||"")+` `+ss),g("visual"),je(new Set),Ne(!1),ae.success(`Added ${wr.length} listing${wr.length===1?"":"s"} to your newsletter.`)},vi=()=>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}}"),Ls=()=>bZe(j,{first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"},p??null,(vt==null?void 0:vt.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}}"),fi=()=>{if(rn){if(Ge==="later"){if(!Ye){ae.error("Pick a date and time to schedule.");return}const js=new Date(Ye).getTime();if(Number.isNaN(js)||js{if(!(!rn||!i)){Te(!1),ve(!0),Ce({sent:0,failed:0,total:Js.length,currentName:"Preparing campaign…"});try{const Dn=`${((o==null?void 0:o.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,wr=vi(),$r=Ls(),ss=Ge==="later",{data:Oe,error:Xe}=await q.from("email_campaigns").insert({user_id:h||i.id,name:`Newsletter: ${r}`,subject:$r,body_html:wr,from_email:Dn,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:Js.length,status:ss?"scheduled":"draft",scheduled_at:ss?new Date(Ye).toISOString():null}).select("id").single();if(Xe)throw Xe;Ce(Nt=>({...Nt,currentName:"Adding recipients…"}));const ot=Js.map(Nt=>({campaign_id:Oe.id,contact_id:Nt.id,email:Nt.email,name:[Nt.first_name,Nt.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let Nt=0;Nt({...xs,sent:Math.min(Nt+Rt.length,ot.length)}))}if(ss){const{error:Nt}=await q.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:Oe.id}});if(Nt)throw Nt;ae.success(`Newsletter scheduled for ${new Date(Ye).toLocaleString()}.`)}else{const{error:Nt}=await q.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:Oe.id}});if(Nt)throw Nt;ae.success(`Sending to ${Js.length} contact${Js.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(js){console.error("Newsletter send failed:",js),ae.error(`Failed to send: ${js.message||"Unknown error"}`)}finally{ve(!1)}}},Jn=js=>{ne(Dn=>{const wr=new Set(Dn);return wr.has(js)?wr.delete(js):wr.add(js),wr})};return e.jsxs(bs,{open:s,onOpenChange:js=>!le&&t(js),children:[e.jsxs(vs,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(cr,{className:"h-5 w-5"})," Send Newsletter"]})}),!As&&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(Gi,{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:In,disabled:Ie,title:"Generate subject lines with AI",children:[Ie?e.jsx(ts,{className:"h-3 w-3 animate-spin"}):e.jsx(un,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(ye,{value:j,onChange:js=>b(js.target.value),placeholder:"Newsletter subject"}),qe.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:"}),qe.map((js,Dn)=>e.jsxs("button",{type:"button",onClick:()=>{b(js),be([])},className:"w-full text-left text-sm px-2 py-1.5 rounded hover:bg-primary/10 transition-colors",children:[e.jsx(un,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),js]},Dn))]}),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}}"})]})]}),gn.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(gL,{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:gn.map((js,Dn)=>e.jsx("li",{children:js},Dn))})]}),(Zt||ft)&&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(Or,{className:"h-3.5 w-3.5 text-primary"}),"Insert your active listings"]}),e.jsx("p",{className:"text-muted-foreground mt-0.5",children:Zt&&ft?"Pick from your live MLS listings or your Listing Exchange listings.":Zt?"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:()=>Ne(!0),children:"Choose listings"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Editing"}),e.jsxs(Br,{value:f,onValueChange:js=>g(js),children:[e.jsxs(Fr,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Kt,{value:"visual",children:[e.jsx(Dm,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Kt,{value:"light",children:[e.jsx(Nr,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(Kt,{value:"advanced",children:[e.jsx(C2,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(is,{value:"visual",className:"mt-3",children:e.jsx(w_t,{html:D,onChange:M})}),e.jsxs(is,{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(Es,{value:S,onChange:js=>A(js.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(Es,{value:T,onChange:js=>L(js.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(is,{value:"advanced",className:"mt-3",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Edit full HTML"}),e.jsx(Es,{value:D,onChange:js=>M(js.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:p!=null&&p.email_signature?"Will append the signature from your profile.":"No signature set. Add one in Profile → Email Signature."})]}),e.jsx(bn,{checked:F&&!!(p!=null&&p.email_signature),disabled:!(p!=null&&p.email_signature),onCheckedChange:z})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Include unsubscribe footer"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds your brokerage info and a one-click unsubscribe link. Strongly recommended for deliverability."})]}),e.jsx(bn,{checked:Ae,onCheckedChange:De})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Recipients"}),e.jsxs(Br,{value:_,onValueChange:js=>v(js),children:[e.jsxs(Fr,{className:"grid grid-cols-4 w-full",children:[e.jsxs(Kt,{value:"all",children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(Kt,{value:"tags",children:[e.jsx(uh,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(Kt,{value:"smartlists",children:[e.jsx(c9,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(Kt,{value:"individual",children:[e.jsx(Xi,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(is,{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:Vt.length})," contact",Vt.length===1?"":"s"," with a valid, non-suppressed email."]})}),e.jsxs(is,{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(hi,{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 tags yet. Add tags to contacts to use this option."}):rt.map(js=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(ui,{checked:V.includes(js.id),onCheckedChange:Dn=>W(wr=>Dn?[...wr,js.id]:wr.filter($r=>$r!==js.id))}),e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:js.color||"#406E71"}}),e.jsx("span",{className:"text-sm",children:js.name})]},js.id))})]}),e.jsxs(is,{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(hi,{className:"h-40 rounded-lg border p-2",children:at.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No smart lists yet. Save one from the contacts page."}):at.map(js=>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:Y===js.id,onChange:()=>K(js.id)}),e.jsx("span",{className:"text-sm",children:js.name})]},js.id))})]}),e.jsxs(is,{value:"individual",className:"mt-3 space-y-2",children:[e.jsx(ye,{placeholder:"Search contacts...",value:ie,onChange:js=>he(js.target.value)}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[J.size," selected"]}),e.jsx("button",{type:"button",className:"underline",onClick:()=>ne(new Set),children:"Clear"})]}),e.jsxs(hi,{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&&Cs.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),Cs.slice(0,200).map(js=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(ui,{checked:J.has(js.id),onCheckedChange:()=>Jn(js.id)}),e.jsxs("div",{className:"text-sm flex-1 min-w-0",children:[e.jsxs("div",{className:"truncate",children:[js.first_name," ",js.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:js.email})]})]},js.id)),Cs.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(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(xr,{className:"h-3 w-3"})," ",Js.length," recipient",Js.length===1?"":"s"]}),As&&e.jsxs(ze,{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:()=>pe(js=>!js),children:ce?e.jsxs(e.Fragment,{children:[e.jsx(xf,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(Er,{className:"h-3 w-3 mr-1"}),"Show"]})})]}),ce?e.jsx("div",{className:"rounded-lg border overflow-hidden bg-white",children:e.jsx("iframe",{title:"newsletter-preview",srcDoc:er,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)."]})]})]}),le&&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(ts,{className:"h-4 w-4 animate-spin"}),"Sending to ",Me.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[Me.sent+Me.failed," / ",Me.total]})]}),e.jsx(pi,{value:Me.total?(Me.sent+Me.failed)/Me.total*100:0}),Me.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[Me.failed," failed"]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(gr,{className:"h-4 w-4"})," When to send"]}),e.jsxs(cb,{value:Ge,onValueChange:js=>Be(js),className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Rd,{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(Rd,{value:"later",id:"send-later"}),e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(om,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),Ge==="later"&&e.jsx(ye,{type:"datetime-local",value:Ye,onChange:js=>We(js.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:"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:le,children:"Cancel"}),e.jsx(B,{onClick:fi,disabled:!rn,children:le?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):Ge==="later"?e.jsxs(e.Fragment,{children:[e.jsx(om,{className:"h-4 w-4 mr-1"}),"Schedule for ",Js.length]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Send to ",Js.length]})})]})]})]})]}),e.jsx(Oo,{open:ge,onOpenChange:Te,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:Ge==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(Mo,{children:[Ge==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',j,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[Js.length," contact",Js.length===1?"":"s"]}),Ge==="later"&&Ye?` for ${new Date(Ye).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:Lr,children:Ge==="later"?e.jsxs(e.Fragment,{children:[e.jsx(om,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Send to ",Js.length]})})]})]})}),e.jsx(bs,{open:Ze,onOpenChange:Ne,children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Or,{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."}),(ms||Jt)&&e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center",children:[e.jsx(ts,{className:"h-4 w-4 animate-spin inline-block mr-2"}),"Loading your listings…"]}),!ms&&!Jt&&Rs.length===0&&Pt.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."}),Rs.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:Rs.map(js=>{var ss,Oe;const Dn=`mls:${js.listing_key}`,wr=it.has(Dn),$r=Array.isArray(js.photos)&&js.photos.length>0?typeof js.photos[0]=="string"?js.photos[0]:((ss=js.photos[0])==null?void 0:ss.MediaURL)||((Oe=js.photos[0])==null?void 0:Oe.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{je(Xe=>{const ot=new Set(Xe);return ot.has(Dn)?ot.delete(Dn):ot.size<6?ot.add(Dn):ae.error("Max 6 listings per newsletter"),ot})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${wr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[$r&&e.jsx("img",{src:$r,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:js.list_price?`$${Number(js.list_price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:js.address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[js.city,js.state?`, ${js.state}`:""]})]}),wr&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(xr,{className:"h-4 w-4"})})]},Dn)})})]}),Pt.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:Pt.map(js=>{const Dn=`ex:${js.id}`,wr=it.has(Dn);return e.jsxs("button",{type:"button",onClick:()=>{je($r=>{const ss=new Set($r);return ss.has(Dn)?ss.delete(Dn):ss.size<6?ss.add(Dn):ae.error("Max 6 listings per newsletter"),ss})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${wr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[js._photo&&e.jsx("img",{src:js._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:js.price?`$${Number(js.price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:js.property_address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[js.city,js.state?`, ${js.state}`:""]})]}),wr&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(xr,{className:"h-4 w-4"})})]},Dn)})})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Ne(!1),children:"Cancel"}),e.jsxs(B,{onClick:ea,disabled:it.size===0,children:["Insert ",it.size>0?it.size:""," listing",it.size===1?"":"s"]})]})]})}),e.jsx(T1e,{open:d,onOpenChange:u,hasPending:!!(c!=null&&c.hasPendingSes),pendingEmails:c==null?void 0:c.pendingEmails})]})}function YVs(){const{user:s}=ys(),t=Ht(),[n,r]=N.useState("starters"),[a,i]=N.useState(!1),[l,o]=N.useState(null),[c,d]=N.useState(null),[u,h]=N.useState(null),{data:p,isLoading:f}=ct({queryKey:["agent-custom-newsletters",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:D,error:M}=await q.from("agent_custom_newsletters").select("*").order("updated_at",{ascending:!1});if(M)throw M;return D||[]}}),g=()=>t.invalidateQueries({queryKey:["agent-custom-newsletters"]}),_=(p==null?void 0:p.filter(D=>D.user_id===(s==null?void 0:s.id)&&!D.is_template))??[],v=(p==null?void 0:p.filter(D=>D.user_id===(s==null?void 0:s.id)&&D.is_template))??[],j=(p==null?void 0:p.filter(D=>D.user_id!==(s==null?void 0:s.id)&&D.is_template&&(D.share_scope==="team"||D.share_scope==="brokerage"||D.share_scope==="global")))??[],b=(p==null?void 0:p.filter(D=>D.share_scope==="global"&&D.is_template))??[],S=n==="starters"?b:n==="mine"?_:n==="templates"?v:j.filter(D=>D.share_scope!=="global"),A=async D=>{if(!s)return;const{error:M}=await q.from("agent_custom_newsletters").insert({user_id:s.id,title:`${D.title} (Copy)`,description:D.description,html_content:D.html_content,is_template:!1,share_scope:"private"});if(M){ae.error(M.message);return}ae.success('Duplicated to "My Newsletters"'),g(),r("mine")},T=async D=>{const{error:M}=await q.from("agent_custom_newsletters").delete().eq("id",D);if(M){ae.error(M.message);return}ae.success("Deleted"),h(null),g()},L=D=>D.share_scope==="global"?e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(un,{className:"h-3 w-3"}),"Starter"]}):D.share_scope==="brokerage"?e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Va,{className:"h-3 w-3"}),"Brokerage"]}):D.share_scope==="team"?e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"}),"Team"]}):e.jsxs(ze,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Kc,{className:"h-3 w-3"}),"Private"]});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{variant:n==="starters"?"default":"outline",size:"sm",onClick:()=>r("starters"),className:"gap-1.5",children:[e.jsx(un,{className:"h-3.5 w-3.5"}),"Starter Templates (",b.length,")"]}),e.jsxs(B,{variant:n==="mine"?"default":"outline",size:"sm",onClick:()=>r("mine"),children:["My Newsletters (",_.length,")"]}),e.jsxs(B,{variant:n==="templates"?"default":"outline",size:"sm",onClick:()=>r("templates"),children:["My Templates (",v.length,")"]}),e.jsxs(B,{variant:n==="shared"?"default":"outline",size:"sm",onClick:()=>r("shared"),children:["Shared with Me (",j.filter(D=>D.share_scope!=="global").length,")"]})]}),e.jsxs(B,{onClick:()=>{o(null),i(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Create Newsletter"]})]}),f&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((D,M)=>e.jsx(Ws,{className:"h-48 w-full"},M))}),n==="starters"&&!f&&e.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/5 px-4 py-3 text-sm flex items-start gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("span",{children:["Click ",e.jsx("strong",{children:"Use"}),' on any starter to copy it into your "My Newsletters" — then edit, send, or save as your own template.']})]}),!f&&S.length===0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Nr,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),n==="starters"&&e.jsx("p",{children:"No starter templates available yet."}),n==="mine"&&e.jsx("p",{children:`You haven't created any newsletters yet. Try a Starter Template or click "Create Newsletter"!`}),n==="templates"&&e.jsx("p",{children:`You haven't saved any templates yet. Toggle "Save as reusable template" when creating a newsletter.`}),n==="shared"&&e.jsx("p",{children:"No team or brokerage templates have been shared with you yet."})]})}),!f&&S.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:S.map(D=>{const M=D.user_id===(s==null?void 0:s.id);return e.jsxs(fe,{className:"overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"aspect-[3/2] bg-muted relative overflow-hidden",children:[D.thumbnail_url?e.jsx("img",{src:D.thumbnail_url,alt:D.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:`
${D.html_content}
`}}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[D.is_template&&e.jsx(ze,{className:"bg-primary/90",children:"Template"}),L(D)]})]}),e.jsxs(Ee,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:D.title}),D.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:D.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Updated ",Ss(new Date(D.updated_at||D.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsxs(B,{size:"sm",onClick:()=>d(D),className:"flex-1 min-w-[80px]",children:[e.jsx(cr,{className:"h-3.5 w-3.5 mr-1"})," Send"]}),M?e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{o(D),i(!0)},children:e.jsx(_a,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>A(D),children:e.jsx(Xr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>h(D.id),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]}):e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>A(D),children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},D.id)})}),e.jsx(zVs,{open:a,onOpenChange:i,initial:l,onSaved:g}),c&&e.jsx(xLe,{open:!!c,onOpenChange:D=>!D&&d(null),newsletterId:c.id,newsletterTitle:c.title,htmlCode:c.html_content}),e.jsx(Oo,{open:!!u,onOpenChange:D=>!D&&h(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete this newsletter?"}),e.jsx(Mo,{children:"This cannot be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>u&&T(u),children:"Delete"})]})]})})]})}function ZVs(){const s=Mn(),[t,n]=N.useState(""),[r,a]=N.useState("grid"),[i,l]=N.useState(null),{data:o,isLoading:c}=ct({queryKey:["newsletters"],queryFn:async()=>{const{data:T,error:L}=await q.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(L)throw L;return T}}),{data:d}=ct({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:T}=await q.from("newsletter_likes").select("newsletter_id");return T||[]}}),{data:u}=ct({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:T}=await q.from("newsletter_comments").select("newsletter_id");return T||[]}}),{data:h}=ct({queryKey:["newsletter-resource-counts"],queryFn:async()=>{const[T,L,D,M]=await Promise.all([q.from("newsletter_canva_links").select("newsletter_id"),q.from("newsletter_pdfs").select("newsletter_id"),q.from("newsletter_videos").select("newsletter_id"),q.from("newsletter_drive_links").select("newsletter_id")]);return{canva:T.data||[],pdfs:L.data||[],videos:D.data||[],drives:M.data||[]}}}),p=T=>(d==null?void 0:d.filter(L=>L.newsletter_id===T).length)||0,f=T=>(u==null?void 0:u.filter(L=>L.newsletter_id===T).length)||0,g=T=>{var L;return((L=h==null?void 0:h.canva)==null?void 0:L.filter(D=>D.newsletter_id===T).length)||0},_=T=>{var L;return((L=h==null?void 0:h.pdfs)==null?void 0:L.filter(D=>D.newsletter_id===T).length)||0},v=T=>{var L;return((L=h==null?void 0:h.videos)==null?void 0:L.filter(D=>D.newsletter_id===T).length)||0},j=T=>{var L;return((L=h==null?void 0:h.drives)==null?void 0:L.filter(D=>D.newsletter_id===T).length)||0},b=T=>g(T)+_(T)+v(T)+j(T),S=o==null?void 0:o.filter(T=>{var L;return T.title.toLowerCase().includes(t.toLowerCase())||((L=T.description)==null?void 0:L.toLowerCase().includes(t.toLowerCase()))}),A=T=>{s(`/newsletters/${T}`)};return e.jsx(Ts,{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(Br,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(Fr,{children:[e.jsx(Kt,{value:"custom",children:"Build & Send"}),e.jsx(Kt,{value:"curated",children:"Curated Monthly"})]}),e.jsx(is,{value:"custom",className:"mt-2",children:e.jsx(YVs,{})}),e.jsxs(is,{value:"curated",className:"space-y-6 mt-2",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(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(yf,{className:"h-4 w-4"})}),e.jsx(B,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(Tp,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[(S==null?void 0:S.length)||0," item",(S==null?void 0:S.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,L)=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-0",children:[e.jsx(Ws,{className:"aspect-[3/2] w-full"}),e.jsxs("div",{className:"p-4 space-y-2",children:[e.jsx(Ws,{className:"h-5 w-3/4"}),e.jsx(Ws,{className:"h-4 w-full"})]})]})},L))}),!c&&(S==null?void 0:S.length)===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Nr,{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&&S&&S.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:S.map(T=>{const L=b(T.id),D=g(T.id),M=_(T.id),F=v(T.id);return r==="grid"?e.jsxs(fe,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer border-border/50",onClick:()=>A(T.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:T.preview_image_url?e.jsx("img",{src:T.preview_image_url,alt:T.title,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(Nr,{className:"h-16 w-16"})})}),e.jsxs(Ee,{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(yr,{className:"h-3 w-3"}),Ss(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,"")}),L>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[D>0&&e.jsxs(ze,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(fl,{className:"h-3 w-3"})," ",D," Template",D>1?"s":""]}),M>0&&e.jsxs(ze,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Pa,{className:"h-3 w-3"})," ",M," PDF",M>1?"s":""]}),F>0&&e.jsxs(ze,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Al,{className:"h-3 w-3"})," ",F," Video",F>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(Vm,{className:"h-3 w-3"})," ",p(T.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3 w-3"})," ",f(T.id)]})]}),T.html_code&&e.jsxs(B,{size:"sm",className:"w-full bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:z=>{z.stopPropagation(),l(T)},children:[e.jsx(cr,{className:"h-4 w-4 mr-1.5"}),"Send Newsletter"]})]})]},T.id):e.jsx(fe,{className:"group overflow-hidden hover:shadow-md transition-all duration-200 cursor-pointer border-border/50",onClick:()=>A(T.id),children:e.jsxs("div",{className:"flex flex-row",children:[e.jsx("div",{className:"relative overflow-hidden bg-muted w-40 sm:w-48 shrink-0",children:T.preview_image_url?e.jsx("img",{src:T.preview_image_url,alt:T.title,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground min-h-[100px]",children:e.jsx(Nr,{className:"h-10 w-10"})})}),e.jsxs(Ee,{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(yr,{className:"h-3 w-3"}),Ss(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:[L>0&&e.jsxs("span",{children:[L," resource",L>1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vm,{className:"h-3 w-3"})," ",p(T.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3 w-3"})," ",f(T.id)]})]})]}),T.html_code&&e.jsx("div",{className:"p-3 flex items-center shrink-0",children:e.jsxs(B,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:z=>{z.stopPropagation(),l(T)},children:[e.jsx(cr,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},T.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(xLe,{open:!!i,onOpenChange:T=>!T&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function QVs({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(fe,{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(Ee,{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 XVs(){const{id:s}=bi(),t=Mn(),{user:n}=ys(),{toast:r}=Ba(),a=Ht(),{trackEngagement:i}=KD(),[l,o]=N.useState(""),[c,d]=N.useState(!1),{data:u,isLoading:h}=ct({queryKey:["newsletter",s],queryFn:async()=>{const{data:D,error:M}=await q.from("newsletter_content").select("*").eq("id",s).single();if(M)throw M;return D},enabled:!!s});N.useEffect(()=>{u&&i("newsletter",u.id,u.title,"view")},[u==null?void 0:u.id]);const{data:p}=ct({queryKey:["newsletter-drives",s],queryFn:async()=>{const{data:D}=await q.from("newsletter_drive_links").select("*").eq("newsletter_id",s).order("sort_order");return D||[]},enabled:!!s}),{data:f}=ct({queryKey:["newsletter-pdfs",s],queryFn:async()=>{const{data:D}=await q.from("newsletter_pdfs").select("*").eq("newsletter_id",s).order("sort_order");return D||[]},enabled:!!s}),{data:g}=ct({queryKey:["newsletter-videos",s],queryFn:async()=>{const{data:D}=await q.from("newsletter_videos").select("*").eq("newsletter_id",s).order("sort_order");return D||[]},enabled:!!s}),{data:_}=ct({queryKey:["newsletter-canva-links",s],queryFn:async()=>{const{data:D}=await q.from("newsletter_canva_links").select("*").eq("newsletter_id",s).order("sort_order");return D||[]},enabled:!!s}),{data:v}=ct({queryKey:["newsletter-likes",s],queryFn:async()=>{const{data:D}=await q.from("newsletter_likes").select("*").eq("newsletter_id",s);return D||[]},enabled:!!s}),{data:j}=ct({queryKey:["newsletter-comments",s],queryFn:async()=>{const{data:D}=await q.from("newsletter_comments").select("*, profiles:user_id(name)").eq("newsletter_id",s).order("created_at",{ascending:!1});return D||[]},enabled:!!s}),b=v==null?void 0:v.some(D=>D.user_id===(n==null?void 0:n.id)),S=gt({mutationFn:async()=>{b?await q.from("newsletter_likes").delete().eq("newsletter_id",s).eq("user_id",n==null?void 0:n.id):await q.from("newsletter_likes").insert({newsletter_id:s,user_id:n==null?void 0:n.id})},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-likes",s]})}}),A=gt({mutationFn:async D=>{const{error:M}=await q.from("newsletter_comments").insert({newsletter_id:s,user_id:n==null?void 0:n.id,content:D});if(M)throw M},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),o(""),r({title:"Comment added"})}}),T=gt({mutationFn:async D=>{const{error:M}=await q.from("newsletter_comments").delete().eq("id",D);if(M)throw M},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),r({title:"Comment deleted"})}}),L=D=>{if(D.includes("player.mediadelivery.net")||D.includes("iframe.mediadelivery.net")){const M=D.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(M)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://iframe.mediadelivery.net/embed/${M[1]}/${M[2]}?autoplay=false`,className:"absolute inset-0 w-full h-full rounded-lg",allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})})}if(D.includes("youtube.com")||D.includes("youtu.be")){const M=D.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([^&\s]+)/);if(M)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://www.youtube.com/embed/${M[1]}`,className:"absolute inset-0 w-full h-full rounded-lg",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}return e.jsxs("a",{href:D,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Al,{className:"h-4 w-4"})," Watch Video"]})};return h?e.jsx(Ts,{title:"",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-8 w-32"}),e.jsx(Ws,{className:"h-64 w-full"}),e.jsx(Ws,{className:"h-32 w-full"})]})}):u?e.jsx(Ts,{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(Hr,{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:Ss(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(QVs,{rows:u.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(XD,{resourceType:"newsletter",resourceId:u.id,resourceTitle:u.title}),e.jsxs(B,{variant:b?"default":"outline",size:"sm",onClick:()=>S.mutate(),children:[e.jsx(gi,{className:`h-4 w-4 mr-1 ${b?"fill-current":""}`}),(v==null?void 0:v.length)||0," ",(v==null?void 0:v.length)===1?"Like":"Likes"]}),u.html_code&&e.jsxs(B,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:()=>d(!0),children:[e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),u.html_code&&e.jsx(xLe,{open:c,onOpenChange:d,newsletterId:u.id,newsletterTitle:u.title,htmlCode:u.html_code}),_&&_.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-lg",children:"Canva Templates"})}),e.jsx(Ee,{className:"space-y-2",children:_.map(D=>e.jsxs("a",{href:D.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(fl,{className:"h-5 w-5 text-purple-500"}),e.jsx("span",{className:"font-medium",children:D.title}),e.jsx(tr,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},D.id))})]}),p&&p.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-lg",children:"Google Drive Files"})}),e.jsx(Ee,{className:"space-y-2",children:p.map(D=>e.jsxs("a",{href:D.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:D.title})]},D.id))})]}),f&&f.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-lg",children:"PDF Downloads"})}),e.jsx(Ee,{className:"space-y-2",children:f.map(D=>e.jsxs("a",{href:D.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(Nr,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:D.name}),e.jsx(Pa,{className:"h-4 w-4 text-muted-foreground"})]},D.id))})]}),g&&g.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-lg",children:"Videos"})}),e.jsx(Ee,{className:"space-y-6",children:g.map(D=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:D.title}),L(D.video_url)]},D.id))})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"text-lg",children:["Comments (",(j==null?void 0:j.length)||0,")"]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Es,{placeholder:"Write a comment...",value:l,onChange:D=>o(D.target.value),className:"flex-1"}),e.jsx(B,{onClick:()=>l.trim()&&A.mutate(l),disabled:!l.trim()||A.isPending,children:e.jsx(cr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:j==null?void 0:j.map(D=>{var M,F,z;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ra,{className:"h-8 w-8",children:e.jsx(aa,{children:((F=(M=D.profiles)==null?void 0:M.name)==null?void 0:F[0])||"U"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-sm",children:((z=D.profiles)==null?void 0:z.name)||"User"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date(D.created_at),"MMM d, yyyy")}),D.user_id===(n==null?void 0:n.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>T.mutate(D.id),children:e.jsx(_n,{className:"h-3 w-3"})})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:D.content})]})]},D.id)})})]})]})]})}):e.jsx(Ts,{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 JVs({rows:s,onChange:t}){const[n,r]=N.useState(null),[a,i]=N.useState(null),l=()=>{t([...s,{columns:[{title:"",description:""},{title:"",description:""},{title:"",description:""}]}])},o=h=>{t(s.filter((p,f)=>f!==h))},c=(h,p,f,g)=>{const _=[...s];_[h]={..._[h],columns:_[h].columns.map((v,j)=>j===p?{...v,[f]:g}:v)},t(_)},d=async(h,p,f)=>{var v;const g=(v=f.target.files)==null?void 0:v[0];if(!g)return;const _=`${h}-${p}`;r(_);try{const j=`content-blocks/${Date.now()}-${g.name}`,{error:b}=await q.storage.from("newsletter-content").upload(j,g);if(!b){const{data:S}=q.storage.from("newsletter-content").getPublicUrl(j);c(h,p,"image_url",S.publicUrl)}}finally{r(null)}},u=(h,p)=>{c(h,p,"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(Is,{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,p)=>e.jsxs(fe,{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(p),children:e.jsx(Bn,{className:"h-4 w-4"})}),e.jsxs(Ee,{className:"p-4 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Fu,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Row ",p+1]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:h.columns.map((f,g)=>{const _=`${p}-${g}`;return e.jsxs("div",{className:"space-y-2 border border-border/50 rounded-md p-3 bg-muted/20",children:[e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:["Column ",g+1]}),f.image_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:f.image_url,alt:"",className:"w-full h-20 object-cover rounded"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>u(p,g),children:e.jsx(Bn,{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-${_}`,onChange:v=>d(p,g,v)}),e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",disabled:n===_,asChild:!0,children:e.jsx("label",{htmlFor:`block-img-${_}`,className:"cursor-pointer",children:n===_?"...":e.jsxs(e.Fragment,{children:[e.jsx(nl,{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:p,col:g}),children:[e.jsx(Hg,{className:"h-3 w-3 mr-1"})," Library"]})]}),e.jsx(ye,{placeholder:"Title",value:f.title,onChange:v=>c(p,g,"title",v.target.value),className:"h-8 text-sm"}),e.jsx(Es,{placeholder:"Description",value:f.description,onChange:v=>c(p,g,"description",v.target.value),className:"text-sm min-h-[60px] resize-none"})]},g)})})]})]},p)),e.jsx(bs,{open:!!a,onOpenChange:h=>!h&&i(null),children:e.jsxs(vs,{className:"sm:max-w-2xl",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Choose a Graphic"})}),e.jsx(__t,{onSelect:h=>{a&&(c(a.row,a.col,"image_url",h.image_url),i(null))}})]})})]})}function eHs(){const{toast:s}=Ba(),t=Ht(),[n,r]=N.useState(!1),[a,i]=N.useState(null),[l,o]=N.useState({title:"",description:"",publish_date:Ss(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),[c,d]=N.useState(null),[u,h]=N.useState(null),[p,f]=N.useState([]),[g,_]=N.useState([]),[v,j]=N.useState([]),[b,S]=N.useState([]),[A,T]=N.useState([]),[L,D]=N.useState(""),[M,F]=N.useState([]),[z,V]=N.useState(!1),{data:W,isLoading:Y}=ct({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:Ae,error:De}=await q.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(De)throw De;return Ae}}),K=gt({mutationFn:async Ae=>{const{data:De,error:Ie}=await q.from("newsletter_content").insert({title:Ae.title,description:Ae.description||null,preview_image_url:Ae.preview_image_url,publish_date:Ae.publish_date,is_published:Ae.is_published,content_blocks:Ae.content_blocks,html_code:Ae.html_code}).select().single();if(Ie)throw Ie;return De},onSuccess:async Ae=>{await ie(Ae.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),Ae.is_published&&i_s(Ae.title,Ae.id),pe()},onError:Ae=>{s({title:"Error creating newsletter",description:Ae.message,variant:"destructive"})}}),J=gt({mutationFn:async Ae=>{const{error:De}=await q.from("newsletter_content").update({title:Ae.title,description:Ae.description||null,preview_image_url:Ae.preview_image_url,publish_date:Ae.publish_date,is_published:Ae.is_published,content_blocks:Ae.content_blocks,html_code:Ae.html_code}).eq("id",Ae.id);if(De)throw De;return Ae.id},onSuccess:async Ae=>{await ie(Ae),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),pe()},onError:Ae=>{s({title:"Error updating newsletter",description:Ae.message,variant:"destructive"})}}),ne=gt({mutationFn:async Ae=>{const{error:De}=await q.from("newsletter_content").delete().eq("id",Ae);if(De)throw De},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:Ae=>{s({title:"Error deleting newsletter",description:Ae.message,variant:"destructive"})}}),ie=async Ae=>{await q.from("newsletter_drive_links").delete().eq("newsletter_id",Ae),await q.from("newsletter_pdfs").delete().eq("newsletter_id",Ae),await q.from("newsletter_videos").delete().eq("newsletter_id",Ae),await q.from("newsletter_canva_links").delete().eq("newsletter_id",Ae);for(const De of M){const Ie=`${Ae}/${Date.now()}-${De.file.name}`,{error:Fe}=await q.storage.from("newsletter-content").upload(Ie,De.file);if(!Fe){const{data:qe}=q.storage.from("newsletter-content").getPublicUrl(Ie);g.push({name:De.name,file_url:qe.publicUrl,file_size:De.file.size,sort_order:g.length})}}p.length>0&&await q.from("newsletter_drive_links").insert(p.map((De,Ie)=>({newsletter_id:Ae,title:De.title,drive_url:De.drive_url,sort_order:Ie}))),g.length>0&&await q.from("newsletter_pdfs").insert(g.map((De,Ie)=>({newsletter_id:Ae,name:De.name,file_url:De.file_url,file_size:De.file_size||null,sort_order:Ie}))),v.length>0&&await q.from("newsletter_videos").insert(v.map((De,Ie)=>({newsletter_id:Ae,title:De.title,video_url:De.video_url,sort_order:Ie}))),b.length>0&&await q.from("newsletter_canva_links").insert(b.map((De,Ie)=>({newsletter_id:Ae,title:De.title,canva_share_link:De.canva_share_link,sort_order:Ie})))},he=async Ae=>{i(Ae),o({title:Ae.title,description:Ae.description||"",publish_date:Ss(new Date(Ae.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:Ae.is_published}),h(Ae.preview_image_url),T(Ae.content_blocks||[]),D(Ae.html_code||"");const[De,Ie,Fe,qe]=await Promise.all([q.from("newsletter_drive_links").select("*").eq("newsletter_id",Ae.id).order("sort_order"),q.from("newsletter_pdfs").select("*").eq("newsletter_id",Ae.id).order("sort_order"),q.from("newsletter_videos").select("*").eq("newsletter_id",Ae.id).order("sort_order"),q.from("newsletter_canva_links").select("*").eq("newsletter_id",Ae.id).order("sort_order")]);f(De.data||[]),_(Ie.data||[]),j(Fe.data||[]),S(qe.data||[]),F([]),r(!0)},ce=async Ae=>{const[De,Ie,Fe,qe]=await Promise.all([q.from("newsletter_drive_links").select("*").eq("newsletter_id",Ae.id).order("sort_order"),q.from("newsletter_pdfs").select("*").eq("newsletter_id",Ae.id).order("sort_order"),q.from("newsletter_videos").select("*").eq("newsletter_id",Ae.id).order("sort_order"),q.from("newsletter_canva_links").select("*").eq("newsletter_id",Ae.id).order("sort_order")]);i(null),o({title:`${Ae.title} (Copy)`,description:Ae.description||"",publish_date:Ss(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),h(Ae.preview_image_url),T(Ae.content_blocks||[]),D(Ae.html_code||""),f((De.data||[]).map(({id:be,...Ze})=>Ze)),_((Ie.data||[]).map(({id:be,...Ze})=>Ze)),j((Fe.data||[]).map(({id:be,...Ze})=>Ze)),S((qe.data||[]).map(({id:be,...Ze})=>Ze)),F([]),r(!0)},pe=()=>{r(!1),i(null),o({title:"",description:"",publish_date:Ss(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),d(null),h(null),f([]),_([]),j([]),S([]),T([]),D(""),F([])},le=async Ae=>{var Ie;const De=(Ie=Ae.target.files)==null?void 0:Ie[0];De&&(d(De),h(URL.createObjectURL(De)))},ve=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}V(!0);let Ae=u;if(c){const De=`previews/${Date.now()}-${c.name}`,{error:Ie}=await q.storage.from("newsletter-content").upload(De,c);if(!Ie){const{data:Fe}=q.storage.from("newsletter-content").getPublicUrl(De);Ae=Fe.publicUrl}}a?J.mutate({id:a.id,...l,preview_image_url:Ae,content_blocks:A,html_code:L||null}):K.mutate({...l,preview_image_url:Ae,content_blocks:A,html_code:L||null}),V(!1)},ge=()=>f([...p,{title:"",drive_url:"",sort_order:p.length}]),Te=()=>j([...v,{title:"",video_url:"",sort_order:v.length}]),Me=()=>S([...b,{title:"",canva_share_link:"",sort_order:b.length}]),Ce=Ae=>{const De=Ae.target.files;if(!De)return;const Ie=Array.from(De).map(Fe=>({file:Fe,name:Fe.name.replace(/\.[^/.]+$/,"")}));F([...M,...Ie])};return e.jsx(Ts,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{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(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:(W==null?void 0:W.length)||0})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:(W==null?void 0:W.filter(Ae=>Ae.is_published).length)||0})})]})]}),e.jsxs(bs,{open:n,onOpenChange:Ae=>!Ae&&pe(),children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{onClick:()=>r(!0),children:[e.jsx(Is,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),e.jsxs(vs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:a?"Edit Newsletter":"Add Newsletter"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Title *"}),e.jsx(ye,{value:l.title,onChange:Ae=>o({...l,title:Ae.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:Ae=>o({...l,publish_date:Ae.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Lb,{content:l.description,onChange:Ae=>o({...l,description:Ae}),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(Bn,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx(ye,{type:"file",accept:"image/*",onChange:le,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(Na,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bn,{checked:l.is_published,onCheckedChange:Ae=>o({...l,is_published:Ae})}),e.jsx(se,{children:"Published"})]}),e.jsx(JVs,{rows:A,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:L,onChange:Ae=>D(Ae.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:Me,children:[e.jsx(Is,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),b.map((Ae,De)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ye,{placeholder:"Link title",value:Ae.title,onChange:Ie=>{const Fe=[...b];Fe[De].title=Ie.target.value,S(Fe)},className:"w-1/3"}),e.jsx(ye,{placeholder:"Canva share link",value:Ae.canva_share_link,onChange:Ie=>{const Fe=[...b];Fe[De].canva_share_link=Ie.target.value,S(Fe)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>S(b.filter((Ie,Fe)=>Fe!==De)),children:e.jsx(Bn,{className:"h-4 w-4"})})]},De))]}),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:ge,children:[e.jsx(Is,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),p.map((Ae,De)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ye,{placeholder:"Link title",value:Ae.title,onChange:Ie=>{const Fe=[...p];Fe[De].title=Ie.target.value,f(Fe)},className:"w-1/3"}),e.jsx(ye,{placeholder:"Google Drive URL",value:Ae.drive_url,onChange:Ie=>{const Fe=[...p];Fe[De].drive_url=Ie.target.value,f(Fe)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>f(p.filter((Ie,Fe)=>Fe!==De)),children:e.jsx(Bn,{className:"h-4 w-4"})})]},De))]}),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:Ce,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(Na,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),g.map((Ae,De)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:Ae.name}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>_(g.filter((Ie,Fe)=>Fe!==De)),children:e.jsx(Bn,{className:"h-4 w-4"})})]},`existing-${De}`)),M.map((Ae,De)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:Ae.name,onChange:Ie=>{const Fe=[...M];Fe[De].name=Ie.target.value,F(Fe)},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:()=>F(M.filter((Ie,Fe)=>Fe!==De)),children:e.jsx(Bn,{className:"h-4 w-4"})})]},`pending-${De}`))]}),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:Te,children:[e.jsx(Is,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),v.map((Ae,De)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ye,{placeholder:"Video title",value:Ae.title,onChange:Ie=>{const Fe=[...v];Fe[De].title=Ie.target.value,j(Fe)},className:"w-1/3"}),e.jsx(ye,{placeholder:"Video URL",value:Ae.video_url,onChange:Ie=>{const Fe=[...v];Fe[De].video_url=Ie.target.value,j(Fe)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>j(v.filter((Ie,Fe)=>Fe!==De)),children:e.jsx(Bn,{className:"h-4 w-4"})})]},De))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(B,{variant:"outline",onClick:pe,children:"Cancel"}),e.jsx(B,{onClick:ve,disabled:z||K.isPending||J.isPending,children:z?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Publish Date"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:Y?e.jsx(Hs,{children:e.jsx(ut,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(W==null?void 0:W.length)===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:4,className:"text-center py-8 text-muted-foreground",children:"No newsletters yet. Create your first one!"})}):W==null?void 0:W.map(Ae=>e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Ae.preview_image_url?e.jsx("img",{src:Ae.preview_image_url,alt:Ae.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(Nr,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ae.title}),Ae.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Ae.description.replace(/<[^>]*>/g,"")})]})]})}),e.jsx(ut,{children:Ss(new Date(Ae.publish_date),"MMM d, yyyy")}),e.jsx(ut,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${Ae.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:Ae.is_published?"Published":"Draft"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>he(Ae),title:"Edit",children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ce(Ae),title:"Duplicate",children:e.jsx(Xr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",title:"Delete",onClick:()=>{confirm("Are you sure you want to delete this newsletter?")&&ne.mutate(Ae.id)},children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},Ae.id))})]})})})]})})}const tHs=["Headers","Footers","Seasonal","Holidays","Market Updates","Just Sold","Just Listed","Open House","Buyer Tips","Seller Tips","Testimonials","CTAs & Buttons","Dividers","General"];function sHs(){const s=Ht(),t=N.useRef(null),[n,r]=N.useState(""),[a,i]=N.useState("all"),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[p,f]=N.useState({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),{data:g=[],isLoading:_}=ct({queryKey:["admin-newsletter-graphics"],queryFn:async()=>{const{data:V,error:W}=await q.from("newsletter_graphics").select("*").order("is_featured",{ascending:!1}).order("created_at",{ascending:!1});if(W)throw W;return V||[]}}),v=N.useMemo(()=>{const V=new Set(tHs);return g.forEach(W=>V.add(W.category)),Array.from(V).sort()},[g]),j=N.useMemo(()=>{const V=n.trim().toLowerCase();return g.filter(W=>a!=="all"&&W.category!==a?!1:V?W.title.toLowerCase().includes(V)||(W.description||"").toLowerCase().includes(V)||W.tags.some(Y=>Y.toLowerCase().includes(V)):!0)},[g,n,a]),b=()=>{f({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),o(null)},S=()=>{b(),d(!0)},A=V=>{o(V),f({title:V.title,description:V.description||"",image_url:V.image_url,category:V.category,tags:V.tags.join(", "),is_active:V.is_active,is_featured:V.is_featured}),d(!0)},T=async V=>{var W;if(!V.type.startsWith("image/")){ae.error("Please choose an image file");return}if(V.size>15*1024*1024){ae.error("Image must be under 15MB");return}h(!0);try{const Y=((W=V.name.split(".").pop())==null?void 0:W.toLowerCase())||"png",K=`graphics-library/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${Y}`,{error:J}=await q.storage.from("newsletter-content").upload(K,V,{cacheControl:"31536000",upsert:!1,contentType:V.type});if(J)throw J;const{data:ne}=q.storage.from("newsletter-content").getPublicUrl(K);f(ie=>({...ie,image_url:ne.publicUrl,title:ie.title||V.name.replace(/\.[^.]+$/,"").replace(/[-_]/g," ")})),ae.success("Uploaded")}catch(Y){ae.error(Y.message||"Upload failed")}finally{h(!1),t.current&&(t.current.value="")}},L=gt({mutationFn:async()=>{var Y;if(!p.image_url)throw new Error("Please upload an image");if(!p.title.trim())throw new Error("Please add a title");const V=p.tags.split(",").map(K=>K.trim()).filter(Boolean),W={title:p.title.trim(),description:p.description.trim()||null,image_url:p.image_url,category:p.category||"General",tags:V,is_active:p.is_active,is_featured:p.is_featured};if(l){const{error:K}=await q.from("newsletter_graphics").update(W).eq("id",l.id);if(K)throw K}else{const{data:K}=await q.auth.getUser(),{error:J}=await q.from("newsletter_graphics").insert({...W,created_by:(Y=K.user)==null?void 0:Y.id});if(J)throw J}},onSuccess:()=>{ae.success(l?"Updated":"Graphic added to library"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}),d(!1),b()},onError:V=>ae.error(V.message||"Save failed")}),D=gt({mutationFn:async V=>{const{error:W}=await q.from("newsletter_graphics").delete().eq("id",V);if(W)throw W},onSuccess:()=>{ae.success("Deleted"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]})},onError:V=>ae.error(V.message||"Delete failed")}),M=async V=>{const{error:W}=await q.from("newsletter_graphics").update({is_active:!V.is_active}).eq("id",V.id);W?ae.error(W.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},F=async V=>{const{error:W}=await q.from("newsletter_graphics").update({is_featured:!V.is_featured}).eq("id",V.id);W?ae.error(W.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},z=V=>{navigator.clipboard.writeText(V),ae.success("URL copied")};return e.jsxs(Ts,{children:[e.jsxs("div",{className:"p-4 md:p-6 max-w-7xl mx-auto space-y-5",children:[e.jsx(Ud,{title:"Newsletter Graphics Library",description:"Upload branded graphics agents can drop into their newsletters and email campaigns."}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex flex-col md:flex-row gap-3 md:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:n,onChange:V=>r(V.target.value),placeholder:"Search graphics by title, tag, description...",className:"pl-9"})]}),e.jsxs(ds,{value:a,onValueChange:i,children:[e.jsx(ls,{className:"w-full md:w-56",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All categories"}),v.map(V=>e.jsx(Qe,{value:V,children:V},V))]})]}),e.jsxs(B,{onClick:S,className:"gap-1.5 whitespace-nowrap",children:[e.jsx(ry,{className:"h-4 w-4"})," Add Graphic"]})]})}),_?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):j.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-16 text-center",children:[e.jsx(nl,{className:"h-10 w-10 mx-auto mb-3 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:g.length===0?"No graphics uploaded yet — add your first one to get started.":"No graphics match your filters."}),g.length===0&&e.jsxs(B,{onClick:S,className:"gap-1.5",children:[e.jsx(ry,{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:j.map(V=>e.jsxs(fe,{className:`overflow-hidden group ${V.is_active?"":"opacity-60"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative overflow-hidden",children:[e.jsx("img",{src:V.image_url,alt:V.title,loading:"lazy",className:"w-full h-full object-cover"}),V.is_featured&&e.jsxs(ze,{className:"absolute top-2 left-2 gap-0.5 bg-amber-500 hover:bg-amber-500 text-white border-0",children:[e.jsx(ca,{className:"h-3 w-3 fill-current"})," Featured"]}),!V.is_active&&e.jsx(ze,{variant:"secondary",className:"absolute top-2 right-2",children:"Hidden"})]}),e.jsxs(Ee,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm truncate",children:V.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:V.category})]}),V.tags.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:V.tags.slice(0,3).map(W=>e.jsx(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:W},W))}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>A(V),title:"Edit",children:e.jsx(_a,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>F(V),title:V.is_featured?"Unfeature":"Feature",children:e.jsx(ca,{className:`h-3.5 w-3.5 ${V.is_featured?"fill-amber-500 text-amber-500":""}`})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>z(V.image_url),title:"Copy URL",children:e.jsx(Xr,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bn,{checked:V.is_active,onCheckedChange:()=>M(V)}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:()=>{confirm(`Delete "${V.title}"?`)&&D.mutate(V.id)},children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})]})]},V.id))})]}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:l?"Edit Graphic":"Add New Graphic"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Image"}),e.jsx("input",{ref:t,type:"file",accept:"image/*",className:"hidden",onChange:V=>{var Y;const W=(Y=V.target.files)==null?void 0:Y[0];W&&T(W)}}),p.image_url?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border bg-muted/30 mt-1.5",children:[e.jsx("img",{src:p.image_url,alt:"Preview",className:"w-full max-h-64 object-contain"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>f(V=>({...V,image_url:""})),children:e.jsx(Bn,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{type:"button",onClick:()=>{var V;return(V=t.current)==null?void 0:V.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(ts,{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(Na,{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:p.title,onChange:V=>f(W=>({...W,title:V.target.value})),placeholder:"e.g. Fall Market Update Banner"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"g-desc",children:"Description"}),e.jsx(Es,{id:"g-desc",value:p.description,onChange:V=>f(W=>({...W,description:V.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(ds,{value:p.category,onValueChange:V=>f(W=>({...W,category:V})),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:v.map(V=>e.jsx(Qe,{value:V,children:V},V))})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"g-tags",children:"Tags (comma-separated)"}),e.jsx(ye,{id:"g-tags",value:p.tags,onChange:V=>f(W=>({...W,tags:V.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(bn,{checked:p.is_featured,onCheckedChange:V=>f(W=>({...W,is_featured:V}))})]}),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(bn,{checked:p.is_active,onCheckedChange:V=>f(W=>({...W,is_active:V}))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>L.mutate(),disabled:L.isPending,children:[L.isPending&&e.jsx(ts,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),l?"Save Changes":"Add to Library"]})]})]})})]})}const _Ze={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 nHs(){const{user:s}=ys(),{toast:t}=Ba(),n=Mn(),r=Ht(),[a,i]=N.useState(""),[l,o]=N.useState("popular"),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState(""),[g,_]=N.useState(!1),{data:v=[],isLoading:j}=ct({queryKey:["wishlist-items",l,g],queryFn:async()=>{let L=q.from("wishlist_items").select("*");g&&s&&(L=L.eq("user_id",s.id)),l==="latest"?L=L.order("created_at",{ascending:!1}):l==="popular"?L=L.order("vote_count",{ascending:!1}):l==="trending"&&(L=L.order("vote_count",{ascending:!1}));const{data:D,error:M}=await L;if(M)throw M;const F=[...new Set((D==null?void 0:D.map(ne=>ne.user_id))||[])],{data:z}=await q.from("profiles").select("id, name").in("id",F),V=new Map((z==null?void 0:z.map(ne=>[ne.id,ne]))||[]);let W=[];if(s){const{data:ne}=await q.from("wishlist_votes").select("item_id").eq("user_id",s.id);W=(ne==null?void 0:ne.map(ie=>ie.item_id))||[]}const Y=(D==null?void 0:D.map(ne=>ne.id))||[],{data:K}=await q.from("wishlist_comments").select("item_id").in("item_id",Y),J=new Map;return K==null||K.forEach(ne=>{J.set(ne.item_id,(J.get(ne.item_id)||0)+1)}),D==null?void 0:D.map(ne=>{const ie=V.get(ne.user_id),he=(ie==null?void 0:ie.name)||"Unknown";return{...ne,user_name:he,user_initials:he.split(" ").map(ce=>ce[0]).join("").toUpperCase().slice(0,2),has_voted:W.includes(ne.id),comment_count:J.get(ne.id)||0}})}}),b=gt({mutationFn:async({title:L,description:D})=>{const{error:M}=await q.from("wishlist_items").insert({user_id:s.id,title:L,description:D});if(M)throw M},onSuccess:()=>{r.invalidateQueries({queryKey:["wishlist-items"]}),d(!1),h(""),f(""),t({title:"Idea submitted!",description:"Your idea has been added to the wishlist."})},onError:L=>{t({title:"Error",description:L.message,variant:"destructive"})}}),S=gt({mutationFn:async({itemId:L,hasVoted:D})=>{if(D){const{error:M}=await q.from("wishlist_votes").delete().eq("item_id",L).eq("user_id",s.id);if(M)throw M;return{itemId:L,wasAdded:!1}}else{const{error:M}=await q.from("wishlist_votes").insert({item_id:L,user_id:s.id});if(M)throw M;return{itemId:L,wasAdded:!0}}},onSuccess:async L=>{if(r.invalidateQueries({queryKey:["wishlist-items"]}),L!=null&&L.wasAdded){const D=v.find(F=>F.id===L.itemId),M=((D==null?void 0:D.vote_count)||0)+1;q.functions.invoke("wishlist-notify",{body:{itemId:L.itemId,voteCount:M}}).catch(console.error)}},onError:L=>{t({title:"Error",description:L.message,variant:"destructive"})}}),A=v.filter(L=>L.title.toLowerCase().includes(a.toLowerCase())||L.description.toLowerCase().includes(a.toLowerCase())),T=()=>{if(!u.trim()||!p.trim()){t({title:"Error",description:"Please fill in both title and description.",variant:"destructive"});return}b.mutate({title:u.trim(),description:p.trim()})};return e.jsx(Ts,{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(vw,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold",children:"Wishlist"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Share ideas and vote on what we build next"})]})]}),e.jsxs(bs,{open:c,onOpenChange:d,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Submit a New Idea"})}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title"}),e.jsx(ye,{id:"title",placeholder:"Give your idea a clear title...",value:u,onChange:L=>h(L.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Es,{id:"description",placeholder:"Describe your idea in detail. What problem does it solve? How would it help agents?",value:p,onChange:L=>f(L.target.value),rows:4})]}),e.jsx(B,{onClick:T,className:"w-full",disabled:b.isPending,children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Submitting..."]}):"Submit Idea"})]})]})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 mb-6",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search ideas...",value:a,onChange:L=>i(L.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Br,{value:l,onValueChange:L=>o(L),children:e.jsxs(Fr,{children:[e.jsx(Kt,{value:"popular",children:"Most Popular"}),e.jsx(Kt,{value:"latest",children:"Latest"}),e.jsx(Kt,{value:"trending",children:"Trending"})]})})})]}),e.jsx("div",{className:"flex items-center gap-2 mb-4",children:e.jsx(B,{variant:g?"default":"outline",size:"sm",onClick:()=>_(!g),children:g?"Show All Ideas":"My Ideas"})}),j?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ts,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):A.length===0?e.jsxs("div",{className:"text-center py-12 bg-muted/30 rounded-lg",children:[e.jsx(vw,{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(Is,{className:"h-4 w-4 mr-2"}),"Add Idea"]})]}):e.jsx("div",{className:"space-y-3",children:A.map(L=>e.jsx("div",{className:"bg-card border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>n(`/wishlist/${L.id}`),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:D=>{D.stopPropagation(),S.mutate({itemId:L.id,hasVoted:L.has_voted||!1})},className:Et("flex flex-col items-center justify-center min-w-[50px] py-2 px-3 rounded-lg border transition-colors",L.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[e.jsx(Ru,{className:Et("h-4 w-4",L.has_voted&&"fill-current")}),e.jsx("span",{className:"text-sm font-semibold",children:L.vote_count})]}),e.jsx(ra,{className:"h-10 w-10 bg-primary/20",children:e.jsx(aa,{className:"bg-primary/20 text-primary text-sm font-medium",children:L.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:L.title}),e.jsx(ze,{className:Et("text-xs",_Ze[L.status].color),children:_Ze[L.status].label})]}),e.jsx("p",{className:"text-muted-foreground text-sm line-clamp-2",children:L.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:L.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(L.created_at).toLocaleDateString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Ei,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:L.comment_count})]})]})},L.id))})]})})}const wZe={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 rHs(){const{itemId:s}=bi(),t=Mn(),{user:n}=ys(),{toast:r}=Ba(),a=Ht(),[i,l]=N.useState(""),{data:o=!1}=ct({queryKey:["user-is-admin",n==null?void 0:n.id],queryFn:async()=>{if(!n)return!1;const{data:v,error:j}=await q.from("user_roles").select("role").eq("user_id",n.id).eq("role","admin").maybeSingle();return!j&&!!v},enabled:!!n}),{data:c,isLoading:d}=ct({queryKey:["wishlist-item",s],queryFn:async()=>{const{data:v,error:j}=await q.from("wishlist_items").select("*").eq("id",s).single();if(j)throw j;const{data:b}=await q.from("profiles").select("name").eq("id",v.user_id).single();let S=!1;if(n){const{data:A}=await q.from("wishlist_votes").select("id").eq("item_id",s).eq("user_id",n.id).maybeSingle();S=!!A}return{...v,user_name:(b==null?void 0:b.name)||"Unknown",user_initials:((b==null?void 0:b.name)||"U").split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),has_voted:S}}}),{data:u=[],isLoading:h}=ct({queryKey:["wishlist-comments",s],queryFn:async()=>{const{data:v,error:j}=await q.from("wishlist_comments").select("*").eq("item_id",s).order("created_at",{ascending:!0});if(j)throw j;const b=[...new Set((v==null?void 0:v.map(T=>T.user_id))||[])],{data:S}=await q.from("profiles").select("id, name").in("id",b),A=new Map((S==null?void 0:S.map(T=>[T.id,T]))||[]);return v==null?void 0:v.map(T=>{const L=A.get(T.user_id),D=(L==null?void 0:L.name)||"Unknown";return{...T,user_name:D,user_initials:D.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2)}})}}),p=gt({mutationFn:async v=>{if(v){const{error:j}=await q.from("wishlist_votes").delete().eq("item_id",s).eq("user_id",n.id);if(j)throw j;return{wasAdded:!1}}else{const{error:j}=await q.from("wishlist_votes").insert({item_id:s,user_id:n.id});if(j)throw j;return{wasAdded:!0}}},onSuccess:async v=>{if(a.invalidateQueries({queryKey:["wishlist-item",s]}),a.invalidateQueries({queryKey:["wishlist-items"]}),v!=null&&v.wasAdded&&c){const j=(c.vote_count||0)+1;q.functions.invoke("wishlist-notify",{body:{itemId:s,voteCount:j}}).catch(console.error)}},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),f=gt({mutationFn:async v=>{const{error:j}=await q.from("wishlist_comments").insert({item_id:s,user_id:n.id,content:v});if(j)throw j},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),l(""),r({title:"Comment added!"})},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),g=gt({mutationFn:async v=>{const{error:j}=await q.from("wishlist_comments").delete().eq("id",v);if(j)throw j},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),r({title:"Comment deleted"})},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),_=()=>{i.trim()&&f.mutate(i.trim())};return d?e.jsx(Ts,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(Ws,{className:"h-8 w-32 mb-6"}),e.jsx(Ws,{className:"h-48 w-full mb-6"}),e.jsx(Ws,{className:"h-32 w-full"})]})}):c?e.jsx(Ts,{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(Hr,{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:()=>p.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(Ru,{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(ze,{className:Et("text-xs",wZe[c.status].color),children:wZe[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(aa,{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(Mxe,{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:_,disabled:!i.trim()||f.isPending,size:"icon",className:"h-auto",children:f.isPending?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"})})]}),h?e.jsx("div",{className:"space-y-4",children:[1,2].map(v=>e.jsx(Ws,{className:"h-20 w-full"},v))}):u.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No comments yet. Be the first to share your thoughts!"}):e.jsx("div",{className:"space-y-4",children:u.map(v=>e.jsxs("div",{className:"flex gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsx(ra,{className:"h-8 w-8",children:e.jsx(aa,{className:"bg-primary/20 text-primary text-xs",children:v.user_initials})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium text-sm",children:v.user_name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(v.created_at).toLocaleDateString()})]}),e.jsx(KIe,{content:v.content,className:"text-sm text-foreground"})]}),(n==null?void 0:n.id)===v.user_id&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>g.mutate(v.id),children:e.jsx(_n,{className:"h-4 w-4"})})]},v.id))})]})]})}):e.jsx(Ts,{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 jZe={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"}},NZe=["open","under_review","planned","in_progress","launched","declined"];function aHs(){const{toast:s}=Ba(),t=Mn(),n=Ht(),[r,a]=N.useState(""),[i,l]=N.useState("all"),[o,c]=N.useState(!1),[d,u]=N.useState(null),{data:h=[],isLoading:p}=ct({queryKey:["admin-wishlist-items"],queryFn:async()=>{const{data:j,error:b}=await q.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(b)throw b;const S=[...new Set((j==null?void 0:j.map(F=>F.user_id))||[])],{data:A}=await q.from("profiles").select("id, name, email").in("id",S),T=new Map((A==null?void 0:A.map(F=>[F.id,F]))||[]),L=(j==null?void 0:j.map(F=>F.id))||[],{data:D}=await q.from("wishlist_comments").select("item_id").in("item_id",L),M=new Map;return D==null||D.forEach(F=>{M.set(F.item_id,(M.get(F.item_id)||0)+1)}),j==null?void 0:j.map(F=>{const z=T.get(F.user_id);return{...F,user_name:(z==null?void 0:z.name)||"Unknown",user_email:(z==null?void 0:z.email)||"",comment_count:M.get(F.id)||0}})}}),f=gt({mutationFn:async({itemId:j,status:b})=>{const{error:S}=await q.from("wishlist_items").update({status:b}).eq("id",j);if(S)throw S},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:j=>{s({title:"Error",description:j.message,variant:"destructive"})}}),g=gt({mutationFn:async j=>{const{error:b}=await q.from("wishlist_items").delete().eq("id",j);if(b)throw b},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),c(!1),u(null),s({title:"Item deleted!"})},onError:j=>{s({title:"Error",description:j.message,variant:"destructive"})}}),_=h.filter(j=>{const b=j.title.toLowerCase().includes(r.toLowerCase())||j.description.toLowerCase().includes(r.toLowerCase())||j.user_name.toLowerCase().includes(r.toLowerCase()),S=i==="all"||j.status===i;return b&&S}),v={total:h.length,open:h.filter(j=>j.status==="open").length,inProgress:h.filter(j=>j.status==="in_progress").length,launched:h.filter(j=>j.status==="launched").length,highVotes:h.filter(j=>j.vote_count>=10).length};return e.jsx(Ts,{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(Hr,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Wishlist Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Review and manage community ideas"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Ideas"}),e.jsx("p",{className:"text-2xl font-bold",children:v.total})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Open"}),e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:v.open})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"In Progress"}),e.jsx("p",{className:"text-2xl font-bold text-orange-600",children:v.inProgress})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Launched"}),e.jsx("p",{className:"text-2xl font-bold text-green-600",children:v.launched})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"10+ Votes"}),e.jsx("p",{className:"text-2xl font-bold text-primary",children:v.highVotes})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{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:j=>a(j.target.value),className:"pl-10"})]}),e.jsxs(ds,{value:i,onValueChange:j=>l(j),children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(us,{placeholder:"Filter by status"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Statuses"}),NZe.map(j=>e.jsx(Qe,{value:j,children:jZe[j].label},j))]})]})]}),p?e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(j=>e.jsx(Ws,{className:"h-16 w-full"},j))}):e.jsx("div",{className:"bg-card border rounded-lg overflow-hidden",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{className:"w-[60px]",children:"Votes"}),e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{className:"hidden md:table-cell",children:"Submitted By"}),e.jsx(Ct,{className:"hidden sm:table-cell",children:"Comments"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(ha,{children:_.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):_.map(j=>e.jsxs(Hs,{className:Et(j.vote_count>=10&&"bg-primary/5"),children:[e.jsx(ut,{children:e.jsx(ze,{variant:j.vote_count>=10?"default":"secondary",children:j.vote_count})}),e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium line-clamp-1",children:j.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:j.description})]})}),e.jsx(ut,{className:"hidden md:table-cell",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:j.user_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j.user_email})]})}),e.jsx(ut,{className:"hidden sm:table-cell",children:j.comment_count}),e.jsx(ut,{children:e.jsxs(ds,{value:j.status,onValueChange:b=>f.mutate({itemId:j.id,status:b}),children:[e.jsx(ls,{className:"w-[140px] h-8",children:e.jsx(us,{})}),e.jsx(cs,{children:NZe.map(b=>e.jsx(Qe,{value:b,children:jZe[b].label},b))})]})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>window.open(`/wishlist/${j.id}`,"_blank"),children:e.jsx(tr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{u(j.id),c(!0)},children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},j.id))})]})}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Delete Wishlist Item"})}),e.jsx("p",{className:"text-muted-foreground",children:"Are you sure you want to delete this idea? This will also delete all votes and comments."}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>d&&g.mutate(d),disabled:g.isPending,children:g.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function iHs(){const{user:s}=ys(),[t,n]=N.useState([]),[r,a]=N.useState(!0),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,p]=N.useState(null),[f,g]=N.useState(""),[_,v]=N.useState(""),[j,b]=N.useState(""),[S,A]=N.useState(""),[T,L]=N.useState(""),[D,M]=N.useState(!1),[F,z]=N.useState(""),[V,W]=N.useState("once"),[Y,K]=N.useState([]),[J,ne]=N.useState([]),[ie,he]=N.useState(!1),[ce,pe]=N.useState(!1),[le,ve]=N.useState([]),[ge,Te]=N.useState({total:0,dismissed:0});N.useEffect(()=>{Me()},[]);const Me=async()=>{const{data:at,error:He}=await q.from("levelup_briefs").select("*").order("created_at",{ascending:!1});He?(ae.error("Failed to fetch briefs"),console.error(He)):n(at||[]),a(!1)},Ce=()=>{g(""),v(""),b(""),A(""),L(""),M(!1),z(new Date().toISOString().slice(0,16)),W("once"),K([]),ne([]),c(null)},Ae=()=>{Ce(),l(!0)},De=async at=>{c(at),g(at.title),v(at.description||""),b(at.video_url||""),A(at.graphic_url||""),L(at.graphic_link_url||""),M(at.is_published),z(at.publish_date.slice(0,16)),W(at.show_frequency);const{data:He}=await q.from("levelup_brief_links").select("*").eq("brief_id",at.id).order("sort_order");K((He==null?void 0:He.map(bt=>({title:bt.title,url:bt.url})))||[]);const{data:dt}=await q.from("levelup_brief_polls").select("*").eq("brief_id",at.id).order("sort_order");if(dt){const bt=[];for(const vt of dt){const{data:Bt}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",vt.id).order("sort_order");bt.push({question:vt.question,poll_type:vt.poll_type,options:(Bt==null?void 0:Bt.map(Zt=>Zt.option_text))||[]})}ne(bt)}l(!0)},Ie=async at=>{var dt;const He=(dt=at.target.files)==null?void 0:dt[0];if(He){he(!0);try{const bt=await q.functions.invoke("bunny-upload",{body:{action:"create",title:He.name.replace(/\.[^/.]+$/,"")}});if(bt.error)throw bt.error;const{videoId:vt,libraryId:Bt}=bt.data,Zt=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:vt}});if(Zt.error)throw Zt.error;const{uploadUrl:Fs,apiKey:Rs}=Zt.data,ms=new XMLHttpRequest;await new Promise((Jt,ft)=>{ms.upload.addEventListener("progress",Vt=>{if(Vt.lengthComputable){const Ms=Math.round(Vt.loaded/Vt.total*100);console.log("Upload progress:",Ms)}}),ms.addEventListener("load",()=>{ms.status>=200&&ms.status<300?Jt():ft(new Error(`Upload failed with status ${ms.status}`))}),ms.addEventListener("error",()=>ft(new Error("Upload failed"))),ms.open("PUT",Fs),ms.setRequestHeader("AccessKey",Rs),ms.send(He)});const Pt=`https://player.mediadelivery.net/embed/${Bt}/${vt}`;b(Pt),ae.success("Video uploaded successfully! It may take a few minutes to process.")}catch(bt){console.error("Upload error:",bt),ae.error("Failed to upload video")}finally{he(!1)}}},Fe=async()=>{if(!f.trim()){ae.error("Title is required");return}try{let at;if(o){const{error:He}=await q.from("levelup_briefs").update({title:f,description:_||null,video_url:j||null,graphic_url:S||null,graphic_link_url:T||null,is_published:D,publish_date:F,show_frequency:V}).eq("id",o.id);if(He)throw He;at=o.id,await q.from("levelup_brief_links").delete().eq("brief_id",at);const{data:dt}=await q.from("levelup_brief_polls").select("id").eq("brief_id",at);if(dt)for(const bt of dt)await q.from("levelup_brief_poll_options").delete().eq("poll_id",bt.id);await q.from("levelup_brief_polls").delete().eq("brief_id",at)}else{const{data:He,error:dt}=await q.from("levelup_briefs").insert({title:f,description:_||null,video_url:j||null,graphic_url:S||null,graphic_link_url:T||null,is_published:D,publish_date:F,show_frequency:V,created_by:s==null?void 0:s.id}).select().single();if(dt)throw dt;at=He.id}if(Y.length>0){const He=Y.map((dt,bt)=>({brief_id:at,title:dt.title,url:dt.url,sort_order:bt}));await q.from("levelup_brief_links").insert(He)}for(let He=0;He0){const Bt=dt.options.map((Zt,Fs)=>({poll_id:bt.id,option_text:Zt,sort_order:Fs}));await q.from("levelup_brief_poll_options").insert(Bt)}}ae.success(o?"Brief updated":"Brief created"),l(!1),Ce(),Me()}catch(at){console.error("Error saving brief:",at),ae.error("Failed to save brief")}},qe=async at=>{if(confirm("Are you sure you want to delete this brief?"))try{const{error:He}=await q.from("levelup_briefs").delete().eq("id",at);if(He)throw He;ae.success("Brief deleted"),Me()}catch(He){console.error("Error deleting brief:",He),ae.error("Failed to delete brief")}},be=async at=>{p(at);const{count:He}=await q.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",at.id),{count:dt}=await q.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",at.id).not("dismissed_at","is",null);Te({total:He||0,dismissed:dt||0});const{data:bt}=await q.from("levelup_brief_polls").select("*").eq("brief_id",at.id).order("sort_order");if(bt){const vt=[];for(const Bt of bt){const{data:Zt}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",Bt.id).order("sort_order"),{data:Fs}=await q.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",Bt.id),Rs=[...new Set((Fs==null?void 0:Fs.map(Vt=>Vt.user_id))||[])];let ms={};if(Rs.length>0){const{data:Vt}=await q.from("profiles").select("id, name, email").in("id",Rs);Vt&&Vt.forEach(Ms=>{ms[Ms.id]=Ms.name||Ms.email||"Unknown"})}const Pt=(Fs||[]).map(Vt=>({optionId:Vt.option_id,userName:ms[Vt.user_id]||"Unknown",userId:Vt.user_id})),Jt={};let ft=0;Zt&&Zt.forEach(Vt=>{const Ms=(Fs==null?void 0:Fs.filter(Xt=>Xt.option_id===Vt.id).length)||0;Jt[Vt.id]=Ms,ft+=Ms}),vt.push({...Bt,options:Zt||[],results:Jt,respondents:Pt,totalResponses:Bt.poll_type==="single"?new Set(Fs==null?void 0:Fs.map(Vt=>Vt.user_id)).size:ft})}ve(vt)}u(!0)},Ze=()=>{K([...Y,{title:"",url:""}])},Ne=(at,He,dt)=>{const bt=[...Y];bt[at][He]=dt,K(bt)},it=at=>{K(Y.filter((He,dt)=>dt!==at))},je=()=>{ne([...J,{question:"",poll_type:"single",options:["",""]}])},Ge=(at,He)=>{const dt=[...J];dt[at].question=He,ne(dt)},Be=(at,He)=>{const dt=[...J];dt[at].poll_type=He,ne(dt)},Ye=at=>{const He=[...J];He[at].options.push(""),ne(He)},We=(at,He,dt)=>{const bt=[...J];bt[at].options[He]=dt,ne(bt)},rt=(at,He)=>{const dt=[...J];dt[at].options=dt[at].options.filter((bt,vt)=>vt!==He),ne(dt)},tt=at=>{ne(J.filter((He,dt)=>dt!==at))};return e.jsxs(Ts,{title:"The LevelUp Brief",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{title:"The LevelUp Brief",description:"Create engaging popup briefs for your agents",children:e.jsxs(B,{onClick:Ae,children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Frequency"}),e.jsx(Ct,{children:"Publish Date"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:r?e.jsx(Hs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(at=>e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:at.title}),e.jsx(ut,{children:e.jsx(ze,{variant:at.is_published?"default":"secondary",children:at.is_published?"Published":"Draft"})}),e.jsx(ut,{className:"capitalize",children:at.show_frequency.replace("_"," ")}),e.jsx(ut,{children:Ss(new Date(at.publish_date),"MMM d, yyyy h:mm a")}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>be(at),children:e.jsx(yo,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>De(at),children:e.jsx(ku,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>qe(at.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},at.id))})]})})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs(Br,{defaultValue:"content",className:"w-full",children:[e.jsxs(Fr,{className:"grid w-full grid-cols-4",children:[e.jsx(Kt,{value:"content",children:"Content"}),e.jsx(Kt,{value:"media",children:"Media"}),e.jsx(Kt,{value:"links",children:"Links"}),e.jsx(Kt,{value:"polls",children:"Polls"})]}),e.jsxs(is,{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:f,onChange:at=>g(at.target.value),placeholder:"What's happening at LevelUp..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Lb,{content:_,onChange:at=>v(at),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:F,onChange:at=>z(at.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Show Frequency"}),e.jsxs(ds,{value:V,onValueChange:W,children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"once",children:"Once (until dismissed)"}),e.jsx(Qe,{value:"every_login",children:"Every login"}),e.jsx(Qe,{value:"daily",children:"Daily"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(bn,{checked:D,onCheckedChange:M}),e.jsx(se,{children:"Publish immediately"})]})]}),e.jsxs(is,{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:Ie,disabled:ie})}),ie&&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:j,onChange:at=>b(at.target.value),placeholder:"https://iframe.mediadelivery.net/embed/..."})]}),j&&e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:j,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 at=>{var dt;const He=(dt=at.target.files)==null?void 0:dt[0];if(He){pe(!0);try{const bt=He.name.split(".").pop(),vt=`brief-graphics/${Date.now()}.${bt}`,{error:Bt}=await q.storage.from("banner-images").upload(vt,He,{upsert:!0});if(Bt)throw Bt;const{data:Zt}=q.storage.from("banner-images").getPublicUrl(vt);A(Zt.publicUrl),ae.success("Image uploaded!")}catch(bt){console.error(bt),ae.error("Failed to upload image")}finally{pe(!1)}}},disabled:ce})}),ce&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Or paste Image URL"}),e.jsx(ye,{value:S,onChange:at=>A(at.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:at=>L(at.target.value),placeholder:"https://example.com/landing-page"})]}),S&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted border",children:e.jsx("img",{src:S,alt:"Brief graphic preview",className:"w-full object-contain max-h-64"})})]})]}),e.jsxs(is,{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:Ze,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),Y.map((at,He)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(ye,{value:at.title,onChange:dt=>Ne(He,"title",dt.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(ye,{value:at.url,onChange:dt=>Ne(He,"url",dt.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>it(He),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]},He)),Y.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),e.jsxs(is,{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:je,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),J.map((at,He)=>e.jsx(fe,{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:at.question,onChange:dt=>Ge(He,dt.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),e.jsxs(ds,{value:at.poll_type,onValueChange:dt=>Be(He,dt),children:[e.jsx(ls,{className:"w-32",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"single",children:"Single"}),e.jsx(Qe,{value:"multi",children:"Multi-select"})]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>tt(He),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[at.options.map((dt,bt)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:dt,onChange:vt=>We(He,bt,vt.target.value),placeholder:`Option ${bt+1}`}),at.options.length>2&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>rt(He,bt),children:e.jsx(_n,{className:"h-4 w-4 text-muted-foreground"})})]},bt)),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>Ye(He),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},He)),J.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:Fe,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(bs,{open:d,onOpenChange:u,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Results: ",h==null?void 0:h.title]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total Views"})}),e.jsx(Ee,{children:e.jsx("p",{className:"text-2xl font-bold",children:ge.total})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Dismissed"})}),e.jsx(Ee,{children:e.jsx("p",{className:"text-2xl font-bold",children:ge.dismissed})})]})]}),le.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Poll Results"}),le.map(at=>e.jsxs(fe,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:at.question}),e.jsx("div",{className:"space-y-2",children:at.options.map(He=>{const dt=at.results[He.id]||0,bt=at.totalResponses>0?Math.round(dt/at.totalResponses*100):0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:He.option_text}),e.jsxs("span",{className:"text-muted-foreground",children:[dt," (",bt,"%)"]})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${bt}%`}})}),dt>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(at.respondents||[]).filter(vt=>vt.optionId===He.id).map((vt,Bt)=>e.jsx(ze,{variant:"secondary",className:"text-xs font-normal",children:vt.userName},Bt))})]},He.id)})})]},at.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const oHs=()=>{const{user:s}=ys(),{toast:t}=Ba(),n=Ht(),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=N.useState(null),[h,p]=N.useState(""),{data:f=[],isLoading:g}=ct({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:T,error:L}=await q.from("additional_services").select("*").order("publish_date",{ascending:!1});if(L)throw L;return T}}),_=gt({mutationFn:async T=>{let L=T.existingImageUrl;if(T.image){const M=T.image.name.split(".").pop(),F=`${Date.now()}-${Math.random().toString(36).substring(7)}.${M}`,{error:z}=await q.storage.from("service-images").upload(F,T.image);if(z)throw z;const{data:V}=q.storage.from("service-images").getPublicUrl(F);L=V.publicUrl}const D={name:T.item.name,description:T.item.description||null,preview_image_url:L,signup_link_url:T.item.signup_link_url,publish_date:T.item.publish_date?new Date(T.item.publish_date).toISOString():new Date().toISOString(),is_published:T.item.is_published,created_by:s==null?void 0:s.id};if(T.itemId){const{error:M}=await q.from("additional_services").update(D).eq("id",T.itemId);if(M)throw M}else{const{error:M}=await q.from("additional_services").insert(D);if(M)throw M}},onSuccess:()=>{n.invalidateQueries({queryKey:["additional-services-admin"]}),n.invalidateQueries({queryKey:["additional-services"]}),t({title:i?"Service updated":"Service created"}),a(!1),j()},onError:T=>{t({title:"Error saving service",description:T.message,variant:"destructive"})}}),v=gt({mutationFn:async T=>{const{error:L}=await q.from("additional_services").delete().eq("id",T);if(L)throw L},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"})}}),j=()=>{c({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),p(""),l(null)},b=T=>{l(T),c({name:T.name,description:T.description||"",signup_link_url:T.signup_link_url,publish_date:T.publish_date?new Date(T.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:T.is_published}),p(T.preview_image_url||""),a(!0)},S=T=>{var D;const L=(D=T.target.files)==null?void 0:D[0];L&&(u(L),p(URL.createObjectURL(L)))},A=T=>{if(T.preventDefault(),!o.name.trim()){t({title:"Name is required",variant:"destructive"});return}if(!o.signup_link_url.trim()){t({title:"Signup link URL is required",variant:"destructive"});return}_.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(Ts,{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(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.length})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.filter(T=>T.is_published).length})})]})]}),e.jsxs(bs,{open:r,onOpenChange:T=>{a(T),T||j()},children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:i?"Edit Service":"Add New Service"})}),e.jsxs("form",{onSubmit:A,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(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(Lb,{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(bn,{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),p("")},children:e.jsx(Bn,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(nl,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(ye,{type:"file",accept:"image/*",onChange:S,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:_.isPending,children:_.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:g?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):f.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No services yet. Click "Add Service" to create your first one.'}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{className:"w-16",children:"Preview"}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Signup Link"}),e.jsx(Ct,{children:"Publish Date"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:f.map(T=>e.jsxs(Hs,{children:[e.jsx(ut,{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(nl,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(ut,{className:"font-medium",children:T.name}),e.jsx(ut,{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(ut,{children:new Date(T.publish_date).toLocaleDateString()}),e.jsx(ut,{children:e.jsx(ze,{variant:T.is_published?"default":"secondary",children:T.is_published?"Published":"Draft"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>b(T),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this service?")&&v.mutate(T.id)},children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},T.id))})]})})})]})})};function lHs(){const{toast:s}=Ba(),[t,n]=N.useState([]),[r,a]=N.useState(!0),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""});N.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:v,error:j}=await q.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(j)throw j;n(v.coupons||[])}catch(v){console.error("Error fetching coupons:",v),s({title:"Error",description:"Failed to load coupons",variant:"destructive"})}finally{a(!1)}},p=async()=>{if(!d.name){s({title:"Error",description:"Please enter a coupon name",variant:"destructive"});return}if(d.discountType==="percent"&&!d.percentOff){s({title:"Error",description:"Please enter a percent off value",variant:"destructive"});return}if(d.discountType==="amount"&&!d.amountOff){s({title:"Error",description:"Please enter an amount off value",variant:"destructive"});return}if(d.duration==="repeating"&&!d.durationInMonths){s({title:"Error",description:"Please enter duration in months",variant:"destructive"});return}l(!0);try{const v={action:"create",name:d.name,duration:d.duration,promotion_code:d.promotionCode.trim()||void 0};d.discountType==="percent"?v.percent_off=parseFloat(d.percentOff):(v.amount_off=Math.round(parseFloat(d.amountOff)*100),v.currency="usd"),d.duration==="repeating"&&(v.duration_in_months=parseInt(d.durationInMonths));const{data:j,error:b}=await q.functions.invoke("stripe-manage-coupons",{body:v});if(b)throw b;s({title:"Success",description:"Coupon created successfully"}),c(!1),u({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""}),h()}catch(v){console.error("Error creating coupon:",v),s({title:"Error",description:v.message||"Failed to create coupon",variant:"destructive"})}finally{l(!1)}},f=async v=>{if(confirm("Are you sure you want to delete this coupon?"))try{const{error:j}=await q.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:v}});if(j)throw j;s({title:"Success",description:"Coupon deleted successfully"}),h()}catch(j){console.error("Error deleting coupon:",j),s({title:"Error",description:j.message||"Failed to delete coupon",variant:"destructive"})}},g=v=>v.percent_off?`${v.percent_off}% off`:v.amount_off?`$${(v.amount_off/100).toFixed(2)} off`:"N/A",_=v=>{switch(v.duration){case"once":return"Once";case"forever":return"Forever";case"repeating":return`${v.duration_in_months} months`;default:return v.duration}};return e.jsx(Ts,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(bs,{open:o,onOpenChange:c,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create New Coupon"}),e.jsx(Qn,{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:v=>u({...d,promotionCode:v.target.value.toUpperCase().replace(/[^A-Z0-9]/g,"")}),className:"font-mono uppercase"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Letters and numbers only. This is the code users enter at checkout."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Coupon Name (internal label)"}),e.jsx(ye,{placeholder:"e.g., 50% Off Brokerage Launch",value:d.name,onChange:v=>u({...d,name:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Discount Type"}),e.jsxs(ds,{value:d.discountType,onValueChange:v=>{const j=v==="amount"&&d.duration==="forever"?"once":d.duration;u({...d,discountType:v,duration:j})},children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"percent",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(a4,{className:"mr-2 h-4 w-4"}),"Percentage Off"]})}),e.jsx(Qe,{value:"amount",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(Zl,{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:v=>u({...d,percentOff:v.target.value})}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(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:v=>u({...d,amountOff:v.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Duration"}),e.jsxs(ds,{value:d.duration,onValueChange:v=>u({...d,duration:v}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"once",children:"Once (first payment only)"}),e.jsx(Qe,{value:"repeating",children:"Multiple months"}),e.jsxs(Qe,{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:v=>u({...d,durationInMonths:v.target.value})})]}),e.jsx(B,{onClick:p,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Active Coupons"}),e.jsx(Vn,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),e.jsx(Ee,{children:r?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ts,{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(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Promo Code"}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Discount"}),e.jsx(Ct,{children:"Duration"}),e.jsx(Ct,{children:"Redemptions"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:t.map(v=>{var j;return e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-mono font-medium",children:((j=v.promotion_codes)==null?void 0:j.length)>0?v.promotion_codes.join(", "):e.jsx("span",{className:"text-muted-foreground text-xs",children:"No promo code"})}),e.jsx(ut,{children:v.name||"-"}),e.jsx(ut,{children:g(v)}),e.jsx(ut,{children:_(v)}),e.jsx(ut,{children:v.times_redeemed}),e.jsx(ut,{children:e.jsx(ze,{variant:v.valid?"default":"secondary",children:v.valid?"Active":"Inactive"})}),e.jsx(ut,{className:"text-right",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>f(v.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})})]},v.id)})})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"How to Use Coupons"})}),e.jsxs(Ee,{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 _Ne={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 cHs(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("all"),[l,o]=N.useState(null),{data:c,isLoading:d,refetch:u}=ct({queryKey:["admin-subscriptions"],queryFn:async()=>{const{data:j,error:b}=await q.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(b)throw b;return j}}),{data:h}=ct({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:j,error:b}=await q.from("brokerages").select("*").order("name");if(b)throw b;return await Promise.all((j||[]).map(async A=>{const{data:T}=await q.from("profiles").select("id, name, email, subscription_status, subscription_product_id").eq("brokerage_id",A.id),{data:L}=await q.from("user_roles").select("user_id").eq("role","brokerage_manager"),D=(L==null?void 0:L.map(z=>z.user_id))||[],M=(T==null?void 0:T.filter(z=>D.includes(z.id)))||[],F=(T==null?void 0:T.length)||0;return{...A,managers:M,agentCount:F}}))}}),{data:p}=ct({queryKey:["admin-website-subscriptions"],queryFn:async()=>{const{data:j,error:b}=await q.from("local_move_subscriptions").select("*").order("created_at",{ascending:!1});if(b)throw b;return j}}),f=j=>{if(j.is_grandfathered)return{status:"Grandfathered",badge:"Legacy",variant:"secondary"};if(j.brokerage_id&&!j.subscription_product_id)return{status:"Brokerage",badge:"Team Member",variant:"outline"};if(j.is_trial&&j.trial_expires_at)return new Date(j.trial_expires_at)>new Date?{status:"Trial",badge:"Active Trial",variant:"default"}:{status:"Trial Expired",badge:"Expired",variant:"destructive"};if(j.subscription_status==="active"||j.subscription_status==="trialing"){const b=_Ne[j.subscription_product_id];return{status:(b==null?void 0:b.name)||"Active",badge:j.subscription_status==="trialing"?"Trial":"Active",variant:"default"}}return j.subscription_status==="canceled"||j.subscription_status==="past_due"?{status:"Canceled",badge:"Inactive",variant:"destructive"}:{status:"None",badge:"No Subscription",variant:"outline"}},g=c==null?void 0:c.filter(j=>{var S,A;if(!(((S=j.name)==null?void 0:S.toLowerCase().includes(s.toLowerCase()))||((A=j.email)==null?void 0:A.toLowerCase().includes(s.toLowerCase()))))return!1;if(a!=="all"){const T=j.subscription_source||"platform";if(a==="platform"&&T==="local_move_website"||a==="local_move_website"&&T!=="local_move_website")return!1}switch(f(j),n){case"active":return j.subscription_status==="active";case"trialing":return j.subscription_status==="trialing"||j.is_trial&&new Date(j.trial_expires_at)>new Date;case"grandfathered":return j.is_grandfathered;case"brokerage":return j.brokerage_id&&!j.subscription_product_id&&!j.is_grandfathered;case"expired":return j.subscription_status==="canceled"||j.subscription_status==="past_due"||j.is_trial&&new Date(j.trial_expires_at)<=new Date;case"none":return!j.subscription_status||j.subscription_status==="none";default:return!0}}),_={totalUsers:(c==null?void 0:c.length)||0,activeSubscriptions:(c==null?void 0:c.filter(j=>j.subscription_status==="active").length)||0,trials:(c==null?void 0:c.filter(j=>j.subscription_status==="trialing"||j.is_trial&&new Date(j.trial_expires_at)>new Date).length)||0,grandfathered:(c==null?void 0:c.filter(j=>j.is_grandfathered).length)||0,brokerageMembers:(c==null?void 0:c.filter(j=>j.brokerage_id&&!j.subscription_product_id&&!j.is_grandfathered).length)||0,individualSubscribers:(c==null?void 0:c.filter(j=>j.subscription_status==="active"&&j.subscription_product_id==="prod_Tc07cYplXUGNkm").length)||0,brokerageSubscribers:(c==null?void 0:c.filter(j=>j.subscription_status==="active"&&(j.subscription_product_id==="prod_Tc08MupgoVySDG"||j.subscription_product_id==="prod_Tc09N1tJ4RrAFn")).length)||0},v=j=>{window.open(`https://dashboard.stripe.com/customers/${j}`,"_blank")};return e.jsx(Ts,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs(B,{onClick:()=>u(),variant:"outline",size:"sm",children:[e.jsx(Ti,{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(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nn,{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:_.totalUsers})]})}),e.jsx(fe,{className:"border-green-500/50",children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pf,{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:_.activeSubscriptions})]})}),e.jsx(fe,{className:"border-blue-500/50",children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gr,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Trials"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-blue-600",children:_.trials})]})}),e.jsx(fe,{className:"border-purple-500/50",children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ff,{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:_.grandfathered})]})}),e.jsx(fe,{className:"border-orange-500/50",children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Va,{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:_.brokerageMembers})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bb,{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:_.individualSubscribers})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Va,{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:_.brokerageSubscribers})]})})]}),e.jsxs(Br,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(Fr,{children:[e.jsx(Kt,{value:"users",children:"All Users"}),e.jsx(Kt,{value:"brokerages",children:"Brokerages"}),e.jsxs(Kt,{value:"websites",className:"gap-2",children:[e.jsx(lc,{className:"h-4 w-4"}),"Website Subscriptions",p&&p.length>0&&e.jsx(ze,{variant:"secondary",className:"ml-1",children:p.length})]})]}),e.jsxs(is,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:s,onChange:j=>t(j.target.value),className:"pl-9"})]}),e.jsxs(ds,{value:a,onValueChange:j=>i(j),children:[e.jsx(ls,{className:"w-[200px]",children:e.jsx(us,{placeholder:"Source"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Sources"}),e.jsx(Qe,{value:"platform",children:"Platform"}),e.jsx(Qe,{value:"local_move_website",children:"Local Move Website"})]})]}),e.jsxs(ds,{value:n,onValueChange:j=>r(j),children:[e.jsx(ls,{className:"w-[200px]",children:e.jsx(us,{placeholder:"Filter by status"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Statuses"}),e.jsx(Qe,{value:"active",children:"Active Subscriptions"}),e.jsx(Qe,{value:"trialing",children:"Trials"}),e.jsx(Qe,{value:"grandfathered",children:"Grandfathered"}),e.jsx(Qe,{value:"brokerage",children:"Brokerage Members"}),e.jsx(Qe,{value:"expired",children:"Expired/Canceled"}),e.jsx(Qe,{value:"none",children:"No Subscription"})]})]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"User"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Plan"}),e.jsx(Ct,{children:"Brokerage"}),e.jsx(Ct,{children:"End Date"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:d?e.jsx(Hs,{children:e.jsx(ut,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(g==null?void 0:g.length)===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):g==null?void 0:g.map(j=>{var A,T;const b=f(j),S=_Ne[j.subscription_product_id];return e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:j.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:j.email})]})}),e.jsx(ut,{children:e.jsx(ze,{variant:b.variant,children:b.badge})}),e.jsx(ut,{children:e.jsx("span",{className:"text-sm",children:j.is_grandfathered?"Legacy Access":j.brokerage_id&&!j.subscription_product_id?"Brokerage Subscription":(S==null?void 0:S.name)||b.status})}),e.jsx(ut,{children:(A=j.brokerages)!=null&&A.name?e.jsx("span",{className:"text-sm",children:j.brokerages.name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(ut,{children:j.subscription_end_date?e.jsx("span",{className:"text-sm",children:Ss(new Date(j.subscription_end_date),"MMM d, yyyy")}):j.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",Ss(new Date(j.trial_expires_at),"MMM d, yyyy")]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[j.stripe_customer_id&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>v(j.stripe_customer_id),children:e.jsx(tr,{className:"h-4 w-4"})}),e.jsxs(bs,{children:[e.jsx(Ai,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",onClick:()=>o(j),children:"Details"})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Subscription Details"}),e.jsxs(Qn,{children:[j.name," (",j.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(ze,{variant:b.variant,className:"mt-1",children:b.badge})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Plan"}),e.jsx("p",{className:"font-medium",children:j.is_grandfathered?"Grandfathered (Legacy)":j.brokerage_id&&!j.subscription_product_id?"Brokerage Subscription":(S==null?void 0:S.name)||"None"})]}),j.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=j.brokerages)==null?void 0:T.name)||"Unknown"})]}),j.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:Ss(new Date(j.subscription_end_date),"MMMM d, yyyy")})]}),j.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:Ss(new Date(j.trial_expires_at),"MMMM d, yyyy")})]}),j.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:j.stripe_customer_id})]})]}),j.stripe_customer_id&&e.jsxs(B,{className:"w-full",onClick:()=>v(j.stripe_customer_id),children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},j.id)})})]})})})]}),e.jsx(is,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:h==null?void 0:h.map(j=>{var S,A;const b=(S=j.managers)==null?void 0:S.some(T=>T.subscription_status==="active"&&(T.subscription_product_id==="prod_Tc08MupgoVySDG"||T.subscription_product_id==="prod_Tc09N1tJ4RrAFn"));return e.jsxs(fe,{children:[e.jsx(Mt,{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(Va,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:j.name}),e.jsxs(Vn,{children:[j.agentCount," agents"]})]})]}),e.jsx(ze,{variant:b?"default":"outline",children:b?"Active Subscription":"No Active Subscription"})]})}),e.jsx(Ee,{children:((A=j.managers)==null?void 0:A.length)>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Managers:"}),j.managers.map(T=>{const L=_Ne[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:L?e.jsxs("div",{children:[e.jsx(ze,{variant:"default",children:L.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:L.price})]}):e.jsx(ze,{variant:"outline",children:"No Subscription"})})]},T.id)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},j.id)})})}),e.jsx(is,{value:"websites",className:"space-y-4",children:e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(lc,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(Vn,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(Ee,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Setup Fee"}),e.jsx(Ct,{children:"Monthly"}),e.jsx(Ct,{children:"Next Renewal"}),e.jsx(Ct,{children:"Started"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:p?p.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):p.map(j=>e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:j.agent_name||"—"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:j.agent_email})]})}),e.jsx(ut,{children:e.jsx(ze,{variant:j.status==="active"?"default":j.status==="canceled"?"destructive":"outline",children:j.status})}),e.jsx(ut,{children:j.setup_fee_paid?e.jsxs(ze,{variant:"secondary",children:["Paid · $",(j.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx(ze,{variant:"outline",children:"Unpaid"})}),e.jsxs(ut,{className:"font-medium",children:["$",(j.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(ut,{children:j.current_period_end?e.jsx("span",{className:"text-sm",children:Ss(new Date(j.current_period_end),"MMM d, yyyy")}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(ut,{children:e.jsx("span",{className:"text-sm",children:Ss(new Date(j.created_at),"MMM d, yyyy")})}),e.jsx(ut,{className:"text-right",children:j.stripe_customer_id&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>v(j.stripe_customer_id),children:e.jsx(tr,{className:"h-4 w-4"})})})]},j.id)):e.jsx(Hs,{children:e.jsx(ut,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function dHs(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(""),[l,o]=N.useState("all"),[c,d]=N.useState({total:0,qualified:0,pending:0,cancelled:0,totalDiscounts:0});N.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:g,error:_}=await q.from("referrals").select(` *, referrer_brokerage:brokerages!referrer_brokerage_id(name), referred_brokerage:brokerages!referred_brokerage_id(name), referred_user:profiles!referred_user_id(name, email) `).order("created_at",{ascending:!1});if(_)throw _;t(g||[]);const v=(g==null?void 0:g.filter(S=>S.status==="qualified").length)||0,j=(g==null?void 0:g.filter(S=>S.status==="pending").length)||0,b=(g==null?void 0:g.filter(S=>S.status==="cancelled").length)||0;d({total:(g==null?void 0:g.length)||0,qualified:v,pending:j,cancelled:b,totalDiscounts:v*25})}catch(g){console.error("Error fetching referrals:",g),ae.error("Failed to load referrals")}finally{r(!1)}},h=async()=>{try{ae.loading("Processing qualifications...");const{error:g}=await q.functions.invoke("process-referral-qualifications");if(g)throw g;ae.dismiss(),ae.success("Qualifications processed successfully"),u()}catch(g){ae.dismiss(),console.error("Error processing qualifications:",g),ae.error("Failed to process qualifications")}},p=s.filter(g=>{var j,b,S,A,T,L;const _=((b=(j=g.referrer_brokerage)==null?void 0:j.name)==null?void 0:b.toLowerCase().includes(a.toLowerCase()))||((A=(S=g.referred_brokerage)==null?void 0:S.name)==null?void 0:A.toLowerCase().includes(a.toLowerCase()))||((L=(T=g.referred_user)==null?void 0:T.email)==null?void 0:L.toLowerCase().includes(a.toLowerCase())),v=l==="all"||g.status===l;return _&&v}),f=g=>{switch(g){case"qualified":return e.jsxs(ze,{className:"bg-green-100 text-green-800",children:[e.jsx(Ri,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return e.jsxs(ze,{variant:"secondary",children:[e.jsx(gr,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs(ze,{variant:"destructive",children:[e.jsx(Hc,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return e.jsx(ze,{children:g})}};return e.jsx(Ts,{title:"Referral Program",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{title:"Referral Program",description:"Track and manage brokerage referrals",children:e.jsxs(B,{onClick:h,variant:"outline",children:[e.jsx(Ti,{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(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nn,{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(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ri,{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(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gr,{className:"h-5 w-5 text-amber-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.pending}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pending"})]})]})})}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hc,{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(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zl,{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(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"All Referrals"}),e.jsx(Vn,{children:"View and manage all referral relationships"})]}),e.jsxs(Ee,{children:[e.jsxs("div",{className:"flex gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by brokerage or email...",value:a,onChange:g=>i(g.target.value),className:"pl-10"})]}),e.jsxs(ds,{value:l,onValueChange:o,children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(us,{placeholder:"Filter by status"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Statuses"}),e.jsx(Qe,{value:"pending",children:"Pending"}),e.jsx(Qe,{value:"qualified",children:"Qualified"}),e.jsx(Qe,{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(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Referrer"}),e.jsx(Ct,{children:"Referred"}),e.jsx(Ct,{children:"Signup Date"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Qualified Date"}),e.jsx(Ct,{children:"Discount"})]})}),e.jsx(ha,{children:p.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):p.map(g=>{var _,v,j,b;return e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:((_=g.referrer_brokerage)==null?void 0:_.name)||"Unknown"}),e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("p",{children:((v=g.referred_brokerage)==null?void 0:v.name)||((j=g.referred_user)==null?void 0:j.name)||"Pending setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(b=g.referred_user)==null?void 0:b.email})]})}),e.jsx(ut,{children:Ss(new Date(g.signup_date),"MMM d, yyyy")}),e.jsx(ut,{children:f(g.status)}),e.jsx(ut,{children:g.qualified_date?Ss(new Date(g.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(ut,{children:g.discount_applied?e.jsx(ze,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})})]},g.id)})})]})]})]})]})})}const wNe=[{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"}],uHs=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function hHs(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(null),[c,d]=N.useState({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0});N.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:b,error:S}=await q.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(S)throw S;t(b||[])}catch(b){console.error("Error fetching checklist items:",b),ae.error("Failed to load checklist items")}finally{r(!1)}},h=()=>{o(null),d({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0}),i(!0)},p=b=>{o(b),d({title:b.title,description:b.description||"",action_type:b.action_type,target_role:b.target_role,is_active:b.is_active}),i(!0)},f=async()=>{if(!c.title.trim()){ae.error("Title is required");return}try{if(l){const{error:b}=await q.from("onboarding_checklist_items").update({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active}).eq("id",l.id);if(b)throw b;ae.success("Checklist item updated")}else{const b=s.filter(A=>A.target_role===c.target_role).reduce((A,T)=>Math.max(A,T.sort_order),-1),{error:S}=await q.from("onboarding_checklist_items").insert({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active,sort_order:b+1});if(S)throw S;ae.success("Checklist item created")}i(!1),u()}catch(b){console.error("Error saving checklist item:",b),ae.error("Failed to save checklist item")}},g=async b=>{if(confirm("Are you sure you want to delete this checklist item?"))try{const{error:S}=await q.from("onboarding_checklist_items").delete().eq("id",b);if(S)throw S;ae.success("Checklist item deleted"),u()}catch(S){console.error("Error deleting checklist item:",S),ae.error("Failed to delete checklist item")}},_=async b=>{try{const{error:S}=await q.from("onboarding_checklist_items").update({is_active:!b.is_active}).eq("id",b.id);if(S)throw S;ae.success(b.is_active?"Item deactivated":"Item activated"),u()}catch(S){console.error("Error toggling item:",S),ae.error("Failed to update item")}},v=s.filter(b=>b.target_role==="brokerage_manager"),j=s.filter(b=>b.target_role==="agent");return e.jsxs(Ts,{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(Is,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(ze,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),e.jsx(Ee,{children:v.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{className:"w-12",children:"#"}),e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Action Type"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:v.map((b,S)=>{var A;return e.jsxs(Hs,{children:[e.jsx(ut,{className:"text-muted-foreground",children:S+1}),e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:b.title}),b.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:b.description})]})}),e.jsx(ut,{children:e.jsx(ze,{variant:"outline",children:((A=wNe.find(T=>T.value===b.action_type))==null?void 0:A.label)||b.action_type})}),e.jsx(ut,{children:e.jsx(bn,{checked:b.is_active,onCheckedChange:()=>_(b)})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>p(b),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>g(b.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},b.id)})})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(ze,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),e.jsx(Ee,{children:j.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for agents"}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{className:"w-12",children:"#"}),e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Action Type"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:j.map((b,S)=>{var A;return e.jsxs(Hs,{children:[e.jsx(ut,{className:"text-muted-foreground",children:S+1}),e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:b.title}),b.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:b.description})]})}),e.jsx(ut,{children:e.jsx(ze,{variant:"outline",children:((A=wNe.find(T=>T.value===b.action_type))==null?void 0:A.label)||b.action_type})}),e.jsx(ut,{children:e.jsx(bn,{checked:b.is_active,onCheckedChange:()=>_(b)})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>p(b),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>g(b.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},b.id)})})]})})]})]}),e.jsx(bs,{open:a,onOpenChange:i,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:l?"Edit Checklist Item":"Add Checklist Item"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",value:c.title,onChange:b=>d({...c,title:b.target.value}),placeholder:"e.g., Watch your first academy video"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Es,{id:"description",value:c.description,onChange:b=>d({...c,description:b.target.value}),placeholder:"Optional description for the checklist item",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Target Role"}),e.jsxs(ds,{value:c.target_role,onValueChange:b=>d({...c,target_role:b}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:uHs.map(b=>e.jsx(Qe,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Action Type"}),e.jsxs(ds,{value:c.action_type,onValueChange:b=>d({...c,action_type:b}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:wNe.map(b=>e.jsx(Qe,{value:b.value,children:b.label},b.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bn,{id:"is_active",checked:c.is_active,onCheckedChange:b=>d({...c,is_active:b})}),e.jsx(se,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(B,{onClick:f,children:l?"Save Changes":"Create Item"})]})]})})]})}function mHs(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("name"),[l,o]=N.useState("asc"),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState(""),[g,_]=N.useState(""),{data:v}=ct({queryKey:["admin-brokerages"],queryFn:async()=>{const{data:z,error:V}=await q.from("brokerages").select("id, name").order("name");if(V)throw V;return z}}),j=async z=>{let W=[],Y=0,K=!0;for(;K;){const{data:J,error:ne}=await z(Y,Y+1e3-1);if(ne)throw ne;J&&J.length>0?(W=[...W,...J],Y+=1e3,K=J.length===1e3):K=!1}return W},{data:b,isLoading:S}=ct({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const z=await j((De,Ie)=>q.from("profiles").select("id, name, email, brokerage_id, created_at").range(De,Ie)),{data:V}=await q.from("brokerages").select("id, name"),W=new Map((V==null?void 0:V.map(De=>[De.id,De.name]))||[]),[{data:Y},{data:K},{data:J},{data:ne},{data:ie},{data:he},{data:ce}]=await Promise.all([q.rpc("get_admin_contact_counts"),q.rpc("get_admin_video_counts"),q.rpc("get_admin_popby_counts"),q.rpc("get_admin_listing_counts"),q.rpc("get_admin_deal_counts"),q.rpc("get_admin_portal_counts"),q.rpc("get_admin_sendable_card_counts")]),pe=new Map;Y==null||Y.forEach(De=>pe.set(De.owner_user_id,De.contact_count));const le=new Map;K==null||K.forEach(De=>le.set(De.owner_user_id,De.video_count));const ve=new Map;J==null||J.forEach(De=>ve.set(De.owner_user_id,De.popby_count));const ge=new Map;ne==null||ne.forEach(De=>ge.set(De.agent_id,De.listing_count));const Te=new Map;ie==null||ie.forEach(De=>Te.set(De.owner_user_id,De.deal_count));const Me=new Map;he==null||he.forEach(De=>Me.set(De.owner_user_id,{total:De.portal_count,active:De.active_portal_count}));const Ce=new Map;return ce==null||ce.forEach(De=>Ce.set(De.owner_user_id,{total:De.card_count,sent:De.sent_card_count,views:De.total_card_views})),z.map(De=>{const Ie=Me.get(De.id),Fe=Ce.get(De.id);return{id:De.id,name:De.name||"Unknown",email:De.email||"",brokerage_id:De.brokerage_id,brokerage_name:De.brokerage_id&&W.get(De.brokerage_id)||null,contact_count:pe.get(De.id)||0,video_count:le.get(De.id)||0,popby_count:ve.get(De.id)||0,listing_count:ge.get(De.id)||0,deal_count:Te.get(De.id)||0,portal_count:(Ie==null?void 0:Ie.total)||0,active_portal_count:(Ie==null?void 0:Ie.active)||0,card_count:(Fe==null?void 0:Fe.total)||0,sent_card_count:(Fe==null?void 0:Fe.sent)||0,total_card_views:(Fe==null?void 0:Fe.views)||0,created_at:De.created_at}})}}),A=N.useMemo(()=>{if(!b)return[];let z=b.filter(V=>{const W=s.toLowerCase(),Y=!s||V.name.toLowerCase().includes(W)||V.email.toLowerCase().includes(W),K=n==="all"||n==="none"&&!V.brokerage_id||V.brokerage_id===n,J=parseInt(c)||0,ne=parseInt(u)||0,ie=parseInt(p)||0,he=parseInt(g)||0,ce=V.contact_count>=J&&V.video_count>=ne&&V.popby_count>=ie&&V.listing_count>=he;return Y&&K&&ce});return z.sort((V,W)=>{let Y=0;return a==="name"?Y=V.name.localeCompare(W.name):Y=V[a]-W[a],l==="asc"?Y:-Y}),z},[b,s,n,a,l,c,u,p,g]),T=z=>{a===z?o(l==="asc"?"desc":"asc"):(i(z),o("desc"))},L=()=>{const z=["Name","Email","Brokerage","Contacts","Videos","Popbys","Listings","Deals","Portals (Active)","Cards Created","Cards Sent","Card Views"],V=A.map(ne=>[ne.name,ne.email,ne.brokerage_name||"None",ne.contact_count,ne.video_count,ne.popby_count,ne.listing_count,ne.deal_count,`${ne.portal_count} (${ne.active_portal_count})`,ne.card_count,ne.sent_card_count,ne.total_card_views]),W=[z.join(","),...V.map(ne=>ne.map(ie=>`"${ie}"`).join(","))].join(` `),Y=new Blob([W],{type:"text/csv"}),K=URL.createObjectURL(Y),J=document.createElement("a");J.href=K,J.download=`agent-os-user-stats-${new Date().toISOString().split("T")[0]}.csv`,J.click(),URL.revokeObjectURL(K)},D=N.useMemo(()=>A.length?A.reduce((z,V)=>({contacts:z.contacts+V.contact_count,videos:z.videos+V.video_count,popbys:z.popbys+V.popby_count,listings:z.listings+V.listing_count,deals:z.deals+V.deal_count,portals:z.portals+V.portal_count,activePortals:z.activePortals+V.active_portal_count,cards:z.cards+V.card_count,sentCards:z.sentCards+V.sent_card_count,cardViews:z.cardViews+V.total_card_views}),{contacts:0,videos:0,popbys:0,listings:0,deals:0,portals:0,activePortals:0,cards:0,sentCards:0,cardViews:0}):{contacts:0,videos:0,popbys:0,listings:0,deals:0,portals:0,activePortals:0,cards:0,sentCards:0,cardViews:0},[A]),M=N.useMemo(()=>A.length?{portals:A.filter(z=>z.portal_count>0).length,cards:A.filter(z=>z.card_count>0).length}:{portals:0,cards:0},[A]),F=({field:z,children:V})=>e.jsx(Ct,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>T(z),children:e.jsxs("div",{className:"flex items-center gap-1",children:[V,e.jsx(em,{className:`h-3 w-3 ${a===z?"text-primary":"text-muted-foreground"}`})]})});return e.jsx(Ww,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(fe,{className:"border-blue-500/20 bg-gradient-to-br from-blue-500/5 to-transparent",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(It,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(xw,{className:"h-4 w-4 text-blue-500"}),"Client Portals"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:M.portals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Agents Using"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:D.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:D.activePortals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Active Portals"})]})]})})]}),e.jsxs(fe,{className:"border-violet-500/20 bg-gradient-to-br from-violet-500/5 to-transparent",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(It,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Vs,{className:"h-4 w-4 text-violet-500"}),"Card Studio"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"grid grid-cols-4 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:M.cards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Agents Using"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:D.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:D.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:D.cardViews}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Views"})]})]})})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5"}),"User Activity Analytics"]}),e.jsx(Vn,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:L,children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-6",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:s,onChange:z=>t(z.target.value),className:"pl-9"})]})}),e.jsx("div",{children:e.jsxs(ds,{value:n,onValueChange:r,children:[e.jsxs(ls,{children:[e.jsx(Va,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(us,{placeholder:"Brokerage"})]}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Brokerages"}),e.jsx(Qe,{value:"none",children:"No Brokerage"}),v==null?void 0:v.map(z=>e.jsx(Qe,{value:z.id,children:z.name},z.id))]})]})}),e.jsx("div",{children:e.jsx(ye,{type:"number",placeholder:"Min contacts",value:c,onChange:z=>d(z.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(ye,{type:"number",placeholder:"Min videos",value:u,onChange:z=>h(z.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(ye,{type:"number",placeholder:"Min popbys",value:p,onChange:z=>f(z.target.value),min:"0"})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-8 text-sm",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:A.length}),e.jsx("div",{className:"text-muted-foreground",children:"Users"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:D.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:D.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:D.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:D.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:D.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:D.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:D.cards.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Cards"})]})]}),S?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(ts,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(F,{field:"name",children:"Name"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Brokerage"}),e.jsx(F,{field:"contact_count",children:"Contacts"}),e.jsx(F,{field:"video_count",children:"Videos"}),e.jsx(F,{field:"popby_count",children:"Popbys"}),e.jsx(F,{field:"listing_count",children:"Listings"}),e.jsx(F,{field:"deal_count",children:"Deals"}),e.jsx(F,{field:"portal_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xw,{className:"h-3 w-3 text-blue-500"}),"Portals"]})}),e.jsx(F,{field:"card_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vs,{className:"h-3 w-3 text-violet-500"}),"Cards"]})})]})}),e.jsx(ha,{children:A.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No users found matching your filters"})}):A.map(z=>e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:z.name}),e.jsx(ut,{className:"text-muted-foreground",children:z.email}),e.jsx(ut,{children:z.brokerage_name?e.jsx(ze,{variant:"secondary",children:z.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ut,{children:e.jsx(ze,{variant:z.contact_count>0?"default":"outline",children:z.contact_count})}),e.jsx(ut,{children:e.jsx(ze,{variant:z.video_count>0?"default":"outline",children:z.video_count})}),e.jsx(ut,{children:e.jsx(ze,{variant:z.popby_count>0?"default":"outline",children:z.popby_count})}),e.jsx(ut,{children:e.jsx(ze,{variant:z.listing_count>0?"default":"outline",children:z.listing_count})}),e.jsx(ut,{children:e.jsx(ze,{variant:z.deal_count>0?"default":"outline",children:z.deal_count})}),e.jsx(ut,{children:z.portal_count>0?e.jsxs(Ec,{children:[e.jsx(Ac,{children:e.jsxs(ze,{variant:"default",className:"bg-blue-600 hover:bg-blue-700",children:[z.portal_count,z.active_portal_count>0&&e.jsxs("span",{className:"ml-1 opacity-75",children:["(",z.active_portal_count," active)"]})]})}),e.jsxs(vc,{children:[e.jsxs("p",{children:[z.portal_count," total portals"]}),e.jsxs("p",{children:[z.active_portal_count," currently active"]})]})]}):e.jsx(ze,{variant:"outline",children:"0"})}),e.jsx(ut,{children:z.card_count>0?e.jsxs(Ec,{children:[e.jsx(Ac,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ze,{variant:"default",className:"bg-violet-600 hover:bg-violet-700",children:z.card_count}),z.sent_card_count>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-emerald-600",children:[e.jsx(cr,{className:"h-3 w-3"}),z.sent_card_count]}),z.total_card_views>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-muted-foreground",children:[e.jsx(Er,{className:"h-3 w-3"}),z.total_card_views]})]})}),e.jsxs(vc,{children:[e.jsxs("p",{children:[z.card_count," cards created"]}),e.jsxs("p",{children:[z.sent_card_count," sent"]}),e.jsxs("p",{children:[z.total_card_views," total views"]})]})]}):e.jsx(ze,{variant:"outline",children:"0"})})]},z.id))})]})})]})]})]})})}function pHs(){Ba(),Ht();const[s,t]=N.useState("user-analytics"),{data:n}=ct({queryKey:["admin-feature-flags"],queryFn:async()=>{const{data:f,error:g}=await q.from("feature_flags").select("*").order("key");if(g)throw g;return f}}),{data:r,isLoading:a}=ct({queryKey:["admin-relationship-types"],queryFn:async()=>{const{data:f,error:g}=await q.from("relationship_types").select("*").order("sort_order");if(g)throw g;return f}}),{data:i,isLoading:l}=ct({queryKey:["admin-action-types"],queryFn:async()=>{const{data:f,error:g}=await q.from("action_types").select("*").order("sort_order");if(g)throw g;return f}}),{data:o,isLoading:c}=ct({queryKey:["admin-action-scripts"],queryFn:async()=>{const{data:f,error:g}=await q.from("action_scripts").select("*, action_type:action_types(*)");if(g)throw g;return f}}),{data:d,isLoading:u}=ct({queryKey:["admin-touchpoint-plans"],queryFn:async()=>{const{data:f,error:g}=await q.from("touchpoint_plans").select("*").order("name");if(g)throw g;return f}}),{data:h,isLoading:p}=ct({queryKey:["admin-popby-items"],queryFn:async()=>{const{data:f,error:g}=await q.from("popby_items").select("*").is("owner_user_id",null).order("name");if(g)throw g;return f}});return e.jsx(Ts,{title:"Agent OS Control Center",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{title:"Agent OS Control Center",description:"Manage InnerCircle settings, scripts, and touchpoint plans"}),e.jsxs(Br,{value:s,onValueChange:t,children:[e.jsxs(Fr,{className:"grid w-full grid-cols-9",children:[e.jsxs(Kt,{value:"user-analytics",className:"gap-2",children:[e.jsx(yo,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Kt,{value:"relationship-types",className:"gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),e.jsxs(Kt,{value:"action-types",className:"gap-2",children:[e.jsx(Ar,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Kt,{value:"scripts",className:"gap-2",children:[e.jsx(Nr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),e.jsxs(Kt,{value:"video-scripts",className:"gap-2",children:[e.jsx(Ah,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),e.jsxs(Kt,{value:"plans",className:"gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),e.jsxs(Kt,{value:"popbys",className:"gap-2",children:[e.jsx(Oi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),e.jsxs(Kt,{value:"settings",className:"gap-2",children:[e.jsx(Xo,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(Kt,{value:"feature-flags",className:"gap-2",children:[e.jsx(K2,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(is,{value:"user-analytics",className:"mt-6",children:e.jsx(mHs,{})}),e.jsx(is,{value:"relationship-types",className:"mt-6",children:e.jsx(fHs,{types:r||[],isLoading:a})}),e.jsx(is,{value:"action-types",className:"mt-6",children:e.jsx(xHs,{types:i||[],isLoading:l})}),e.jsx(is,{value:"scripts",className:"mt-6",children:e.jsx(gHs,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(is,{value:"video-scripts",className:"mt-6",children:e.jsx(_Hs,{})}),e.jsx(is,{value:"plans",className:"mt-6",children:e.jsx(yHs,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:u})}),e.jsx(is,{value:"popbys",className:"mt-6",children:e.jsx(bHs,{items:h||[],isLoading:p})}),e.jsx(is,{value:"settings",className:"mt-6",children:e.jsx(wHs,{})}),e.jsx(is,{value:"feature-flags",className:"mt-6",children:e.jsx(vHs,{flags:n||[]})})]})]})})}function fHs({types:s,isLoading:t}){const{toast:n}=Ba(),r=Ht(),[a,i]=N.useState(null),[l,o]=N.useState(!1),c=gt({mutationFn:async u=>{if(u.id){const{error:h}=await q.from("relationship_types").update({name:u.name,description:u.description,icon:u.icon}).eq("id",u.id);if(h)throw h}else{const{error:h}=await q.from("relationship_types").insert([{name:u.name,description:u.description,icon:u.icon,sort_order:s.length}]);if(h)throw h}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-relationship-types"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:u=>{n({title:"Error",description:u.message,variant:"destructive"})}}),d=async u=>{await q.from("relationship_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-relationship-types"]})};return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Relationship Types"}),e.jsx(Vn,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Type"]})]}),e.jsx(Ee,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ts,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{className:"w-12"}),e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"w-24",children:"Actions"})]})}),e.jsx(ha,{children:s.map(u=>e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsx(Fu,{className:"h-4 w-4 text-muted-foreground cursor-grab"})}),e.jsx(ut,{className:"font-medium",children:u.name}),e.jsx(ut,{className:"text-muted-foreground",children:u.description}),e.jsx(ut,{children:e.jsx(bn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(ut,{children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(_a,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsxs(_s,{children:[a?"Edit":"Add"," Relationship Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const h=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:h.get("name"),description:h.get("description"),icon:h.get("icon")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(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(Es,{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(Xn,{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(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function xHs({types:s,isLoading:t}){const{toast:n}=Ba(),r=Ht(),[a,i]=N.useState(null),[l,o]=N.useState(!1),c=gt({mutationFn:async u=>{if(u.id){const{error:h}=await q.from("action_types").update({name:u.name,description:u.description,icon:u.icon,color:u.color}).eq("id",u.id);if(h)throw h}else{const{error:h}=await q.from("action_types").insert([{name:u.name,description:u.description,icon:u.icon,color:u.color,sort_order:s.length}]);if(h)throw h}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-action-types"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:u=>{n({title:"Error",description:u.message,variant:"destructive"})}}),d=async u=>{await q.from("action_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-action-types"]})};return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Action Types"}),e.jsx(Vn,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Action"]})]}),e.jsx(Ee,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ts,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{children:"Color"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"w-24",children:"Actions"})]})}),e.jsx(ha,{children:s.map(u=>e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:u.name}),e.jsx(ut,{className:"text-muted-foreground",children:u.description}),e.jsx(ut,{children:u.color&&e.jsx("div",{className:"w-6 h-6 rounded",style:{backgroundColor:u.color}})}),e.jsx(ut,{children:e.jsx(bn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(ut,{children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(_a,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsxs(_s,{children:[a?"Edit":"Add"," Action Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const h=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:h.get("name"),description:h.get("description"),icon:h.get("icon"),color:h.get("color")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(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(Es,{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(Xn,{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(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function gHs({scripts:s,actionTypes:t,isLoading:n}){const{toast:r}=Ba(),a=Ht(),[i,l]=N.useState(null),[o,c]=N.useState(!1),d=gt({mutationFn:async h=>{if(h.id){const{error:p}=await q.from("action_scripts").update({title:h.title,action_type_id:h.action_type_id,tone:h.tone,script_body:h.script_body,active:h.active}).eq("id",h.id);if(p)throw p}else{const{error:p}=await q.from("action_scripts").insert([{title:h.title,action_type_id:h.action_type_id,tone:h.tone,script_body:h.script_body,active:!0}]);if(p)throw p}},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=gt({mutationFn:async h=>{const{error:p}=await q.from("action_scripts").delete().eq("id",h);if(p)throw p},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),r({title:"Deleted successfully"})}});return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Script Library"}),e.jsx(Vn,{children:"Create and manage scripts for each action type"})]}),e.jsxs(B,{onClick:()=>{l(null),c(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Ee,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ts,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Action Type"}),e.jsx(Ct,{children:"Tone"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"w-24",children:"Actions"})]})}),e.jsx(ha,{children:s.map(h=>{var p;return e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:h.title}),e.jsx(ut,{children:e.jsx(ze,{variant:"outline",children:((p=h.action_type)==null?void 0:p.name)||"Unknown"})}),e.jsx(ut,{className:"text-muted-foreground",children:h.tone}),e.jsx(ut,{children:e.jsx(ze,{variant:h.active?"default":"secondary",children:h.active?"Active":"Inactive"})}),e.jsxs(ut,{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{l(h),c(!0)},children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u.mutate(h.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})]},h.id)})})]})}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{children:e.jsxs(_s,{children:[i?"Edit":"Add"," Script"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const p=new FormData(h.currentTarget);d.mutate({id:i==null?void 0:i.id,title:p.get("title"),action_type_id:p.get("action_type_id"),tone:p.get("tone"),script_body:p.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(ds,{name:"action_type_id",defaultValue:i==null?void 0:i.action_type_id,children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select action type"})}),e.jsx(cs,{children:t.map(h=>e.jsx(Qe,{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(Es,{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(Xn,{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(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function yHs({plans:s,actionTypes:t,scripts:n,isLoading:r}){const{toast:a}=Ba(),i=Ht(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(null),[p,f]=N.useState(!1),[g,_]=N.useState(null),[v,j]=N.useState(null),{data:b}=ct({queryKey:["plan-items",u],queryFn:async()=>{if(!u)return[];const{data:F,error:z}=await q.from("touchpoint_plan_items").select("*").eq("plan_id",u).order("month_number");if(z)throw z;return F},enabled:!!u}),S=gt({mutationFn:async F=>{if(F.id){const{error:z}=await q.from("touchpoint_plans").update({name:F.name,description:F.description,active:F.active}).eq("id",F.id);if(z)throw z}else{const{error:z}=await q.from("touchpoint_plans").insert([{name:F.name,description:F.description,active:!0}]);if(z)throw z}},onSuccess:()=>{i.invalidateQueries({queryKey:["admin-touchpoint-plans"]}),d(!1),o(null),a({title:"Saved successfully"})},onError:F=>{a({title:"Error",description:F.message,variant:"destructive"})}}),A=gt({mutationFn:async F=>{if(F.id){const{error:z}=await q.from("touchpoint_plan_items").update({action_type_id:F.action_type_id,default_script_id:F.default_script_id,notes:F.notes}).eq("id",F.id);if(z)throw z}else{const{error:z}=await q.from("touchpoint_plan_items").insert([{plan_id:F.plan_id,month_number:F.month_number,action_type_id:F.action_type_id,default_script_id:F.default_script_id,notes:F.notes}]);if(z)throw z}},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]}),a({title:"Item saved"})}}),T=gt({mutationFn:async F=>{const{error:z}=await q.from("touchpoint_plan_items").delete().eq("id",F);if(z)throw z},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]})}}),L=gt({mutationFn:async F=>{const{data:z,error:V}=await q.from("action_scripts").insert([{...F,active:!0}]).select().single();if(V)throw V;return z},onSuccess:async F=>{i.invalidateQueries({queryKey:["admin-action-scripts"]}),g&&await A.mutateAsync({id:g.itemId,plan_id:u,month_number:g.month,action_type_id:g.actionTypeId,default_script_id:F.id}),f(!1),_(null),a({title:"Script created and assigned"})},onError:F=>{a({title:"Error",description:F.message,variant:"destructive"})}}),D=(F,z,V)=>{_({month:F,actionTypeId:z,itemId:V}),f(!0)},M=F=>n.find(z=>z.id===F);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Touchpoint Plans"}),e.jsx(Vn,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs(B,{onClick:()=>{o(null),d(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),e.jsx(Ee,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ts,{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(F=>e.jsxs(fe,{className:`cursor-pointer transition-colors ${u===F.id?"border-primary":""}`,onClick:()=>h(F.id),children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(It,{className:"text-base",children:F.name}),e.jsx(B,{variant:"ghost",size:"icon",onClick:z=>{z.stopPropagation(),o(F),d(!0)},children:e.jsx(_a,{className:"h-4 w-4"})})]})}),e.jsxs(Ee,{children:[e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:F.description}),e.jsx(ze,{variant:F.active?"default":"secondary",className:"mt-2",children:F.active?"Active":"Inactive"})]})]},F.id))})})]}),u&&e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Plan Schedule"}),e.jsx(Vn,{children:"Configure the monthly touchpoint schedule. Select an action type for each month, then assign or create a script."})]}),e.jsx(Ee,{children:e.jsx("div",{className:"grid gap-3",children:Array.from({length:12},(F,z)=>z+1).map(F=>{const z=b==null?void 0:b.find(Y=>Y.month_number===F),V=z!=null&&z.default_script_id?M(z.default_script_id):null,W=n.filter(Y=>Y.action_type_id===(z==null?void 0:z.action_type_id)&&Y.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 ",F]}),e.jsxs(ds,{value:(z==null?void 0:z.action_type_id)||"none",onValueChange:Y=>{Y==="none"&&z?T.mutate(z.id):Y!=="none"&&A.mutate({id:z==null?void 0:z.id,plan_id:u,month_number:F,action_type_id:Y,default_script_id:null})},children:[e.jsx(ls,{className:"w-40",children:e.jsx(us,{placeholder:"No action"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"No action"}),t.filter(Y=>Y.active).map(Y=>e.jsx(Qe,{value:Y.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[Y.color&&e.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Y.color}}),Y.name]})},Y.id))]})]}),z&&e.jsxs(e.Fragment,{children:[e.jsxs(ds,{value:z.default_script_id||"none",onValueChange:Y=>{j(null),A.mutate({id:z.id,default_script_id:Y==="none"?null:Y})},children:[e.jsx(ls,{className:"w-56",children:e.jsx(us,{placeholder:"Select script"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"No default script"}),W.map(Y=>e.jsxs(Qe,{value:Y.id,children:[Y.title," ",Y.tone&&`(${Y.tone})`]},Y.id))]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>D(F,z.action_type_id,z.id),children:[e.jsx(Is,{className:"h-3 w-3 mr-1"}),"New Script"]}),V&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>j((v==null?void 0:v.id)===V.id?null:V),children:(v==null?void 0:v.id)===V.id?"Hide":"Preview"})]})]}),v&&(z==null?void 0:z.default_script_id)===v.id&&e.jsxs("div",{className:"ml-24 p-3 bg-muted rounded-lg text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ze,{variant:"outline",children:v.title}),v.tone&&e.jsx(ze,{variant:"secondary",children:v.tone})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:v.script_body})]})]},F)})})})]}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsxs(_s,{children:[l?"Edit":"Add"," Touchpoint Plan"]})}),e.jsxs("form",{onSubmit:F=>{F.preventDefault();const z=new FormData(F.currentTarget);S.mutate({id:l==null?void 0:l.id,name:z.get("name"),description:z.get("description"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(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(Es,{id:"description",name:"description",defaultValue:(l==null?void 0:l.description)||"",rows:3})]})]}),e.jsxs(Xn,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:S.isPending,children:[S.isPending&&e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),e.jsx(bs,{open:p,onOpenChange:f,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create New Script"}),e.jsxs(Qn,{children:["Create a script for Month ",g==null?void 0:g.month,". Use ","{{FirstName}}",", ","{{LastName}}",", and ","{{AgentName}}"," as placeholders."]})]}),e.jsxs("form",{onSubmit:F=>{F.preventDefault();const z=new FormData(F.currentTarget);L.mutate({title:z.get("title"),action_type_id:g.actionTypeId,tone:z.get("tone"),script_body:z.get("script_body")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(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(Es,{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(Xn,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:L.isPending,children:[L.isPending&&e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function vHs({flags:s}){const{toast:t}=Ba(),n=Ht(),r=async(a,i)=>{const{error:l}=await q.from("feature_flags").update({...i,updated_at:new Date().toISOString()}).eq("id",a.id);l?t({title:"Error",description:l.message,variant:"destructive"}):(n.invalidateQueries({queryKey:["admin-feature-flags"]}),t({title:"Flag updated"}))};return e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Feature Flags"}),e.jsx(Vn,{children:"Control which features are enabled for members"})]}),e.jsx(Ee,{children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Flag"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Notes"}),e.jsx(Ct,{children:"Last Updated"})]})}),e.jsx(ha,{children:s.map(a=>e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-mono text-sm",children:a.key}),e.jsx(ut,{children:e.jsx(bn,{checked:a.enabled,onCheckedChange:i=>r(a,{enabled:i})})}),e.jsx(ut,{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(ut,{className:"text-muted-foreground text-sm",children:new Date(a.updated_at).toLocaleDateString()})]},a.id))})]})})]})}function bHs({items:s,isLoading:t}){const{toast:n}=Ba(),r=Ht(),[a,i]=N.useState(null),[l,o]=N.useState(!1),c=gt({mutationFn:async h=>{if(h.id){const{error:p}=await q.from("popby_items").update({name:h.name,description:h.description}).eq("id",h.id);if(p)throw p}else{const{error:p}=await q.from("popby_items").insert([{name:h.name,description:h.description,owner_user_id:null}]);if(p)throw p}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:h=>{n({title:"Error",description:h.message,variant:"destructive"})}}),d=async h=>{await q.from("popby_items").update({is_active:!h.is_active}).eq("id",h.id),r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]})},u=async h=>{await q.from("popby_items").delete().eq("id",h),r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]}),n({title:"Deleted successfully"})};return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Popby Ideas"}),e.jsx(Vn,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsx(Ee,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ts,{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(Oi,{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(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"w-24",children:"Actions"})]})}),e.jsx(ha,{children:s.map(h=>e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:h.name}),e.jsx(ut,{className:"text-muted-foreground",children:h.description}),e.jsx(ut,{children:e.jsx(bn,{checked:h.is_active,onCheckedChange:()=>d(h)})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{i(h),o(!0)},children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u(h.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},h.id))})]})}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsxs(_s,{children:[a?"Edit":"Add"," Popby Idea"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const p=new FormData(h.currentTarget);c.mutate({id:a==null?void 0:a.id,name:p.get("name"),description:p.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(Es,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),e.jsxs(Xn,{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(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function _Hs(){var f;const{toast:s}=Ba(),t=Ht(),[n,r]=N.useState(null),[a,i]=N.useState(!1),{data:l,isLoading:o}=ct({queryKey:["admin-video-script-categories"],queryFn:async()=>{const{data:g,error:_}=await q.from("video_script_categories").select("*").order("sort_order");if(_)throw _;return g}}),{data:c,isLoading:d}=ct({queryKey:["admin-video-scripts"],queryFn:async()=>{const{data:g,error:_}=await q.from("video_scripts").select("*, category:video_script_categories(*)").order("title");if(_)throw _;return g}}),u=gt({mutationFn:async g=>{var _,v;if(g.id){const{error:j}=await q.from("video_scripts").update({title:g.title,script_text:g.script_text,category_id:g.category_id,tags:((_=g.tags)==null?void 0:_.split(",").map(b=>b.trim()).filter(Boolean))||[]}).eq("id",g.id);if(j)throw j}else{const{error:j}=await q.from("video_scripts").insert([{title:g.title,script_text:g.script_text,category_id:g.category_id||null,tags:((v=g.tags)==null?void 0:v.split(",").map(b=>b.trim()).filter(Boolean))||[]}]);if(j)throw j}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-video-scripts"]}),i(!1),r(null),s({title:"Video script saved!"})},onError:g=>s({title:"Error",description:g.message,variant:"destructive"})}),h=async g=>{await q.from("video_scripts").update({is_active:!g.is_active}).eq("id",g.id),t.invalidateQueries({queryKey:["admin-video-scripts"]})},p=async g=>{confirm("Delete this video script?")&&(await q.from("video_scripts").delete().eq("id",g),t.invalidateQueries({queryKey:["admin-video-scripts"]}),s({title:"Script deleted"}))};return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Video Scripts"}),e.jsx(Vn,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs(B,{onClick:()=>{r(null),i(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Ee,{children:d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ts,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Title"}),e.jsx(Ct,{children:"Category"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"w-24",children:"Actions"})]})}),e.jsx(ha,{children:c==null?void 0:c.map(g=>{var _;return e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:g.title}),e.jsx(ut,{className:"text-muted-foreground",children:((_=g.category)==null?void 0:_.name)||"Uncategorized"}),e.jsx(ut,{children:e.jsx(bn,{checked:g.is_active,onCheckedChange:()=>h(g)})}),e.jsxs(ut,{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{r(g),i(!0)},children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>p(g.id),children:e.jsx(_n,{className:"h-4 w-4"})})]})]},g.id)})})]})}),e.jsx(bs,{open:a,onOpenChange:i,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{children:e.jsxs(_s,{children:[n?"Edit":"Add"," Video Script"]})}),e.jsxs("form",{onSubmit:g=>{g.preventDefault();const _=new FormData(g.currentTarget);u.mutate({id:n==null?void 0:n.id,title:_.get("title"),script_text:_.get("script_text"),category_id:_.get("category_id")||null,tags:_.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(ds,{name:"category_id",defaultValue:(n==null?void 0:n.category_id)||"",children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select category"})}),e.jsx(cs,{children:l==null?void 0:l.map(g=>e.jsx(Qe,{value:g.id,children:g.name},g.id))})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script_text",children:"Script Text"}),e.jsx(Es,{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:((f=n==null?void 0:n.tags)==null?void 0:f.join(", "))||"",placeholder:"birthday, follow-up, thank-you"})]})]}),e.jsxs(Xn,{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(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function wHs(){const{toast:s}=Ba(),[t,n]=N.useState(""),[r,a]=N.useState(!0),[i,l]=N.useState(!1);N.useEffect(()=>{(async()=>{a(!0);try{const{data:d}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();d!=null&&d.value&&n(d.value)}catch(d){console.error("Error fetching settings:",d)}a(!1)})()},[]);const o=async()=>{l(!0);try{await q.from("settings").upsert({key:"mapbox_public_token",value:t.trim()}),s({title:"Mapbox token saved!"})}catch{s({title:"Error saving token",variant:"destructive"})}l(!1)};return r?e.jsx(fe,{children:e.jsx(Ee,{className:"flex justify-center py-8",children:e.jsx(ts,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsx("div",{className:"space-y-6",children:e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(ka,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(Vn,{children:"Configure the map feature for popbys"})]}),e.jsxs(Ee,{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(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),t&&e.jsx(ze,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const jHs=()=>{const[s,t]=N.useState(""),[n,r]=N.useState("grid"),a=Mn(),{data:i=[],isLoading:l}=ct({queryKey:["additional-services"],queryFn:async()=>{const{data:c,error:d}=await q.from("additional_services").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(d)throw d;return c}}),o=i.filter(c=>{var u;return c.name.toLowerCase().includes(s.toLowerCase())||((u=c.description)==null?void 0:u.toLowerCase().includes(s.toLowerCase()))});return e.jsx(Ts,{title:"Additional Services",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Additional Services"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Explore our additional services and offerings"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(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(yf,{className:"h-4 w-4"})}),e.jsx(B,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>r("list"),className:"rounded-full",children:e.jsx(Tp,{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(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx(Ws,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(Ws,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ws,{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(fe,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${n==="list"?"flex flex-row":""}`,onClick:()=>a(`/additional-services/${c.id}`),children:[e.jsx("div",{className:`relative overflow-hidden bg-muted ${n==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:c.preview_image_url?e.jsx("img",{src:c.preview_image_url,alt:c.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(un,{className:"h-8 w-8"})})}),e.jsxs(Ee,{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:Xz(c.description)})]})]},c.id))})]})})},NHs=()=>{const{serviceId:s}=bi(),t=Mn(),{data:n,isLoading:r}=ct({queryKey:["additional-service",s],queryFn:async()=>{const{data:a,error:i}=await q.from("additional_services").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;return a},enabled:!!s});return r?e.jsx(Ts,{title:"Loading...",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(Ws,{className:"h-8 w-48"}),e.jsx(Ws,{className:"h-64 w-full rounded-lg"}),e.jsx(Ws,{className:"h-24 w-full"})]})}):n?e.jsx(Ts,{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(Hr,{className:"h-4 w-4"}),"Back to Services"]}),e.jsx(fe,{className:"overflow-hidden",children:e.jsx("div",{className:"relative bg-muted",children:n.preview_image_url?e.jsx("img",{src:n.preview_image_url,alt:n.name,className:"w-full h-auto max-h-[500px] object-contain mx-auto"}):e.jsx("div",{className:"w-full h-64 flex items-center justify-center text-muted-foreground",children:e.jsx(un,{className:"h-16 w-16"})})})}),e.jsx(fe,{children:e.jsxs(Ee,{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(yr,{className:"h-4 w-4 mr-1"}),"Published ",Ss(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(Ts,{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(Hr,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},LF=[{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 kHs(){const[s,t]=N.useState(LF[0].id),n=LF.find(r=>r.id===s)||LF[0];return e.jsx(Ts,{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(YS,{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(ds,{value:s,onValueChange:t,children:[e.jsx(ls,{className:"w-full",children:e.jsx(us,{placeholder:"Select a tool"})}),e.jsx(cs,{children:LF.map(r=>e.jsx(Qe,{value:r.id,children:r.name},r.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(Br,{value:s,onValueChange:t,className:"w-full",children:e.jsx(Fr,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:LF.map(r=>e.jsx(Kt,{value:r.id,className:"flex-1 min-w-[150px] text-xs lg:text-sm whitespace-normal h-auto py-2",children:r.name},r.id))})})}),e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-full max-w-[700px]",dangerouslySetInnerHTML:{__html:n.iframe}})})]})})}const kZe="agent-os-onboarding-completed",hG=[{icon:sx,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:hh,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:Nn,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:Tl,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:Oi,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:yo,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"]}],SHs=()=>{const[s,t]=N.useState(!1),[n,r]=N.useState(0),[a,i]=N.useState(!1);N.useEffect(()=>{if(!localStorage.getItem(kZe)){const g=setTimeout(()=>t(!0),500);return()=>clearTimeout(g)}},[]);const l=()=>{n{r(n+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem(kZe,"true"),t(!1)},d=hG[n],u=d.icon,h=n===hG.length-1,p=f=>{f||c(),t(f)};return e.jsx(bs,{open:s,onOpenChange:p,children:e.jsxs(vs,{className:"sm:max-w-lg overflow-hidden p-0 gap-0",children:[e.jsxs("div",{className:`relative bg-gradient-to-br ${d.bgGradient} p-8 pb-12 transition-all duration-500`,children:[e.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[e.jsx("div",{className:"absolute -top-4 -right-4 w-32 h-32 bg-white/10 rounded-full blur-2xl animate-pulse"}),e.jsx("div",{className:"absolute -bottom-8 -left-8 w-40 h-40 bg-white/10 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),e.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-64 h-64 bg-white/5 rounded-full blur-3xl"})]}),e.jsxs("div",{className:`relative mx-auto flex h-20 w-20 items-center justify-center transition-all duration-300 ${a?"scale-75 opacity-0":"scale-100 opacity-100"}`,children:[e.jsx("div",{className:"absolute inset-0 bg-white/20 rounded-2xl blur-xl"}),e.jsx("div",{className:"relative flex h-20 w-20 items-center justify-center rounded-2xl bg-white/20 backdrop-blur-sm border border-white/30 shadow-2xl",children:e.jsx(u,{className:`h-10 w-10 ${d.iconColor} drop-shadow-lg`})})]}),n===0&&e.jsxs("div",{className:"absolute top-4 right-4 px-3 py-1 rounded-full bg-white/20 backdrop-blur-sm border border-white/30 text-white text-xs font-medium flex items-center gap-1.5",children:[e.jsx(un,{className:"h-3 w-3"}),"Beta"]})]}),e.jsxs("div",{className:"p-6 pt-4",children:[e.jsxs(ws,{className:"text-center sm:text-center pb-2",children:[e.jsx(_s,{className:`text-2xl font-bold transition-all duration-300 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.title}),e.jsx(Qn,{className:`text-base pt-2 transition-all duration-300 delay-75 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.description})]}),d.highlights&&e.jsx("div",{className:`space-y-2.5 py-4 transition-all duration-300 delay-100 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.highlights.map((f,g)=>e.jsxs("div",{className:"flex items-center gap-3 group",style:{transitionDelay:`${150+g*50}ms`},children:[e.jsx("div",{className:`flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-gradient-to-br ${d.bgGradient} shadow-sm`,children:e.jsx(Ir,{className:"h-3.5 w-3.5 text-white"})}),e.jsx("span",{className:"text-sm text-muted-foreground group-hover:text-foreground transition-colors",children:f})]},g))}),e.jsx("div",{className:"flex justify-center gap-2 py-4",children:hG.map((f,g)=>e.jsx("button",{onClick:()=>{g!==n&&(i(!0),setTimeout(()=>{r(g),i(!1)},150))},className:`h-2 rounded-full transition-all duration-300 ${g===n?"w-8 bg-gradient-to-r "+d.bgGradient:g{const{user:s}=ys();return ct({queryKey:["contact-snoozes",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_snoozes").select("*").gte("snoozed_until",new Date().toISOString());if(n)throw n;return t},enabled:!!s})},THs=()=>{const s=Ht(),{user:t}=ys();return gt({mutationFn:async({contactId:n,days:r})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const a=Bl(new Date,r);await q.from("contact_snoozes").delete().eq("contact_id",n);const{error:i}=await q.from("contact_snoozes").insert({contact_id:n,owner_user_id:t.id,snoozed_until:a.toISOString()});if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),s.invalidateQueries({queryKey:["today-actions"]}),s.invalidateQueries({queryKey:["popby-logs"]}),Pr({title:"Touch snoozed!",description:"Contact has been snoozed."})},onError:n=>{Pr({title:"Error snoozing contact",description:n.message,variant:"destructive"})}})},EHs=()=>{const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("contact_snoozes").delete().eq("contact_id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),Pr({title:"Snooze cancelled"})},onError:t=>{Pr({title:"Error cancelling snooze",description:t.message,variant:"destructive"})}})},AHs=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function A1e({open:s,onOpenChange:t,contactId:n,contactName:r}){const[a,i]=N.useState(null),l=THs(),o=async()=>{a&&(await l.mutateAsync({contactId:n,days:a}),i(null),t(!1))},c=d=>Ss(Bl(new Date,d),"MMM d, yyyy");return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(gr,{className:"h-5 w-5"}),"Snooze Touch"]}),e.jsxs(Qn,{children:["Postpone the next scheduled touch for ",r,". Select how long to snooze."]})]}),e.jsx("div",{className:"space-y-3 py-4",children:AHs.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(yr,{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 MHs={Crown:ff,FileText:Nr,Users:Nn,Globe:lc,Star:ca,Phone:Ar,MessageSquare:Ei,PenTool:r4,Video:br,Gift:Oi};function IHs({actions:s,onMarkComplete:t,onViewScript:n,isLoading:r,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=Mn(),[c,d]=N.useState("name"),[u,h]=N.useState("asc"),[p,f]=N.useState(null),[g,_]=N.useState(""),v=T=>{c===T?h(L=>L==="asc"?"desc":"asc"):(d(T),h("asc"))},j=N.useMemo(()=>[...s].sort((T,L)=>{var M,F;let D=0;switch(c){case"name":{const z=`${T.contact.first_name} ${T.contact.last_name||""}`.toLowerCase(),V=`${L.contact.first_name} ${L.contact.last_name||""}`.toLowerCase();D=z.localeCompare(V);break}case"relationship_type":D=(T.relationshipTypeName||"").localeCompare(L.relationshipTypeName||"");break;case"action_type":D=(((M=T.actionType)==null?void 0:M.name)||"").localeCompare(((F=L.actionType)==null?void 0:F.name)||"");break;case"last_touch":D=(T.monthNumber||0)-(L.monthNumber||0);break}return u==="asc"?D:-D}),[s,c,u]),b=T=>MHs[T||"Phone"]||Ar,S=({field:T,children:L})=>e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>v(T),children:[L,c===T?u==="asc"?e.jsx(Ru,{className:"ml-2 h-4 w-4"}):e.jsx(am,{className:"ml-2 h-4 w-4"}):e.jsx(em,{className:"ml-2 h-4 w-4 opacity-50"})]}),A=(T,L,D)=>{f(T),_(`${L} ${D||""}`.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(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{className:"bg-muted/50",children:[e.jsx(Ct,{className:"w-[180px]",children:e.jsx(S,{field:"name",children:"Contact"})}),e.jsx(Ct,{className:"w-[130px]",children:e.jsx(S,{field:"relationship_type",children:"Type"})}),e.jsx(Ct,{className:"w-[120px]",children:e.jsx(S,{field:"action_type",children:"Action"})}),e.jsx(Ct,{className:"w-[130px]",children:"Phone"}),e.jsx(Ct,{className:"w-[200px]",children:"Quick Actions"})]})}),e.jsx(ha,{children:j.map((T,L)=>{var W,Y,K,J,ne,ie;const D=T.isSpecialDate,M=T.specialDateType,F=D?M==="birthday"?cu:Or:b(((W=T.actionType)==null?void 0:W.icon)||null),z=T.contact.phone,V=T.contact.email;return e.jsxs(Hs,{className:Et("hover:bg-muted/50 transition-colors",D&&M==="birthday"&&"bg-pink-50/50 dark:bg-pink-950/20",D&&M==="anniversary"&&"bg-purple-50/50 dark:bg-purple-950/20"),children:[e.jsx(ut,{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(ut,{children:T.relationshipTypeName?e.jsx(ze,{variant:"secondary",className:"text-xs",children:T.relationshipTypeName}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ut,{children:e.jsx("div",{className:"flex items-center gap-1.5",children:D?e.jsx(ze,{className:Et("gap-1",M==="birthday"&&"bg-pink-500 hover:bg-pink-600",M==="anniversary"&&"bg-purple-500 hover:bg-purple-600"),children:M==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(cu,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(Or,{className:"h-3 w-3"})," Anniversary"]})}):e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(F,{className:"h-3 w-3"}),(Y=T.actionType)==null?void 0:Y.name]})})}),e.jsx(ut,{children:z?e.jsx("span",{className:"text-sm font-mono",children:T.contact.phone}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[z&&e.jsx("a",{href:`tel:${T.contact.phone}`,className:"p-1.5 rounded bg-primary/10 hover:bg-primary/20 text-primary transition-colors",title:"Call",children:e.jsx(Ar,{className:"h-3.5 w-3.5"})}),z&&e.jsx("a",{href:a(T.contact.phone,(K=T.script)==null?void 0:K.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(Ei,{className:"h-3.5 w-3.5"})}),V&&(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(Vs,{className:"h-3.5 w-3.5"})}):e.jsx("a",{href:i(T.contact.email,(J=T.script)==null?void 0:J.script_body,(ne=T.script)==null?void 0:ne.email_subject,(ie=T.actionType)==null?void 0:ie.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(Vs,{className:"h-3.5 w-3.5"})})),D&&e.jsxs("button",{onClick:()=>{const he=`${T.contact.first_name}${T.contact.last_name?" "+T.contact.last_name:""}`,ce=M==="birthday"?"birthday":"home_anniversary",pe=new URLSearchParams({cardType:ce,contactId:T.contact.id,name:he,...T.contact.address?{address:T.contact.address}:{},...M==="anniversary"&&T.contact.home_anniversary?{date:T.contact.home_anniversary}:{}});o(`/mission-control/card-studio?${pe.toString()}`)},className:Et("h-7 px-2 rounded text-xs font-semibold flex items-center gap-1 transition-colors",M==="birthday"?"bg-pink-500/15 hover:bg-pink-500/25 text-pink-600 dark:text-pink-400":"bg-purple-500/15 hover:bg-purple-500/25 text-purple-600 dark:text-purple-400"),title:`Send ${M==="birthday"?"Birthday":"Anniversary"} Card`,children:[e.jsx(Vs,{className:"h-3.5 w-3.5"}),"Send Card"]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:()=>A(T.contact.id,T.contact.first_name,T.contact.last_name),title:"Snooze",children:e.jsx(bf,{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 he;return t(T.contact.id,T.actionType.id,(he=T.script)==null?void 0:he.id)},disabled:r,children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-1"}),"Done"]})]})})]},`${T.contact.id}-${L}`)})})]})}),e.jsx(A1e,{open:!!p,onOpenChange:T=>!T&&f(null),contactId:p||"",contactName:g})]})}function PHs({onSelect:s}){const{user:t}=ys(),[n,r]=N.useState("root"),[a,i]=N.useState(null),{data:l=[],isLoading:o}=ct({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:j,error:b}=await q.from("email_template_categories").select("*").order("sort_order");if(b)throw b;return j}}),{data:c=[],isLoading:d}=ct({queryKey:["agent-email-templates",a],enabled:n==="category"&&!!a,queryFn:async()=>{const{data:j,error:b}=await q.from("agent_email_templates").select("*").eq("is_active",!0).eq("category_id",a).order("sort_order");if(b)throw b;return j}}),{data:u=[],isLoading:h}=ct({queryKey:["picker-campaign-templates",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:j,error:b}=await q.from("campaign_templates").select("id,name,subject,body_html,is_shared,user_id,updated_at").or(`user_id.eq.${t.id},is_shared.eq.true`).order("updated_at",{ascending:!1});if(b)throw b;return j}}),p=u.filter(j=>j.user_id===(t==null?void 0:t.id)&&!j.is_shared),f=u.filter(j=>j.is_shared),g=l.find(j=>j.id===a);if(o)return e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(ts,{className:"h-5 w-5 animate-spin text-muted-foreground"})});const _=j=>{s({title:j.name,subject:j.subject,body:j.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(Xi,{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:[p.length," template",p.length===1?"":"s"," you've created"]})]})]}),e.jsx(xa,{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(lc,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Shared Library"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[f.length," team template",f.length===1?"":"s"]})]})]}),e.jsx(xa,{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(j=>e.jsxs("button",{onClick:()=>{i(j.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:j.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:j.name}),j.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:j.description})]})]}),e.jsx(xa,{className:"h-4 w-4 text-muted-foreground shrink-0"})]},j.id))})]})]});const v=e.jsxs("button",{onClick:()=>{r("root"),i(null)},className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(pl,{className:"h-3.5 w-3.5"}),"Back"]});return n==="my"?e.jsxs("div",{className:"space-y-2",children:[v,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(Xi,{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(ts,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):p.length===0?e.jsxs("div",{className:"text-center py-6 space-y-2",children:[e.jsx(un,{className:"h-6 w-6 text-muted-foreground mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You haven't created any templates yet."}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Create beautiful templates in ",e.jsx("span",{className:"font-medium",children:"Email Templates"})," in the sidebar — they'll appear here."]})]}):e.jsx(hi,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:p.map(j=>e.jsxs("button",{onClick:()=>_(j),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:j.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:j.subject||"(no subject)"})]},j.id))})})]}):n==="shared"?e.jsxs("div",{className:"space-y-2",children:[v,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(lc,{className:"h-3.5 w-3.5"})," Shared Library"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(ts,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No shared templates yet."}):e.jsx(hi,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:f.map(j=>e.jsxs("button",{onClick:()=>_(j),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:j.name}),e.jsx(ze,{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:j.subject||"(no subject)"})]},j.id))})})]}):e.jsxs("div",{className:"space-y-2",children:[v,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx("span",{children:g==null?void 0:g.icon})," ",g==null?void 0:g.name]}),d?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(ts,{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(hi,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:c.map(j=>e.jsxs("button",{onClick:()=>s(j),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:j.title}),j.tone&&e.jsx(ze,{variant:"secondary",className:"text-[10px] shrink-0",children:j.tone})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:j.subject})]},j.id))})})]})}function M1e(){const{user:s}=ys(),t=Ht(),{data:n,isLoading:r}=ct({queryKey:["contact-intake-page",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:d,error:u}=await q.from("contact_intake_pages").select("*").eq("user_id",s.id).maybeSingle();if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),a=gt({mutationFn:async d=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:u,error:h}=await q.from("contact_intake_pages").insert({user_id:s.id,slug:d.toLowerCase().replace(/[^a-z0-9-]/g,"-")}).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),ae.success("Connect page created!")},onError:d=>{var u;(u=d.message)!=null&&u.includes("duplicate")?ae.error("That slug is already taken. Try another."):ae.error("Failed to create page")}}),i=gt({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page");const{error:u}=await q.from("contact_intake_pages").update({...d,updated_at:new Date().toISOString()}).eq("id",n.id);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),ae.success("Page updated!")},onError:()=>ae.error("Failed to update page")}),{data:l=[],isLoading:o}=ct({queryKey:["contact-intake-submissions",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:d,error:u}=await q.from("contact_intake_submissions").select("*").eq("agent_user_id",s.id).order("created_at",{ascending:!1}).limit(100);if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),c=gt({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page. Create your Connect page first.");const{data:u,error:h}=await q.from("contact_intake_tokens").insert({contact_id:d,intake_page_id:n.id}).select("token").single();if(h)throw h;return`${window.location.origin}/connect/${n.slug}?t=${u.token}`}});return{intakePage:n,isLoading:r,createPage:a,updatePage:i,submissions:l,loadingSubmissions:o,generateUpdateLink:c}}function S_t({value:s,onChange:t,userId:n,placeholder:r}){const[a,i]=N.useState(!1),[l,o]=N.useState([]),[c,d]=N.useState(!1),[u,h]=N.useState(0),p=N.useRef(null),f=N.useRef(null);N.useEffect(()=>{const _=v=>{p.current&&!p.current.contains(v.target)&&i(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]),N.useEffect(()=>{f.current&&clearTimeout(f.current);const _=s.trim();if(!n||_.length<1||_.includes("@")&&_.indexOf("@")>0&&/\S+@\S+\.\S+/.test(_)){o([]);return}return f.current=setTimeout(async()=>{d(!0);const v=`%${_}%`,j=q,{data:b,error:S}=await j.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",n).not("email","is",null).or(`first_name.ilike.${v},last_name.ilike.${v},email.ilike.${v}`).order("first_name",{ascending:!0}).limit(8);d(!1),!S&&b&&(o(b),h(0),i(b.length>0))},180),()=>{f.current&&clearTimeout(f.current)}},[s,n]);const g=_=>{_.email&&(t(_.email),i(!1))};return e.jsxs("div",{ref:p,className:"relative",children:[e.jsx(ye,{id:"gmail-to",value:s,onChange:_=>t(_.target.value),onFocus:()=>l.length>0&&i(!0),onKeyDown:_=>{!a||l.length===0||(_.key==="ArrowDown"?(_.preventDefault(),h(v=>Math.min(v+1,l.length-1))):_.key==="ArrowUp"?(_.preventDefault(),h(v=>Math.max(v-1,0))):_.key==="Enter"?(_.preventDefault(),g(l[u])):_.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(ts,{className:"h-3 w-3 animate-spin"})," Searching..."]}):l.map((_,v)=>{const j=[_.first_name,_.last_name].filter(Boolean).join(" ")||"(No name)";return e.jsxs("button",{type:"button",onMouseEnter:()=>h(v),onClick:()=>g(_),className:`w-full flex items-center gap-2 px-3 py-2 text-left text-sm border-b last:border-b-0 ${v===u?"bg-accent":"bg-popover"}`,children:[e.jsx(Xi,{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:j}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:_.email})]})]},_.id)})})]})}function LHs(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 jNe=25*1024*1024,SZe=Math.floor(6.5*1024*1024),DHs=750*1024,c2=50,RHs=["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 mG(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function OHs(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 FHs(s){if(!s)return"";const t=s.trim();return t.split(/\s+/)[0]||t}function d2(s,t){const n=FHs(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 t1({open:s,onOpenChange:t,contact:n,bulkContacts:r,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o,sendSource:c,logTouchpoint:d=!0}){const{user:u}=ys(),h=Ht(),{isReady:p,settings:f}=bR(),{data:g}=C1e(),[_,v]=N.useState(!1),{intakePage:j}=M1e(),b=j?`https://contacts.relevelup.com/${j.slug}`:null,S=!!r&&r.length>0,A=p,T=S?r:n?[n]:[],L=T[0],D=S?Math.ceil(T.length/c2):1,M=S&&T.length>c2,[F,z]=N.useState((L==null?void 0:L.email)||""),[V,W]=N.useState(a),[Y,K]=N.useState(i),[J,ne]=N.useState(!1),[ie,he]=N.useState(!1),[ce,pe]=N.useState([]),le=N.useRef(new Map),[ve,ge]=N.useState(a),[Te,Me]=N.useState(i),[Ce,Ae]=N.useState("composing"),[De,Ie]=N.useState(0),[Fe,qe]=N.useState(0),[be,Ze]=N.useState(0),[Ne,it]=N.useState(0),je=N.useRef(!1),[Ge,Be]=N.useState(null);N.useEffect(()=>{if(s){const Vt=/<[a-z][\s\S]*>/i.test(i),Ms=Vt?LHs(i):i;at.current=Vt?{plain:Ms,html:i}:null,z((L==null?void 0:L.email)||""),ge(a),Me(Ms),W(d2(a,L||{first_name:""})),K(d2(Ms,L||{first_name:""})),he(!a&&!i),pe([]),le.current=new Map,Ae("composing"),Ie(0),qe(0),Ze(0),it(0),je.current=!1,Be(null)}},[s,L,a,i]);const Ye=async Vt=>{const Ms=Vt.target.files;if(!Ms)return;const Xt=ce.reduce((As,rn)=>As+rn.size,0),Js=[];let Cs=Xt;for(const As of Array.from(Ms)){if(!RHs.includes(As.type)){ae.error(`${As.name}: Unsupported file type`);continue}if(Cs+As.size>jNe){ae.error(`Total attachments exceed ${mG(jNe)} limit`);break}try{const rn=await OHs(As);Js.push({name:As.name,type:As.type,size:As.size,data:rn}),Cs+=As.size}catch{ae.error(`Failed to read ${As.name}`)}}pe(As=>[...As,...Js]),Vt.target.value=""},We=Vt=>{const Ms=ce[Vt];Ms&&le.current.delete(`${Ms.name}::${Ms.size}`),pe(Xt=>Xt.filter((Js,Cs)=>Cs!==Vt))},rt=async()=>{if(ce.length===0||!u)return{inline:[],paths:[]};const Vt=[],Ms=[];for(const Xt of ce){const Js=`${Xt.name}::${Xt.size}`,Cs=le.current.get(Js);if(Cs){Ms.push(Cs);continue}if(Xt.size<=DHs){Vt.push(Xt);continue}const As=Xt.name.replace(/[^a-zA-Z0-9._-]/g,"_"),rn=`${u.id}/${Date.now()}-${As}`,tn=atob(Xt.data),er=new Uint8Array(tn.length);for(let In=0;In{if(!/<[a-z][\s\S]*>/i.test(Vt)||typeof window>"u")return Vt;const Ms=Vt.replace(/<\s*(br|\/p|\/div|\/li|\/h[1-6]|\/tr)\s*[^>]*>/gi,` `).replace(/<\s*li\b[^>]*>/gi,"• ").replace(/<\s*(p|div|h[1-6]|tr)\b[^>]*>/gi,""),Xt=document.createElement("div");return Xt.innerHTML=Ms,(Xt.textContent||Xt.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()},at=N.useRef(null),He=Vt=>{const Ms=/<[a-z][\s\S]*>/i.test(Vt.body),Xt=Ms?tt(Vt.body):Vt.body;at.current=Ms?{plain:Xt,html:Vt.body}:null,ge(Vt.subject),Me(Xt),W(d2(Vt.subject,L||{first_name:""})),K(d2(Xt,L||{first_name:""})),he(!1)},dt=Vt=>/<\s*(p|div|span|table|tr|td|img|br|h[1-6]|a|body|html|section|article|ul|ol|li)\b/i.test(Vt)?Vt:Vt.split(/\n\n+/).map(Ms=>`

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

`).join(""),bt=(Vt,Ms)=>{const Xt="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-email-track";let Js=Vt.replace(/]*?)href=(["'])(.*?)\2([^>]*)>/gi,(As,rn,tn,er,gn)=>{if(!er||/^(mailto:|tel:|#)/i.test(er)||er.includes("/bulk-email-track")||er.includes("/ses-campaign-track"))return As;const In=`${Xt}?s=${Ms}&t=click&u=${encodeURIComponent(er)}`;return``});const Cs=``;return/<\/body>/i.test(Js)?Js=Js.replace(/<\/body>/i,`${Cs}`):Js=`${Js}${Cs}`,Js},vt=async Vt=>{if(!(Vt!=null&&Vt.email))return ae.error("Please enter a recipient email"),!1;const Ms=Vt||{first_name:""},Xt=d2(ve,Ms),Js=at.current,Cs=Js&&Te===Js.plain,As=d2(Cs?Js.html:Te,Ms);let rn=Cs?As:dt(As);const tn=u&&Vt.id?crypto.randomUUID():null;tn&&(rn=bt(rn,tn));try{if(u&&Vt.email){const In=new Date(Date.now()-6e5).toISOString(),{data:Zn}=await q.from("bulk_email_sends").select("id").eq("user_id",u.id).eq("contact_email",Vt.email).eq("subject",Xt).gte("sent_at",In).limit(1);if(Zn&&Zn.length>0)return console.log(`Skipping duplicate send to ${Vt.email} (same subject within 10 min)`),ae.info(`Skipped ${Vt.first_name||Vt.email} — already sent this in the last 10 min`),!0}const{inline:er,paths:gn}=await rt();if(A){const In=(f==null?void 0:f.display_name)||"ReLevelUp",Zn=`${In.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,ea=`${In} <${Zn}>`;let vi=gn[0];if(!vi&&er.length>0&&u){const Lr=er[0],Jn=Lr.name.replace(/[^a-zA-Z0-9._-]/g,"_"),js=`${u.id}/${Date.now()}-${Jn}`,Dn=atob(Lr.data),wr=new Uint8Array(Dn.length);for(let ss=0;ss({name:ea,type:vi,data:Ls})),attachment_paths:gn}});if(Zn)throw Zn;if(!(In!=null&&In.success))throw new Error((In==null?void 0:In.error)||"Failed to send")}if(u&&Vt.id&&tn&&(await q.from("bulk_email_sends").insert({id:tn,user_id:u.id,contact_id:Vt.id,contact_email:Vt.email,subject:Xt,source:c||(A?"ses_bulk":"sphere_gaps")}),d))try{await q.from("contact_touch_logs").insert({owner_user_id:u.id,contact_id:Vt.id,action_type_id:"9a88a47c-cb2a-4401-a2b5-111a76b19f9d",notes:`Mass Email: ${Xt}`,completed_at:new Date().toISOString()})}catch(In){console.warn("touch log insert failed",In)}return!0}catch(er){return console.error("Send error:",er),ae.error("Failed to send to "+Vt.first_name+": "+(er instanceof Error?er.message:"Unknown error")),!1}},Bt=()=>{const Vt=De*c2;return T.slice(Vt,Vt+c2)},Zt=async()=>{if(!V||!Y){ae.error("Please fill in subject and message");return}const Vt=Bt();ne(!0),Ae("sending");let Ms=0,Xt=0;for(let Cs=0;CssetTimeout(rn,150));qe(Cs=>Cs+Ms),Ze(Cs=>Cs+Xt),ne(!1),h.invalidateQueries({queryKey:["bulk-email-sends"]}),h.invalidateQueries({queryKey:["contact-touch-logs"]}),h.invalidateQueries({queryKey:["contacts-last-touch"]}),De>=D-1||je.current?Ae("all_done"):Ae("batch_complete")},Fs=async()=>{if(!V||!Y){ae.error("Please fill in subject and message");return}if(A&&g&&!g.hasVerifiedSes&&!g.hasGmail){v(!0);return}if(!S){const Vt=L||{id:"",first_name:"",last_name:"",email:F.trim()};if(!Vt.email){ae.error("Please enter a recipient email");return}ne(!0);try{await vt(Vt)&&(h.invalidateQueries({queryKey:["bulk-email-sends"]}),ae.success("Email sent successfully!"),t(!1),o==null||o())}finally{ne(!1)}return}await Zt()},Rs=async()=>{Ie(Vt=>Vt+1),it(0),await new Promise(Vt=>setTimeout(Vt,50)),await Zt()};N.useEffect(()=>{},[De]);const ms=()=>{if(J){je.current=!0;return}t(!1),o==null||o()},Pt=De*c2,Jt=Math.min(Pt+c2,T.length),ft=S&&T.length>0?Math.round((Fe+be)/T.length*100):0;return e.jsxs(bs,{open:s,onOpenChange:ms,children:[e.jsxs(vs,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:`h-5 w-5 ${A?"text-orange-500":"text-red-500"}`}),S?`Send to ${T.length} Contacts`:"Compose Email"]}),A?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-medium",children:"Mass Email"})," (reply-to: ",f==null?void 0:f.reply_to_email,")"]}):l?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:l})]}):null,S&&Ce==="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."]})]}),Ce==="sending"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(ts,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending batch ",De+1," of ",D,"..."]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Ne," of ",Bt().length," in this batch"]})]}),e.jsx(pi,{value:Ne/Bt().length*100,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Overall: ",Fe+be," / ",T.length]}),e.jsxs("span",{children:[Fe," sent • ",be," failed"]})]}),e.jsx(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{je.current=!0},children:"Stop Sending"})]}),Ce==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(xr,{className:"h-8 w-8 text-emerald-500 mx-auto"}),e.jsxs("p",{className:"font-medium",children:["Batch ",De+1," Complete!"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Fe," sent, ",be," failed so far"]})]}),e.jsx(pi,{value:ft,className:"h-2"}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground",children:[T.length-Fe-be," contacts remaining (",D-De-1," batches left)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",className:"flex-1",onClick:ms,children:"Done for Now"}),e.jsxs(B,{className:"flex-1 gap-2",onClick:Rs,children:[e.jsx(cr,{className:"h-4 w-4"}),"Send Next ",Math.min(c2,T.length-Jt)," Contacts"]})]})]}),Ce==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(xr,{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:[Fe," emails sent successfully",be>0&&e.jsxs("span",{className:"text-destructive",children:[" • ",be," failed"]})]})]}),e.jsx(B,{className:"w-full",onClick:ms,children:"Close"})]}),Ce==="composing"&&e.jsxs("div",{className:"space-y-4",children:[ie?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(Nr,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>he(!1),className:"h-7 px-2 text-xs",children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(PHs,{onSelect:He})]}):e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>he(!0),children:[e.jsx(Nr,{className:"h-4 w-4"}),"Browse Templates"]}),e.jsx(ll,{}),!S&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"gmail-to",children:"To"}),e.jsx(S_t,{value:F,onChange:z,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:V,onChange:Vt=>{W(Vt.target.value),ge(Vt.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(ze,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{K(Vt=>Vt+"{{first_name}}"),Me(Vt=>Vt+"{{first_name}}")},children:"{{first_name}}"}),e.jsx(ze,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{K(Vt=>Vt+"{{last_name}}"),Me(Vt=>Vt+"{{last_name}}")},children:"{{last_name}}"}),b&&e.jsx(ze,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-primary/10 border-primary/40 text-primary",onClick:()=>{const Vt=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${b} `;K(Ms=>Ms+Vt),Me(Ms=>Ms+Vt)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),e.jsx(Es,{id:"gmail-body",value:Y,onChange:Vt=>{K(Vt.target.value),Me(Vt.target.value)},placeholder:"Write your message...",rows:10,className:"resize-y"}),S&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{{first_name}}",", ","{{last_name}}"," to personalize. You'll preview each recipient's email in the next step."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-2",onClick:()=>{var Vt;return(Vt=document.getElementById("gmail-attachments"))==null?void 0:Vt.click()},disabled:J,children:[e.jsx(n4,{className:"h-4 w-4"}),"Attach Files"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["PDF, images, Word, Excel (max ",mG(jNe)," total)"]}),e.jsx("input",{id:"gmail-attachments",type:"file",multiple:!0,accept:".pdf,.jpg,.jpeg,.png,.gif,.webp,.doc,.docx,.xls,.xlsx,.csv",className:"hidden",onChange:Ye})]}),ce.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:ce.map((Vt,Ms)=>e.jsxs(ze,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(n4,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:Vt.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",mG(Vt.size),")"]}),e.jsx("button",{type:"button",onClick:()=>We(Ms),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx(Bn,{className:"h-3 w-3"})})]},Ms))}),A&&ce.some(Vt=>Vt.size>SZe)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Files over ",mG(SZe)," 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"}),S?e.jsxs(B,{onClick:()=>{Be(T[0]||null),Ae("reviewing")},disabled:!V||!Y,className:"gap-2",children:["Review Emails",e.jsx(Oa,{className:"h-4 w-4"})]}):e.jsxs(B,{onClick:Fs,disabled:J||!V||!Y||!F.trim(),className:"gap-2",children:[J?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"}),J?"Sending...":"Send Email"]})]})]}),Ce==="reviewing"&&S&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-xs text-primary bg-primary/10 rounded-md px-2.5 py-1.5",children:["✉️ Click any recipient below to preview the ",e.jsx("span",{className:"font-semibold",children:"exact personalized email"})," they will receive."]}),M&&e.jsxs("p",{className:"text-xs text-amber-600 bg-amber-500/10 rounded-md px-2.5 py-1.5",children:["📦 ",T.length," contacts will be sent in ",D," batches of up to ",c2,". You'll confirm before each batch."]}),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(Vt=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(Ge==null?void 0:Ge.id)===Vt.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>Be(Vt),children:[Vt.first_name," ",Vt.last_name," — ",Vt.email]},Vt.id))})]}),Ge&&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(Vs,{className:"h-3.5 w-3.5"}),"Preview for ",Ge.first_name," ",Ge.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:"})," ",Ge.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Subject:"})," ",d2(ve,Ge)]})]}),e.jsx(ll,{}),e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:d2(Te,Ge)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>{Ae("composing"),Be(null)},children:[e.jsx(Hr,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs(B,{onClick:Fs,disabled:J,className:"gap-2",children:[J?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"}),M?`Send First ${c2}`:`Send to ${T.length}`]})]})]})]}),e.jsx(T1e,{open:_,onOpenChange:v,hasPending:!!(g!=null&&g.hasPendingSes),pendingEmails:g==null?void 0:g.pendingEmails})]})}function zHs(){const s=Mn(),{data:t}=ox(),{data:n}=YD(),r=fU(),{isGmailConnected:a,gmailEmail:i}=Oh(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(new Set),p=kf(new Date),f=Bl(p,30),g=T=>{if(!T)return null;const L=T.split(/[-/T]/);if(L.length<3)return null;const D=parseInt(L[1],10)-1,M=parseInt(L[2],10);return isNaN(D)||isNaN(M)?null:new Date(p.getFullYear(),D,M)},_=N.useMemo(()=>{if(!t)return[];const T=[];for(const L of t){if(L.birthday){const D=g(L.birthday);D&&(Vl(D,p)||Bv(D,p)&&wb(D,f))&&T.push({contact:L,type:"birthday",date:D,daysUntil:Gx(D,p),dateStr:L.birthday})}if(L.home_anniversary){const D=g(L.home_anniversary);D&&(Vl(D,p)||Bv(D,p)&&wb(D,f))&&T.push({contact:L,type:"anniversary",date:D,daysUntil:Gx(D,p),dateStr:L.home_anniversary})}if(L.wedding_anniversary){const D=g(L.wedding_anniversary);D&&(Vl(D,p)||Bv(D,p)&&wb(D,f))&&T.push({contact:L,type:"wedding_anniversary",date:D,daysUntil:Gx(D,p),dateStr:L.wedding_anniversary})}}return T.sort((L,D)=>L.daysUntil-D.daysUntil),T},[t]),v=T=>T==="birthday"?"Birthday":T==="wedding_anniversary"?"Wedding Anniversary":"Home Anniversary",j=async T=>{const L=(n==null?void 0:n.find(D=>D.name==="Call"))||(n==null?void 0:n[0]);if(L)try{await r.mutateAsync({contactId:T.contact.id,actionTypeId:L.id,notes:`${v(T.type)} outreach`}),h(D=>new Set(D).add(`${T.contact.id}-${T.type}`)),Pr({title:"Touch logged!",description:`Logged outreach for ${T.contact.first_name}`})}catch{Pr({title:"Error",description:"Failed to log touch",variant:"destructive"})}},b=T=>{const L=`${T.contact.first_name}${T.contact.last_name?" "+T.contact.last_name:""}`,D=T.type==="birthday"?"birthday":T.type==="wedding_anniversary"?"wedding_anniversary":"home_anniversary",M=new URLSearchParams({cardType:D,contactId:T.contact.id,name:L,...T.contact.address?{address:T.contact.address}:{},...(T.type==="anniversary"||T.type==="wedding_anniversary")&&T.dateStr?{date:T.dateStr}:{}});s(`/mission-control/card-studio?${M.toString()}`)},S=T=>T===0?"Today!":T===1?"Tomorrow":`${T} days`,A=T=>T===0?"bg-red-500/15 text-red-600 dark:text-red-400 border-red-500/30":T<=3?"bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30":T<=7?"bg-blue-500/15 text-blue-600 dark:text-blue-400 border-blue-500/30":"bg-muted text-muted-foreground border-border";return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:[e.jsx(Tl,{className:"h-5 w-5 text-primary"}),"Upcoming Milestones",e.jsx(ze,{variant:"secondary",className:"text-xs font-normal",children:"Next 30 days"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[_.length," event",_.length!==1?"s":""]})]})}),e.jsxs(Ee,{className:"space-y-2",children:[_.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-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."})]}),_.map((T,L)=>{var z,V;const D=`${T.contact.id}-${T.type}`,M=u.has(D),F=`${((z=T.contact.first_name)==null?void 0:z[0])||""}${((V=T.contact.last_name)==null?void 0:V[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(aa,{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:F})}),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(ze,{variant:"outline",className:Et("text-[10px] shrink-0 whitespace-nowrap",A(T.daysUntil)),children:S(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(cu,{className:"h-3 w-3"})," Birthday"]}):T.type==="wedding_anniversary"?e.jsxs(e.Fragment,{children:[e.jsx(gi,{className:"h-3 w-3"})," Wedding Anniversary"]}):e.jsxs(e.Fragment,{children:[e.jsx(Or,{className:"h-3 w-3"})," Home Anniversary"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Ss(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(Ar,{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(Ei,{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(Vs,{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(br,{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:()=>b(T),children:[e.jsx(un,{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",M&&"text-green-600"),title:"Log a touch",disabled:M||r.isPending,onClick:()=>j(T),children:e.jsx(xr,{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(Er,{className:"h-3.5 w-3.5"})})]})]},`${D}-${L}`)})]})]}),a&&l&&e.jsx(t1,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function BHs(s){const[t,n]=N.useState([]),[r,a]=N.useState(!1),{data:i,isLoading:l}=ct({queryKey:["active-visitors",s],queryFn:async()=>{if(!s)return[];try{await q.rpc("cleanup_stale_visitors")}catch{}const{data:u}=await q.from("lead_site_active_visitors").select("*").eq("lead_site_id",s).gte("last_seen_at",new Date(Date.now()-2*60*1e3).toISOString()).order("last_seen_at",{ascending:!1});if(!u)return[];const h=u.map(g=>g.contact_id).filter(Boolean);let p={};if(h.length>0){const{data:g}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",h);(g||[]).forEach(_=>{p[_.id]=_})}const f=u.map(g=>g.auth_user_id).filter(Boolean);if(f.length>0){const{data:g}=await q.from("lead_site_consumer_profiles").select("user_id, name, phone, contact_id").eq("lead_site_id",s).in("user_id",f);(g||[]).forEach(_=>{const v=u.find(j=>j.auth_user_id===_.user_id);v&&!v.contact_id&&_.contact_id&&(v.contact_id=_.contact_id),v&&!p[v.contact_id||""]&&_.name&&(p[v.contact_id||v.auth_user_id||""]={first_name:_.name.split(" ")[0],last_name:_.name.split(" ").slice(1).join(" ")||null,email:null,phone:_.phone})})}return u.map(g=>{var _,v;return{...g,contact_name:p[g.contact_id||g.auth_user_id||""]?`${p[g.contact_id||g.auth_user_id||""].first_name} ${p[g.contact_id||g.auth_user_id||""].last_name||""}`.trim():null,contact_email:((_=p[g.contact_id||g.auth_user_id||""])==null?void 0:_.email)||null,contact_phone:((v=p[g.contact_id||g.auth_user_id||""])==null?void 0:v.phone)||null}})},enabled:!!s,refetchInterval:6e4});N.useEffect(()=>{if(!s)return;const u=q.channel(`active-visitors-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"lead_site_active_visitors",filter:`lead_site_id=eq.${s}`},h=>{h.eventType==="INSERT"?n(p=>p.find(g=>g.id===h.new.id)?p:[h.new,...p]):h.eventType==="UPDATE"?n(p=>p.map(f=>f.id===h.new.id?{...f,...h.new}:f)):h.eventType==="DELETE"&&n(p=>p.filter(f=>f.id!==h.old.id))}).subscribe(h=>{h==="SUBSCRIBED"&&a(!0)});return()=>{q.removeChannel(u)}},[s]);const o=r&&t.length>0?$Hs([...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 $Hs(s){const t=new Set;return s.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const UHs={property_view:{label:"Viewed",icon:Er,color:"text-blue-500",bgColor:"bg-blue-500/10"},new_lead:{label:"New Lead",icon:Fo,color:"text-emerald-500",bgColor:"bg-emerald-500/10"},saved_listing:{label:"Saved",icon:gi,color:"text-rose-500",bgColor:"bg-rose-500/10"}};function qHs(){const{user:s}=ys(),t=Mn(),{isGmailConnected:n,gmailEmail:r}=Oh(),{leadSite:a}=Ip(),{count:i}=BHs(a==null?void 0:a.id),[l,o]=N.useState(!1),[c,d]=N.useState(null),{data:u,isLoading:h}=ct({queryKey:["lead-site-activity",s==null?void 0:s.id],queryFn:async()=>{const{data:j,error:b}=await q.rpc("get_lead_site_activity",{_user_id:s.id});if(b)throw b;return j},enabled:!!s,refetchInterval:6e4});if(h||!(u!=null&&u.has_site))return null;const p=(u.activities||[]).filter(j=>j.visitor_name&&j.visitor_name!=="Site Visitor"),f=p.filter(j=>j.activity_type==="new_lead"),g=(u.activities||[]).filter(j=>j.activity_type==="property_view").length,_=(u.activities||[]).filter(j=>j.activity_type==="saved_listing").length,v=j=>{if(j.visitor_email)if(n){const b=(j.visitor_name||"").split(" ");d({id:j.contact_id||"",first_name:b[0]||"",last_name:b.slice(1).join(" ")||null,email:j.visitor_email}),o(!0)}else window.location.href=`mailto:${j.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(lc,{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(Oa,{className:"h-4 w-4"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-emerald-500/5 border border-emerald-200 dark:border-emerald-800",children:[e.jsx(Fo,{className:"h-4 w-4 text-emerald-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-emerald-600 dark:text-emerald-400",children:f.length}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"New Leads"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-blue-500/5 border border-blue-200 dark:border-blue-800",children:[e.jsx(Er,{className:"h-4 w-4 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-blue-600 dark:text-blue-400",children:g}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Views"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-rose-500/5 border border-rose-200 dark:border-rose-800",children:[e.jsx(gi,{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:_}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Saved"})]})]})]}),p.length>0?e.jsxs("div",{className:"space-y-2",children:[p.slice(0,5).map((j,b)=>{const S=UHs[j.activity_type],A=S.icon,T=Vo(new Date(j.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 ${S.bgColor}`,children:e.jsx(A,{className:`h-3.5 w-3.5 ${S.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:()=>{j.contact_id&&t(`/mission-control/contacts/${j.contact_id}`)},children:j.visitor_name}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:S.label}),j.mls_number&&e.jsxs("span",{children:["· MLS# ",j.mls_number]}),j.lead_type&&e.jsxs("span",{children:["· ",j.lead_type]}),e.jsxs("span",{children:["· ",T]})]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[j.visitor_email&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>v(j),children:e.jsx(Vs,{className:"h-3.5 w-3.5"})}),j.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:${j.visitor_phone}`,children:e.jsx(Ar,{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:${j.visitor_phone}`,children:e.jsx(Ei,{className:"h-3.5 w-3.5"})})]}),j.contact_id&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${j.contact_id}`),children:e.jsx(xa,{className:"h-3.5 w-3.5"})})]})]},`${j.activity_type}-${j.occurred_at}-${b}`)}),p.length>5&&e.jsxs(B,{variant:"outline",className:"w-full text-xs",onClick:()=>t("/mission-control/website-activity"),children:["View ",p.length-5," more activities",e.jsx(Oa,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 text-center",children:[e.jsx(nm,{className:"h-8 w-8 text-muted-foreground/30 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No actionable website activity yet."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:g>0?`${g} anonymous listing views recorded.`:"Lead engagement will appear here as visitors interact with your site."}),e.jsxs(B,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>t("/mission-control/website-activity"),children:["View Full Activity",e.jsx(Oa,{className:"h-3.5 w-3.5 ml-1"})]})]})}),n&&c&&e.jsx(t1,{open:l,onOpenChange:o,contact:c,gmailEmail:r})]})}const CZe={Crown:ff,FileText:Nr,Users:Nn,Globe:lc,Star:ca,Phone:Ar,MessageSquare:Ei,PenTool:r4,Video:br,Gift:Oi},VHs={"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 HHs(){var We,rt,tt,at,He,dt;const s=Mn(),{user:t}=ys(),{data:n}=Sy(),{data:r}=Zmt(),{data:a}=ox(),{data:i}=YD(),{data:l}=tpt(),o=lrs(),c=v6e(),d=irs(90),u=fU(),[h,p]=N.useState(null),[f,g]=N.useState(null),[_,v]=N.useState(!1),[j,b]=N.useState(""),[S,A]=N.useState(!1),[T,L]=N.useState(""),[D,M]=N.useState(Pfe()),[F,z]=N.useState("cards"),[V,W]=N.useState(!1),[Y,K]=N.useState(null),[J,ne]=N.useState(null),[ie,he]=N.useState(""),{isGmailConnected:ce,gmailEmail:pe}=Oh(),le=()=>{const bt=parseInt(T,10);if(isNaN(bt)||bt<1){Pr({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}M(bt),ept(bt),A(!1),Pr({title:"Goal updated",description:`Weekly touch goal set to ${bt}`})},ve=()=>{L(D.toString()),A(!0)};N.useEffect(()=>{(async()=>{if(!(t!=null&&t.id))return;const{data:vt}=await q.from("profiles").select("name").eq("id",t.id).single();vt!=null&&vt.name&&b(vt.name.split(" ")[0])})()},[t==null?void 0:t.id]),N.useEffect(()=>{o.mutate()},[]);const ge=kf(new Date),Te=Bl(ge,7),Me=bt=>{if(!bt)return null;const vt=bt.split(/[-/T]/);if(vt.length<3)return null;const Bt=parseInt(vt[1],10)-1,Zt=parseInt(vt[2],10);return isNaN(Bt)||isNaN(Zt)?null:new Date(ge.getFullYear(),Bt,Zt)},Ce=(a==null?void 0:a.filter(bt=>{const vt=Me(bt.birthday),Bt=Me(bt.home_anniversary);return vt&&Vl(vt,ge)||Bt&&Vl(Bt,ge)}))||[];a!=null&&a.filter(bt=>{if(!bt.birthday&&!bt.home_anniversary)return!1;const vt=Bt=>{if(!Bt)return!1;const Zt=Me(Bt);return Zt?Bv(Zt,ge)&&wb(Zt,Te):!1};return vt(bt.birthday)||vt(bt.home_anniversary)}).slice(0,5);const Ae=[],De=(i==null?void 0:i.find(bt=>bt.name==="Call"))||(i==null?void 0:i[0]);for(const bt of Ce){const vt=Me(bt.birthday),Bt=Me(bt.home_anniversary),Zt=vt&&Vl(vt,ge),Fs=Bt&&Vl(Bt,ge);Zt&&Ae.push({contact:bt,actionType:De||{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:((tt=(rt=(We=bt.tags)==null?void 0:We[0])==null?void 0:rt.relationship_type)==null?void 0:tt.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),Fs&&Ae.push({contact:bt,actionType:De||{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:((dt=(He=(at=bt.tags)==null?void 0:at[0])==null?void 0:He.relationship_type)==null?void 0:dt.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const Fe=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((bt,vt)=>{var Zt,Fs,Rs;const Bt=i==null?void 0:i[vt%((i==null?void 0:i.length)||1)];return Bt?{contact:bt,actionType:Bt,planName:"Quick Touch",relationshipTypeName:((Rs=(Fs=(Zt=bt.tags)==null?void 0:Zt[0])==null?void 0:Fs.relationship_type)==null?void 0:Rs.name)||"",monthNumber:0}:null}).filter(Boolean))||[],qe=[...Ae,...Fe],be=async(bt,vt,Bt)=>{await u.mutateAsync({contactId:bt,actionTypeId:vt,scriptUsedId:Bt}),v(!1),g(null)},Ze=bt=>{bt.script?(g(bt),v(!0)):be(bt.contact.id,bt.actionType.id)},Ne=bt=>CZe[bt||"Phone"]||Ar,it=bt=>CZe[bt||"Users"]||Nn,je=(bt,vt)=>bt.replace(/\{\{FirstName\}\}/g,vt.first_name).replace(/\{\{LastName\}\}/g,vt.last_name||"").replace(/\{\{AgentName\}\}/g,j||"there"),Ge=(bt,vt)=>({Call:`Thinking of you, ${vt}!`,Text:`Quick hello, ${vt}`,Email:`Checking in, ${vt}`,"Handwritten Note":`A note for ${vt}`,Video:`Video message for ${vt}`,Gift:`Something special for you, ${vt}`})[bt]||`Hello ${vt}!`,Be=(bt,vt,Bt)=>{const Zt=`sms:${bt}`;if(vt&&Bt){const Fs=je(vt,Bt);return`${Zt}?body=${encodeURIComponent(Fs)}`}return Zt},Ye=(bt,vt,Bt,Zt,Fs)=>{const Rs=`mailto:${bt}`,ms=[];if(Fs){const Pt=Bt||Ge(Zt||"Email",Fs.first_name);if(ms.push(`subject=${encodeURIComponent(Pt)}`),vt){const Jt=je(vt,Fs);ms.push(`body=${encodeURIComponent(Jt)}`)}}return ms.length>0?`${Rs}?${ms.join("&")}`:Rs};return e.jsxs(e.Fragment,{children:[e.jsxs(Ts,{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 items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",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.jsx(qHs,{}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold mb-4",children:"Your Sphere"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:n==null?void 0:n.filter(bt=>bt.active).map(bt=>{const vt=it(bt.icon),Bt=(r==null?void 0:r[bt.id])||0,Zt=h===bt.id,Fs=VHs[bt.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{Zt?(p(null),s("/mission-control/contacts")):(p(bt.id),s(`/mission-control/contacts?type=${bt.id}`))},className:` flex items-center gap-2 px-4 py-3 rounded-lg border transition-all ${Zt?Fs:"bg-card hover:bg-accent"} `,children:[e.jsx(vt,{className:"h-5 w-5"}),e.jsxs("div",{className:"text-left",children:[e.jsx("div",{className:"font-medium",children:bt.name}),e.jsxs("div",{className:`text-sm ${Zt?"opacity-90":"text-muted-foreground"}`,children:[Bt," Contacts"]})]})]},bt.id)})})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs(B,{onClick:()=>s("/mission-control/video/record"),className:"w-full bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(Ah,{className:"h-4 w-4 mr-1"}),"Quick Video"]}),e.jsxs(B,{onClick:()=>s("/mission-control/contacts"),className:"w-full",variant:"outline",children:["View Contacts",e.jsx(xa,{className:"h-4 w-4 ml-1"})]}),e.jsx(B,{variant:"outline",onClick:()=>s("/mission-control/video-library"),className:"w-full",children:"Video Library"}),e.jsx(B,{variant:"outline",onClick:()=>s("/mission-control/plans"),className:"w-full",children:"Manage Plans"})]}),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(ze,{variant:"outline",className:"gap-1",children:[e.jsx(un,{className:"h-3 w-3"}),"Plan-based"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-1 border rounded-lg p-0.5",children:[e.jsx(B,{variant:F==="cards"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>z("cards"),title:"Card view",children:e.jsx(yf,{className:"h-4 w-4"})}),e.jsx(B,{variant:F==="table"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>z("table"),title:"Table view",children:e.jsx(Tp,{className:"h-4 w-4"})})]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-4",children:qe.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"})]}):F==="table"?e.jsx(IHs,{actions:qe,onMarkComplete:be,onViewScript:Ze,isLoading:u.isPending,buildSmsLink:Be,buildEmailLink:Ye,onGmailCompose:ce?bt=>{K(bt),W(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[qe.map((bt,vt)=>{var ft,Vt,Ms,Xt,Js,Cs,As;const Bt=bt.isSpecialDate,Zt=bt.specialDateType,Fs=Bt?Zt==="birthday"?cu:Or:Ne(((ft=bt.actionType)==null?void 0:ft.icon)||null),Rs=bt.contact.phone,ms=bt.contact.email,Pt=Bt?Zt==="birthday"?"#EC4899":"#8B5CF6":((Vt=bt.actionType)==null?void 0:Vt.color)||"#3B82F6",Jt=Bt?Zt==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(Ms=bt.actionType)==null?void 0:Ms.name;return e.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${Bt?"ring-2 ring-offset-2":""}`,style:Bt?{"--tw-ring-color":Pt}:void 0,children:[e.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:Pt},children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:Jt})]}),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:[Rs&&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(Ar,{className:"h-3 w-3"}),"Call"]}),e.jsxs("a",{href:Be(bt.contact.phone,(Xt=bt.script)==null?void 0:Xt.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(Ei,{className:"h-3 w-3"}),"Text"]})]}),ms&&(ce?e.jsxs("button",{onClick:()=>{K({id:bt.contact.id,first_name:bt.contact.first_name,last_name:bt.contact.last_name,email:bt.contact.email}),W(!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(Vs,{className:"h-3 w-3"}),"Email"]}):e.jsxs("a",{href:Ye(bt.contact.email,(Js=bt.script)==null?void 0:Js.script_body,(Cs=bt.script)==null?void 0:Cs.email_subject,(As=bt.actionType)==null?void 0:As.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(Vs,{className:"h-3 w-3"}),"Email"]}))]}),Bt&&e.jsxs("button",{onClick:()=>{const rn=`${bt.contact.first_name}${bt.contact.last_name?" "+bt.contact.last_name:""}`,tn=Zt==="birthday"?"birthday":"home_anniversary",er=new URLSearchParams({cardType:tn,contactId:bt.contact.id,name:rn,...bt.contact.address?{address:bt.contact.address}:{},...Zt==="anniversary"&&bt.contact.home_anniversary?{date:bt.contact.home_anniversary}:{}});s(`/mission-control/card-studio?${er.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(Vs,{className:"h-3 w-3"}),"Send ",Zt==="birthday"?"Birthday":"Anniversary"," Card"]}),!Rs&&!ms&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No contact info"}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[bt.relationshipTypeName&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:bt.relationshipTypeName}),bt.monthNumber>0&&e.jsxs(ze,{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:()=>{ne(bt.contact.id),he(`${bt.contact.first_name} ${bt.contact.last_name||""}`.trim())},children:[e.jsx(bf,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx(B,{size:"sm",className:"flex-1",onClick:()=>{var rn;return be(bt.contact.id,bt.actionType.id,(rn=bt.script)==null?void 0:rn.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]},bt.contact.id+vt)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsxs(B,{variant:"ghost",className:"h-full w-full",children:[e.jsx(Qf,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(cc,{children:e.jsx(Qr,{onClick:()=>s("/mission-control/contacts"),children:"View all contacts"})})]})})]})})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(It,{className:"text-lg",children:"Momentum"}),e.jsxs(bs,{open:S,onOpenChange:A,children:[e.jsx(Ai,{asChild:!0,children:e.jsx("button",{onClick:ve,className:"p-0.5 rounded hover:bg-muted transition-colors","aria-label":"Edit weekly goal",children:e.jsx(Xo,{className:"h-4 w-4 text-muted-foreground hover:text-primary"})})}),e.jsxs(vs,{className:"sm:max-w-[360px]",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Set Weekly Goal"}),e.jsx(Qn,{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=>L(bt.target.value),placeholder:"20",onKeyDown:bt=>{bt.key==="Enter"&&le()}})]}),e.jsx(B,{onClick:le,className:"w-full",children:"Save Goal"})]})]})]})]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx(pi,{value:Math.min(c.actionsThisWeek/D*100,100),className:"h-3 w-full max-w-full"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Dc,{className:"h-5 w-5 text-orange-500"}),e.jsxs("span",{className:"font-medium",children:[c.actionsThisWeek," / ",D]}),e.jsx("span",{className:"text-muted-foreground",children:"Actions Completed This Week"})]}),c.streak>0&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-lg",children:"🔥"}),e.jsx("span",{className:"font-medium",children:"Great Job!"}),e.jsxs("span",{className:"text-muted-foreground",children:["Keep Your Streak Going! (",c.streak," days)"]})]}),d.count>0&&e.jsxs("button",{onClick:()=>s("/mission-control/contacts?filter=not-touched-90"),className:"flex items-start gap-2 text-sm pt-2 border-t w-full text-left hover:bg-accent/50 -mx-4 px-4 py-2 rounded-md transition-colors",children:[e.jsx(gr,{className:"h-4 w-4 text-orange-500 mt-0.5"}),e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-orange-600 dark:text-orange-400",children:[d.count," Contact",d.count!==1?"s":""]}),e.jsx("span",{className:"text-muted-foreground",children:" Not Reached in 90+ Days"})]}),e.jsx(xa,{className:"h-4 w-4 text-muted-foreground ml-auto mt-0.5"})]})]})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsx(fpt,{}),e.jsx(zHs,{})]})]}),e.jsx(bs,{open:_,onOpenChange:v,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{children:e.jsx(_s,{className:"flex items-center gap-2",children:f&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:f.actionType.color||"#3B82F6"}}),f.actionType.name," Script"]})})}),f&&f.script&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["For: ",e.jsxs("span",{className:"font-medium text-foreground",children:[f.contact.first_name," ",f.contact.last_name]})]}),e.jsx("div",{className:"bg-muted p-4 rounded-lg",children:e.jsx("p",{className:"whitespace-pre-wrap",children:je(f.script.script_body,f.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",className:"flex-1",onClick:()=>v(!1),children:"Close"}),e.jsx(B,{className:"flex-1",onClick:()=>{var bt;return be(f.contact.id,f.actionType.id,(bt=f.script)==null?void 0:bt.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(SHs,{})]}),ce&&Y&&e.jsx(t1,{open:V,onOpenChange:W,contact:Y,gmailEmail:pe}),e.jsx(A1e,{open:!!J,onOpenChange:bt=>!bt&&ne(null),contactId:J||"",contactName:ie})]})}const GHs=[{value:"bidirectional",label:"Two-Way",icon:em,tooltip:"Sync contacts in both directions"},{value:"push_only",label:"Push Only",icon:Ru,tooltip:"Only push Agent OS → BoldTrail"},{value:"pull_only",label:"Pull Only",icon:am,tooltip:"Only pull BoldTrail → Agent OS"}];function X5e({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(FL,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:GHs.map(a=>e.jsxs(Ec,{children:[e.jsx(Ac,{asChild:!0,children:e.jsxs(QA,{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(vc,{children:a.tooltip})]},a.value))})]})}function TZe(){const s=Ht(),[t,n]=N.useState(!1),[r,a]=N.useState(null),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(null),[f,g]=N.useState(0),_=N.useRef(!1),{data:v}=ct({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:F,error:z}=await q.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(z)throw z;return F}}),j=(v==null?void 0:v.sync_direction)||"bidirectional",b=d??j,S=gt({mutationFn:async()=>{const{data:F,error:z}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(z)throw z;if(F!=null&&F.error)throw new Error(F.error);return F},onSuccess:F=>{u(null),a(F),n(!0)},onError:F=>{ae.error(F.message||"Failed to generate sync preview")}}),A=gt({mutationFn:async()=>{_.current=!1,p("Initializing sync..."),g(5);const{data:F,error:z}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:b}});if(z)throw z;if(F!=null&&F.error)throw new Error(F.error);const V=F;let W=V.sync_log_id,Y=V.next_phase,K=V.next_offset,J=V.push_total||0,ne=V.pull_total||0,ie=V.update_total||0,he=0,ce=0,pe=0;for(;Y!=="finalize"&&!_.current;){const ge=J+ne+ie;Y==="fetch_bt"?p("Fetching BoldTrail contacts..."):Y==="analyze"?(p("Analyzing contacts..."),g(15)):Y==="push"?(p(`Pushing contacts to BoldTrail... (${he}/${J})`),g(ge>0?he/ge*90:0)):Y==="pull"?(p(`Pulling contacts from BoldTrail... (${ce}/${ne})`),g(ge>0?(J+ce)/ge*90:0)):Y==="update"&&(p(`Updating existing contacts... (${pe}/${ie})`),g(ge>0?(J+ne+pe)/ge*90:0));const{data:Te,error:Me}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:Y,offset:K,sync_log_id:W,sync_direction:b}});if(Me)throw Me;if(Te!=null&&Te.error)throw new Error(Te.error);const Ce=Te;he+=Ce.chunk_pushed||0,ce+=Ce.chunk_pulled||0,pe+=Ce.chunk_updated||0,Ce.push_total!==void 0&&(J=Ce.push_total||0),Ce.pull_total!==void 0&&(ne=Ce.pull_total||0),Ce.update_total!==void 0&&(ie=Ce.update_total||0),Ce.progress&&p(Ce.progress),Y=Ce.next_phase,K=Ce.next_offset}p("Finalizing sync..."),g(95);const{data:le,error:ve}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:W,sync_direction:b}});if(ve)throw ve;return g(100),le},onSuccess:F=>{p(null),g(0),n(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]});const z=[`Pushed ${F.contacts_pushed||0}`,`pulled ${F.contacts_pulled||0}`,`updated ${F.contacts_updated||0}`,`skipped ${F.contacts_skipped||0} duplicates`];ae.success(`Sync complete! ${z.join(", ")}.`)},onError:F=>{p(null),g(0),ae.error(F.message||"Sync failed")}});if(!(v!=null&&v.connected))return null;const T=b==="pull_only"?0:(r==null?void 0:r.to_push)??0,L=b==="push_only"?0:(r==null?void 0:r.to_pull)??0,D=(r==null?void 0:r.to_update)??0,M=T>0||L>0||D>0;return e.jsxs(e.Fragment,{children:[e.jsxs(Ec,{children:[e.jsx(Ac,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"icon",onClick:()=>S.mutate(),disabled:S.isPending,className:"shrink-0",children:S.isPending?e.jsx(Ti,{className:"h-4 w-4 animate-spin"}):e.jsx(em,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(vc,{children:"Sync with BoldTrail"})]}),e.jsx(bs,{open:t,onOpenChange:F=>{A.isPending||n(F)},children:e.jsxs(vs,{className:"sm:max-w-lg",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(em,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Qn,{children:"Review what will happen when you sync your contacts."})]}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(X5e,{value:b,onChange:u,size:"sm"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:`rounded-lg border p-3 text-center ${b==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:T}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Ru,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${b==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:L}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(am,{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:D}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(fL,{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(Nn,{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"]}),D>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(fL,{className:"h-3 w-3 inline mr-1"}),D," contacts have missing fields that will be filled from the other system"]}),T>0&&e.jsxs(dy,{open:i,onOpenChange:l,children:[e.jsx(uy,{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(Ru,{className:"h-3 w-3 text-emerald-600"}),T," contacts to push to BoldTrail"]}),e.jsx(io,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`})]})}),e.jsx(hy,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.push_preview.map((F,z)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:F.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:F.email})]},z)),r.to_push>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",r.to_push-20," more"]})]})})]}),L>0&&e.jsxs(dy,{open:o,onOpenChange:c,children:[e.jsx(uy,{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(am,{className:"h-3 w-3 text-blue-600"}),L," contacts to pull from BoldTrail"]}),e.jsx(io,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(hy,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.pull_preview.map((F,z)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:F.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:F.email})]},z)),r.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",r.to_pull-20," more"]})]})})]}),!M&&!A.isPending&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"✅ Everything is already in sync! No contacts to transfer or update."}),A.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(pi,{value:f||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:h||"Sync in progress..."})]}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>n(!1),disabled:A.isPending,children:"Cancel"}),e.jsxs(B,{onClick:()=>A.mutate(),disabled:A.isPending||!M,className:"gap-2",children:[A.isPending?e.jsx(Ti,{className:"h-4 w-4 animate-spin"}):e.jsx(em,{className:"h-4 w-4"}),A.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const WHs=()=>{const{user:s}=ys();return ct({queryKey:["popby-items",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("popby_items").select("*").or(`owner_user_id.is.null,owner_user_id.eq.${s==null?void 0:s.id}`).eq("is_active",!0).order("name");if(n)throw n;return t},enabled:!!s})},I1e=s=>{const{user:t}=ys();return ct({queryKey:["popby-logs",t==null?void 0:t.id,s],queryFn:async()=>{let n=q.from("popby_logs").select("*").order("completed_at",{ascending:!1});if(s){const i=new Date;i.setDate(i.getDate()-s),n=n.gte("completed_at",i.toISOString())}const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})},gLe=()=>{const{user:s}=ys();return ct({queryKey:["relationship-type-popby-defaults",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("relationship_type_popby_defaults").select("*");if(n)throw n;return t},enabled:!!s})},C_t=()=>{const{user:s}=ys();return ct({queryKey:["contact-popby-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_popby_settings").select("*");if(n)throw n;return t},enabled:!!s})},KHs=()=>{const{data:s}=ox();Sy();const{data:t}=I1e(),{data:n}=C_t(),{data:r}=gLe(),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=kf(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 _=d.tags.map(v=>i.get(v.relationship_type_id)).filter(v=>v!==void 0);_.length>0&&(u=Math.min(..._))}const h=a.get(d.id)||null,p=h?Wv(o,kf(new Date(h))):null,f=p===null||p>=u,g=f&&p!==null?p-u:0;return{...d,lastPopby:h,daysSinceLastPopby:p,frequencyDays:u,isDue:f,daysOverdue:g}}).sort((d,u)=>u.daysOverdue-d.daysOverdue)},T_t=()=>KHs().filter(t=>t.isDue),YHs=()=>{const s=Ht(),{user:t}=ys();return gt({mutationFn:async n=>{const{error:r}=await q.from("popby_items").insert({...n,owner_user_id:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-items"]}),Pr({title:"Popby item created!"})},onError:n=>{Pr({title:"Error creating popby item",description:n.message,variant:"destructive"})}})},ZHs=()=>{const s=Ht(),{user:t}=ys();return gt({mutationFn:async n=>{const r=new Date().toISOString(),{error:a}=await q.from("popby_logs").insert({...n,owner_user_id:t==null?void 0:t.id,completed_at:r});if(a)throw a;try{const{data:i}=await q.from("action_types").select("id").ilike("name","Pop-By").eq("active",!0).maybeSingle();i!=null&&i.id&&await q.from("contact_touch_logs").insert({owner_user_id:t==null?void 0:t.id,contact_id:n.contact_id,action_type_id:i.id,notes:n.notes??"Pop-by logged",completed_at:r})}catch(i){console.error("Failed to log corresponding touch for popby",i)}},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-logs"]}),s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),Pr({title:"Popby logged!"})},onError:n=>{Pr({title:"Error logging popby",description:n.message,variant:"destructive"})}})},QHs=()=>{const s=Ht(),{user:t}=ys();return gt({mutationFn:async n=>{const{error:r}=await q.from("relationship_type_popby_defaults").upsert({...n,owner_user_id:t==null?void 0:t.id},{onConflict:"relationship_type_id,owner_user_id"});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["relationship-type-popby-defaults"]}),Pr({title:"Frequency updated!"})},onError:n=>{Pr({title:"Error updating frequency",description:n.message,variant:"destructive"})}})},XHs=()=>{const{data:s}=I1e(30),t=T_t(),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 JHs(){const{user:s}=ys();return ct({queryKey:["contact-touch-logs",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_touch_logs").select("*").order("completed_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function E_t(s){const{data:t}=JHs(),{data:n}=C_t(),{data:r}=gLe(),{data:a}=CHs();return N.useMemo(()=>{const i=a==null?void 0:a.find(v=>v.contact_id===s.id),l=i?new Date(i.snoozed_until):null,o=kf(new Date);if(l&&!wb(l,o))return{nextTouchDate:l,daysUntil:Wv(l,o),status:"snoozed",frequencyDays:90,lastTouchDate:null,snoozedUntil:l};const d=((t==null?void 0:t.filter(v=>v.contact_id===s.id))||[]).sort((v,j)=>new Date(j.completed_at).getTime()-new Date(v.completed_at).getTime())[0],u=d?new Date(d.completed_at):null;let h=90;const p=n==null?void 0:n.find(v=>v.contact_id===s.id&&v.is_active);if(p)h=p.frequency_days;else if(s.tags&&s.tags.length>0){const v=s.tags.map(j=>{const b=r==null?void 0:r.find(S=>S.relationship_type_id===j.relationship_type_id);return b==null?void 0:b.frequency_days}).filter(j=>j!==void 0);v.length>0&&(h=Math.min(...v))}if(!u)return{nextTouchDate:null,daysUntil:null,status:"never-touched",frequencyDays:h,lastTouchDate:null,snoozedUntil:null};const f=Bl(kf(u),h),g=Wv(f,o);let _;return g<0?_="overdue":g<=7?_="due-soon":_="on-track",{nextTouchDate:f,daysUntil:g,status:_,frequencyDays:h,lastTouchDate:u,snoozedUntil:null}},[s,t,n,r,a])}function Fge({contact:s}){const t=E_t(s),r=(()=>{switch(t.status){case"overdue":return{variant:"destructive",icon:Gi,text:`${Math.abs(t.daysUntil)} days overdue`,className:""};case"due-soon":return{variant:"secondary",icon:gr,text:t.daysUntil===0?"Due today":`Due in ${t.daysUntil} days`,className:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400"};case"on-track":return{variant:"secondary",icon:xr,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:bf,text:`Snoozed until ${Ss(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:yr,text:"Never touched",className:"border-dashed"}}})(),a=r.icon;return e.jsxs(ze,{variant:r.variant,className:Et("gap-1",r.className),children:[e.jsx(a,{className:"h-3 w-3"}),r.text]})}function eGs({contact:s,onLogTouch:t,onSnooze:n}){const r=E_t(s),a=EHs(),[i,l]=N.useState(!1),o=()=>{switch(r.status){case"overdue":return"text-destructive";case"due-soon":return"text-amber-600 dark:text-amber-400";case"on-track":return"text-emerald-600 dark:text-emerald-400";case"snoozed":return"text-slate-600 dark:text-slate-400";case"never-touched":return"text-muted-foreground"}},c=()=>{switch(r.status){case"overdue":return e.jsx(Gi,{className:"h-5 w-5 text-destructive"});case"due-soon":return e.jsx(gr,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(xr,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(bf,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(yr,{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(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(It,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),"Next Touch"]})}),e.jsxs(Ee,{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:"})," ",Ss(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:"})," ",Ss(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:"})," ",Ss(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(Bn,{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(bf,{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(A1e,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const NNe=768;function wR(){const[s,t]=N.useState(void 0);return N.useEffect(()=>{const n=window.matchMedia(`(max-width: ${NNe-1}px)`),r=()=>{t(window.innerWidthn.removeEventListener("change",r)},[]),!!s}function tGs(){const{user:s}=ys(),{hasLeadSite:t,leadSite:n}=Ip(),{data:r,isLoading:a}=ct({queryKey:["website-active-contacts",s==null?void 0:s.id,n==null?void 0:n.id],queryFn:async()=>{if(!n)return new Set;const{data:i}=await q.from("lead_site_visitors").select("contact_id").eq("lead_site_id",n.id).not("contact_id","is",null),{data:l}=await q.from("lead_site_consumer_profiles").select("contact_id").eq("lead_site_id",n.id).not("contact_id","is",null),o=new Set;return(i||[]).forEach(c=>{c.contact_id&&o.add(c.contact_id)}),(l||[]).forEach(c=>{c.contact_id&&o.add(c.contact_id)}),o},enabled:!!s&&t,staleTime:5*60*1e3});return{activeContactIds:r??new Set,hasLeadSite:t,isLoading:a}}const sGs={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"}},nGs={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 J5e({score:s,showScore:t=!1,showTooltip:n=!0,size:r="sm",className:a}){const i=sGs[s.status],l=nGs[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(Ww,{children:e.jsxs(Ec,{children:[e.jsx(Ac,{asChild:!0,children:o}),e.jsx(vc,{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(pi,{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 rGs=[{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}],pG=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]},aGs=({open:s,onOpenChange:t,relationshipTypes:n,onSuccess:r})=>{const{user:a}=ys(),{toast:i}=Ba(),l=N.useRef(null),[o,c]=N.useState("upload"),[d,u]=N.useState([]),[h,p]=N.useState([]),[f,g]=N.useState({}),[_,v]=N.useState([]),[j,b]=N.useState([]),[S,A]=N.useState([]),[T,L]=N.useState(""),[D,M]=N.useState(!1),[F,z]=N.useState([]),[V,W]=N.useState(!1),[Y,K]=N.useState(null);N.useEffect(()=>{!s||!(a!=null&&a.id)||(async()=>{const{data:Fe}=await q.from("contact_custom_tags").select("id, name, color").eq("owner_user_id",a.id).order("name");b(Fe||[])})()},[s,a==null?void 0:a.id]);const J=Fe=>{A(qe=>qe.includes(Fe)?qe.filter(be=>be!==Fe):[...qe,Fe])},ne=async()=>{const Fe=T.trim();if(!(!Fe||!(a!=null&&a.id))){M(!0);try{const{data:qe,error:be}=await q.from("contact_custom_tags").insert({owner_user_id:a.id,name:Fe}).select("id, name, color").single();if(be)throw be;qe&&(b(Ze=>[...Ze,qe].sort((Ne,it)=>Ne.name.localeCompare(it.name))),A(Ze=>[...Ze,qe.id]),L(""))}catch(qe){i({title:"Could not create tag",description:qe.message||"Try a different name.",variant:"destructive"})}finally{M(!1)}}},ie=()=>{c("upload"),u([]),p([]),g({}),v([]),A([]),L(""),z([]),K(null),l.current&&(l.current.value="")},he=()=>{ie(),t(!1)},ce=Fe=>{const qe=Fe.split(` `).map(Ge=>Ge.trim()).filter(Ge=>Ge);if(qe.length===0)return{headers:[],data:[]};const be=Ge=>{const Be=[];let Ye="",We=!1;for(let rt=0;rt0&&(Ze[0]=Ze[0].replace(/^\uFEFF/,""));const Ne=new Map,it=Ze.map((Ge,Be)=>{let Ye=(Ge||"").trim();Ye||(Ye=`Column ${Be+1}`);const We=Ne.get(Ye)||0;return Ne.set(Ye,We+1),We===0?Ye:`${Ye} (${We+1})`}),je=qe.slice(1).map(be);return{headers:it,data:je}},pe=Fe=>{var Ze;const qe=(Ze=Fe.target.files)==null?void 0:Ze[0];if(!qe)return;const be=new FileReader;be.onload=Ne=>{var Ye;const it=(Ye=Ne.target)==null?void 0:Ye.result,{headers:je,data:Ge}=ce(it);if(je.length===0){i({title:"No data found",description:"The CSV file appears to be empty.",variant:"destructive"});return}u(je),p(Ge);const Be={};je.forEach(We=>{const rt=We.toLowerCase().replace(/[_\s-]/g,"");rt.includes("firstname")||rt==="first"?Be.first_name=We:rt.includes("lastname")||rt==="last"?Be.last_name=We:rt.includes("spouse")&&rt.includes("email")?Be.spouse_email=We:rt.includes("spouse")||rt.includes("partner")?Be.spouse_name=We:rt.includes("email")?Be.email=We:rt.includes("phone")||rt.includes("mobile")||rt.includes("cell")?Be.phone=We:rt.includes("address")||rt.includes("street")?Be.address=We:rt==="city"?Be.city=We:rt==="state"||rt==="province"?Be.state=We:rt==="zip"||rt==="zipcode"||rt==="postalcode"?Be.zip=We:rt.includes("company")||rt.includes("organization")||rt.includes("business")?Be.company_name=We:rt.includes("jobtitle")||rt.includes("title")&&!rt.includes("spouse")?Be.job_title=We:rt.includes("birthday")||rt.includes("dob")||rt.includes("birthdate")?Be.birthday=We:rt.includes("anniversary")||rt.includes("homeanniversary")?Be.home_anniversary=We:(rt.includes("notes")||rt.includes("comment"))&&(Be.notes=We)}),g(Be),c("mapping")},be.readAsText(qe)},le=(Fe,qe)=>{g(be=>{if(qe==="none"){const{[Fe]:Ze,...Ne}=be;return Ne}return{...be,[Fe]:qe}})},ve=Fe=>{v(qe=>qe.includes(Fe)?qe.filter(be=>be!==Fe):[...qe,Fe])},ge=async()=>{if(!(a!=null&&a.id))return;const{data:Fe}=await q.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),qe=new Set((Fe||[]).filter(Ne=>Ne.email).map(Ne=>Ne.email.toLowerCase())),be=new Set((Fe||[]).filter(Ne=>Ne.phone).map(Ne=>Ne.phone.replace(/[^0-9]/g,""))),Ze=h.map(Ne=>{const it=rt=>{const tt=f[rt];if(!tt)return"";const at=d.indexOf(tt);return at>=0?(Ne[at]||"").trim():""},je=it("first_name"),Ge=it("email"),Be=it("phone"),Ye=je.length>0,We=!!(Ge&&qe.has(Ge.toLowerCase())||Be&&be.has(Be.replace(/[^0-9]/g,"")));return{first_name:je,last_name:it("last_name"),email:Ge,phone:Be,address:it("address"),city:it("city"),state:it("state"),zip:it("zip"),spouse_name:it("spouse_name"),spouse_email:it("spouse_email"),company_name:it("company_name"),job_title:it("job_title"),birthday:it("birthday"),home_anniversary:it("home_anniversary"),notes:it("notes"),isValid:Ye,isDuplicate:We,error:Ye?void 0:"First name is required"}});z(Ze),c("preview")},Te=Fe=>{const qe=Fe.trim().split(/\s+/);return{first_name:qe[0],last_name:qe.length>1?qe.slice(1).join(" "):null}},Me=async()=>{if(!(a!=null&&a.id))return;const Fe=F.filter(Ne=>Ne.isValid);if(Fe.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}W(!0);let qe=0,be=0,Ze=0;try{for(const Ne of Fe)try{let it=null;if(Ne.email){const{data:Be}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Ne.email).maybeSingle();it=Be}if(!it&&Ne.phone){const Be=Ne.phone.replace(/[^0-9]/g,""),{data:Ye}=await q.from("innercircle_contacts").select("id, phone").eq("owner_user_id",a.id).not("phone","is",null);if(Ye){const We=Ye.find(rt=>rt.phone&&rt.phone.replace(/[^0-9]/g,"")===Be);We&&(it={id:We.id})}}const je={owner_user_id:a.id,first_name:Ne.first_name,last_name:Ne.last_name||null,email:Ne.email||null,phone:Ne.phone||null,address:Ne.address||null,city:Ne.city||null,state:Ne.state||null,zip:Ne.zip||null,spouse_name:Ne.spouse_name||null,spouse_email:Ne.spouse_email||null,company_name:Ne.company_name||null,job_title:Ne.job_title||null,birthday:pG(Ne.birthday),home_anniversary:pG(Ne.home_anniversary),notes:Ne.notes||null};let Ge=null;if(it){const{data:Be}=await q.from("innercircle_contacts").select("*").eq("id",it.id).single();if(Be){const Ye={},We=["last_name","email","phone","address","city","state","zip","spouse_name","spouse_email","company_name","job_title","birthday","home_anniversary","notes"];for(const rt of We){const tt=Be[rt],at=je[rt];(!tt||tt==="")&&at&&(Ye[rt]=at)}Object.keys(Ye).length>0&&await q.from("innercircle_contacts").update(Ye).eq("id",it.id)}Ge=it.id,be++}else{const{data:Be,error:Ye}=await q.from("innercircle_contacts").insert(je).select("id").single();Ye?(console.error("Insert error for contact:",Ne.first_name,Ye),Ze++):Be?(Ge=Be.id,_.length>0&&await q.from("innercircle_contact_tags").insert(_.map(We=>({contact_id:Be.id,relationship_type_id:We}))),qe++):Ze++}if(Ge&&S.length>0&&await q.from("contact_custom_tag_assignments").upsert(S.map(Be=>({contact_id:Ge,tag_id:Be})),{onConflict:"contact_id,tag_id",ignoreDuplicates:!0}),Ge&&Ne.spouse_name){const Be=Te(Ne.spouse_name);let Ye=null;if(Ne.spouse_email){const{data:rt}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Ne.spouse_email).maybeSingle();Ye=rt}if(!Ye){const{data:rt}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("first_name",Be.first_name).eq("last_name",Be.last_name||Ne.last_name||"").maybeSingle();Ye=rt}let We=null;if(Ye){We=Ye.id;const rt=pG(Ne.home_anniversary);rt&&await q.from("innercircle_contacts").update({home_anniversary:rt}).eq("id",Ye.id).is("home_anniversary",null)}else{const{data:rt}=await q.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:Be.first_name,last_name:Be.last_name||Ne.last_name||null,email:Ne.spouse_email||null,address:Ne.address||null,city:Ne.city||null,state:Ne.state||null,zip:Ne.zip||null,home_anniversary:pG(Ne.home_anniversary),spouse_name:`${Ne.first_name}${Ne.last_name?" "+Ne.last_name:""}`,spouse_email:Ne.email||null,notes:`Spouse of ${Ne.first_name} ${Ne.last_name||""} (imported via CSV)`.trim()}).select("id").single();rt&&(We=rt.id,qe++)}We&&(await q.from("innercircle_contacts").update({spouse_contact_id:We}).eq("id",Ge),await q.from("innercircle_contacts").update({spouse_contact_id:Ge}).eq("id",We))}}catch(it){console.error("Error importing contact:",it),Ze++}K({created:qe,updated:be,failed:Ze}),c("result"),(qe>0||be>0)&&r(),i({title:"Import Complete",description:`${qe} created, ${be} updated${Ze>0?`, ${Ze} failed`:""}.`})}catch(Ne){console.error("Import error:",Ne),i({title:"Import Failed",description:Ne.message||"Failed to import contacts",variant:"destructive"})}finally{W(!1)}},Ce=F.filter(Fe=>Fe.isValid).length,Ae=F.filter(Fe=>!Fe.isValid).length,De=F.filter(Fe=>Fe.isValid&&Fe.isDuplicate).length,Ie=Ce-De;return e.jsx(bs,{open:s,onOpenChange:he,children:e.jsxs(vs,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(gw,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),e.jsx(Qn,{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:pe,className:"hidden"}),e.jsx(Na,{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 Fe;return(Fe=l.current)==null?void 0:Fe.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 Fe=`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`,qe=new Blob([Fe],{type:"text/csv"}),be=URL.createObjectURL(qe),Ze=document.createElement("a");Ze.href=be,Ze.download="contact_import_template.csv",Ze.click(),URL.revokeObjectURL(be)},children:[e.jsx(Pa,{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:rGs.map(Fe=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(se,{className:"w-40 text-sm",children:[Fe.label,Fe.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(ds,{value:f[Fe.key]||"none",onValueChange:qe=>le(Fe.key,qe),children:[e.jsx(ls,{className:"w-48",children:e.jsx(us,{placeholder:"Select column..."})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"-- Not mapped --"}),d.map(qe=>e.jsx(Qe,{value:qe,children:qe},qe))]})]})]},Fe.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(Fe=>e.jsx(ze,{variant:_.includes(Fe.id)?"default":"outline",className:"cursor-pointer",onClick:()=>ve(Fe.id),children:Fe.name},Fe.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."}),j.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:j.map(Fe=>{const qe=S.includes(Fe.id);return e.jsxs(ze,{variant:qe?"default":"outline",className:"cursor-pointer gap-1",style:qe&&Fe.color?{backgroundColor:Fe.color,borderColor:Fe.color}:void 0,onClick:()=>J(Fe.id),children:[Fe.name,qe&&e.jsx(Bn,{className:"h-3 w-3"})]},Fe.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:Fe=>L(Fe.target.value),onKeyDown:Fe=>{Fe.key==="Enter"&&(Fe.preventDefault(),ne())},className:"max-w-xs"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:ne,disabled:!T.trim()||D,children:[D?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{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(xr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[Ie," new"]})]}),De>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Gi,{className:"h-4 w-4"}),e.jsxs("span",{children:[De," existing (will merge gaps)"]})]}),Ae>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Gi,{className:"h-4 w-4"}),e.jsxs("span",{children:[Ae," invalid"]})]})]}),De>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(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{className:"bg-muted/30",children:[e.jsx(Ct,{children:"First Name"}),e.jsx(Ct,{children:"Last Name"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Phone"}),e.jsx(Ct,{children:"Status"})]})}),e.jsx(ha,{children:F.slice(0,100).map((Fe,qe)=>e.jsxs(Hs,{children:[e.jsx(ut,{children:Fe.first_name}),e.jsx(ut,{children:Fe.last_name}),e.jsx(ut,{children:Fe.email}),e.jsx(ut,{children:Fe.phone}),e.jsx(ut,{children:Fe.isValid?Fe.isDuplicate?e.jsx(ze,{variant:"outline",className:"bg-accent text-accent-foreground",children:"Merge"}):e.jsx(ze,{variant:"secondary",className:"bg-primary/10 text-primary",children:"New"}):e.jsx(ze,{variant:"destructive",children:Fe.error||"Invalid"})})]},qe))})]}),F.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",F.length," contacts"]})]})]}),o==="result"&&Y&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx(xr,{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:[Y.created," created, ",Y.updated," merged"]}),Y.failed>0&&e.jsxs("p",{className:"text-destructive",children:[Y.failed," failed to import"]})]}),e.jsxs(Xn,{children:[o==="upload"&&e.jsx(B,{variant:"outline",onClick:he,children:"Cancel"}),o==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:ie,children:"Back"}),e.jsx(B,{onClick:ge,disabled:!f.first_name,children:"Continue"})]}),o==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:()=>c("mapping"),children:"Back"}),e.jsx(B,{onClick:Me,disabled:V||Ce===0,children:V?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${Ce} Contact${Ce!==1?"s":""}`})]}),o==="result"&&e.jsx(B,{onClick:he,children:"Done"})]})]})})};function iGs(){return"contacts"in navigator&&"ContactsManager"in window}function oGs(s){const t=[],n=s.split("BEGIN:VCARD").filter(r=>r.trim());for(const r of n){const a=r.split(/\r?\n/);let i="",l="",o="",c="",d="";for(const u of a){const h=u.replace(/^\s+/,"");if(h.startsWith("N:")||h.startsWith("N;")){const f=h.substring(h.indexOf(":")+1).split(";");l=(f[0]||"").trim(),i=(f[1]||"").trim()}if((h.startsWith("FN:")||h.startsWith("FN;"))&&!i){const f=h.substring(h.indexOf(":")+1).trim().split(" ");i=f[0]||"",l=f.slice(1).join(" ")}(h.startsWith("EMAIL")||h.match(/^item\d+\.EMAIL/i))&&!o&&(o=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("TEL")||h.match(/^item\d+\.TEL/i))&&!c&&(c=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("ADR")||h.match(/^item\d+\.ADR/i))&&!d&&(d=h.substring(h.indexOf(":")+1).split(";").map(g=>g.trim()).filter(Boolean).join(", "))}(i||l)&&t.push({first_name:i,last_name:l,email:o,phone:c,address:d})}return t}function lGs({open:s,onOpenChange:t,onComplete:n}){ys();const{data:r}=ox(),a=Uye(),i=N.useRef(null),[l,o]=N.useState("choose"),[c,d]=N.useState([]),[u,h]=N.useState(new Set),[p,f]=N.useState(0),[g,_]=N.useState(0),v=iGs(),j=N.useCallback(z=>{if(!r)return z;const V=new Set(r.filter(Y=>Y.email).map(Y=>Y.email.toLowerCase())),W=new Set(r.filter(Y=>Y.phone).map(Y=>Y.phone.replace(/\D/g,"")));return z.map(Y=>{var ne,ie;const K=(ne=Y.email)==null?void 0:ne.toLowerCase(),J=(ie=Y.phone)==null?void 0:ie.replace(/\D/g,"");return K&&V.has(K)?{...Y,isDuplicate:!0,duplicateField:"email"}:J&&J.length>=7&&W.has(J)?{...Y,isDuplicate:!0,duplicateField:"phone"}:Y})},[r]),b=async()=>{try{const z=["name","email","tel","address"],V=await navigator.contacts.select(z,{multiple:!0});if(!V||V.length===0)return;const W=V.map(J=>{var he,ce,pe,le;const ie=(((he=J.name)==null?void 0:he[0])||"").split(" ");return{first_name:ie[0]||"",last_name:ie.slice(1).join(" "),email:((ce=J.email)==null?void 0:ce[0])||"",phone:((pe=J.tel)==null?void 0:pe[0])||"",address:(le=J.address)!=null&&le[0]?[J.address[0].streetAddress,J.address[0].city,J.address[0].region,J.address[0].postalCode].filter(Boolean).join(", "):""}}),Y=j(W);d(Y);const K=new Set;Y.forEach((J,ne)=>{J.isDuplicate||K.add(ne)}),h(K),o("preview")}catch(z){console.error("Contact Picker error:",z),Pr({title:"Could not access contacts",description:"Please try the file upload option instead.",variant:"destructive"})}},S=z=>{var Y;const V=(Y=z.target.files)==null?void 0:Y[0];if(!V)return;const W=new FileReader;W.onload=K=>{var ce;const J=(ce=K.target)==null?void 0:ce.result,ne=oGs(J);if(ne.length===0){Pr({title:"No contacts found",description:"The file didn't contain any valid contacts.",variant:"destructive"});return}const ie=j(ne);d(ie);const he=new Set;ie.forEach((pe,le)=>{pe.isDuplicate||he.add(le)}),h(he),o("preview")},W.readAsText(V),i.current&&(i.current.value="")},A=async()=>{const z=c.filter((W,Y)=>u.has(Y));if(z.length===0)return;o("importing");let V=0;for(const W of z)try{await a.mutateAsync({first_name:W.first_name,last_name:W.last_name||void 0,email:W.email||void 0,phone:W.phone||void 0,address:W.address||void 0}),V++,_(Math.round(V/z.length*100))}catch(Y){console.error(`Failed to import ${W.first_name} ${W.last_name}:`,Y)}f(V),o("done")},T=z=>{h(V=>{const W=new Set(V);return W.has(z)?W.delete(z):W.add(z),W})},L=()=>{u.size===c.length?h(new Set):h(new Set(c.map((z,V)=>V)))},D=z=>{z||(o("choose"),d([]),h(new Set),f(0),_(0),l==="done"&&n()),t(z)},M=c.filter(z=>z.isDuplicate).length,F=u.size;return e.jsx(bs,{open:s,onOpenChange:D,children:e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(ng,{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(Qn,{children:"Add contacts from your phone directly into Agent OS."})]}),l==="choose"&&e.jsxs("div",{className:"space-y-4 pt-2",children:[v&&e.jsxs(B,{onClick:b,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(ng,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Select from Phone"}),e.jsx("div",{className:"text-xs opacity-80",children:"Pick contacts directly from your device"})]})]}),e.jsxs("div",{className:"relative",children:[v&&e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),v&&e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-background px-2 text-muted-foreground",children:"or"})})]}),e.jsxs(B,{variant:v?"outline":"default",onClick:()=>{var z;return(z=i.current)==null?void 0:z.click()},className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(Na,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Upload Contact File"}),e.jsx("div",{className:"text-xs opacity-80",children:v?"Import a .vcf file exported from your Contacts app":"Export contacts from your phone as a .vcf file, then upload here"})]})]}),e.jsx("input",{ref:i,type:"file",accept:".vcf,.vcard",onChange:S,className:"hidden"}),!v&&e.jsxs("div",{className:"rounded-lg bg-muted p-3 text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{className:"font-medium",children:"How to export contacts:"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"iPhone:"}),e.jsx("p",{className:"text-xs",children:'Open Contacts → select contacts → Share → choose "Export vCard"'})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"Android:"}),e.jsx("p",{className:"text-xs",children:"Open Contacts → Menu → Export → save as .vcf file"})]})]})]}),l==="preview"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{children:[c.length," contact",c.length!==1?"s":""," found",M>0&&e.jsxs("span",{className:"text-amber-600 ml-1",children:["(",M," already exist)"]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:L,children:u.size===c.length?"Deselect All":"Select All"})]}),e.jsx(hi,{className:"h-[350px] rounded-md border",children:e.jsx("div",{className:"divide-y",children:c.map((z,V)=>e.jsxs("div",{className:`flex items-start gap-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors ${z.isDuplicate?"opacity-60":""}`,onClick:()=>T(V),children:[e.jsx(ui,{checked:u.has(V),onCheckedChange:()=>T(V),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-sm truncate",children:[z.first_name," ",z.last_name]}),z.isDuplicate&&e.jsxs(ze,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-amber-500/10 text-amber-600 border-amber-200",children:["Exists (",z.duplicateField,")"]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 mt-0.5",children:[z.phone&&e.jsx("div",{children:z.phone}),z.email&&e.jsx("div",{className:"truncate",children:z.email})]})]})]},V))})}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>o("choose"),children:"Back"}),e.jsxs(B,{onClick:A,disabled:F===0,children:["Import ",F," Contact",F!==1?"s":""]})]})]}),l==="importing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(ts,{className:"h-8 w-8 animate-spin text-primary"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-medium",children:"Importing contacts..."}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[g,"% complete"]})]}),e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${g}%`}})})]}),l==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-emerald-500/10 flex items-center justify-center",children:e.jsx(Ir,{className:"h-6 w-6 text-emerald-600"})}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"font-semibold text-lg",children:[p," contact",p!==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:()=>D(!1),className:"mt-2",children:"Done"})]})]})})}function cGs(s){return ct({queryKey:["video-share-recipients",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("video_share_recipients").select("*").eq("video_id",s).order("sent_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function dGs(){const{user:s}=ys();return ct({queryKey:["video-share-stats",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:n}=await q.from("video_share_recipients").select("*").eq("owner_user_id",s.id);if(n)throw n;const r=t;return{totalSent:r.length,totalOpened:r.filter(a=>a.opened_at).length,totalClicked:r.filter(a=>a.clicked_at).length,totalWatched:r.filter(a=>a.watched_at).length,openRate:r.length>0?Math.round(r.filter(a=>a.opened_at).length/r.length*100):0,clickRate:r.length>0?Math.round(r.filter(a=>a.clicked_at).length/r.length*100):0,watchRate:r.length>0?Math.round(r.filter(a=>a.watched_at).length/r.length*100):0}},enabled:!!(s!=null&&s.id)})}function uGs(){const{user:s}=ys();return ct({queryKey:["video-share-history",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await q.from("video_share_recipients").select(` *, agent_videos!inner(id, title, thumbnail_url, share_token, duration_seconds) `).eq("owner_user_id",s.id).order("sent_at",{ascending:!1}).limit(200);if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function A_t(){const{user:s}=ys(),t=Ht();return gt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await q.from("video_share_recipients").insert([{video_id:n.video_id,owner_user_id:s.id,recipient_email:n.recipient_email,recipient_name:n.recipient_name||null,contact_id:n.contact_id||null,sent_via:n.sent_via||"gmail",share_token:"placeholder"}]).select().single();if(a)throw a;return r},onSuccess:n=>{t.invalidateQueries({queryKey:["video-share-recipients",n.video_id]}),t.invalidateQueries({queryKey:["video-share-stats"]}),t.invalidateQueries({queryKey:["video-share-history"]})}})}function M_t(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function I_t(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const hGs=100;function mGs({open:s,onOpenChange:t,contacts:n,isGmailConnected:r,isMassEmailReady:a,onSendComplete:i}){const l=Mn(),o=ma(),c=A_t(),[d,u]=N.useState([]),[h,p]=N.useState(!1),[f,g]=N.useState(""),[_,v]=N.useState(null),[j,b]=N.useState(""),[S,A]=N.useState(""),[T,L]=N.useState(!1),[D,M]=N.useState({done:0,total:0,failed:0}),F=n.filter(ie=>!!ie.email),z=n.length-F.length,V=F.length>hGs;N.useEffect(()=>{s&&(v(null),g(""),M({done:0,total:0,failed:0}))},[s]),N.useEffect(()=>{!s||!o||(p(!0),q.from("agent_videos").select("id, title, share_token, thumbnail_url, playback_url, duration_seconds, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:ie})=>{u(ie||[]),p(!1)}))},[s,o]),N.useEffect(()=>{if(!_)return;const ie=_.title||"a quick video";b(`I recorded a video for you — ${ie}`),A("Hey {{first_name}}! I recorded a quick video just for you. Click below to watch it:")},[_]);const W=d.filter(ie=>!f||(ie.title||"").toLowerCase().includes(f.toLowerCase())),Y=(ie,he)=>{if(!_)return"";const ce=_.share_token?`https://video.relevelup.com/share/video/${_.share_token}`:"",pe=_.share_token?`https://video.relevelup.com/thumb/${_.share_token}`:_.thumbnail_url||"",le=_.title||"Video Message",ge=S.replace(/\{\{first_name\}\}/gi,ie).split(/\n\n+/).map(Ce=>`

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

`).join(""),Te=he?I_t(he):ce,Me=he?``:"";return`
`},K=async()=>{if(!_)return;L(!0),M({done:0,total:F.length,failed:0});let ie=0,he=0;for(const ce of F)try{let pe;try{pe=(await c.mutateAsync({video_id:_.id,recipient_email:ce.email,recipient_name:`${ce.first_name} ${ce.last_name||""}`.trim(),contact_id:ce.id,sent_via:"gmail"})).share_token}catch(Me){console.warn("Tracking record failed for",ce.email,Me)}const le=Y(ce.first_name,pe),ve=j.replace(/\{\{first_name\}\}/gi,ce.first_name),{data:ge,error:Te}=await q.functions.invoke("gmail-send",{body:{to:ce.email,subject:ve,body:le,contactId:ce.id}});if(Te||!(ge!=null&&ge.success))throw new Error((ge==null?void 0:ge.error)||(Te==null?void 0:Te.message)||"Send failed");ie+=1}catch(pe){console.error("Failed to send to",ce.email,pe),he+=1}finally{M({done:ie+he,total:F.length,failed:he}),await new Promise(pe=>setTimeout(pe,250))}L(!1),he===0?ae.success(`Video sent to ${ie} ${ie===1?"contact":"contacts"}!`):ae.warning(`Sent to ${ie}, ${he} failed. Check console for details.`),t(!1),i==null||i()},J=()=>{if(!_)return;const ie=Y("there",void 0);l("/admin/email-campaigns/new",{state:{directRecipients:F.map(he=>({email:he.email,name:`${he.first_name} ${he.last_name||""}`.trim()})),initialSubject:j,initialBodyHtml:ie}}),t(!1)},ne=!!_&&!!j.trim()&&F.length>0&&(V?a:r);return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[640px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(br,{className:"h-5 w-5 text-primary"}),"Send Video to ",F.length," ",F.length===1?"Contact":"Contacts"]}),e.jsxs(Qn,{children:[V?e.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600",children:[e.jsx($d,{className:"h-3.5 w-3.5"}),F.length," recipients — will be sent as a Mass Email campaign"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Vs,{className:"h-3.5 w-3.5"}),"Sent individually via your connected Gmail"]}),z>0&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",z," skipped — no email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[V&&!a&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Gi,{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 ",F.length," recipients."]})]}),!V&&!r&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Gi,{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(Is,{className:"h-3.5 w-3.5"})," Record new"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search your video library...",value:f,onChange:ie=>g(ie.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(Ws,{className:"h-14 w-full"}),e.jsx(Ws,{className:"h-14 w-full"})]}):W.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."}):W.map(ie=>{const he=(_==null?void 0:_.id)===ie.id;return e.jsxs("button",{type:"button",onClick:()=>v(ie),className:`w-full flex items-center gap-3 p-2 rounded-md border text-left transition-colors ${he?"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:[ie.thumbnail_url?e.jsx("img",{src:ie.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx(Ah,{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(Al,{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:ie.title||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ie.duration_seconds?`${Math.round(ie.duration_seconds)}s`:"",ie.created_at?` · ${new Date(ie.created_at).toLocaleDateString()}`:""]})]})]},ie.id)})})]}),e.jsx(ll,{}),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:j,onChange:ie=>b(ie.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(Es,{id:"bulk-video-message",value:S,onChange:ie=>A(ie.target.value),rows:4,className:"resize-y"})]}),T&&D.total>0&&e.jsxs("div",{className:"p-3 rounded-md bg-muted text-sm",children:["Sending… ",D.done," / ",D.total,D.failed>0&&e.jsxs("span",{className:"text-destructive ml-2",children:["(",D.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"}),V?e.jsxs(B,{onClick:J,disabled:!ne,className:"gap-2",children:[e.jsx($d,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs(B,{onClick:K,disabled:!ne||T,className:"gap-2",children:[T?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"}),T?"Sending…":`Send to ${F.length}`]})]})]})]})})}function P1e(){const s=ma();return ct({queryKey:["drip-campaigns",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_campaigns").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("is_starter",{ascending:!1}).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function pGs(s){return ct({queryKey:["drip-campaign",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("drip_campaigns").select("*").eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function fGs(){const s=ma(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("drip_campaigns").insert({owner_user_id:s,name:n.name,description:n.description??null,category:n.category??"nurture",icon:n.icon??"🌱",cover_color:n.cover_color??"from-emerald-500 to-teal-600",goal:n.goal??null,is_active:!1}).select().single();if(a)throw a;return r},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function P_t(){const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("drip_campaigns").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["drip-campaigns"]}),s.invalidateQueries({queryKey:["drip-campaign",n.id]})}})}function xGs(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("drip_campaigns").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-campaigns"]})})}function L_t(){const s=ma(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const[{data:r,error:a},{data:i,error:l}]=await Promise.all([q.from("drip_campaigns").select("*").eq("id",n).single(),q.from("drip_campaign_steps").select("*").eq("campaign_id",n).order("step_order")]);if(a)throw a;if(l)throw l;const{data:o,error:c}=await q.from("drip_campaigns").insert({owner_user_id:s,name:r.name,description:r.description,category:r.category,icon:r.icon,cover_color:r.cover_color,goal:r.goal,is_active:!1,is_starter:!1}).select().single();if(c)throw c;if(i&&i.length>0){const d=i.map(h=>({campaign_id:o.id,step_order:h.step_order,channel:h.channel,subject:h.subject,body:h.body,video_url:h.video_url,delay_type:h.delay_type,delay_days:h.delay_days,delay_hours:h.delay_hours,anchor_field:h.anchor_field,anchor_offset_days:h.anchor_offset_days,send_window_start:h.send_window_start,send_window_end:h.send_window_end})),{error:u}=await q.from("drip_campaign_steps").insert(d);if(u)throw u}return o},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function D_t(s){return ct({queryKey:["drip-campaign-steps",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_campaign_steps").select("*").eq("campaign_id",s).order("step_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function gGs(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("drip_campaign_steps").insert({campaign_id:t.campaign_id,step_order:t.step_order,channel:t.channel??"email",subject:t.subject??"",body:t.body??"",video_url:t.video_url??null,delay_type:t.delay_type??"relative",delay_days:t.delay_days??0,delay_hours:t.delay_hours??0,anchor_field:t.anchor_field??null,anchor_offset_days:t.anchor_offset_days??0}).select().single();if(r)throw r;return n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["drip-campaign-steps",n.campaign_id]})})}function yGs(){const s=Ht();return gt({mutationFn:async({id:t,campaign_id:n,...r})=>{const{data:a,error:i}=await q.from("drip_campaign_steps").update(r).eq("id",t).select().single();if(i)throw i;return{data:a,campaign_id:n}},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t.campaign_id]})})}function vGs(){const s=Ht();return gt({mutationFn:async({id:t,campaign_id:n})=>{const{error:r}=await q.from("drip_campaign_steps").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t]})})}function bGs(s){return ct({queryKey:["campaign-enrollments",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_campaign_enrollments").select("*, contact:innercircle_contacts(id, first_name, last_name, email)").eq("campaign_id",s).order("enrolled_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function _Gs(s){return ct({queryKey:["campaign-enrollment-count",s],queryFn:async()=>{if(!s)return 0;const{count:t,error:n}=await q.from("drip_campaign_enrollments").select("id",{count:"exact",head:!0}).eq("campaign_id",s).eq("status","active");if(n)throw n;return t??0},enabled:!!s,staleTime:3e4})}function R_t(){const s=Ht();return gt({mutationFn:async({campaignId:t,contactIds:n})=>{const{data:r,error:a}=await q.functions.invoke("enroll-contacts-in-campaign",{body:{campaign_id:t,contact_ids:n}});if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}function wGs(){const s=Ht();return gt({mutationFn:async({id:t,status:n})=>{const r={status:n};n==="paused"&&(r.paused_at=new Date().toISOString()),n==="exited"&&(r.exited_at=new Date().toISOString(),r.exit_reason="manual");const{data:a,error:i}=await q.from("drip_campaign_enrollments").update(r).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}const jGs=[{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"}],L1e={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"},NGs={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 a6({userId:s,onSelect:t,onSelectVideo:n,triggerLabel:r="Library",triggerSize:a="sm",triggerVariant:i="outline",triggerClassName:l}){const[o,c]=N.useState(!1),[d,u]=N.useState([]),[h,p]=N.useState(!1),[f,g]=N.useState("");N.useEffect(()=>{!o||!s||(p(!0),q.from("agent_videos").select("id, title, recipient_name, playback_url, thumbnail_url, created_at, duration_seconds").eq("owner_user_id",s).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:v})=>{u(v||[]),p(!1)}))},[o,s]);const _=d.filter(v=>!f||(v.title||v.recipient_name||"").toLowerCase().includes(f.toLowerCase()));return e.jsxs(bs,{open:o,onOpenChange:c,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{variant:i,size:a,className:l||"gap-1.5 shrink-0",children:[e.jsx(Ah,{className:"h-3.5 w-3.5"}),r]})}),e.jsxs(vs,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Select from Video Library"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a video from your library"})]}),e.jsxs("div",{className:"relative mb-3",children:[e.jsx(vr,{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:f,onChange:v=>g(v.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-2 min-h-0",children:h?e.jsxs(e.Fragment,{children:[e.jsx(Ws,{className:"h-16 w-full"}),e.jsx(Ws,{className:"h-16 w-full"})]}):_.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"}):_.map(v=>e.jsxs("button",{onClick:()=>{t(v.playback_url||""),n==null||n(v),c(!1)},className:"w-full flex items-center gap-3 p-3 rounded-lg border border-border hover:border-primary/50 hover:bg-accent/50 transition-colors text-left",children:[e.jsx("div",{className:"w-16 h-10 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden",children:v.thumbnail_url?e.jsx("img",{src:v.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:j=>{const b=j.currentTarget.parentElement;if(b){j.currentTarget.remove();const S=document.createElement("span");S.innerHTML="🎬",S.className="text-lg",b.appendChild(S)}}}):e.jsx(br,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:v.title||v.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.duration_seconds?`${Math.round(v.duration_seconds)}s`:"",v.created_at?` · ${new Date(v.created_at).toLocaleDateString()}`:""]})]})]},v.id))})]})]})}function kGs(){return ct({queryKey:["video-script-categories"],queryFn:async()=>{const{data:s,error:t}=await q.from("video_script_categories").select("*").order("sort_order");if(t)throw t;return s}})}function SGs(s){return ct({queryKey:["video-scripts",s],queryFn:async()=>{let t=q.from("video_scripts").select("*, category:video_script_categories(*)").eq("is_active",!0).order("title");const{data:n,error:r}=await t;if(r)throw r;return n}})}function CGs(){const{user:s}=ys();return ct({queryKey:["user-video-scripts",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await q.from("user_video_scripts").select("*, category:video_script_categories(*)").eq("owner_user_id",s.id).order("title");if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function TGs(){const{user:s}=ys(),t=Ht();return gt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await q.from("user_video_scripts").insert([{owner_user_id:s.id,source_script_id:n.id,category_id:n.category_id,title:n.title,script_text:n.script_text,tags:n.tags,is_custom:!1}]).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["user-video-scripts"]})}})}function EGs(s){const{user:t}=ys();return ct({queryKey:["agent-videos",t==null?void 0:t.id,s],queryFn:async()=>{if(!(t!=null&&t.id))return[];let n=q.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("owner_user_id",t.id).order("created_at",{ascending:!1});n=n.eq("is_deleted",!1);const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!(t!=null&&t.id)})}function AGs(s){return ct({queryKey:["agent-video",s],queryFn:async()=>{const{data:t,error:n}=await q.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function IN(){const{user:s}=ys(),t=Ht();return gt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await q.from("agent_videos").insert([{owner_user_id:s.id,contact_id:n.contact_id,bunny_video_id:n.bunny_video_id,playback_url:n.playback_url,thumbnail_url:n.thumbnail_url,preview_url:n.preview_url,duration_seconds:n.duration_seconds,file_size_mb:n.file_size_mb||0,title:n.title,notes:n.notes,task_id:n.task_id,status:n.status||"processing",touch_type:n.touch_type||"video",page_template:"default",category:n.category||"general"}]).select("*, share_token").single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-videos"]}),t.invalidateQueries({queryKey:["storage-usage"]})}})}function MGs(){const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("agent_videos").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["agent-video",t.id]})}})}function IGs(){const s=Ht();return gt({mutationFn:async({id:t,bunnyVideoId:n,hardDelete:r=!1})=>{if(console.log("Deleting video:",{id:t,bunnyVideoId:n,hardDelete:r}),n){console.log("Calling bunny-upload delete for videoId:",n);const{data:a,error:i}=await q.functions.invoke("bunny-upload",{body:{action:"delete",videoId:n,isAgentVideo:!0}});i?console.error("Failed to delete from Bunny:",i):console.log("Bunny delete response:",a)}else console.warn("No bunnyVideoId provided, skipping Bunny.net deletion");if(r){console.log("Hard deleting from database:",t);const{error:a}=await q.from("agent_videos").delete().eq("id",t);if(a)throw a}else{console.log("Soft deleting from database:",t);const{error:a}=await q.from("agent_videos").update({is_deleted:!0}).eq("id",t);if(a)throw a}console.log("Video deletion complete")},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["storage-usage"]})}})}function D1e(){const{user:s}=ys();return ct({queryKey:["storage-usage",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:n}=await q.from("agent_storage_usage").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t||{user_id:s.id,total_storage_mb:0,storage_tier:"basic",max_storage_mb:1024}},enabled:!!(s!=null&&s.id)})}function O_t(){const{data:s,isLoading:t}=D1e(),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 i6(s){const{data:t,error:n}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:s,isAgentVideo:!0}});if(n)throw n;return t}async function o6(s){const{data:t,error:n}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}async function $w(s){const{data:t,error:n}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}function PGs(){const{user:s}=ys(),t=Ht();return gt({mutationFn:async({contactId:n,videoId:r,notes:a})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:i}=await q.from("action_types").select("id").eq("name","Video").single();if(!i)throw new Error("Video action type not found");const{data:l,error:o}=await q.from("contact_touch_logs").insert([{owner_user_id:s.id,contact_id:n,action_type_id:i.id,notes:a||`Quick Video Touch - Video ID: ${r}`}]).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-touch-logs"]}),t.invalidateQueries({queryKey:["contacts"]})}})}function F_t({open:s,onOpenChange:t,onUploadComplete:n}){const{data:r}=ox(),{data:a}=D1e(),i=IN(),l=N.useRef(null),[o,c]=N.useState(null),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(""),[_,v]=N.useState(!1),[j,b]=N.useState(0),[S,A]=N.useState("idle"),T=(a==null?void 0:a.total_storage_mb)||0,D=((a==null?void 0:a.max_storage_mb)||1024)-T,M=W=>{var J;const Y=(J=W.target.files)==null?void 0:J[0];if(!Y)return;if(!Y.type.startsWith("video/")){ae.error("Please select a video file");return}const K=Y.size/(1024*1024);if(K>500){ae.error("Video file must be less than 500MB");return}if(K>D){ae.error(`Not enough storage. You have ${D.toFixed(1)} MB remaining.`);return}c(Y),d||u(Y.name.replace(/\.[^/.]+$/,""))},F=async()=>{if(!o){ae.error("Please select a video file");return}v(!0),b(0),A("creating");try{const{data:W,error:Y}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d||o.name,isAgentVideo:!0}});if(Y)throw new Error(Y.message);const{videoId:K,libraryId:J}=W;A("uploading");const{data:ne,error:ie}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:K,isAgentVideo:!0}});if(ie)throw new Error(ie.message);await new Promise((pe,le)=>{const ve=new XMLHttpRequest;ve.upload.addEventListener("progress",ge=>{if(ge.lengthComputable){const Te=Math.round(ge.loaded/ge.total*100);b(Te)}}),ve.addEventListener("load",()=>{ve.status>=200&&ve.status<300?pe():le(new Error(`Upload failed with status ${ve.status}`))}),ve.addEventListener("error",()=>le(new Error("Upload failed"))),ve.open("PUT",ne.uploadUrl),ve.setRequestHeader("AccessKey",ne.apiKey),ve.send(o)}),A("processing");const he=o.size/(1024*1024),ce=`https://iframe.mediadelivery.net/embed/${J}/${K}`;await i.mutateAsync({bunny_video_id:K,playback_url:ce,file_size_mb:he,title:d||o.name,notes:h||void 0,contact_id:f||void 0,status:"processing",touch_type:"video_upload"}),ae.success("Video uploaded successfully! Processing may take a few minutes."),n==null||n(ce),z()}catch(W){console.error("Upload error:",W),ae.error(W instanceof Error?W.message:"Failed to upload video")}finally{v(!1),A("idle")}},z=()=>{_||(c(null),u(""),p(""),g(""),b(0),A("idle"),t(!1))},V=()=>{switch(S){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${j}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(bs,{open:s,onOpenChange:z,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Upload Video"}),e.jsx(Qn,{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(br,{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"]})]}),!_&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:W=>{W.stopPropagation(),c(null)},children:e.jsx(Bn,{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 W;return(W=l.current)==null?void 0:W.click()},children:[e.jsx(Na,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select a video file"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"MP4, MOV, WebM (max 500MB)"})]}),e.jsx("input",{ref:l,type:"file",accept:"video/*",className:"hidden",onChange:M,disabled:_})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title"}),e.jsx(ye,{id:"title",value:d,onChange:W=>u(W.target.value),placeholder:"Enter video title",disabled:_})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Associate with Contact (optional)"}),e.jsxs(ds,{value:f||"__none__",onValueChange:W=>g(W==="__none__"?"":W),disabled:_,children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select a contact"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"__none__",children:"No contact"}),r==null?void 0:r.map(W=>e.jsxs(Qe,{value:W.id,children:[W.first_name," ",W.last_name||""]},W.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"notes",children:"Notes (optional)"}),e.jsx(Es,{id:"notes",value:h,onChange:W=>p(W.target.value),placeholder:"Add any notes about this video",rows:2,disabled:_})]}),_&&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(ts,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:V()})]}),e.jsx(pi,{value:S==="uploading"?j:S==="processing"?100:10})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:z,disabled:_,children:"Cancel"}),e.jsx(B,{onClick:F,disabled:!o||_,children:_?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Na,{className:"h-4 w-4 mr-2"}),"Upload Video"]})})]})]})})}const LGs=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"],DGs={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"},EZe=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=>DGs[t.toLowerCase()]||t).replace(/\n{3,}/g,` `).replace(/[ \t]+\n/g,` `).trim():s:"";function z_t({open:s,onOpenChange:t,campaignId:n}){const[r,a]=N.useState(n??null),[i,l]=N.useState("details");N.useEffect(()=>{a(n??null),l("details")},[n,s]);const o=r,c=!!o,{data:d}=pGs(o||void 0),{data:u,isLoading:h}=D_t(o||void 0),p=fGs(),f=P_t(),g=gGs(),[_,v]=N.useState(""),[j,b]=N.useState(""),[S,A]=N.useState("nurture"),[T,L]=N.useState("🌱"),[D,M]=N.useState("");N.useEffect(()=>{d?(v(d.name),b(d.description||""),A(d.category),L(d.icon),M(d.goal||"")):c||(v(""),b(""),A("nurture"),L("🌱"),M(""))},[d,c,s]);const F=NGs[S],z=async()=>{if(!_.trim()){ae.error("Give your campaign a name");return}try{if(c&&o)await f.mutateAsync({id:o,name:_,description:j,category:S,icon:T,goal:D,cover_color:F}),ae.success("Campaign updated");else{const W=await p.mutateAsync({name:_,description:j,category:S,icon:T,goal:D,cover_color:F});return ae.success("Campaign created — now add your first step!"),a(W.id),l("steps"),W}}catch(W){ae.error(W.message||"Failed to save")}},V=async()=>{if(!o){ae.error("Save the campaign first, then add steps");return}const W=((u==null?void 0:u.length)||0)+1;try{await g.mutateAsync({campaign_id:o,step_order:W,channel:"email",subject:"",body:"",delay_type:"relative",delay_days:W===1?0:2,delay_hours:0})}catch{ae.error("Failed to add step")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${F} p-5 text-white shrink-0`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-4xl drop-shadow-sm",children:T}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(_s,{className:"text-lg font-bold text-white",children:c?"Edit Campaign":"Create New Campaign"}),e.jsx(Qn,{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(Br,{value:i,onValueChange:W=>l(W),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(Fr,{className:"mx-5 mt-4 grid grid-cols-2 w-fit",children:[e.jsx(Kt,{value:"details",children:"Details"}),e.jsxs(Kt,{value:"steps",disabled:!c,children:["Steps ",u&&u.length>0&&e.jsx(ze,{variant:"secondary",className:"ml-1.5 text-[10px]",children:u.length})]})]}),e.jsx(is,{value:"details",className:"flex-1 overflow-hidden mt-0 min-h-0",children:e.jsx(hi,{className:"h-full",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:_,onChange:W=>v(W.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(Es,{value:j,onChange:W=>b(W.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:D,onChange:W=>M(W.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(ds,{value:S,onValueChange:W=>A(W),children:[e.jsx(ls,{className:"mt-1",children:e.jsx(us,{})}),e.jsx(cs,{children:Object.entries(L1e).map(([W,Y])=>e.jsx(Qe,{value:W,children:Y},W))})]})]}),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:LGs.map(W=>e.jsx("button",{type:"button",onClick:()=>L(W),className:`h-8 w-8 rounded-md text-lg flex items-center justify-center transition-all ${T===W?"bg-primary/15 ring-2 ring-primary":"hover:bg-muted"}`,children:W},W))})]})]}),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(is,{value:"steps",className:"flex-1 overflow-hidden mt-0 min-h-0",children:e.jsx(hi,{className:"h-full",children:e.jsx("div",{className:"p-5 space-y-3",children:h?e.jsx("div",{className:"text-center text-sm text-muted-foreground py-8",children:"Loading steps…"}):!u||u.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl",children:[e.jsx(un,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No steps yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Build your sequence — each step waits for its delay, then sends."}),e.jsxs(B,{size:"sm",onClick:V,disabled:g.isPending,children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[u.map((W,Y)=>e.jsx(RGs,{step:W,index:Y,totalSteps:u.length},W.id)),e.jsxs(B,{variant:"outline",size:"sm",onClick:V,disabled:g.isPending,className:"w-full",children:[g.isPending?e.jsx(ts,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(Xn,{className:"border-t p-4 shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:c?"Done":"Cancel"}),e.jsxs(B,{onClick:z,disabled:p.isPending||f.isPending,children:[(p.isPending||f.isPending)&&e.jsx(ts,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c?"Save Changes":"Create Campaign"]})]})]})})}function RGs({step:s,index:t,totalSteps:n}){const r=yGs(),a=vGs(),i=ma(),[l,o]=N.useState(!1),[c,d]=N.useState(()=>({...s,body:EZe(s.body)})),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[g,_]=N.useState(""),[v,j]=N.useState(!1);N.useEffect(()=>{d({...s,body:EZe(s.body)})},[s]);const b=JSON.stringify(c)!==JSON.stringify(s),S=async()=>{h(!0);try{await r.mutateAsync({id:s.id,campaign_id:s.campaign_id,channel:c.channel,subject:c.subject,body:c.body,video_url:c.video_url,delay_type:c.delay_type,delay_days:c.delay_days,delay_hours:c.delay_hours,anchor_field:c.anchor_field,anchor_offset_days:c.anchor_offset_days}),ae.success(`Step ${t+1} saved`)}catch{ae.error("Failed to save step")}finally{h(!1)}},A=async()=>{if(confirm(`Delete step ${t+1}?`))try{await a.mutateAsync({id:s.id,campaign_id:s.campaign_id}),ae.success("Step deleted")}catch{ae.error("Failed to delete")}},T=D=>{d({...c,body:c.body+D})},L=()=>{if(c.delay_type==="calendar_anchor"){const M=c.anchor_field==="birthday"?"birthday":"home anniversary",F=c.anchor_offset_days||0;return F===0?`On their ${M}`:F<0?`${Math.abs(F)}d before ${M}`:`${F}d after ${M}`}if(t===0&&!c.delay_days&&!c.delay_hours)return"Sends immediately";const D=[];return c.delay_days&&D.push(`${c.delay_days}d`),c.delay_hours&&D.push(`${c.delay_hours}h`),t===0?`After ${D.join(" ")||"0"}`:`+${D.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(yr,{className:"h-3 w-3"}):e.jsx(gr,{className:"h-3 w-3"}),e.jsx("span",{children:L()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(Vs,{className:"h-3 w-3"}):e.jsx(Ei,{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(tx,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(io,{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(ds,{value:c.channel,onValueChange:D=>d({...c,channel:D}),children:[e.jsx(ls,{className:"mt-1 h-9",children:e.jsx(us,{})}),e.jsx(cs,{children:e.jsx(Qe,{value:"email",children:"📧 Email"})})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Timing Type"}),e.jsxs(ds,{value:c.delay_type,onValueChange:D=>d({...c,delay_type:D}),children:[e.jsx(ls,{className:"mt-1 h-9",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"relative",children:"⏱ Relative delay"}),e.jsx(Qe,{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:D=>d({...c,delay_days:parseInt(D.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:D=>d({...c,delay_hours:parseInt(D.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(ds,{value:c.anchor_field||"birthday",onValueChange:D=>d({...c,anchor_field:D}),children:[e.jsx(ls,{className:"mt-1 h-9",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"birthday",children:"🎂 Birthday"}),e.jsx(Qe,{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:D=>d({...c,anchor_offset_days:parseInt(D.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:D=>d({...c,subject:D.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(Es,{value:c.body,onChange:D=>d({...c,body:D.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:"}),jGs.map(D=>e.jsx("button",{type:"button",onClick:()=>T(D.key),className:"text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20",children:D.label},D.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(br,{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(a6,{userId:i||void 0,onSelect:D=>d({...c,video_url:D}),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:()=>j(!0),children:[e.jsx(Na,{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:()=>{_(""),f(!0)},children:[e.jsx(Jo,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(F_t,{open:v,onOpenChange:j,onUploadComplete:D=>d({...c,video_url:D})}),e.jsx(bs,{open:p,onOpenChange:f,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Add video URL"}),e.jsx(Qn,{children:"Paste a YouTube, Loom, or direct video URL."})]}),e.jsx(ye,{value:g,onChange:D=>_(D.target.value),placeholder:"https://...",autoFocus:!0,onKeyDown:D=>{D.key==="Enter"&&g.trim()&&(d({...c,video_url:g.trim()}),f(!1))}}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>f(!1),children:"Cancel"}),e.jsx(B,{disabled:!g.trim(),onClick:()=>{d({...c,video_url:g.trim()}),f(!1)},children:"Add video"})]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:A,className:"text-destructive hover:text-destructive",children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-1"})," Delete step"]}),e.jsxs(B,{size:"sm",onClick:S,disabled:!b||u,children:[u&&e.jsx(ts,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save step"]})]})]})]})}function OGs({open:s,onOpenChange:t,contactIds:n,onSuccess:r}){const{data:a,isLoading:i}=P1e(),l=R_t(),[o,c]=N.useState(""),[d,u]=N.useState(null),[h,p]=N.useState(!1),f=(a||[]).filter(v=>!v.is_starter),g=f.filter(v=>v.name.toLowerCase().includes(o.toLowerCase())||(v.description||"").toLowerCase().includes(o.toLowerCase())),_=async()=>{if(d)try{const v=await l.mutateAsync({campaignId:d,contactIds:n}),j=[`${v.enrolled} enrolled`];v.skipped>0&&j.push(`${v.skipped} skipped`),v.errors>0&&j.push(`${v.errors} errors`),ae.success(j.join(" · ")),t(!1),u(null),r==null||r()}catch(v){ae.error(v.message||"Failed to enroll contacts")}};return e.jsxs(bs,{open:s,onOpenChange:t,children:[e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),"Enroll in Drip Campaign"]}),e.jsxs(Qn,{children:[n.length," contact",n.length!==1?"s":""," will be added to the selected campaign. Already-enrolled contacts will be skipped."]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search campaigns...",value:o,onChange:v=>c(v.target.value),className:"pl-9 h-9"})]}),e.jsx(hi,{className:"h-[320px] -mx-1 px-1",children:i?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"Loading..."}):g.length===0?e.jsx("div",{className:"text-center py-8",children:f.length===0?e.jsxs(e.Fragment,{children:[e.jsx(un,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No campaigns yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Build a custom drip campaign to nurture these contacts on autopilot."}),e.jsxs(B,{size:"sm",onClick:()=>p(!0),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"})," Create campaign"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No campaigns match your search."})}):e.jsx("div",{className:"space-y-1.5",children:g.map(v=>e.jsxs("button",{onClick:()=>u(v.id),className:`w-full flex items-start gap-3 p-3 rounded-lg border text-left transition-all ${d===v.id?"border-primary bg-primary/5 ring-1 ring-primary":"border-border hover:border-primary/40 hover:bg-muted/30"}`,children:[e.jsx("div",{className:`shrink-0 h-9 w-9 rounded-lg bg-gradient-to-br ${v.cover_color} flex items-center justify-center text-lg`,children:v.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:v.name}),v.is_active&&e.jsx(ze,{variant:"outline",className:"text-[9px] bg-emerald-500/10 text-emerald-600 border-emerald-200 px-1 py-0",children:"Active"})]}),v.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:v.description})]}),d===v.id&&e.jsx(Ir,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},v.id))})})]}),e.jsxs(Xn,{className:"gap-2 sm:gap-2",children:[f.length>0&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>p(!0),className:"mr-auto text-xs",children:[e.jsx(Is,{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:_,disabled:!d||l.isPending,children:[l.isPending&&e.jsx(ts,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Enroll ",n.length," contact",n.length!==1?"s":""]})]})]}),e.jsx(z_t,{open:h,onOpenChange:p})]})}function FGs({selectedIds:s,contacts:t,onClearSelection:n,onSendToLeadPond:r,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=Mn(),{data:c}=Sy(),d=y6e(),u=Ht(),{isGmailConnected:h}=Oh(),{isReady:p}=bR(),{data:f}=_R(),g=pLe(),_=j_t(),[v,j]=N.useState(!1),[b,S]=N.useState(!1),[A,T]=N.useState(!1),[L,D]=N.useState(!1),[M,F]=N.useState(!1),[z,V]=N.useState(""),W=s.size;if(W===0)return null;const Y=async pe=>{j(!0);try{const ve=Array.from(s).map(Te=>({contact_id:Te,relationship_type_id:pe})),{error:ge}=await q.from("innercircle_contact_tags").upsert(ve,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(ge)throw ge;u.invalidateQueries({queryKey:["innercircle-contacts"]}),u.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Pr({title:`Assigned type to ${W} contacts`}),n()}catch(le){Pr({title:"Error assigning type",description:le.message,variant:"destructive"})}finally{j(!1)}},K=async pe=>{j(!0);try{const le=Array.from(s);for(const ve of le)try{await _.mutateAsync({contactId:ve,tagId:pe})}catch{}u.invalidateQueries({queryKey:["all-contact-custom-tags"]}),Pr({title:`Tagged ${W} contacts`}),F(!1),V("")}catch(le){Pr({title:"Error adding tags",description:le.message,variant:"destructive"})}finally{j(!1)}},J=async()=>{if(z.trim()){j(!0);try{const pe=await g.mutateAsync({name:z.trim()});await K(pe.id)}catch(pe){Pr({title:"Error creating tag",description:pe.message,variant:"destructive"}),j(!1)}}},ne=(f==null?void 0:f.filter(pe=>pe.name.toLowerCase().includes(z.toLowerCase())))||[],ie=f==null?void 0:f.find(pe=>pe.name.toLowerCase()===z.trim().toLowerCase()),he=()=>{const pe=t.filter(Ae=>s.has(Ae.id)),le=["First Name","Last Name","Email","Phone","Address","Birthday","Home Anniversary","Notes","Relationship Types"],ve=pe.map(Ae=>{var De;return[Ae.first_name,Ae.last_name||"",Ae.email||"",Ae.phone||"",Ae.address||"",Ae.birthday||"",Ae.home_anniversary||"",Ae.notes||"",((De=Ae.tags)==null?void 0:De.map(Ie=>{var Fe;return(Fe=Ie.relationship_type)==null?void 0:Fe.name}).join("; "))||""]}),ge=[le.join(","),...ve.map(Ae=>Ae.map(De=>`"${(De||"").replace(/"/g,'""')}"`).join(","))].join(` `),Te=new Blob([ge],{type:"text/csv"}),Me=URL.createObjectURL(Te),Ce=document.createElement("a");Ce.href=Me,Ce.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,Ce.click(),URL.revokeObjectURL(Me),Pr({title:`Exported ${W} contacts`})},ce=async()=>{if(confirm(`Are you sure you want to delete ${W} contacts? This cannot be undone.`)){j(!0);try{const pe=Array.from(s);for(const le of pe)await d.mutateAsync(le);n()}catch(pe){Pr({title:"Error deleting contacts",description:pe.message,variant:"destructive"})}finally{j(!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(ze,{variant:"secondary",className:"font-semibold",children:[W," selected"]}),e.jsxs(ds,{onValueChange:Y,disabled:v,children:[e.jsx(ls,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(uh,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm",children:"Assign Type"})]})}),e.jsx(cs,{children:c==null?void 0:c.filter(pe=>pe.active).map(pe=>e.jsx(Qe,{value:pe.id,children:pe.name},pe.id))})]}),e.jsxs(el,{open:M,onOpenChange:F,children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",disabled:v,children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(Ho,{className:"w-56 p-2",align:"start",children:[e.jsx(ye,{placeholder:"Search or create tag...",value:z,onChange:pe=>V(pe.target.value),onKeyDown:pe=>{pe.key==="Enter"&&z.trim()&&!ie?(pe.preventDefault(),J()):pe.key==="Enter"&&ie&&(pe.preventDefault(),K(ie.id))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[ne.map(pe=>e.jsxs("button",{onClick:()=>K(pe.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:pe.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:pe.name})]},pe.id)),z.trim()&&!ie&&e.jsxs("button",{onClick:J,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(Is,{className:"h-3.5 w-3.5"}),'Create "',z.trim(),'"']}),ne.length===0&&!z.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create a tag"})]})]})]}),h&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>S(!0),disabled:v,children:[e.jsx(Vs,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),p&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{const pe=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${pe}`)},disabled:v,children:[e.jsx($d,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>T(!0),disabled:v,children:[e.jsx(br,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>D(!0),disabled:v,children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1"}),"Enroll in Campaign"]}),a&&r&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>r(Array.from(s)),disabled:v,children:[e.jsx(mb,{className:"h-3.5 w-3.5 mr-1"}),"Send to Lead Pond"]}),l&&i&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>i(Array.from(s)),disabled:v,children:[e.jsx(mw,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:he,disabled:v,children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ce,disabled:v,className:"text-destructive hover:text-destructive",children:[e.jsx(_n,{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(Bn,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(OGs,{open:L,onOpenChange:D,contactIds:Array.from(s),onSuccess:n}),e.jsx(t1,{open:b,onOpenChange:S,bulkContacts:Array.from(s).map(pe=>{const le=t.find(ve=>ve.id===pe);return le?{id:le.id,first_name:le.first_name,last_name:le.last_name,email:le.email||""}:null}).filter(pe=>pe!==null&&pe.email!==""),onSendComplete:()=>{S(!1),n()}}),e.jsx(mGs,{open:A,onOpenChange:T,contacts:Array.from(s).map(pe=>t.find(le=>le.id===pe)).filter(pe=>!!pe).map(pe=>({id:pe.id,first_name:pe.first_name,last_name:pe.last_name,email:pe.email})),isGmailConnected:!!h,isMassEmailReady:!!p,onSendComplete:()=>{T(!1),n()}})]})}function AZe({contact:s,onEdit:t,onDelete:n,onSnooze:r,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=Mn(),{isReady:d}=bR(),u=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:h=>h.stopPropagation(),children:e.jsx(Qf,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",onClick:h=>h.stopPropagation(),children:[e.jsxs(Qr,{onClick:()=>c(`/mission-control/contacts/${s.id}?tab=activity&action=log`),children:[e.jsx(Ar,{className:"h-4 w-4 mr-2"}),"Log Touch"]}),e.jsxs(Qr,{onClick:()=>c(`/mission-control/video?contactId=${s.id}`),children:[e.jsx(br,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(Qr,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Schedule Pop-by"]}),d&&s.email&&e.jsxs(Qr,{onClick:()=>c(`/admin/email-campaigns/new?contactIds=${s.id}`),children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(Qr,{onClick:()=>r(s.id,u),children:[e.jsx(bf,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(Qr,{onClick:()=>a(s.id),children:[e.jsx(mb,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(Qr,{onClick:()=>l(s.id),children:[e.jsx(mw,{className:"h-4 w-4 mr-2"}),"Transfer to Team Member"]}),e.jsxs(Qr,{onClick:()=>t(s),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Qr,{onClick:()=>n(s.id),className:"text-destructive focus:text-destructive",children:[e.jsx(_n,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function MZe({currentFilters:s,currentSortBy:t,onApplySmartList:n}){const{data:r}=fLe(),a=N_t(),i=k_t(),[l,o]=N.useState(!1),[c,d]=N.useState(""),u=s.search||s.type&&s.type!=="all"||s.status&&s.status!=="all"||s.behavior&&Object.values(s.behavior).some(p=>p!==void 0&&p!==!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(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(Rv,{className:"h-3.5 w-3.5"}),"Smart Filters",r&&r.length>0&&e.jsx(ze,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r.length}),e.jsx(io,{className:"h-3.5 w-3.5"})]})}),e.jsxs(cc,{align:"start",className:"w-56",children:[r&&r.length>0?e.jsxs(e.Fragment,{children:[r.map(p=>e.jsxs(Qr,{className:"flex items-center justify-between group",children:[e.jsx("span",{className:"flex-1 cursor-pointer",onClick:()=>n(p.filters,p.sort_by),children:p.name}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:f=>{f.stopPropagation(),i.mutate(p.id)},children:e.jsx(_n,{className:"h-3 w-3 text-destructive"})})]},p.id)),e.jsx(Zg,{})]}):e.jsx(Qr,{disabled:!0,className:"text-muted-foreground text-xs",children:"No saved filters yet"}),u&&e.jsxs(Qr,{onClick:()=>o(!0),children:[e.jsx(JP,{className:"h-4 w-4 mr-2"}),"Save Current Filter"]})]})]}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{className:"max-w-sm",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Save Smart Filter"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ye,{placeholder:"e.g. Buyers in 40205",value:c,onChange:p=>d(p.target.value),onKeyDown:p=>p.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 zGs=[{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 BGs({open:s,onOpenChange:t,hasLeadSite:n,behavior:r,onApply:a,selectedType:i,onSelectedTypeChange:l,relationshipTypes:o}){const[c,d]=N.useState(r),[u,h]=N.useState(n?"behavior":"contact");N.useEffect(()=>{s&&d(r)},[s,r]);const p=g=>d(_=>({..._,...g})),f=Object.entries(c).filter(([,g])=>g!==void 0&&g!==!1).length;return e.jsx(cg,{open:s,onOpenChange:t,children:e.jsxs(ix,{side:"right",className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsxs(n0,{children:[e.jsxs(r0,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),"Advanced Filters"]}),e.jsx(aU,{children:"Slice your database by website activity, contact details, and engagement."})]}),e.jsxs(Br,{value:u,onValueChange:g=>h(g),className:"mt-4",children:[e.jsxs(Fr,{className:"grid w-full grid-cols-3",children:[e.jsxs(Kt,{value:"contact",className:"gap-1.5",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," Contact"]}),e.jsxs(Kt,{value:"behavior",disabled:!n,className:"gap-1.5",children:[e.jsx(nm,{className:"h-3.5 w-3.5"})," Behavior"]}),e.jsx(Kt,{value:"engagement",children:"Engagement"})]}),e.jsx(is,{value:"contact",className:"space-y-4 mt-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Contact Type"}),e.jsxs(ds,{value:i,onValueChange:l,children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"All types"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Types"}),o==null?void 0:o.map(g=>e.jsx(Qe,{value:g.id,children:g.name},g.id))]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"More contact-detail filters (assigned user, city, address) coming soon."})]})}),e.jsx(is,{value:"behavior",className:"space-y-6 mt-4",children:n?e.jsxs(e.Fragment,{children:[e.jsxs(fG,{title:"Last Active On Site",children:[e.jsx(cb,{value:c.lastActive||"",onValueChange:g=>p({lastActive:g||void 0}),className:"grid grid-cols-2 gap-2",children:zGs.map(g=>e.jsxs("label",{className:"flex items-center gap-2 rounded-md border px-3 py-2 cursor-pointer hover:bg-accent",children:[e.jsx(Rd,{value:g.value}),e.jsx("span",{className:"text-sm",children:g.label})]},g.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(fG,{title:"Registration",children:[e.jsx(u2,{label:"Registered on lead site",checked:c.registered==="yes",onChange:g=>p({registered:g?"yes":void 0})}),e.jsx(u2,{label:"Anonymous visitors only",checked:c.registered==="no",onChange:g=>p({registered:g?"no":void 0})})]}),e.jsxs(fG,{title:"Property Activity",children:[e.jsx(u2,{label:"Viewed any listing",checked:c.viewedListing==="any",onChange:g=>p({viewedListing:g?"any":void 0})}),e.jsx(u2,{label:"Hot buyer — 3+ views in last 7 days",checked:c.viewedListing==="multiple7d",onChange:g=>p({viewedListing:g?"multiple7d":void 0})}),e.jsx(u2,{label:"Saved a property",checked:!!c.savedProperty,onChange:g=>p({savedProperty:g||void 0})}),e.jsx(u2,{label:"Has an active saved search / alert",checked:!!c.hasSavedSearch,onChange:g=>p({hasSavedSearch:g||void 0})})]}),e.jsxs(fG,{title:"Requests",children:[e.jsx(u2,{label:"Requested a showing / asked a question",checked:!!c.requestedShowing,onChange:g=>p({requestedShowing:g||void 0})}),e.jsx(u2,{label:"Requested a home valuation",checked:!!c.requestedValuation,onChange:g=>p({requestedValuation:g||void 0})})]})]}):e.jsx("div",{className:"rounded-md border border-dashed p-4 text-sm text-muted-foreground",children:"Connect a Lead Site with MLS to unlock website behavior filters."})}),e.jsxs(is,{value:"engagement",className:"space-y-4 mt-4",children:[e.jsx(u2,{label:"Any website activity",checked:!!c.websiteActiveOnly,onChange:g=>p({websiteActiveOnly:g||void 0})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"More engagement filters (last emailed, awaiting response, past-due tasks) are in the pipeline."})]})]}),e.jsxs(Sdt,{className:"mt-6 flex-row gap-2 sm:justify-between",children:[e.jsx(B,{variant:"ghost",onClick:()=>d({}),disabled:f===0,children:"Clear behavior filters"}),e.jsx(B,{onClick:()=>{a(c),t(!1)},children:"Apply"})]})]})})}function fG({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 u2({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(bn,{checked:t,onCheckedChange:n})]})}function $Gs({behavior:s,onRemove:t,onClearAll:n}){const r=UGs(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 UGs(s){const t=[];if(s.lastActive){const n={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:n[s.lastActive]})}return 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"}),t}async function FI(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 DF(){return{lastActiveAt:null,registered:!1,propertyViewCount:0,propertyViewCount7d:0,savedListingCount:0,activeSavedSearchCount:0,showingRequests:0,valuationRequests:0,viewedCities:[],viewedZips:[]}}function qGs(){const{user:s}=ys(),{leadSite:t,hasLeadSite:n}=Ip(),{data:r,isLoading:a}=ct({queryKey:["contact-behavior-summary",s==null?void 0:s.id,t==null?void 0:t.id],queryFn:async()=>{const i=new Map;if(!t)return i;const l=(j,b)=>{const S=i.get(j)||DF();i.set(j,{...S,...b})},o=await FI((j,b)=>q.from("lead_site_visitors").select("id, contact_id, last_seen_at, email").eq("lead_site_id",t.id).not("contact_id","is",null).range(j,b)),c=new Map,d=new Map;o.forEach(j=>{if(!j.contact_id)return;c.set(j.id,j.contact_id),j.email&&d.set(j.email.toLowerCase(),j.contact_id);const b=i.get(j.contact_id);(!b||!b.lastActiveAt||j.last_seen_at>b.lastActiveAt)&&l(j.contact_id,{lastActiveAt:j.last_seen_at})});const u=await FI((j,b)=>q.from("lead_site_consumer_profiles").select("contact_id, user_id").eq("lead_site_id",t.id).not("contact_id","is",null).range(j,b)),h=new Map;u.forEach(j=>{j.contact_id&&(h.set(j.user_id,j.contact_id),l(j.contact_id,{registered:!0}))});const p=new Date(Date.now()-7*24*60*60*1e3).toISOString();return(await FI((j,b)=>q.from("lead_site_property_views").select("visitor_id, viewed_at, property_address").eq("lead_site_id",t.id).not("visitor_id","is",null).range(j,b))).forEach(j=>{const b=j.visitor_id?c.get(j.visitor_id):null;if(!b)return;const S=i.get(b)||DF();S.propertyViewCount+=1,j.viewed_at>=p&&(S.propertyViewCount7d+=1),i.set(b,S)}),(await FI((j,b)=>q.from("lead_site_saved_listings").select("user_id, mls_number").eq("lead_site_id",t.id).range(j,b))).forEach(j=>{const b=h.get(j.user_id);if(!b)return;const S=i.get(b)||DF();S.savedListingCount+=1,i.set(b,S)}),(await FI((j,b)=>q.from("lead_site_saved_searches").select("user_id").eq("lead_site_id",t.id).eq("is_active",!0).range(j,b))).forEach(j=>{const b=h.get(j.user_id);if(!b)return;const S=i.get(b)||DF();S.activeSavedSearchCount+=1,i.set(b,S)}),(await FI((j,b)=>q.from("lead_site_leads").select("email, lead_type").eq("lead_site_id",t.id).not("email","is",null).range(j,b))).forEach(j=>{if(!j.email)return;const b=d.get(j.email.toLowerCase());if(!b)return;const S=i.get(b)||DF(),A=(j.lead_type||"").toLowerCase();(A.includes("showing")||A.includes("question")||A==="contact")&&(S.showingRequests+=1),(A.includes("valuation")||A.includes("cma")||A.includes("home_value"))&&(S.valuationRequests+=1),i.set(b,S)}),i},enabled:!!s&&n,staleTime:5*60*1e3});return{behaviorMap:r??new Map,hasLeadSite:n,isLoading:a}}const B_t="innercircle_geocode_cache_v1";function VGs(){try{return JSON.parse(localStorage.getItem(B_t)||"{}")}catch{return{}}}function HGs(s){try{localStorage.setItem(B_t,JSON.stringify(s))}catch{}}function GGs(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 WGs({open:s,onOpenChange:t,contacts:n,onCitySelect:r}){const a=N.useRef(null),i=N.useRef(null),[l,o]=N.useState(""),[c,d]=N.useState(!0),[u,h]=N.useState([]),[p,f]=N.useState({done:0,total:0}),[g,_]=N.useState(!1),[v,j]=N.useState("heat");N.useEffect(()=>{if(!s)return;let S=!1;return(async()=>{d(!0);const{data:A}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();S||(o((A==null?void 0:A.value)||""),d(!1))})(),()=>{S=!0}},[s]),N.useEffect(()=>{if(!s||!l)return;let S=!1;return(async()=>{const T=VGs(),L=n.map(K=>({c:K,addr:GGs(K)})).filter(K=>K.addr),D=[],M=[];for(const{c:K,addr:J}of L){const ne=T[J];ne!==null&&(ne?D.push({id:K.id,name:`${K.first_name||""} ${K.last_name||""}`.trim(),city:K.city||null,state:K.state||null,zip:K.zip||K.zip_code||null,lat:ne.lat,lng:ne.lng}):M.push({c:K,addr:J}))}if(S||h(D),f({done:D.length,total:L.length}),M.length===0)return;_(!0);const F=6;let z=0;const V={...T},W=[...D],Y=async()=>{var K;for(;z{S=!0}},[s,l,n]);const b=N.useMemo(()=>{const S=new Map;for(const A of n){const T=(A.city||"").trim();if(!T)continue;const L=(A.state||"").trim()||null,D=`${T.toLowerCase()}|${L||""}`,M=S.get(D);M?M.count++:S.set(D,{city:T,state:L,count:1})}return Array.from(S.values()).sort((A,T)=>T.count-A.count)},[n]);return N.useEffect(()=>{if(!(!s||!l||!a.current||i.current))return hl.accessToken=l,i.current=new hl.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new hl.NavigationControl,"top-right"),()=>{var S;(S=i.current)==null||S.remove(),i.current=null}},[s,l]),N.useEffect(()=>{const S=i.current;if(!S||u.length===0)return;const A=()=>{const L={type:"FeatureCollection",features:u.map(M=>({type:"Feature",properties:{id:M.id,name:M.name},geometry:{type:"Point",coordinates:[M.lng,M.lat]}}))},D=S.getSource("contacts-src");if(D?D.setData(L):(S.addSource("contacts-src",{type:"geojson",data:L}),S.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]}}),S.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}}),S.on("click","contacts-points",M=>{var V;const F=(V=M.features)==null?void 0:V[0];if(!F)return;const z=F.geometry.coordinates.slice();new hl.Popup({offset:12}).setLngLat(z).setHTML(`
${F.properties.name||"Contact"}
`).addTo(S)}),S.on("mouseenter","contacts-points",()=>{S.getCanvas().style.cursor="pointer"}),S.on("mouseleave","contacts-points",()=>{S.getCanvas().style.cursor=""})),S.getLayer("contacts-heat")&&S.setLayoutProperty("contacts-heat","visibility",v==="heat"?"visible":"none"),S.getLayer("contacts-points")&&(S.setPaintProperty("contacts-points","circle-opacity",v==="points"?.9:0),S.setLayoutProperty("contacts-points","visibility","visible")),u.length>0&&!S._fitDone){const M=new hl.LngLatBounds;u.forEach(F=>M.extend([F.lng,F.lat]));try{S.fitBounds(M,{padding:60,maxZoom:11,duration:600}),S._fitDone=!0}catch{}}};S.isStyleLoaded()?A():S.once("load",A)},[u,v]),e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 flex flex-col",children:[e.jsx(ws,{className:"p-4 pb-2 border-b",children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Dc,{className:"h-5 w-5 text-orange-500"}),"Geographic Heat Map",e.jsxs(ze,{variant:"secondary",className:"ml-2",children:[u.length," mapped · ",b.length," cities"]})]})}),e.jsxs("div",{className:"flex-1 flex flex-col md:flex-row min-h-0",children:[e.jsx("div",{className:"flex-1 relative min-h-[300px]",children:c?e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):l?e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:a,className:"absolute inset-0"}),e.jsxs("div",{className:"absolute top-3 left-3 flex flex-col gap-2 z-10",children:[e.jsxs("div",{className:"bg-background/95 backdrop-blur rounded-md shadow-md border p-1 flex",children:[e.jsxs(B,{size:"sm",variant:v==="heat"?"default":"ghost",onClick:()=>j("heat"),className:"h-8",children:[e.jsx(Dc,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs(B,{size:"sm",variant:v==="points"?"default":"ghost",onClick:()=>j("points"),className:"h-8",children:[e.jsx(l9,{className:"h-3.5 w-3.5 mr-1"})," Pins"]})]}),g&&e.jsxs("div",{className:"bg-background/95 backdrop-blur rounded-md shadow-md border px-2.5 py-1.5 text-xs flex items-center gap-2",children:[e.jsx(ts,{className:"h-3 w-3 animate-spin"}),"Mapping ",p.done," / ",p.total]})]})]}):e.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(Gi,{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(ka,{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(hi,{className:"flex-1",children:e.jsxs("div",{className:"p-2 space-y-1.5",children:[b.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-3 text-center",children:"No city data on your contacts yet. Add city/state to contacts to populate the map."}),b.slice(0,50).map((S,A)=>{var D;const T=((D=b[0])==null?void 0:D.count)||1,L=S.count/T*100;return e.jsx(fe,{className:"cursor-pointer hover:border-primary transition-colors overflow-hidden",onClick:()=>{r==null||r(S.city,S.state),t(!1)},children:e.jsxs(Ee,{className:"p-2.5 relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/10",style:{width:`${L}%`}}),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:[S.city,S.state?`, ${S.state}`:""]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:A===0?"🔥 Hottest market":`Rank #${A+1}`})]}),e.jsx(ze,{variant:"secondary",className:"shrink-0",children:S.count})]})]})},`${S.city}-${S.state}-${A}`)})]})})]})]})]})})}function DE(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 IZe({birthday:s,homeAnniversary:t,weddingAnniversary:n,className:r,contactId:a,contactName:i,contactAddress:l}){const o=Mn(),c=kNe(s,"birthday",7),d=kNe(t,"anniversary",7),u=kNe(n||null,"anniversary",7);if(!c&&!d&&!u)return null;const h=(p,f,g)=>{g.stopPropagation();const _=new URLSearchParams;a&&_.set("contactId",a),i&&_.set("name",i),l&&_.set("address",l),(p==="home_anniversary"||p==="wedding_anniversary")&&f&&_.set("date",f),_.set("cardType",p),o(`/mission-control/card-studio?${_.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(ze,{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:p=>h("birthday",s,p),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(Vs,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),d&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(ze,{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:p=>h("home_anniversary",t,p),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(Vs,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),u&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(ze,{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:p=>h("wedding_anniversary",n||null,p),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(Vs,{className:"h-2.5 w-2.5"}),"Send Card"]})]})]})}function eTe({deal:s}){if(!s||!s.stage)return null;const{stage:t}=s;return e.jsxs(ze,{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 PZe({count:s,className:t}){return!s||s<=0?null:e.jsxs(ze,{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(UA,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function KGs(){const s=ma();return ct({queryKey:["contacts-campaign-counts",s],queryFn:async()=>{if(!s)return{};const{data:t,error:n}=await q.from("drip_campaign_enrollments").select("contact_id, status").eq("owner_user_id",s).eq("status","active");if(n)throw n;const r={};return(t||[]).forEach(a=>{a.contact_id&&(r[a.contact_id]=(r[a.contact_id]||0)+1)}),r},enabled:!!s,staleTime:6e4})}function YGs(){const s=ma();return ct({queryKey:["contact-deals-map",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_pipeline").select(` id, deal_name, contact_id, deal_type, expected_price, sale_price, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).not("contact_id","is",null);if(n)throw n;const r={};return(t||[]).forEach(a=>{a.contact_id&&!r[a.contact_id]&&(r[a.contact_id]=a)}),r},enabled:!!s})}function ZGs({contactId:s,compact:t=!1}){const{data:n}=_R(),{data:r}=$Vs(s),a=pLe(),i=j_t(),l=VVs(),[o,c]=N.useState(!1),[d,u]=N.useState(""),h=N.useRef(null),p=new Set((r==null?void 0:r.map(j=>j.tag_id))||[]),f=(n==null?void 0:n.filter(j=>j.name.toLowerCase().includes(d.toLowerCase())))||[],g=n==null?void 0:n.find(j=>j.name.toLowerCase()===d.trim().toLowerCase()),_=async j=>{p.has(j.id)?await l.mutateAsync({contactId:s,tagId:j.id}):await i.mutateAsync({contactId:s,tagId:j.id})},v=async()=>{if(!(!d.trim()||g))try{const j=await a.mutateAsync({name:d.trim()});await i.mutateAsync({contactId:s,tagId:j.id}),u("")}catch{}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r==null?void 0:r.map(j=>{var b,S,A;return e.jsxs(ze,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((b=j.tag)==null?void 0:b.color)||"#6366F1",color:((S=j.tag)==null?void 0:S.color)||"#6366F1"},children:[e.jsx(uh,{className:"h-2.5 w-2.5"}),(A=j.tag)==null?void 0:A.name,e.jsx("button",{onClick:T=>{T.stopPropagation(),l.mutate({contactId:s,tagId:j.tag_id})},className:"ml-0.5 rounded-full hover:bg-accent p-0.5",children:e.jsx(Bn,{className:"h-2.5 w-2.5"})})]},j.id)}),e.jsxs(el,{open:o,onOpenChange:c,children:[e.jsx(tl,{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:j=>j.stopPropagation(),children:[e.jsx(Is,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(Ho,{className:"w-56 p-2",align:"start",onClick:j=>j.stopPropagation(),children:[e.jsx(ye,{ref:h,placeholder:"Search or create tag...",value:d,onChange:j=>u(j.target.value),onKeyDown:j=>{j.key==="Enter"&&d.trim()&&!g?(j.preventDefault(),v()):j.key==="Enter"&&g&&!p.has(g.id)&&(j.preventDefault(),_(g))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[f.map(j=>e.jsxs("button",{onClick:()=>_(j),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:j.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:j.name}),p.has(j.id)&&e.jsx(Ir,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},j.id)),d.trim()&&!g&&e.jsxs("button",{onClick:v,className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-primary",children:[e.jsx(Is,{className:"h-3.5 w-3.5"}),'Create "',d.trim(),'"']}),f.length===0&&!d.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create your first tag"})]})]})]})]})}function LZe({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(ze,{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 xG=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function QGs({open:s,onOpenChange:t}){const{data:n,isLoading:r}=_R(),a=pLe(),i=qVs(),l=UVs(),[o,c]=N.useState(""),[d,u]=N.useState(xG[0]),[h,p]=N.useState(null),[f,g]=N.useState(""),[_,v]=N.useState(""),j=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),u(xG[0]),Pr({title:"Tag created"})}catch(T){Pr({title:"Error",description:T.message,variant:"destructive"})}},b=async T=>{if(f.trim())try{await i.mutateAsync({id:T,name:f.trim(),color:_}),p(null),Pr({title:"Tag updated"})}catch(L){Pr({title:"Error",description:L.message,variant:"destructive"})}},S=async(T,L)=>{if(confirm(`Delete tag "${L}"? It will be removed from all contacts.`))try{await l.mutateAsync(T),Pr({title:"Tag deleted"})}catch(D){Pr({title:"Error",description:D.message,variant:"destructive"})}},A=T=>{p(T.id),g(T.name),v(T.color)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Manage Tags"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"New tag name...",value:o,onChange:T=>c(T.target.value),onKeyDown:T=>T.key==="Enter"&&j(),className:"flex-1 h-9"}),e.jsxs(B,{size:"sm",onClick:j,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:xG.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:xG.map(L=>e.jsx("button",{onClick:()=>v(L),className:`h-5 w-5 rounded-full border-2 ${_===L?"border-foreground":"border-transparent"}`,style:{backgroundColor:L}},L))}),e.jsx(ye,{value:f,onChange:L=>g(L.target.value),onKeyDown:L=>L.key==="Enter"&&b(T.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>b(T.id),children:e.jsx(Ir,{className:"h-4 w-4 text-primary"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>p(null),children:e.jsx(Bn,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-3.5 w-3.5 rounded-full shrink-0",style:{backgroundColor:T.color}}),e.jsx("span",{className:"flex-1 text-sm",children:T.name}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>A(T),children:e.jsx(_a,{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:()=>S(T.id,T.name),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})},T.id))]})]})})}function XGs({open:s,onOpenChange:t}){const{data:n,isLoading:r}=ZD(),a=_6e(),i=Vrs(),l=Hrs(),[o,c]=N.useState(""),[d,u]=N.useState(null),[h,p]=N.useState(""),f=async()=>{if(o.trim())try{await a.mutateAsync(o.trim()),c("")}catch(j){ae.error(j.message||"Failed to add lead source")}},g=async j=>{if(h.trim())try{await i.mutateAsync({id:j,name:h.trim()}),u(null)}catch(b){ae.error(b.message||"Failed to update")}},_=async(j,b)=>{if(confirm(`Remove lead source "${b}"? Contacts using it will keep the label but it won't appear in new dropdowns.`))try{await l.mutateAsync(j)}catch(S){ae.error(S.message||"Failed to remove")}},v=j=>{u(j.id),p(j.name)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"New lead source name...",value:o,onChange:j=>c(j.target.value),onKeyDown:j=>j.key==="Enter"&&f(),className:"flex-1 h-9"}),e.jsxs(B,{size:"sm",onClick:f,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(Is,{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(j=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:d===j.id?e.jsxs(e.Fragment,{children:[e.jsx(ye,{value:h,onChange:b=>p(b.target.value),onKeyDown:b=>b.key==="Enter"&&g(j.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>g(j.id),children:e.jsx(Ir,{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(Bn,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-sm",children:j.name}),j.owner_user_id&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>v(j),children:e.jsx(_a,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive",onClick:()=>_(j.id,j.name),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]}),!j.owner_user_id&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Default"})]})},j.id))]})]})})}function $_t({value:s,onChange:t,label:n="Lead Source"}){const{data:r}=ZD(),a=_6e(),[i,l]=N.useState(!1),[o,c]=N.useState(""),d=async()=>{if(o.trim())try{const u=await a.mutateAsync(o.trim());u&&(t(u.id),c(""),l(!1))}catch{}};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:n}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ds,{value:s||"_none",onValueChange:u=>t(u==="_none"?"":u),children:[e.jsx(ls,{className:"flex-1",children:e.jsx(us,{placeholder:"Select lead source"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"_none",children:"No source"}),r==null?void 0:r.map(u=>e.jsx(Qe,{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(Bn,{className:"h-4 w-4"}):e.jsx(Is,{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 tTe({contactId:s,currentSpouseContactId:t,currentSpouseName:n,currentSpouseEmail:r,onLink:a,onUnlink:i,isEditing:l}){const o=Mn(),c=ma(),[d,u]=N.useState(!1),[h,p]=N.useState(""),{data:f}=ct({queryKey:["innercircle-contact-spouse",t],queryFn:async()=>{const{data:_,error:v}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday").eq("id",t).maybeSingle();if(v)throw v;return _},enabled:!!t}),{data:g}=ct({queryKey:["spouse-search",c,s,h],queryFn:async()=>{let _=q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("owner_user_id",c).is("synced_source",null).neq("id",s).order("first_name").limit(20);if(h.trim()){const b=h.replace(/[,()%]/g," ").trim();b&&(_=_.or(`first_name.ilike.%${b}%,last_name.ilike.%${b}%,email.ilike.%${b}%,phone.ilike.%${b}%`))}const{data:v,error:j}=await _;if(j)throw j;return v},enabled:d&&!!c});if(t&&f){const _=`${f.first_name} ${f.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(Xi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("button",{onClick:()=>o(`/mission-control/contacts/${f.id}`),className:"text-sm font-medium text-primary hover:underline truncate block",children:_}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[f.phone,f.email].filter(Boolean).join(" · ")||"No contact info"})]}),l&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:i,className:"shrink-0 h-7 px-2",children:[e.jsx(qA,{className:"h-3.5 w-3.5 mr-1"}),"Unlink"]}),!l&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/contacts/${f.id}`),className:"shrink-0 h-7 px-2",children:e.jsx(Oa,{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(Xi,{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(el,{open:d,onOpenChange:u,children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"shrink-0 h-7 px-2",children:[e.jsx(El,{className:"h-3.5 w-3.5 mr-1"}),"Link Contact"]})}),e.jsx(Ho,{className:"w-72 p-2",align:"end",children:e.jsx(DZe,{search:h,setSearch:p,results:g,onSelect:_=>{a(_),u(!1),p("")}})})]})]})]}):l?e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs(el,{open:d,onOpenChange:u,children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full justify-start text-muted-foreground font-normal h-10",children:[e.jsx(El,{className:"h-4 w-4 mr-2"}),"Link an existing contact as spouse..."]})}),e.jsx(Ho,{className:"w-72 p-2",align:"start",children:e.jsx(DZe,{search:h,setSearch:p,results:g,onSelect:_=>{a(_),u(!1),p("")}})})]})]}):null}function DZe({search:s,setSearch:t,results:n,onSelect:r}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{value:s,onChange:a=>t(a.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(hi,{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 gG=new Map;async function JGs(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 eWs(s,t=256){const n=s.trim().toLowerCase();if(!n||!n.includes("@"))return null;const r=`${n}|${t}`;if(gG.has(r))return gG.get(r)??null;try{const i=`https://gravatar.com/avatar/${await JGs(n)}?s=${t}&d=404`;return gG.set(r,i),i}catch{return gG.set(r,null),null}}function tWs(s,t=256){const[n,r]=N.useState(null);return N.useEffect(()=>{let a=!0;if(!s){r(null);return}return eWs(s,t).then(i=>{a&&r(i)}),()=>{a=!1}},[s,t]),n}function yLe({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=tWs(n?null:r,Math.max(64,a*2)),[u,h]=N.useState(!1);N.useEffect(()=>h(!1),[d]);const p=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:p?e.jsx("img",{src:p,alt:`${s??""} ${t??""}`.trim()||"Contact photo",className:"h-full w-full object-cover",loading:"lazy",onError:()=>h(!0)}):e.jsx("span",{children:o})})}const sWs=5*1024*1024;function U_t({contactId:s,firstName:t,lastName:n,avatarUrl:r,email:a,size:i=88}){const l=N.useRef(null),o=Ht(),[c,d]=N.useState(!1),u=()=>{o.invalidateQueries({queryKey:["innercircle-contacts"]}),o.invalidateQueries({queryKey:["innercircle-contact"]}),o.invalidateQueries({queryKey:["contact",s]})},h=async g=>{const{error:_}=await q.from("innercircle_contacts").update({avatar_url:g}).eq("id",s);if(_)throw _;u()},p=async g=>{var _;if(!g.type.startsWith("image/")){Pr({title:"Please choose an image file",variant:"destructive"});return}if(g.size>sWs){Pr({title:"Image too large",description:"Please use an image under 5MB.",variant:"destructive"});return}d(!0);try{const{data:v}=await q.auth.getUser(),j=(_=v.user)==null?void 0:_.id,b=(g.name.split(".").pop()||"jpg").toLowerCase(),S=`contacts/${j}/${s}-${Date.now()}.${b}`,{error:A}=await q.storage.from("avatars").upload(S,g,{upsert:!0,contentType:g.type});if(A)throw A;const{data:T}=q.storage.from("avatars").getPublicUrl(S);await h(T.publicUrl),Pr({title:"Photo updated"})}catch(v){Pr({title:"Upload failed",description:v.message,variant:"destructive"})}finally{d(!1),l.current&&(l.current.value="")}},f=async()=>{d(!0);try{await h(null),Pr({title:"Photo removed"})}catch(g){Pr({title:"Could not remove photo",description:g.message,variant:"destructive"})}finally{d(!1)}};return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>{var g;return(g=l.current)==null?void 0:g.click()},disabled:c,className:"relative group rounded-full focus:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":r?"Change contact photo":"Upload contact photo",children:[e.jsx(yLe,{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(ts,{className:"h-5 w-5 text-background animate-spin"}):e.jsx(mf,{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(ts,{className:"h-5 w-5 text-background animate-spin"})})]}),r&&e.jsxs(B,{variant:"ghost",size:"sm",className:"text-muted-foreground gap-1.5",onClick:f,disabled:c,children:[e.jsx(_n,{className:"h-3.5 w-3.5"}),"Remove"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:g=>{var v;const _=(v=g.target.files)==null?void 0:v[0];_&&p(_)}})]})}const nWs={warm:"stroke-emerald-500",cooling:"stroke-amber-500","at-risk":"stroke-red-500"},rWs={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 q_t({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:nWs[t]})]}),e.jsx("span",{className:Et("absolute inset-0 flex items-center justify-center font-semibold tabular-nums",rWs[t],n>=56?"text-lg":"text-[11px]"),children:o})]})}function aWs(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 iWs({score:s,contact:t,onEdit:n,onLogTouch:r}){const a=aWs(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(Ir,{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(vw,{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 oWs={warm:"Strong",cooling:"Cooling off","at-risk":"Needs attention"};function lWs({contact:s,deal:t,open:n,onOpenChange:r,onEdit:a,index:i,total:l,onPrev:o,onNext:c}){var A;const d=Mn(),{data:u}=YD(),h=fU(),[p,f]=N.useState(null),g=s==null?void 0:s.spouse_contact_id,{data:_}=ct({queryKey:["innercircle-contact-spouse",g],queryFn:async()=>{const{data:T,error:L}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday, avatar_url").eq("id",g).maybeSingle();if(L)throw L;return T},enabled:!!g&&n});if(!s)return null;const v=async T=>{f(T);try{await h.mutateAsync({contactId:s.id,actionTypeId:T})}finally{f(null)}},j=`${s.first_name||""} ${s.last_name||""}`.trim();j.split(" ").filter(Boolean).map(T=>T[0]).join("").toUpperCase().slice(0,2);const b=[s.city,s.state].filter(Boolean).join(", "),S=s.relationshipScore;return e.jsx(cg,{open:n,onOpenChange:r,children:e.jsxs(ix,{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(pl,{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(xa,{className:"h-4 w-4"})]})]}),e.jsxs("div",{className:"p-5 space-y-5",children:[e.jsxs(n0,{className:"space-y-0 text-left",children:[e.jsx(r0,{className:"sr-only",children:j}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(U_t,{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:j}),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(Vs,{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(Ar,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:s.phone})]}),b&&e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ka,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:b})]})]})]})]})]}),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:oWs[S.status]??S.status}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:S.lastTouchDate?`Last touch ${Ss(new Date(S.lastTouchDate),"MMM d, yyyy")}`:"Never contacted"})]}),e.jsx(q_t,{score:S.score,status:S.status,size:64})]}),e.jsx(iWs,{score:S,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(Fge,{contact:s})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",className:"gap-1.5",asChild:!0,disabled:!s.email,children:e.jsxs("a",{href:s.email?`mailto:${s.email}`:void 0,children:[e.jsx(Vs,{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(Ei,{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(Ar,{className:"h-4 w-4"})," Call"]})})]}),e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsxs(B,{variant:"secondary",className:"w-full gap-1.5",disabled:!!p,children:[p?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(xr,{className:"h-4 w-4"}),"Log a touch"]})}),e.jsxs(cc,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(M4,{children:"What did you do?"}),u==null?void 0:u.map(T=>e.jsx(Qr,{onClick:()=>v(T.id),children:T.name},T.id))]})]}),(t||s.tags&&s.tags.length>0)&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(eTe,{deal:t}),(A=s.tags)==null?void 0:A.map(T=>{var L;return e.jsx(ze,{variant:"secondary",className:"text-xs",children:(L=T.relationship_type)==null?void 0:L.name},T.id)})]}),(_||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(Nn,{className:"h-3.5 w-3.5"})," Spouse / Partner"]}),_?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(yLe,{firstName:_.first_name,lastName:_.last_name,avatarUrl:_.avatar_url,email:_.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/${_.id}`),children:`${_.first_name||""} ${_.last_name||""}`.trim()}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:[_.phone,_.email].filter(Boolean).join(" · ")||"No contact info"})]}),e.jsx(B,{variant:"ghost",size:"icon","aria-label":"Open spouse record",onClick:()=>d(`/mission-control/contacts/${_.id}`),children:e.jsx(tr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(gi,{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||(_==null?void 0:_.birthday))&&e.jsxs("div",{className:"mt-3 flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(cu,{className:"h-3.5 w-3.5"}),"Spouse birthday · ",Ss(Cl(s.spouse_birthday||_.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(yr,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Birthday · ",Ss(Cl(s.birthday),"MMM d, yyyy")]}),s.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Or,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Home anniversary · ",Ss(Cl(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(gr,{className:"h-3.5 w-3.5"}),"Added ",Ss(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(_a,{className:"h-4 w-4"})})]})]})]})})}function cWs({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(Ec,{children:[e.jsx(Ac,{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(Nn,{className:"h-3 w-3"})})}),e.jsx(vc,{children:r})]})}function V_t(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 RZe(s){if(!s)return null;const t=Cl(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:Fo,color:"text-violet-600 dark:text-violet-400",match:s=>s.relationshipScore.daysSinceTouch===null},{key:"stale-90",title:"Stale 90+ Days",icon:gr,color:"text-amber-600 dark:text-amber-400",match:s=>{const t=s.relationshipScore.daysSinceTouch;return t!==null&&t>90}},{key:"cooling",title:"Cooling Off",icon:Ev,color:"text-cyan-600 dark:text-cyan-400",match:s=>s.relationshipScore.status==="cooling"},{key:"birthdays-soon",title:"Birthdays Soon",icon:cu,color:"text-pink-600 dark:text-pink-400",match:(s,t)=>t.daysToBirthday!==null&&t.daysToBirthday<=30},{key:"anniversary-soon",title:"Home Anniversary",icon:Or,color:"text-emerald-600 dark:text-emerald-400",match:(s,t)=>t.daysToAnniv!==null&&t.daysToAnniv<=30},{key:"has-deal",title:"Active Deal",icon:qm,color:"text-teal-700 dark:text-teal-400",match:(s,t)=>t.hasDeal},{key:"website-active",title:"Active on Site",icon:lc,color:"text-indigo-600 dark:text-indigo-400",match:()=>!1},{key:"vips",title:"VIPs",icon:un,color:"text-amber-600 dark:text-amber-300",match:s=>s.relationshipScore.score>=80},{key:"missing-info",title:"Missing Info",icon:$l,color:"text-slate-600 dark:text-slate-400",match:s=>V_t(s)}];function dWs({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}=fLe(),p=N_t(),f=k_t(),[g,_]=N.useState(!1),[v,j]=N.useState(""),b=N.useMemo(()=>{const L={"needs-attention":0,cooling:0,"never-contacted":0,"stale-90":0,"birthdays-soon":0,"anniversary-soon":0,"has-deal":0,"website-active":n.size,"missing-info":0,vips:0};if(!s)return L;for(const D of s){const M={hasDeal:!!(t&&t[D.id]),daysToBirthday:RZe(D.birthday),daysToAnniv:RZe(D.home_anniversary)};for(const F of OZe)F.key!=="website-active"&&F.match(D,M)&&L[F.key]++}return L},[s,t,n]),S=!!l.search||!!l.type&&l.type!=="all"||!!l.status&&l.status!=="all"||!!l.behavior&&Object.values(l.behavior).some(L=>L!==void 0&&L!==!1),A=async()=>{v.trim()&&(await p.mutateAsync({name:v.trim(),filters:l,sort_by:o}),j(""),_(!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(Nn,{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(L=>{const D=c===L.id;return e.jsxs("div",{className:Et(T,"group pr-1",D?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx("button",{type:"button",onClick:()=>d(L.id,L.filters,L.sort_by),children:L.name}),e.jsx("button",{type:"button","aria-label":`Delete view ${L.name}`,className:"h-5 w-5 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-foreground/10",onClick:()=>{f.mutate(L.id),D&&u()},children:e.jsx(Bn,{className:"h-3 w-3"})})]},L.id)}),e.jsx("div",{className:"h-5 w-px bg-border shrink-0"}),OZe.map(L=>{const D=L.icon,M=b[L.key],F=a===L.key;return e.jsxs("button",{type:"button",onClick:()=>i(F?null:L.key),"aria-pressed":F,className:Et(T,F?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border",!F&&M===0&&"opacity-55"),children:[e.jsx(D,{className:Et("h-3.5 w-3.5",F?"":L.color)}),L.title,e.jsx("span",{className:"tabular-nums opacity-70",children:M.toLocaleString()})]},L.key)}),e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 gap-1.5 text-xs shrink-0",disabled:!S,onClick:()=>_(!0),children:[e.jsx(JP,{className:"h-3.5 w-3.5"}),"Save view"]})]}),e.jsx(bs,{open:g,onOpenChange:_,children:e.jsxs(vs,{className:"sm:max-w-sm",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Save this view"}),e.jsx(Qn,{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:v,onChange:L=>j(L.target.value),onKeyDown:L=>L.key==="Enter"&&A()}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),e.jsx(B,{onClick:A,disabled:!v.trim()||p.isPending,children:"Save view"})]})]})})]})}const FZe=[{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"}],SNe={relationship:!0,stage:!0,leadSource:!0,tags:!0,lastTouch:!0,nextAction:!0,dealValue:!0,email:!1,phone:!1,address:!1,birthday:!1},zZe="innercircle:contact-columns:v1";function uWs(){const[s,t]=N.useState(()=>{try{const a=localStorage.getItem(zZe);if(a)return{...SNe,...JSON.parse(a)}}catch{}return SNe});N.useEffect(()=>{try{localStorage.setItem(zZe,JSON.stringify(s))}catch{}},[s]);const n=N.useCallback(a=>{t(i=>({...i,[a]:!i[a]}))},[]),r=N.useCallback(()=>t(SNe),[]);return{columns:s,toggle:n,reset:r}}function hWs({columns:s,onToggle:t,onReset:n}){const r=FZe.filter(a=>s[a.key]).length;return e.jsxs(el,{children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-8 gap-1.5 rounded-lg text-xs",children:[e.jsx(Kk,{className:"h-3.5 w-3.5"}),"Columns",e.jsx(ze,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r})]})}),e.jsxs(Ho,{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(cm,{className:"h-3 w-3"}),"Reset"]})]}),e.jsx("div",{className:"max-h-[320px] overflow-y-auto space-y-0.5",children:FZe.map(a=>e.jsxs("button",{type:"button",onClick:()=>t(a.key),className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx(ui,{checked:s[a.key],className:"pointer-events-none"}),e.jsx("span",{className:"flex-1 text-left",children:a.label})]},a.key))}),e.jsx("p",{className:"px-2 pt-2 text-[11px] text-muted-foreground",children:"Name and actions are always shown."})]})]})}function mWs(){var nr;const s=Mn(),[t,n]=gl(),{user:r}=ys(),a=wR(),i=Ht(),{columns:l,toggle:o,reset:c}=uWs(),d=t.get("type"),u=t.get("filter")??t.get("status"),h=t.get("new")==="true",{contactsWithScores:p,isLoading:f}=Hye(),{activeContactIds:g,hasLeadSite:_}=tGs(),{data:v}=KGs(),{data:j}=Sy(),{data:b}=YGs(),{data:S}=_R(),{data:A}=E1e(),[T,L]=N.useState(new Set),[D,M]=N.useState("any"),F=Uye(),z=g6e(),V=y6e(),W=Qmt(),[Y,K]=N.useState(""),[J,ne]=N.useState(!1),[ie,he]=N.useState(d||"all"),[ce,pe]=N.useState(u||"all"),[le,ve]=N.useState("date-added"),[ge,Te]=N.useState("all"),[Me,Ce]=N.useState({}),[Ae,De]=N.useState(!1),{behaviorMap:Ie,hasLeadSite:Fe}=qGs(),[qe,be]=N.useState(h),[Ze,Ne]=N.useState(null),[it,je]=N.useState(!1),[Ge,Be]=N.useState(!1),[Ye,We]=N.useState(null),[rt,tt]=N.useState(""),[at,He]=N.useState(new Set),[dt,bt]=N.useState(!1),[vt,Bt]=N.useState(null),Zt=Math.max(1,parseInt(t.get("page")||"1",10)||1),[Fs,Rs]=N.useState(Zt),ms=N.useCallback(Ot=>{Rs(fn=>{const sr=typeof Ot=="function"?Ot(fn):Ot;return n(Hn=>{const ta=new URLSearchParams(Hn);return sr<=1?ta.delete("page"):ta.set("page",String(sr)),ta},{replace:!0}),sr})},[]),[Pt,Jt]=N.useState(50),[ft,Vt]=N.useState("my"),[Ms,Xt]=N.useState(!1),[Js,Cs]=N.useState(!1),{data:As}=Zv(),{addToLeadPond:rn}=syt(As==null?void 0:As.teamId),tn=!!((nr=As==null?void 0:As.team)!=null&&nr.lead_pond_enabled&&(As!=null&&As.teamId)),er=!!(As!=null&&As.teamId),[gn,In]=N.useState([]),[Zn,ea]=N.useState(!1),vi=Ot=>{In([Ot]),ea(!0)},Ls=Ot=>{In(Ot),ea(!0)},fi=Ot=>{As!=null&&As.teamId&&rn.mutate({contact_id:Ot,team_id:As.teamId})},Lr=Ot=>{As!=null&&As.teamId&&Ot.forEach(fn=>{rn.mutate({contact_id:fn,team_id:As.teamId})})},Jn=N.useCallback(Ot=>{bt(!1),He(fn=>{const sr=new Set(fn);return sr.has(Ot)?sr.delete(Ot):sr.add(Ot),sr})},[]);N.useEffect(()=>{if(!(r!=null&&r.id))return;const Ot=q.channel(`innercircle_contacts_inserts_${r.id}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"innercircle_contacts",filter:`owner_user_id=eq.${r.id}`},()=>{i.invalidateQueries({queryKey:["innercircle-contacts"]}),i.invalidateQueries({queryKey:["innercircle-contact-counts"]})}).subscribe();return()=>{q.removeChannel(Ot)}},[i,r==null?void 0:r.id]),N.useEffect(()=>{u&&pe(u)},[u]);const[js,Dn]=N.useState({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]});N.useEffect(()=>{h&&be(!0)},[h]),N.useEffect(()=>{var Ot;Ze&&Dn({first_name:Ze.first_name||"",last_name:Ze.last_name||"",email:Ze.email||"",phone:Ze.phone||"",address:Ze.address||"",city:Ze.city||"",state:Ze.state||"",zip_code:Ze.zip_code||"",birthday:Ze.birthday||"",home_anniversary:Ze.home_anniversary||"",spouse_name:Ze.spouse_name||"",spouse_email:Ze.spouse_email||"",lead_source_id:Ze.lead_source_id||"",notes:Ze.notes||"",tagIds:((Ot=Ze.tags)==null?void 0:Ot.map(fn=>fn.relationship_type_id))||[]})},[Ze]);const wr=N.useMemo(()=>{const Ot=new Set;return S==null||S.forEach(fn=>{(fn.name==="Recruits"||fn.name==="Brokerage Agents")&&Ot.add(fn.id)}),Ot},[S]),$r=N.useMemo(()=>Array.from(T).some(Ot=>wr.has(Ot)),[T,wr]),ss=N.useMemo(()=>{const Ot={};return(p||[]).forEach(fn=>{Ot[fn.id]=`${fn.first_name||""} ${fn.last_name||""}`.trim()}),Ot},[p]),Oe=N.useMemo(()=>{if(!p)return[];let Ot=p.filter(Hn=>{var Bi,Za,_i,qi,ga,wn,Ta,Yi,zo,rl,po;if(!$r&&Hn.synced_source)return!1;const ta=Y===""||`${Hn.first_name} ${Hn.last_name}`.toLowerCase().includes(Y.toLowerCase())||((Bi=Hn.email)==null?void 0:Bi.toLowerCase().includes(Y.toLowerCase()))||((Za=Hn.phone)==null?void 0:Za.includes(Y))||((_i=Hn.city)==null?void 0:_i.toLowerCase().includes(Y.toLowerCase()))||((qi=Hn.state)==null?void 0:qi.toLowerCase().includes(Y.toLowerCase()))||((ga=Hn.address)==null?void 0:ga.toLowerCase().includes(Y.toLowerCase()))||((wn=Hn.zip_code)==null?void 0:wn.toLowerCase().includes(Y.toLowerCase())),Zr=ie==="all"||((Ta=Hn.tags)==null?void 0:Ta.some(uc=>uc.relationship_type_id===ie)),ur=T.size===0||(()=>{const uc=(A==null?void 0:A.filter(hc=>hc.contact_id===Hn.id).map(hc=>hc.tag_id))||[];return D==="any"?uc.some(hc=>T.has(hc)):Array.from(T).every(hc=>uc.includes(hc))})(),Mr=!!((Yi=Hn.address)!=null&&Yi.trim()||(zo=Hn.city)!=null&&zo.trim()||(rl=Hn.state)!=null&&rl.trim()||(po=Hn.zip_code)!=null&&po.trim());return ta&&Zr&&ur&&(ge==="all"||ge==="has-address"&&Mr||ge==="no-address"&&!Mr)});ce==="not-touched-90"?Ot=Ot.filter(Hn=>{const ta=Hn.relationshipScore.daysSinceTouch;return ta===null||ta>90}):ce==="at-risk"?Ot=Ot.filter(Hn=>Hn.relationshipScore.status==="at-risk"):ce==="cooling"?Ot=Ot.filter(Hn=>Hn.relationshipScore.status==="cooling"):ce==="warm"?Ot=Ot.filter(Hn=>Hn.relationshipScore.status==="warm"):ce==="has-deal"?Ot=Ot.filter(Hn=>b&&b[Hn.id]):ce==="no-deal"?Ot=Ot.filter(Hn=>!b||!b[Hn.id]):ce==="open-house"?Ot=Ot.filter(Hn=>{var Zr;return(((Zr=Hn.lead_source_ref)==null?void 0:Zr.name)||Hn.lead_source)==="Open House"}):ce==="website-active"?Ot=Ot.filter(Hn=>g.has(Hn.id)):ce==="never-contacted"?Ot=Ot.filter(Hn=>Hn.relationshipScore.daysSinceTouch===null):ce==="vips"?Ot=Ot.filter(Hn=>Hn.relationshipScore.score>=80):ce==="missing-info"?Ot=Ot.filter(Hn=>V_t(Hn)):ce==="birthdays-soon"?Ot=Ot.filter(Hn=>{const ta=DE(Hn.birthday);return ta!==null&&ta<=30}):ce==="anniversary-soon"?Ot=Ot.filter(Hn=>{const ta=DE(Hn.home_anniversary);return ta!==null&&ta<=30}):ce==="in-drip"?Ot=Ot.filter(Hn=>((v==null?void 0:v[Hn.id])??0)>0):ce==="not-in-drip"&&(Ot=Ot.filter(Hn=>((v==null?void 0:v[Hn.id])??0)===0));const fn=Me;if(fn.lastActive||fn.registered||fn.viewedListing||fn.savedProperty||fn.hasSavedSearch||fn.requestedShowing||fn.requestedValuation||fn.websiteActiveOnly){const Hn=Date.now(),ta={today:24*60*60*1e3,"7d":7*24*60*60*1e3,"30d":30*24*60*60*1e3,"90d":90*24*60*60*1e3};Ot=Ot.filter(Zr=>{const ur=Ie.get(Zr.id);if(fn.lastActive==="never"){if(ur!=null&&ur.lastActiveAt)return!1}else if(fn.lastActive){const Mr=Hn-ta[fn.lastActive];if(!(ur!=null&&ur.lastActiveAt)||new Date(ur.lastActiveAt).getTime()0)||fn.viewedListing==="multiple7d"&&!(ur&&ur.propertyViewCount7d>=3)||fn.savedProperty&&!(ur&&ur.savedListingCount>0)||fn.hasSavedSearch&&!(ur&&ur.activeSavedSearchCount>0)||fn.requestedShowing&&!(ur&&ur.showingRequests>0)||fn.requestedValuation&&!(ur&&ur.valuationRequests>0)||fn.websiteActiveOnly&&!g.has(Zr.id))})}return Ot=[...Ot].sort((Hn,ta)=>{switch(le){case"important-dates":{const Zr=DE(Hn.birthday),ur=DE(ta.birthday),Mr=DE(Hn.home_anniversary),zi=DE(ta.home_anniversary),Bi=[Zr,Mr].filter(_i=>_i!==null).sort((_i,qi)=>(_i??1/0)-(qi??1/0))[0]??1/0,Za=[ur,zi].filter(_i=>_i!==null).sort((_i,qi)=>(_i??1/0)-(qi??1/0))[0]??1/0;return Bi-Za}case"last-touched":{const Zr=Hn.relationshipScore.lastTouchDate,ur=ta.relationshipScore.lastTouchDate;return!Zr&&!ur?0:Zr?ur?new Date(Zr).getTime()-new Date(ur).getTime():1:-1}case"next-touch":{const Zr=Hn.relationshipScore.daysSinceTouch,ur=ta.relationshipScore.daysSinceTouch;return Zr===null&&ur===null?0:Zr===null?-1:ur===null?1:ur-Zr}case"score":return Hn.relationshipScore.score-ta.relationshipScore.score;case"date-added":{const Zr=Hn.created_at,ur=ta.created_at;return!Zr&&!ur?0:Zr?ur?new Date(ur).getTime()-new Date(Zr).getTime():-1:1}case"last-name":{const Zr=(Hn.last_name||"").toLowerCase(),ur=(ta.last_name||"").toLowerCase();if(Zr!==ur)return Zr.localeCompare(ur);const Mr=(Hn.first_name||"").toLowerCase(),zi=(ta.first_name||"").toLowerCase();return Mr.localeCompare(zi)}case"name":default:{const Zr=`${Hn.first_name||""} ${Hn.last_name||""}`.toLowerCase(),ur=`${ta.first_name||""} ${ta.last_name||""}`.toLowerCase();return Zr.localeCompare(ur)}}}),Ot},[p,Y,ie,T,D,ce,le,b,A,g,v,ge,Me,Ie,$r]),Xe=Oe.length,ot=Math.max(1,Math.ceil(Xe/Pt)),Nt=Math.min(Fs,ot),Rt=N.useMemo(()=>{const Ot=(Nt-1)*Pt;return Oe.slice(Ot,Ot+Pt)},[Oe,Nt,Pt]),qt=N.useRef(!1);N.useEffect(()=>{if(!qt.current){qt.current=!0;return}ms(1)},[Y,ie,T,D,ce,le,ge,Me]);const xs=N.useCallback(()=>{bt(!1),He(Ot=>Ot.size>0?new Set:new Set(Rt.map(fn=>fn.id)))},[Rt]),rs=N.useCallback(()=>{bt(!0),He(new Set(Oe.map(Ot=>Ot.id)))},[Oe]),[ks,ln]=N.useState(null),Gs=N.useCallback((Ot,fn)=>{K(Ot.search||""),he(Ot.type||"all"),pe(Ot.status||"all"),Ce(Ot.behavior||{}),ve(fn||"name")},[]),Un=()=>{Dn({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]})},jr=async Ot=>{Ot.preventDefault();const fn={...js,lead_source_id:js.lead_source_id||null};Ze?(await z.mutateAsync({id:Ze.id,...fn}),Ne(null)):(await F.mutateAsync(fn),be(!1)),Un()},Sr=async Ot=>{confirm("Are you sure you want to delete this contact?")&&await V.mutateAsync(Ot)};return e.jsx(Ts,{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"})]}),As&&e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsx("button",{onClick:()=>Vt("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${ft==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Contacts"}),(As.team.contact_visibility==="full_team"||As.team.contact_visibility==="leader_only"&&As.role==="team_leader")&&e.jsxs("button",{onClick:()=>Vt("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${ft==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Nn,{className:"h-3.5 w-3.5"}),"Team"]}),As.team.lead_pond_enabled&&e.jsxs("button",{onClick:()=>Vt("lead-pond"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${ft==="lead-pond"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(mb,{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(pl,{className:"h-4 w-4 mr-1"}),"Back"]})}),ft==="team"?e.jsx(YIe,{}):ft==="lead-pond"&&As?e.jsx(ZIe,{teamId:As.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(dWs,{contacts:p,contactDealsMap:b,websiteActiveIds:g,totalCount:(p||[]).length,activeViewId:ks,currentFilters:{search:Y,type:ie,status:ce,behavior:Me},currentSortBy:le,onApplyView:(Ot,fn,sr)=>{ln(Ot),Gs(fn,sr),ms(1)},onClearAll:()=>{ln(null),Gs({search:"",type:"all",status:"all",behavior:{}},"name"),ms(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"}[ce]??null,onSelectSegment:Ot=>{const sr=Ot?{"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"}[Ot]:"all";pe(sr),ms(1)}}),e.jsxs(fe,{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(vr,{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:Y,onChange:Ot=>K(Ot.target.value),className:"pl-9 h-10 rounded-xl bg-muted/40"})]}),e.jsxs(cg,{children:[e.jsx(rU,{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(l4,{className:"h-4 w-4"}),(()=>{const Ot=(ie!=="all"?1:0)+(ce!=="all"?1:0)+(ge!=="all"?1:0)+T.size+Object.values(Me).filter(fn=>fn!==void 0&&fn!==!1).length;return Ot>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:Ot}):null})()]})}),e.jsxs(ix,{side:"bottom",className:"h-[85vh] rounded-t-2xl overflow-y-auto",children:[e.jsx(n0,{className:"text-left",children:e.jsx(r0,{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(ds,{value:ie,onValueChange:he,children:[e.jsx(ls,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(us,{placeholder:"All Types"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Types"}),j==null?void 0:j.filter(Ot=>Ot.active).map(Ot=>e.jsx(Qe,{value:Ot.id,children:Ot.name},Ot.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(ds,{value:ce,onValueChange:pe,children:[e.jsx(ls,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(us,{placeholder:"All Status"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Status"}),e.jsx(Qe,{value:"warm",children:"🟢 Warm"}),e.jsx(Qe,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(Qe,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(Qe,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(Qe,{value:"no-deal",children:"📭 No Deal"}),e.jsx(Qe,{value:"open-house",children:"🏠 Open House"}),_&&e.jsx(Qe,{value:"website-active",children:"🌐 Website Active"}),e.jsx(Qe,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(Qe,{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(ds,{value:ge,onValueChange:Ot=>Te(Ot),children:[e.jsx(ls,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(us,{placeholder:"All Addresses"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Addresses"}),e.jsx(Qe,{value:"has-address",children:"Has Address"}),e.jsx(Qe,{value:"no-address",children:"No Address"})]})]})]}),S&&S.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tags"}),e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-md p-0.5",children:[e.jsx("button",{onClick:()=>M("any"),className:`px-2 py-0.5 rounded text-xs font-medium ${D==="any"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>M("all"),className:`px-2 py-0.5 rounded text-xs font-medium ${D==="all"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:S.map(Ot=>{const fn=T.has(Ot.id);return e.jsxs("button",{onClick:()=>{L(sr=>{const Hn=new Set(sr);return Hn.has(Ot.id)?Hn.delete(Ot.id):Hn.add(Ot.id),Hn})},className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs border transition-colors ${fn?"bg-primary text-primary-foreground border-primary":"bg-background border-border"}`,children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:Ot.color}}),Ot.name]},Ot.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(ds,{value:le,onValueChange:ve,children:[e.jsx(ls,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"name",children:"Name (A-Z)"}),e.jsx(Qe,{value:"last-name",children:"Last Name (A-Z)"}),e.jsx(Qe,{value:"important-dates",children:"Important Dates"}),e.jsx(Qe,{value:"last-touched",children:"Last Touched"}),e.jsx(Qe,{value:"next-touch",children:"Next Touch Due"}),e.jsx(Qe,{value:"score",children:"Relationship Score"}),e.jsx(Qe,{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:()=>De(!0),children:[e.jsx(un,{className:"h-4 w-4"})," Advanced"]}),e.jsxs(B,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>Xt(!0),children:[e.jsx(uh,{className:"h-4 w-4"})," Manage Tags"]})]}),e.jsx("div",{children:e.jsx(MZe,{currentFilters:{search:Y,type:ie,status:ce,behavior:Me},currentSortBy:le,onApplySmartList:Gs})}),e.jsx(B,{variant:"ghost",className:"w-full h-11 rounded-xl text-muted-foreground",onClick:()=>{he("all"),pe("all"),Te("all"),L(new Set),Ce({})},children:"Clear all filters"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(B,{onClick:()=>be(!0),className:"h-11 rounded-xl",children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Add Contact"]}),e.jsxs(B,{onClick:()=>ne(!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(Dc,{className:"h-4 w-4 mr-1.5"})," Heat Map"]})]}),e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full h-10 rounded-xl gap-2",children:[e.jsx(Na,{className:"h-4 w-4"})," Import & Sync"]})}),e.jsxs(cc,{align:"center",className:"w-[calc(100vw-2rem)] max-w-sm",children:[e.jsxs(Qr,{onClick:()=>je(!0),children:[e.jsx(Na,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(Qr,{onClick:()=>Be(!0),children:[e.jsx(ng,{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(TZe,{})})]})]})]}),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(vr,{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:Y,onChange:Ot=>K(Ot.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(Nn,{className:"h-3.5 w-3.5"}),"Grid"]}),e.jsxs("button",{type:"button",onClick:()=>ne(!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(Dc,{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:()=>be(!0),className:"rounded-none rounded-l-xl h-10 px-4 gap-2 shadow-none",children:[e.jsx(Is,{className:"h-4 w-4"}),"Add Contact"]}),e.jsxs(wc,{children:[e.jsx(jc,{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(xa,{className:"h-4 w-4 rotate-90"})})}),e.jsxs(cc,{align:"end",children:[e.jsxs(Qr,{onClick:()=>je(!0),children:[e.jsx(Na,{className:"h-4 w-4 mr-2"}),"Import CSV"]}),e.jsxs(Qr,{onClick:()=>Be(!0),children:[e.jsx(ng,{className:"h-4 w-4 mr-2"}),"Import from Phone"]})]})]})]}),e.jsx(TZe,{}),e.jsxs(el,{children:[e.jsx(tl,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl",title:"Sort contacts",children:e.jsx(Ov,{className:"h-4 w-4"})})}),e.jsxs(Ho,{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(Ot=>e.jsx("button",{onClick:()=>ve(Ot.v),className:`w-full text-left px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors ${le===Ot.v?"bg-accent font-medium text-primary":""}`,children:Ot.l},Ot.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(ds,{value:ie,onValueChange:he,children:[e.jsx(ls,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(us,{placeholder:"All Types"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Types"}),j==null?void 0:j.filter(Ot=>Ot.active).map(Ot=>e.jsx(Qe,{value:Ot.id,children:Ot.name},Ot.id))]})]}),e.jsxs(ds,{value:ce,onValueChange:pe,children:[e.jsx(ls,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(us,{placeholder:"All Status"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Status"}),e.jsx(Qe,{value:"warm",children:"🟢 Warm"}),e.jsx(Qe,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(Qe,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(Qe,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(Qe,{value:"no-deal",children:"📭 No Deal"}),e.jsx(Qe,{value:"open-house",children:"🏠 Open House"}),_&&e.jsx(Qe,{value:"website-active",children:"🌐 Website Active"}),e.jsx(Qe,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(Qe,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]}),e.jsxs(ds,{value:ge,onValueChange:Ot=>Te(Ot),children:[e.jsx(ls,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(us,{placeholder:"All Addresses"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Addresses"}),e.jsx(Qe,{value:"has-address",children:"Has Address"}),e.jsx(Qe,{value:"no-address",children:"No Address"})]})]}),S&&S.length>0&&e.jsxs("div",{className:"inline-flex items-center bg-background border rounded-lg overflow-hidden h-8",children:[e.jsxs(el,{children:[e.jsx(tl,{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(uh,{className:"h-3.5 w-3.5"}),T.size===0?"Filter by Tags":`${T.size} tag${T.size>1?"s":""}`]})}),e.jsx(Ho,{className:"w-60 p-3",align:"start",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Tags"}),e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-md p-0.5",children:[e.jsx("button",{onClick:()=>M("any"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${D==="any"?"bg-background text-foreground shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>M("all"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${D==="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:S.map(Ot=>{const fn=T.has(Ot.id);return e.jsxs("button",{onClick:()=>{L(sr=>{const Hn=new Set(sr);return Hn.has(Ot.id)?Hn.delete(Ot.id):Hn.add(Ot.id),Hn})},className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx(ui,{checked:fn,className:"pointer-events-none"}),e.jsx("div",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:Ot.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:Ot.name})]},Ot.id)})}),T.size>0&&e.jsx(B,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>L(new Set),children:"Clear tags"})]})})]}),e.jsx("div",{className:"w-px h-4 bg-border"}),e.jsxs(wc,{children:[e.jsx(jc,{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(Xo,{className:"h-3.5 w-3.5"})})}),e.jsxs(cc,{align:"end",children:[e.jsxs(Qr,{onClick:()=>Xt(!0),children:[e.jsx(uh,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(Qr,{onClick:()=>Cs(!0),children:[e.jsx(mb,{className:"h-4 w-4 mr-2"}),"Manage Lead Sources"]})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(MZe,{currentFilters:{search:Y,type:ie,status:ce,behavior:Me},currentSortBy:le,onApplySmartList:Gs}),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:()=>De(!0),children:[e.jsx(un,{className:"h-3.5 w-3.5"}),"Advanced Filters",Object.values(Me).filter(Ot=>Ot!==void 0&&Ot!==!1).length>0&&e.jsx(ze,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:Object.values(Me).filter(Ot=>Ot!==void 0&&Ot!==!1).length})]}),e.jsx(hWs,{columns:l,onToggle:o,onReset:c})]})]}),Object.values(Me).some(Ot=>Ot!==void 0&&Ot!==!1)&&e.jsx("div",{className:"px-3 sm:px-4 py-3 border-t bg-background",children:e.jsx($Gs,{behavior:Me,onRemove:Ot=>Ce(fn=>{const sr={...fn};return delete sr[Ot],sr}),onClearAll:()=>Ce({})})})]}),e.jsx(BGs,{open:Ae,onOpenChange:De,hasLeadSite:Fe||_,behavior:Me,onApply:Ce,selectedType:ie,onSelectedTypeChange:he,relationshipTypes:j}),e.jsx(FGs,{selectedIds:at,contacts:Oe,onClearSelection:()=>{He(new Set),bt(!1)},showLeadPondAction:tn,onSendToLeadPond:Lr,showTransferAction:er,onTransfer:Ls}),at.size>0&&at.size===Rt.length&&!dt&&Xe>Pt&&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 ",Rt.length," contacts on this page are selected."]}),e.jsxs(B,{variant:"link",size:"sm",className:"h-auto p-0 font-semibold",onClick:rs,children:["Select all ",Xe.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 ",Xe.toLocaleString()," matching contacts are selected.",e.jsx(B,{variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{He(new Set),bt(!1)},children:"Clear selection"})]}),Xe>Pt&&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 ",(Nt-1)*Pt+1,"–",Math.min(Nt*Pt,Xe)," of ",Xe.toLocaleString()," contacts"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",disabled:Nt<=1,onClick:()=>ms(1),children:"First"}),e.jsx(B,{variant:"outline",size:"sm",disabled:Nt<=1,onClick:()=>ms(Ot=>Ot-1),children:e.jsx(pl,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Nt," of ",ot]}),e.jsx(B,{variant:"outline",size:"sm",disabled:Nt>=ot,onClick:()=>ms(Ot=>Ot+1),children:e.jsx(xa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",disabled:Nt>=ot,onClick:()=>ms(ot),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:f?e.jsx(fe,{className:"p-6 text-center text-muted-foreground",children:"Loading contacts..."}):Oe.length===0?e.jsx(fe,{className:"p-6 text-center text-muted-foreground",children:Y||ie!=="all"||ce!=="all"||ge!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"}):Rt.map(Ot=>{var sr,Hn,ta;const{relationshipScore:fn}=Ot;return e.jsx(fe,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>{const Zr=new URLSearchParams;Y&&Zr.set("search",Y),ie!=="all"&&Zr.set("type",ie),ce!=="all"&&Zr.set("filter",ce),T.size>0&&(Zr.set("tags",Array.from(T).join(",")),Zr.set("tagMode",D));const ur=Zr.toString();s(`/mission-control/contacts/${Ot.id}${ur?`?${ur}`:""}`)},children:e.jsx(Ee,{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:[Ot.first_name," ",Ot.last_name]}),e.jsx(PZe,{count:(v==null?void 0:v[Ot.id])??0}),e.jsx(xa,{className:"h-4 w-4 text-muted-foreground shrink-0 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-sm mb-3",children:[Ot.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Vs,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:Ot.email})]}),Ot.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ar,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:Ot.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(J5e,{score:fn,size:"sm"}),e.jsx(Fge,{contact:Ot}),(((sr=Ot.lead_source_ref)==null?void 0:sr.name)||Ot.lead_source)&&e.jsx(ze,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((Hn=Ot.lead_source_ref)==null?void 0:Hn.name)||Ot.lead_source}),(ta=Ot.tags)==null?void 0:ta.map(Zr=>{var ur;return e.jsx(ze,{variant:"secondary",className:"text-xs",children:(ur=Zr.relationship_type)==null?void 0:ur.name},Zr.id)}),e.jsx(LZe,{contactId:Ot.id,tags:A==null?void 0:A.filter(Zr=>Zr.contact_id===Ot.id)}),e.jsx(eTe,{deal:b==null?void 0:b[Ot.id]})]}),e.jsx(IZe,{birthday:Ot.birthday,homeAnniversary:Ot.home_anniversary,weddingAnniversary:Ot.wedding_anniversary,className:"mb-2",contactId:Ot.id,contactName:`${Ot.first_name}${Ot.last_name?" "+Ot.last_name:""}`,contactAddress:[Ot.address,Ot.city,Ot.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[fn.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),Ss(new Date(fn.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),Ot.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(yr,{className:"h-3 w-3"}),Ss(Cl(Ot.birthday),"MMM d")]}),Ot.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Or,{className:"h-3 w-3"}),Ss(Cl(Ot.home_anniversary),"MMM d")]}),Ot.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Is,{className:"h-3 w-3"}),"Added ",Ss(new Date(Ot.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:Zr=>Zr.stopPropagation(),children:e.jsx(AZe,{contact:Ot,onEdit:Ne,onDelete:Sr,onSnooze:(Zr,ur)=>{We(Zr),tt(ur)},showLeadPondAction:tn,onSendToLeadPond:fi,showTransferAction:er,onTransfer:vi})})]})})},Ot.id)})}):e.jsx(fe,{children:e.jsx(Ee,{className:"p-0 overflow-x-auto",children:e.jsxs(da,{className:"min-w-[800px]",children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{className:"w-[40px]",children:e.jsx(ui,{checked:Rt.length>0&&Rt.every(Ot=>at.has(Ot.id)),onCheckedChange:()=>xs()})}),e.jsx(Ct,{children:e.jsxs("button",{onClick:()=>ve(Ot=>Ot==="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",le==="name"&&e.jsx(xa,{className:"h-3 w-3 rotate-90 text-primary"}),le==="last-name"&&e.jsx(xa,{className:"h-3 w-3 -rotate-90 text-primary"})]})}),l.relationship&&e.jsx(Ct,{children:"Relationship"}),l.stage&&e.jsx(Ct,{children:"Stage"}),l.leadSource&&e.jsx(Ct,{children:"Lead Source"}),l.tags&&e.jsx(Ct,{children:"Tags"}),l.lastTouch&&e.jsx(Ct,{children:"Last Touch"}),l.nextAction&&e.jsx(Ct,{children:"Next Action"}),l.dealValue&&e.jsx(Ct,{title:"Total value of deals linked to this contact in your pipeline",children:"Pipeline Value"}),l.email&&e.jsx(Ct,{children:"Email"}),l.phone&&e.jsx(Ct,{children:"Phone"}),l.address&&e.jsx(Ct,{children:"Address"}),l.birthday&&e.jsx(Ct,{children:"Birthday"}),e.jsx(Ct,{className:"w-[50px]"})]})}),e.jsx(ha,{children:f?e.jsx(Hs,{children:e.jsx(ut,{colSpan:3+Object.values(l).filter(Boolean).length,className:"text-center py-8",children:"Loading contacts..."})}):Oe.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:3+Object.values(l).filter(Boolean).length,className:"text-center py-8 text-muted-foreground",children:Y||ie!=="all"||ce!=="all"||ge!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"})}):Rt.map(Ot=>{var Hn;const{relationshipScore:fn}=Ot,sr=b==null?void 0:b[Ot.id];return e.jsxs(Hs,{className:`cursor-pointer hover:bg-accent/50 ${at.has(Ot.id)?"bg-accent/30":""}`,onClick:()=>Bt(Ot),children:[e.jsx(ut,{onClick:ta=>ta.stopPropagation(),children:e.jsx(ui,{checked:at.has(Ot.id),onCheckedChange:()=>Jn(Ot.id)})}),e.jsx(ut,{className:"min-w-[220px]",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(yLe,{firstName:Ot.first_name,lastName:Ot.last_name,avatarUrl:Ot.avatar_url,email:Ot.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:[Ot.first_name," ",Ot.last_name]}),e.jsx(cWs,{linked:!!Ot.spouse_contact_id||!!Ot.spouse_name,spouseName:Ot.spouse_contact_id&&ss[Ot.spouse_contact_id]||Ot.spouse_name||null}),e.jsx(PZe,{count:(v==null?void 0:v[Ot.id])??0})]}),Ot.email&&!l.email&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ot.email}),Ot.phone&&!l.phone&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Ot.phone})]})]})}),l.relationship&&e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(q_t,{score:fn.score,status:fn.status}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:fn.status==="warm"?"Strong":fn.status==="cooling"?"Cooling":"At Risk"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:fn.daysSinceTouch===null?"Never contacted":fn.daysSinceTouch===0?"Touched today":`${fn.daysSinceTouch}d since touch`})]})]})}),l.stage&&e.jsx(ut,{children:e.jsx(eTe,{deal:sr})}),l.lastTouch&&e.jsx(ut,{children:fn.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(gr,{className:"h-3.5 w-3.5"}),Ss(new Date(fn.lastTouchDate),"MMM d, yyyy")]}):e.jsx("span",{className:"text-xs italic text-muted-foreground",children:"No activity"})}),l.nextAction&&e.jsx(ut,{children:e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(Fge,{contact:Ot}),e.jsx(IZe,{birthday:Ot.birthday,homeAnniversary:Ot.home_anniversary,weddingAnniversary:Ot.wedding_anniversary,contactId:Ot.id,contactName:`${Ot.first_name}${Ot.last_name?" "+Ot.last_name:""}`,contactAddress:[Ot.address,Ot.city,Ot.state].filter(Boolean).join(", ")})]})}),l.dealValue&&e.jsx(ut,{children:(()=>{const ta=(sr==null?void 0:sr.sale_price)??(sr==null?void 0:sr.expected_price);return ta?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:yc(Number(ta))}),(sr==null?void 0:sr.deal_type)&&e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:String(sr.deal_type).replace(/_/g," ")})]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})})()}),l.email&&e.jsx(ut,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:Ot.email||"—"}),l.phone&&e.jsx(ut,{className:"text-sm text-muted-foreground whitespace-nowrap",children:Ot.phone||"—"}),l.address&&e.jsx(ut,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:[Ot.address,Ot.city,Ot.state].filter(Boolean).join(", ")||"—"}),l.birthday&&e.jsx(ut,{className:"text-sm text-muted-foreground whitespace-nowrap",children:Ot.birthday?(()=>{const[ta,Zr,ur]=String(Ot.birthday).split(/[-/T]/).map(Number);return Zr&&ur?`${Zr}/${ur}${ta&&ta>1900?`/${ta}`:""}`:"—"})():"—"}),l.leadSource&&e.jsx(ut,{className:"text-sm text-muted-foreground max-w-[160px] truncate",children:((Hn=Ot.lead_source_ref)==null?void 0:Hn.name)||Ot.lead_source||"—"}),l.tags&&e.jsx(ut,{children:e.jsx("div",{className:"flex flex-wrap items-center gap-1 max-w-[220px]",children:e.jsx(LZe,{contactId:Ot.id,tags:A==null?void 0:A.filter(ta=>ta.contact_id===Ot.id)})})}),e.jsx(ut,{onClick:ta=>ta.stopPropagation(),children:e.jsx(AZe,{contact:Ot,onEdit:Ne,onDelete:Sr,onSnooze:(ta,Zr)=>{We(ta),tt(Zr)},showLeadPondAction:tn,onSendToLeadPond:fi,showTransferAction:er,onTransfer:vi})})]},Ot.id)})})]})})}),e.jsx(lWs,{contact:vt,deal:vt?b==null?void 0:b[vt.id]:void 0,open:!!vt,onOpenChange:Ot=>{Ot||Bt(null)},onEdit:Ot=>{Bt(null),Ne(Ot)},index:vt?Rt.findIndex(Ot=>Ot.id===vt.id):void 0,total:Rt.length,onPrev:(()=>{if(!vt)return;const Ot=Rt.findIndex(fn=>fn.id===vt.id);return Ot>0?()=>Bt(Rt[Ot-1]):void 0})(),onNext:(()=>{if(!vt)return;const Ot=Rt.findIndex(fn=>fn.id===vt.id);return Ot>=0&&OtBt(Rt[Ot+1]):void 0})()}),Xe>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 ",(Nt-1)*Pt+1,"–",Math.min(Nt*Pt,Xe)," of ",Xe.toLocaleString()," contacts"]}),e.jsxs(ds,{value:String(Pt),onValueChange:Ot=>{Jt(Number(Ot)),ms(1)},children:[e.jsx(ls,{className:"w-[80px] h-8",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"50",children:"50"}),e.jsx(Qe,{value:"100",children:"100"}),e.jsx(Qe,{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:Nt<=1,onClick:()=>ms(1),children:"First"}),e.jsx(B,{variant:"outline",size:"sm",disabled:Nt<=1,onClick:()=>ms(Ot=>Ot-1),children:e.jsx(pl,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Nt," of ",ot]}),e.jsx(B,{variant:"outline",size:"sm",disabled:Nt>=ot,onClick:()=>ms(Ot=>Ot+1),children:e.jsx(xa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",disabled:Nt>=ot,onClick:()=>ms(ot),children:"Last"})]})]}),e.jsx(bs,{open:qe||!!Ze,onOpenChange:Ot=>{Ot||(be(!1),Ne(null),Un())},children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:Ze?"Edit Contact":"Add Contact"})}),e.jsxs("form",{onSubmit:jr,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:js.first_name,onChange:Ot=>Dn({...js,first_name:Ot.target.value}),required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"last_name",children:"Last Name"}),e.jsx(ye,{id:"last_name",value:js.last_name,onChange:Ot=>Dn({...js,last_name:Ot.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(ye,{id:"email",type:"email",value:js.email,onChange:Ot=>Dn({...js,email:Ot.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"phone",children:"Phone"}),e.jsx(ye,{id:"phone",value:js.phone,onChange:Ot=>Dn({...js,phone:Ot.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"address",children:"Address"}),e.jsx(ye,{id:"address",value:js.address,onChange:Ot=>Dn({...js,address:Ot.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:js.city,onChange:Ot=>Dn({...js,city:Ot.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"state",children:"State"}),e.jsx(ye,{id:"state",value:js.state,onChange:Ot=>Dn({...js,state:Ot.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"zip_code",children:"Zip"}),e.jsx(ye,{id:"zip_code",value:js.zip_code,onChange:Ot=>Dn({...js,zip_code:Ot.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:js.birthday,onChange:Ot=>Dn({...js,birthday:Ot.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(ye,{id:"home_anniversary",type:"date",value:js.home_anniversary,onChange:Ot=>Dn({...js,home_anniversary:Ot.target.value})})]})]}),Ze&&e.jsx(tTe,{contactId:Ze.id,currentSpouseContactId:(Ze==null?void 0:Ze.spouse_contact_id)||null,currentSpouseName:(Ze==null?void 0:Ze.spouse_name)||null,currentSpouseEmail:(Ze==null?void 0:Ze.spouse_email)||null,onLink:Ot=>W.mutate({contactId:Ze.id,spouseContactId:Ot}),onUnlink:()=>W.mutate({contactId:Ze.id,spouseContactId:null}),isEditing:!0}),e.jsx($_t,{value:js.lead_source_id,onChange:Ot=>Dn({...js,lead_source_id:Ot})}),e.jsxs("div",{children:[e.jsx(se,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:j==null?void 0:j.filter(Ot=>Ot.active).map(Ot=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(ui,{checked:js.tagIds.includes(Ot.id),onCheckedChange:fn=>{Dn(fn?{...js,tagIds:[...js.tagIds,Ot.id]}:{...js,tagIds:js.tagIds.filter(sr=>sr!==Ot.id)})}}),e.jsx("span",{className:"text-sm",children:Ot.name})]},Ot.id))})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"notes",children:"Notes"}),e.jsx(Es,{id:"notes",value:js.notes,onChange:Ot=>Dn({...js,notes:Ot.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>{be(!1),Ne(null),Un()},children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:F.isPending||z.isPending,children:[Ze?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(aGs,{open:it,onOpenChange:je,relationshipTypes:(j==null?void 0:j.filter(Ot=>Ot.active))||[],onSuccess:()=>{je(!1)}}),e.jsx(lGs,{open:Ge,onOpenChange:Be,onComplete:()=>Be(!1)}),e.jsx(A1e,{open:!!Ye,onOpenChange:Ot=>{Ot||We(null)},contactId:Ye||"",contactName:rt}),e.jsx(QGs,{open:Ms,onOpenChange:Xt}),e.jsx(XGs,{open:Js,onOpenChange:Cs}),e.jsx(WGs,{open:J,onOpenChange:ne,contacts:p||[],onCitySelect:Ot=>{K(Ot),ms(1)}}),e.jsx(nyt,{open:Zn,onOpenChange:ea,contactIds:gn,contactNames:gn.map(Ot=>{const fn=Oe.find(sr=>sr.id===Ot);return fn?`${fn.first_name} ${fn.last_name||""}`.trim():""}),onComplete:()=>{In([]),He(new Set),bt(!1)}})]})]})})}const pWs="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function fWs({open:s,onOpenChange:t,contact:n}){var W;const{user:r}=ys(),a=Mn(),i=Ht(),{intakePage:l,isLoading:o}=M1e(),{isGmailConnected:c,gmailEmail:d}=Oh(),u=fU(),{data:h}=ct({queryKey:["profile-for-invite",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&s,queryFn:async()=>{const{data:Y}=await q.from("profiles").select("name, email, avatar_url").eq("id",r.id).maybeSingle();return Y}}),p=(h==null?void 0:h.name)||((W=r==null?void 0:r.email)==null?void 0:W.split("@")[0])||"Your Agent",f=p.split(" ")[0],g=l?`https://contacts.relevelup.com/${l.slug}`:"",_=N.useMemo(()=>`Hi ${n.first_name}, I'm updating my contact list and want to make sure I have your latest info — the best phone, email, address, and a couple of dates I love to remember (like your birthday and home anniversary). It only takes about a minute, and it helps me stay in touch the right way. Thanks so much!`,[n.first_name]),[v,j]=N.useState("gmail"),[b,S]=N.useState(""),[A,T]=N.useState(""),[L,D]=N.useState(!1);N.useEffect(()=>{s&&(S(`Quick favor, ${n.first_name} — can you update your info?`),T(_),j(c?"gmail":"system"))},[s,_,n.first_name,c]);const M=N.useMemo(()=>A.split(/\n\n+/).map(Y=>`

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

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

A note from ${p}

${M}

Update Your Info

Takes about a minute — promise

Share My Info →

${g}

Sent with care by ${p}

Powered by ReLevelUp

`,z=async()=>{if(!l){ae.error("Set up your Connect Page first",{action:{label:"Set Up",onClick:()=>a("/mission-control/connect-page")}});return}if(!b.trim()||!A.trim()){ae.error("Subject and message are required");return}D(!0);const Y=F();try{if(v==="gmail"&&c){const{data:K,error:J}=await q.functions.invoke("gmail-send",{body:{to:n.email,subject:b,body:Y,contactId:n.id}});if(J)throw J;if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Failed to send")}else{const{data:K,error:J}=await q.functions.invoke("send-connect-invite",{body:{contactEmail:n.email,subject:b,htmlBody:Y,replyToEmail:(h==null?void 0:h.email)||(r==null?void 0:r.email),agentName:p}});if(J)throw J;if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Failed to send")}try{await u.mutateAsync({contactId:n.id,actionTypeId:pWs,notes:`Sent Connect Page invite — Subject: "${b}"`})}catch(K){console.warn("Failed to log activity:",K)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),ae.success("Connect Page invite sent!"),t(!1)}catch(K){console.error("Send error:",K),ae.error(K instanceof Error?K.message:"Failed to send invite")}finally{D(!1)}},V=F();return e.jsx(bs,{open:s,onOpenChange:Y=>!L&&t(Y),children:e.jsxs(vs,{className:"sm:max-w-[720px] max-h-[92vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Send Connect Page Invite"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Ask ",e.jsxs("span",{className:"font-medium",children:[n.first_name," ",n.last_name||""]})," to share their latest contact info — takes them about a minute."]})]}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(ts,{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(Br,{value:v,onValueChange:Y=>j(Y),className:"mt-1.5",children:e.jsxs(Fr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Kt,{value:"gmail",disabled:!c,children:[e.jsx(Vs,{className:"h-3.5 w-3.5 mr-1.5"}),c?`Gmail (${d})`:"Gmail (not connected)"]}),e.jsxs(Kt,{value:"system",children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"}),"System Email"]})]})}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:v==="gmail"?"Replies go directly to your Gmail inbox.":`Sent from notifications@dashboard.relevelup.com — replies go to ${(h==null?void 0:h.email)||(r==null?void 0:r.email)||"your account email"}.`})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"invite-subject",children:"Subject"}),e.jsx(ye,{id:"invite-subject",value:b,onChange:Y=>S(Y.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"invite-message",children:"Personal Message"}),e.jsx(Es,{id:"invite-message",value:A,onChange:Y=>T(Y.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:g,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["Open Connect Page ",e.jsx(tr,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"rounded-lg border overflow-hidden bg-muted/30",children:e.jsx("iframe",{srcDoc:V,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:L,children:"Cancel"}),e.jsx(B,{onClick:z,disabled:L,children:L?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-1.5 animate-spin"})," Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-1.5"})," Send Invite"]})})]})]}):e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx(Gi,{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(El,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function xWs(){const{user:s}=ys();return ct({queryKey:["cmas",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("cmas").select("*").eq("agent_id",s.id).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function gWs(s){return ct({queryKey:["cma",s],queryFn:async()=>{const{data:t,error:n}=await q.from("cmas").select("*").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function yWs(s){return ct({queryKey:["cma-comps",s],queryFn:async()=>{const{data:t,error:n}=await q.from("cma_comps").select("*").eq("cma_id",s).order("position",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function H_t(){const s=Ht(),{user:t}=ys(),{leadSite:n}=Ip();return gt({mutationFn:async r=>{const{data:a,error:i}=await q.from("cmas").insert({agent_id:t.id,lead_site_id:(n==null?void 0:n.id)??null,contact_id:r.contactId??null,deal_id:r.dealId??null,buyer_mode:!!r.buyerMode,title:r.title??r.subject.address,subject:r.subject,settings:{sqftPct:.2,monthsBack:6,statuses:["Active","Pending","Closed"]}}).select("*").single();if(i)throw i;return a},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function vWs(){const s=Ht();return gt({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await q.from("cmas").update(n).eq("id",t).select("*").single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["cma",n.id]}),s.invalidateQueries({queryKey:["cmas"]})}})}function bWs(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("cmas").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function _Ws(){const{leadSite:s}=Ip();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("cma-subject-lookup",{body:{...t,leadSiteId:(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function wWs(){const{leadSite:s}=Ip();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("cma-comp-search",{body:{...t,leadSiteId:t.leadSiteId??(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function jWs(){const s=Ht();return gt({mutationFn:async({cmaId:t,comps:n})=>{if(await q.from("cma_comps").delete().eq("cma_id",t),!n.length)return;const r=n.map((i,l)=>({cma_id:t,mls_number:i.mlsNumber??null,source_provider:i.source_provider??null,selected:i.selected!==!1,manual:!!i.manual,score:i.score??null,position:l,snapshot:i})),{error:a}=await q.from("cma_comps").insert(r);if(a)throw a},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["cma-comps",n.cmaId]})})}function BZe(s,t){const n=t.filter(h=>{var p,f;return h.selected!==!1&&(((p=h.snapshot)==null?void 0:p.sqft)||h.sqft)&&(((f=h.snapshot)==null?void 0:f.price)||h.price)});if(!n.length||!s.sqft)return{low:null,likely:null,high:null,ppsf:null};const r=n.map(h=>{const p=h.snapshot||h;return(p.soldPrice||p.price)/p.sqft}).filter(h=>Number.isFinite(h)&&h>0).sort((h,p)=>h-p);if(!r.length)return{low:null,likely:null,high:null,ppsf:null};const a=r[Math.floor(r.length/2)],i=r.reduce((h,p)=>h+p,0)/r.length,l=r.reduce((h,p)=>h+(p-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 NWs(s){return ct({queryKey:["contact-video-replies",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("video_replies").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url) `).eq("contact_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function kWs(s){return ct({queryKey:["client-portal",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("client_portals").select("*").eq("deal_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function vLe(){const s=ma(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("client_portals").insert({deal_id:n.deal_id,owner_user_id:s,slug:"",is_enabled:n.is_enabled??!0,visibility:n.visibility||"private",require_onboarding:n.require_onboarding??!0,allow_spouse:n.allow_spouse??!1,client_name:n.client_name||null,client_email:n.client_email||null,client_phone:n.client_phone||null,invite_method:n.invite_method||"email"}).select().single();if(a)throw a;return r},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["client-portal",r.deal_id]})}})}function jR(){const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("client_portals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function G_t(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("client_portals").update({archived_at:new Date().toISOString(),is_enabled:!1}).eq("id",t).select().single();if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function W_t(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("client_portals").update({archived_at:null}).eq("id",t).select().single();if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function K_t(){const s=Ht();return gt({mutationFn:async({id:t,dealId:n})=>{await q.from("portal_updates").delete().eq("portal_id",t);const{error:r}=await q.from("client_portals").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function SWs(s){return ct({queryKey:["portal-updates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("portal_updates").select("*").eq("portal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function Y_t(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("portal_updates").insert({portal_id:t.portal_id,title:t.title,content:t.content||null,video_url:t.video_url||null,is_stage_change:t.is_stage_change||!1}).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["portal-updates",n.portal_id]})}})}function CWs(){const s=ma();return ct({queryKey:["portal-custom-questions",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("portal_custom_questions").select("*").eq("owner_user_id",s).eq("is_active",!0).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function TWs(){const s=ma(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("portal_custom_questions").insert({owner_user_id:s,question_text:n.question_text,field_type:n.field_type,options:n.options||[],is_required:n.is_required||!1,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function EWs(){const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("portal_custom_questions").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function AWs(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("portal_custom_questions").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function Tw(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function MWs({contactId:s}){const t=Mn(),n=Ht(),[r,a]=N.useState(null),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(null),_=jR(),v=Y_t(),{data:j,isLoading:b}=ct({queryKey:["contact-portals",s],queryFn:async()=>{const{data:M,error:F}=await q.from("deal_pipeline").select("id, deal_name, deal_type").eq("contact_id",s);if(F)throw F;if(!M||M.length===0)return[];const z=M.map(Y=>Y.id),{data:V,error:W}=await q.from("client_portals").select("*").in("deal_id",z).is("archived_at",null);if(W)throw W;return(V||[]).map(Y=>({...Y,deal:M.find(K=>K.id===Y.deal_id)}))},enabled:!!s}),S=(j==null?void 0:j.map(M=>M.id))||[],{data:A}=ct({queryKey:["contact-portal-updates",S],queryFn:async()=>{if(S.length===0)return{};const{data:M,error:F}=await q.from("portal_updates").select("*").in("portal_id",S).order("created_at",{ascending:!1});if(F)throw F;const z={};return(M||[]).forEach(V=>{z[V.portal_id]||(z[V.portal_id]=V)}),z},enabled:S.length>0}),T=M=>{navigator.clipboard.writeText(Tw(M)),a(M),ae.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},L=async M=>{d.trim()&&(await v.mutateAsync({portal_id:M,title:d,content:h||void 0}),c(!1),u(""),p(""),n.invalidateQueries({queryKey:["contact-portal-updates"]}),ae.success("Portal update posted!"))},D=async()=>{f&&(await _.mutateAsync({id:f.id,welcome_message:f.welcome_message,next_step_text:f.next_step_text,is_enabled:f.is_enabled,show_post_close_tips:f.show_post_close_tips,review_url:f.review_url}),l(!1),g(null),n.invalidateQueries({queryKey:["contact-portals",s]}),ae.success("Portal settings updated!"))};return b||!j||j.length===0?null:e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(lc,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(Ee,{className:"space-y-3",children:j.map(M=>{var W,Y,K;const F=((W=M.stage_mapping)==null?void 0:W.length)>0?M.stage_mapping:Mye(((Y=M.deal)==null?void 0:Y.deal_type)||"buyer"),z=F==null?void 0:F[M.current_stage_index??0],V=A==null?void 0:A[M.id];return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:((K=M.deal)==null?void 0:K.deal_name)||"Portal"}),z&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Stage: ",z.label||z.name]})]}),e.jsx(ze,{variant:M.is_enabled?"default":"secondary",className:"text-[10px] flex-shrink-0",children:M.is_enabled?"Active":"Disabled"})]}),V&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-2",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:V.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Ss(new Date(V.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>T(M.slug),children:[r===M.slug?e.jsx(Ir,{className:"h-3 w-3 mr-1"}):e.jsx(Xr,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(Tw(M.slug),"_blank"),children:[e.jsx(tr,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(bs,{open:o,onOpenChange:c,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>c(!0),children:[e.jsx(Ei,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{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:J=>u(J.target.value),placeholder:"e.g. Inspection completed!"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Details (optional)"}),e.jsx(Es,{value:h,onChange:J=>p(J.target.value),placeholder:"Add more details...",rows:3})]}),e.jsxs(B,{onClick:()=>L(M.id),disabled:!d.trim()||v.isPending,className:"w-full",children:[e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(bs,{open:i,onOpenChange:l,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{g({...M}),l(!0)},children:[e.jsx(Xo,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Portal Settings"})}),f&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Portal Enabled"}),e.jsx(bn,{checked:f.is_enabled,onCheckedChange:J=>g({...f,is_enabled:J})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Welcome Message"}),e.jsx(Es,{value:f.welcome_message||"",onChange:J=>g({...f,welcome_message:J.target.value}),placeholder:"Welcome to your home journey!",rows:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Next Step"}),e.jsx(ye,{value:f.next_step_text||"",onChange:J=>g({...f,next_step_text:J.target.value}),placeholder:"What your client should do next..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Review URL"}),e.jsx(ye,{value:f.review_url||"",onChange:J=>g({...f,review_url:J.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Show Post-Close Tips"}),e.jsx(bn,{checked:f.show_post_close_tips,onCheckedChange:J=>g({...f,show_post_close_tips:J})})]}),e.jsx(ll,{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{onClick:D,disabled:_.isPending,className:"flex-1",children:"Save Settings"}),e.jsxs(B,{variant:"outline",onClick:()=>t(`/mission-control/pipeline?deal=${M.deal_id}`),children:[e.jsx(Oa,{className:"h-4 w-4 mr-1"}),"Full Settings"]})]})]})]})]})]}),j.length>1&&e.jsx(ll,{})]},M.id)})})]})}function IWs({contactId:s}){const{data:t}=ct({queryKey:["agent-lead-sites-slugs"],queryFn:async()=>{const{data:l,error:o}=await q.from("lead_sites").select("id, subdomain_slug").eq("is_active",!0);if(o)throw o;return new Map((l||[]).map(c=>[c.id,c.subdomain_slug]))},staleTime:6e5}),n=t&&t.size>0,{data:r,isLoading:a}=ct({queryKey:["contact-property-views",s],queryFn:async()=>{const{data:l,error:o}=await q.rpc("get_contact_property_views",{p_contact_id:s});if(o)throw o;return l||[]},enabled:!!s&&!!n});if(!n||a||!r||r.length===0)return null;const i=l=>{const o=t==null?void 0:t.get(l.lead_site_id);return o?`https://${o}.thelocalmove.com/listing/${l.mls_number}`:null};return e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:"h-7 w-7 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(Er,{className:"h-4 w-4 text-primary"})}),"Property Activity",e.jsxs(ze,{variant:"secondary",className:"text-xs ml-auto",children:[r.length," ",r.length===1?"property":"properties"]})]})}),e.jsx(Ee,{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(Or,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("span",{className:"font-medium text-sm truncate",children:c})}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(gr,{className:"h-3 w-3"}),e.jsx("span",{title:Ss(new Date(l.viewed_at),"PPp"),children:Vo(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 PWs=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function $Ze({value:s,onChange:t,onAdd:n,suggestions:r,placeholder:a,icon:i}){const[l,o]=N.useState(!1),c=N.useRef(null),d=N.useRef(null);N.useEffect(()=>{const h=p=>{d.current&&!d.current.contains(p.target)&&c.current&&!c.current.contains(p.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(io,{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(Is,{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(ka,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),h]},h))})]})}function LWs({contactId:s,contactName:t}){var le,ve,ge;const{user:n}=ys(),r=ma(),{hasLeadSite:a}=Ip(),i=Ht(),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState(!1),[g,_]=N.useState(""),[v,j]=N.useState(null),[b,S]=N.useState(!1),[A,T]=N.useState(!1),{data:L}=ct({queryKey:["agent-lead-site-config",r],queryFn:async()=>{const{data:Te,error:Me}=await q.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",r).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(Me||!Te)return{cities:[],zipCodes:[]};const Ce=Te.theme_config||{},Ae=Array.isArray(Ce.searchCities)?Ce.searchCities:[];Te.mls_market_area&&!Ae.includes(Te.mls_market_area)&&Ae.unshift(Te.mls_market_area);const De=Array.isArray(Ce.searchZipCodes)?Ce.searchZipCodes:[];return{cities:Ae,zipCodes:De}},enabled:!!r}),{data:D,isLoading:M}=ct({queryKey:["contact-property-alert",s],queryFn:async()=>{const{data:Te,error:Me}=await q.from("contact_property_alerts").select("*").eq("contact_id",s).maybeSingle();if(Me)throw Me;return Te},enabled:!!s&&!!n}),[F,z]=N.useState({}),V=()=>{z({is_active:(D==null?void 0:D.is_active)??!0,min_price:(D==null?void 0:D.min_price)??null,max_price:(D==null?void 0:D.max_price)??null,min_beds:(D==null?void 0:D.min_beds)??null,min_baths:(D==null?void 0:D.min_baths)??null,min_sqft:(D==null?void 0:D.min_sqft)??null,max_sqft:(D==null?void 0:D.max_sqft)??null,cities:(D==null?void 0:D.cities)??[],zip_codes:(D==null?void 0:D.zip_codes)??[],property_types:(D==null?void 0:D.property_types)??[],frequency:(D==null?void 0:D.frequency)??"daily"}),o(!0)},W=gt({mutationFn:async()=>{const Te={contact_id:s,owner_user_id:r,is_active:F.is_active??!0,min_price:F.min_price||null,max_price:F.max_price||null,min_beds:F.min_beds||null,min_baths:F.min_baths||null,min_sqft:F.min_sqft||null,max_sqft:F.max_sqft||null,cities:F.cities||[],zip_codes:F.zip_codes||[],property_types:F.property_types||[],frequency:F.frequency||"daily"};if(D!=null&&D.id){const{error:Me}=await q.from("contact_property_alerts").update(Te).eq("id",D.id);if(Me)throw Me}else{const{error:Me}=await q.from("contact_property_alerts").insert(Te);if(Me)throw Me}},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),ae.success("Property alert saved!")},onError:Te=>{ae.error(Te.message||"Failed to save alert")}}),Y=gt({mutationFn:async()=>{if(!(D!=null&&D.id))return;const{error:Te}=await q.from("contact_property_alerts").delete().eq("id",D.id);if(Te)throw Te},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),ae.success("Property alert removed")}}),K=Te=>{var Ce;const Me=Te.trim();Me&&!((Ce=F.cities)!=null&&Ce.includes(Me))&&z(Ae=>({...Ae,cities:[...Ae.cities||[],Me]})),d("")},J=Te=>{var Ce;const Me=Te.trim();Me&&!((Ce=F.zip_codes)!=null&&Ce.includes(Me))&&z(Ae=>({...Ae,zip_codes:[...Ae.zip_codes||[],Me]})),h("")},ne=Te=>{z(Me=>{const Ce=Me.property_types||[];return{...Me,property_types:Ce.includes(Te)?Ce.filter(Ae=>Ae!==Te):[...Ce,Te]}})},ie=async()=>{if(D!=null&&D.id){S(!0),f(!0),_(""),j(null);try{const{data:Te,error:Me}=await q.functions.invoke("process-property-alerts",{body:{alert_id:D.id,mode:"preview"}});if(Me)throw Me;Te!=null&&Te.html?(_(Te.html),j({count:Te.listings_count||0,recipient:Te.recipient,subject:Te.subject})):j({count:0,message:(Te==null?void 0:Te.message)||"No matching listings found right now."})}catch(Te){ae.error(Te.message||"Failed to generate preview"),f(!1)}finally{S(!1)}}},he=async()=>{if(D!=null&&D.id&&confirm(`Send property alert email to ${t} now?`)){T(!0);try{const{data:Te,error:Me}=await q.functions.invoke("process-property-alerts",{body:{alert_id:D.id,mode:"send"}});if(Me)throw Me;Te!=null&&Te.sent_count?(ae.success(`Sent ${Te.sent_count} ${Te.sent_count===1?"listing":"listings"} to ${Te.recipient}`),i.invalidateQueries({queryKey:["contact-property-alert",s]})):ae.info((Te==null?void 0:Te.message)||"No new matching listings to send right now.")}catch(Te){ae.error(Te.message||"Failed to send alert")}finally{T(!1)}}};if(!a||M)return null;if(D&&!l)return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:`h-7 w-7 rounded-lg flex items-center justify-center ${D.is_active?"bg-green-500/10":"bg-muted"}`,children:D.is_active?e.jsx(im,{className:"h-4 w-4 text-green-600"}):e.jsx(pw,{className:"h-4 w-4 text-muted-foreground"})}),"Property Alerts",e.jsxs(ze,{variant:D.is_active?"default":"secondary",className:"text-xs ml-auto",children:[D.is_active?"Active":"Paused"," · ",D.frequency]})]})}),e.jsxs(Ee,{className:"pt-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-xs",children:[D.min_price||D.max_price?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Zl,{className:"h-3 w-3"}),D.min_price?`$${(D.min_price/1e3).toFixed(0)}k`:"$0"," - ",D.max_price?`$${(D.max_price/1e3).toFixed(0)}k`:"Any"]}):null,D.min_beds?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(H2,{className:"h-3 w-3"}),D.min_beds,"+ beds"]}):null,D.min_baths?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Cp,{className:"h-3 w-3"}),D.min_baths,"+ baths"]}):null,(le=D.cities)==null?void 0:le.map(Te=>e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(ka,{className:"h-3 w-3"}),Te]},Te)),(ve=D.zip_codes)==null?void 0:ve.map(Te=>e.jsx(ze,{variant:"outline",children:Te},Te)),(ge=D.property_types)==null?void 0:ge.map(Te=>e.jsx(ze,{variant:"outline",children:Te},Te))]}),D.last_sent_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sent: ",new Date(D.last_sent_at).toLocaleDateString()]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:ie,disabled:b,children:[b?e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Er,{className:"h-4 w-4 mr-1"}),"Preview Email"]}),e.jsxs(B,{size:"sm",onClick:he,disabled:A||!D.is_active,title:D.is_active?"Send this alert email now":"Activate alert to send",children:[A?e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Send Now"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:V,children:"Manage Alert"}),e.jsxs(B,{variant:"destructive",size:"sm",onClick:()=>Y.mutate(),disabled:Y.isPending,children:[Y.isPending?e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Bn,{className:"h-4 w-4 mr-1"}),"Remove"]})]})]})]}),e.jsx(bs,{open:p,onOpenChange:f,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Property Alert Email Preview"}),(v==null?void 0:v.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:"})," ",v.recipient]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Subject:"})," ",v.subject]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Listings:"})," ",v.count]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden border rounded-md bg-muted/30",children:b?e.jsxs("div",{className:"flex items-center justify-center h-96 text-muted-foreground",children:[e.jsx(ts,{className:"h-5 w-5 mr-2 animate-spin"})," Building preview…"]}):g?e.jsx("iframe",{srcDoc:g,title:"Property alert preview",className:"w-full h-[65vh] bg-white rounded-md"}):e.jsx("div",{className:"flex items-center justify-center h-96 text-sm text-muted-foreground p-6 text-center",children:(v==null?void 0:v.message)||"No matching listings found right now."})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>f(!1),children:"Close"}),g&&e.jsxs(B,{onClick:()=>{f(!1),he()},disabled:A||!D.is_active,children:[e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Send to ",t]})]})]})})]});const ce=((L==null?void 0:L.cities)||[]).filter(Te=>{var Me;return!((Me=F.cities)!=null&&Me.includes(Te))}),pe=((L==null?void 0:L.zipCodes)||[]).filter(Te=>{var Me;return!((Me=F.zip_codes)!=null&&Me.includes(Te))});return l?e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(im,{className:"h-4 w-4 text-primary"}),D?"Edit":"Setup"," Property Alert for ",t]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Alert Active"}),e.jsx(bn,{checked:F.is_active??!0,onCheckedChange:Te=>z(Me=>({...Me,is_active:Te}))})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Zl,{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:F.min_price??"",onChange:Te=>z(Me=>({...Me,min_price:Te.target.value?Number(Te.target.value):null}))}),e.jsx(ye,{type:"number",placeholder:"Max price",value:F.max_price??"",onChange:Te=>z(Me=>({...Me,max_price:Te.target.value?Number(Te.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(H2,{className:"h-3.5 w-3.5"})," Min Beds"]}),e.jsxs(ds,{value:F.min_beds?String(F.min_beds):"any",onValueChange:Te=>z(Me=>({...Me,min_beds:Te==="any"?null:Number(Te)})),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Any"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"any",children:"Any"}),[1,2,3,4,5].map(Te=>e.jsxs(Qe,{value:String(Te),children:[Te,"+"]},Te))]})]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Cp,{className:"h-3.5 w-3.5"})," Min Baths"]}),e.jsxs(ds,{value:F.min_baths?String(F.min_baths):"any",onValueChange:Te=>z(Me=>({...Me,min_baths:Te==="any"?null:Number(Te)})),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Any"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"any",children:"Any"}),[1,1.5,2,2.5,3,4].map(Te=>e.jsxs(Qe,{value:String(Te),children:[Te,"+"]},Te))]})]})]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(J2,{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:F.min_sqft??"",onChange:Te=>z(Me=>({...Me,min_sqft:Te.target.value?Number(Te.target.value):null}))}),e.jsx(ye,{type:"number",placeholder:"Max sqft",value:F.max_sqft??"",onChange:Te=>z(Me=>({...Me,max_sqft:Te.target.value?Number(Te.target.value):null}))})]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx($Ze,{value:c,onChange:d,onAdd:K,suggestions:ce,placeholder:"Type to search cities..."}),F.cities&&F.cities.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:F.cities.map(Te=>e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[Te,e.jsx("button",{onClick:()=>z(Me=>{var Ce;return{...Me,cities:(Ce=Me.cities)==null?void 0:Ce.filter(Ae=>Ae!==Te)}}),children:e.jsx(Bn,{className:"h-3 w-3"})})]},Te))})]}),e.jsxs("div",{children:[e.jsx(se,{className:"mb-1.5",children:"Zip Codes"}),e.jsx($Ze,{value:u,onChange:h,onAdd:J,suggestions:pe,placeholder:"Type to search zip codes...",icon:e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"#"})}),F.zip_codes&&F.zip_codes.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:F.zip_codes.map(Te=>e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[Te,e.jsx("button",{onClick:()=>z(Me=>{var Ce;return{...Me,zip_codes:(Ce=Me.zip_codes)==null?void 0:Ce.filter(Ae=>Ae!==Te)}}),children:e.jsx(Bn,{className:"h-3 w-3"})})]},Te))})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Or,{className:"h-3.5 w-3.5"})," Property Types"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:PWs.map(Te=>{var Me;return e.jsx(ze,{variant:(Me=F.property_types)!=null&&Me.includes(Te)?"default":"outline",className:"cursor-pointer",onClick:()=>ne(Te),children:Te},Te)})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"mb-1.5",children:"Frequency"}),e.jsxs(ds,{value:F.frequency||"daily",onValueChange:Te=>z(Me=>({...Me,frequency:Te})),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"daily",children:"Daily"}),e.jsx(Qe,{value:"weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{onClick:()=>W.mutate(),disabled:W.isPending,className:"flex-1",children:[W.isPending?e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(qo,{className:"h-4 w-4 mr-1"}),"Save Alert"]}),e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),D&&e.jsx(B,{variant:"destructive",size:"icon",onClick:()=>Y.mutate(),disabled:Y.isPending,children:e.jsx(Bn,{className:"h-4 w-4"})})]})]})]}):e.jsx(fe,{className:"overflow-hidden",children:e.jsx(Ee,{className:"p-4",children:e.jsxs("button",{onClick:V,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(im,{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 DWs({contactId:s,contactName:t}){var ne;const{user:n}=ys(),r=ma(),{hasLeadSite:a}=Ip(),i=Ht(),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState([]),[p,f]=N.useState(!1),[g,_]=N.useState(!1),[v,j]=N.useState(!1),[b,S]=N.useState(""),A=N.useRef(null),T=N.useRef(null),{data:L}=ct({queryKey:["agent-lead-site-cities",r],queryFn:async()=>{const{data:ie,error:he}=await q.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",r).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(he||!ie)return[];const ce=ie.theme_config||{},pe=Array.isArray(ce.searchCities)?ce.searchCities:[];return ie.mls_market_area&&!pe.includes(ie.mls_market_area)&&pe.unshift(ie.mls_market_area),pe},enabled:!!r}),{data:D,isLoading:M}=ct({queryKey:["contact-market-report",s],queryFn:async()=>{const{data:ie,error:he}=await q.from("innercircle_contacts").select("market_report_enabled, market_report_cities").eq("id",s).single();if(he)throw he;return ie},enabled:!!s&&!!n});N.useEffect(()=>{const ie=he=>{T.current&&!T.current.contains(he.target)&&A.current&&!A.current.contains(he.target)&&_(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[]);const F=()=>{f((D==null?void 0:D.market_report_enabled)??!1),h((D==null?void 0:D.market_report_cities)??[]),o(!0)},z=ie=>{const he=(ie||c).trim();he&&!u.includes(he)&&h([...u,he]),d(""),_(!1)},V=(L||[]).filter(ie=>!u.includes(ie)&&ie.toLowerCase().includes(c.toLowerCase())),W=gt({mutationFn:async()=>{const{data:ie,error:he}=await q.functions.invoke("send-market-report",{body:{action:"preview",agentId:r,cities:(D==null?void 0:D.market_report_cities)??[]}});if(he)throw new Error(he.message||"Failed to generate preview");if(ie&&!ie.ok&&ie.error)throw new Error(ie.error);return ie},onSuccess:ie=>{S(ie.html),j(!0)},onError:ie=>{ae.error(ie.message||"Failed to generate preview")}}),Y=gt({mutationFn:async()=>{const{data:ie,error:he}=await q.functions.invoke("send-market-report",{body:{action:"send",agentId:r,cities:(D==null?void 0:D.market_report_cities)??[],contactIds:[s]}});if(he)throw new Error(he.message||"Failed to send report");if(ie&&!ie.ok&&ie.error)throw new Error(ie.error);return ie},onSuccess:()=>{ae.success(`Market report sent to ${t}!`)},onError:ie=>{ae.error(ie.message||"Failed to send report")}}),K=gt({mutationFn:async()=>{const{error:ie}=await q.from("innercircle_contacts").update({market_report_enabled:p,market_report_cities:u}).eq("id",s);if(ie)throw ie},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),ae.success(p?"Monthly market report enabled!":"Market report disabled")},onError:ie=>{ae.error(ie.message||"Failed to save")}}),J=gt({mutationFn:async()=>{const{error:ie}=await q.from("innercircle_contacts").update({market_report_enabled:!1,market_report_cities:[]}).eq("id",s);if(ie)throw ie},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),f(!1),h([]),ae.success("Market report removed")},onError:ie=>{ae.error(ie.message||"Failed to remove market report")}});return!a||M?null:D!=null&&D.market_report_enabled&&!l?e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:"h-7 w-7 rounded-lg flex items-center justify-center bg-primary/10",children:e.jsx(yo,{className:"h-4 w-4 text-primary"})}),"Monthly Market Report",e.jsx(ze,{variant:"default",className:"text-xs ml-auto",children:"Active"})]})}),e.jsxs(Ee,{className:"pt-0 space-y-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5 text-xs",children:((ne=D.market_report_cities)==null?void 0:ne.length)>0?D.market_report_cities.map(ie=>e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(ka,{className:"h-3 w-3"}),ie]},ie)):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:()=>W.mutate(),disabled:W.isPending,className:"flex-1",children:[W.isPending?e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Er,{className:"h-4 w-4 mr-1"}),"Preview"]}),e.jsxs(B,{variant:"default",size:"sm",onClick:()=>Y.mutate(),disabled:Y.isPending,className:"flex-1",children:[Y.isPending?e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(cr,{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:F,className:"flex-1",children:"Manage"}),e.jsxs(B,{variant:"destructive",size:"sm",onClick:()=>J.mutate(),disabled:J.isPending,className:"flex-1",children:[J.isPending?e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Bn,{className:"h-4 w-4 mr-1"}),"Remove"]})]}),e.jsx(bs,{open:v,onOpenChange:j,children:e.jsxs(vs,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(yo,{className:"h-5 w-5 text-primary"}),"Market Report Preview"]})}),e.jsx("div",{className:"flex-1 overflow-y-auto -mx-6 px-6",children:e.jsx("div",{className:"border rounded-lg overflow-hidden",dangerouslySetInnerHTML:{__html:b}})}),e.jsxs("div",{className:"flex gap-2 pt-4 border-t",children:[e.jsxs(B,{onClick:()=>{j(!1),Y.mutate()},disabled:Y.isPending,className:"flex-1",children:[Y.isPending?e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(cr,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx(B,{variant:"outline",onClick:()=>j(!1),children:"Close"})]})]})})]})]}):l?e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(yo,{className:"h-4 w-4 text-primary"}),"Market Report for ",t]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Send Monthly Report"}),e.jsx(bn,{checked:p,onCheckedChange:f})]}),p&&e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ka,{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:A,value:c,onChange:ie=>{d(ie.target.value),_(!0)},onFocus:()=>_(!0),placeholder:"Type to search cities...",onKeyDown:ie=>{ie.key==="Enter"&&(ie.preventDefault(),V.length>0?z(V[0]):z())}}),e.jsx(io,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none"})]}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:()=>z(),children:e.jsx(Is,{className:"h-4 w-4"})})]}),g&&V.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:V.map(ie=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors flex items-center gap-2",onClick:()=>z(ie),children:[e.jsx(ka,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),ie]},ie))})]}),u.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:u.map(ie=>e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[ie,e.jsx("button",{onClick:()=>h(u.filter(he=>he!==ie)),children:e.jsx(Bn,{className:"h-3 w-3"})})]},ie))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{onClick:()=>K.mutate(),disabled:K.isPending,className:"flex-1",children:[K.isPending?e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(qo,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"})]})]})]}):e.jsx(fe,{className:"overflow-hidden",children:e.jsx(Ee,{className:"p-4",children:e.jsxs("button",{onClick:F,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(yo,{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 RWs(s){return ct({queryKey:["contact-drip-activity",s],queryFn:async()=>{if(!s)return{enrollments:[],stepLogs:[]};const{data:t,error:n}=await q.from("drip_campaign_enrollments").select("id, campaign_id, current_step, status, next_send_at, enrolled_at, completed_at, exited_at, exit_reason").eq("contact_id",s).order("enrolled_at",{ascending:!1});if(n)throw console.error("[ContactDripActivity] enrollments error",n),n;const r=(t||[]).map(c=>c.id),a=Array.from(new Set((t||[]).map(c=>c.campaign_id)));let i=new Map;if(a.length>0){const{data:c}=await q.from("drip_campaigns").select("id, name, description, is_active").in("id",a);(c||[]).forEach(d=>i.set(d.id,d))}const l=(t||[]).map(c=>({...c,campaign:i.get(c.campaign_id)||null}));let o=[];if(r.length>0){const{data:c,error:d}=await q.from("drip_campaign_step_log").select("id, enrollment_id, campaign_id, step_order, channel, recipient_email, subject, status, error_message, sent_at").in("enrollment_id",r).order("sent_at",{ascending:!1});d?console.error("[ContactDripActivity] step log error",d):o=(c||[]).map(u=>{var h;return{...u,campaign:{name:((h=i.get(u.campaign_id))==null?void 0:h.name)??""}}})}return{enrollments:l,stepLogs:o}},enabled:!!s})}function OWs(s){switch(s){case"active":return e.jsx(ze,{variant:"secondary",className:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",children:"Active"});case"paused":return e.jsx(ze,{variant:"secondary",className:"bg-amber-500/10 text-amber-600 border-amber-500/20",children:"Paused"});case"completed":return e.jsx(ze,{variant:"secondary",className:"bg-sky-500/10 text-sky-600 border-sky-500/20",children:"Completed"});case"exited":return e.jsx(ze,{variant:"outline",children:"Exited"});default:return e.jsx(ze,{variant:"outline",children:s})}}function UZe(s){return s==="sent"?e.jsx(xr,{className:"h-4 w-4 text-emerald-500"}):s==="failed"?e.jsx($l,{className:"h-4 w-4 text-destructive"}):s==="skipped"?e.jsx(bf,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(gr,{className:"h-4 w-4 text-muted-foreground"})}function FWs({contactId:s}){const t=Mn(),{data:n,isLoading:r}=RWs(s),[a,i]=N.useState(null);if(r)return null;const l=(n==null?void 0:n.enrollments)||[],o=(n==null?void 0:n.stepLogs)||[];return l.length===0&&o.length===0?null:e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(UA,{className:"h-5 w-5 text-emerald-500"}),"Drip Campaign Activity"]})}),e.jsxs(Ee,{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(UA,{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"}),OWs(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: ",Vo(new Date(c.next_send_at),{addSuffix:!0})]}),c.completed_at&&e.jsxs(e.Fragment,{children:[" · Completed ",Vo(new Date(c.completed_at),{addSuffix:!0})]}),c.exited_at&&!c.completed_at&&e.jsxs(e.Fragment,{children:[" · ",c.exit_reason||"Exited"," ",Vo(new Date(c.exited_at),{addSuffix:!0})]})]})]}),e.jsx(xa,{className:"h-4 w-4 text-muted-foreground mt-1 flex-shrink-0"})]},c.id)})]}),o.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Send History (",o.length,")"]}),e.jsxs("div",{className:"space-y-1",children:[o.slice(0,8).map(c=>{var d,u;return e.jsxs(bs,{open:(a==null?void 0:a.id)===c.id,onOpenChange:h=>!h&&i(null),children:[e.jsx(Ai,{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:UZe(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(Ei,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}):e.jsx(Vs,{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"," · ",Ss(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(vs,{className:"max-w-lg",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[UZe(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:Ss(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 Z_t({contactId:s}={}){const{user:t}=ys();return ct({queryKey:["sent-emails",t==null?void 0:t.id,s??"all"],enabled:!!t,queryFn:async()=>{const n=t.id;let r=q.from("gmail_sent_emails").select("id, contact_id, to_email, subject, sent_at, source").eq("user_id",n).or("source.is.null,source.neq.drip_campaign").order("sent_at",{ascending:!1}).limit(1e3);s&&(r=r.eq("contact_id",s));let a=q.from("bulk_email_sends").select("id, contact_id, contact_email, subject, sent_at, source, opened_at, clicked_at").eq("user_id",n).order("sent_at",{ascending:!1}).limit(1e3);s&&(a=a.eq("contact_id",s));const i=await q.from("email_campaigns").select("id, subject").eq("user_id",n),l=(i.data||[]).map(_=>_.id),o=new Map((i.data||[]).map(_=>[_.id,_.subject]));let c=[];if(l.length>0){let _=q.from("email_campaign_recipients").select("id, contact_id, email, sent_at, campaign_id, opened_at, clicked_at").in("campaign_id",l).eq("status","sent").not("sent_at","is",null).order("sent_at",{ascending:!1}).limit(1e3);s&&(_=_.eq("contact_id",s)),c=(await _).data||[]}const[d,u]=await Promise.all([r,a]),h=(d.data||[]).map(_=>({id:`g-${_.id}`,channel:_.source==="portal_invite"?"Client Portal Invite":"Gmail",subject:_.subject,to_email:_.to_email,contact_id:_.contact_id,sent_at:_.sent_at,source:_.source})),p=(u.data||[]).map(_=>({id:`b-${_.id}`,channel:"Mass Email",subject:_.subject,to_email:_.contact_email,contact_id:_.contact_id,sent_at:_.sent_at,source:_.source,opened_at:_.opened_at,clicked_at:_.clicked_at})),f=c.map(_=>({id:`c-${_.id}`,channel:"Campaign",subject:o.get(_.campaign_id)||"(campaign)",to_email:_.email,contact_id:_.contact_id,sent_at:_.sent_at,source:null,campaign_id:_.campaign_id,opened_at:_.opened_at,clicked_at:_.clicked_at})),g=[...h,...p,...f];return g.sort((_,v)=>_.sent_at0&&e.jsx(ze,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(Ee,{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(Vs,{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(ze,{variant:"outline",className:`text-xs ${zWs[l.channel]}`,children:l.channel}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(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(Ln,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}function $Ws({videoId:s}){var l;const{data:t,isLoading:n,error:r}=AGs(s);if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"w-full aspect-video rounded-lg"}),e.jsx(Ws,{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($l,{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 UWs({contactId:s}){const t=Mn(),[n,r]=N.useState(!1),{data:a,isLoading:i}=ct({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:p}=await q.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(p)throw p;return h},enabled:!!s}),l=async(h,p)=>{const f=p==="done"?"todo":"done";await q.from("deal_tasks").update({status:f,completed_at:f==="done"?new Date().toISOString():null}).eq("id",h),window.dispatchEvent(new CustomEvent("refetch-contact-tasks"))},{refetch:o}=ct({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:p}=await q.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(p)throw p;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(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Ir,{className:"h-4 w-4"}),"Tasks",d.length>0&&e.jsx(ze,{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(Is,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(Ee,{className:"space-y-1",children:i?e.jsx(Ws,{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:Ss(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(qWs,{contactId:s,open:n,onOpenChange:h=>{r(h),h||o()}})]})}function qWs({contactId:s,open:t,onOpenChange:n}){const[r,a]=N.useState(""),[i,l]=N.useState("medium"),[o,c]=N.useState(),{data:d}=ct({queryKey:["session"],queryFn:async()=>{const{data:h}=await q.auth.getSession();return h.session}}),u=async()=>{var p;if(!r.trim()||!((p=d==null?void 0:d.user)!=null&&p.id))return;const{error:h}=await q.from("deal_tasks").insert([{owner_user_id:d.user.id,contact_id:s,title:r.trim(),priority:i,status:"todo",due_date:o?Ss(o,"yyyy-MM-dd"):null}]);if(h){console.error("Task create error:",h);return}n(!1)};return e.jsx(bs,{open:t,onOpenChange:n,children:e.jsxs(vs,{className:"sm:max-w-[400px]",children:[e.jsx(ws,{children:e.jsx(_s,{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?Ss(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 VWs({contactId:s}){const t=Mn(),{data:n,isLoading:r}=ct({queryKey:["contact-linked-deals",s],queryFn:async()=>{const{data:a,error:i}=await q.from("deal_pipeline").select(` id, deal_name, deal_type, expected_price, property_address, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).eq("contact_id",s).order("updated_at",{ascending:!1});if(i)throw i;return a},enabled:!!s});return r||!n||n.length===0?null:e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(qm,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(Ee,{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(ze,{variant:"outline",className:"text-[10px] capitalize",children:a.deal_type}),i&&e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1",style:{borderColor:i.color,color:i.color,backgroundColor:`${i.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:i.color}}),i.name]})]})]}),e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0"})]})},a.id)})})]})}function HWs(){var Pt,Jt,ft,Vt,Ms;const{contactId:s}=bi(),t=Mn(),[n]=gl(),r=n.get("search")||"",a=n.get("type")||"all",i=n.get("status")||n.get("filter")||"all",l=n.get("tags")||"",o=n.get("tagMode")==="all"?"all":"any",c=N.useMemo(()=>new Set(l.split(",").map(Xt=>Xt.trim()).filter(Boolean)),[l]),{data:d,isLoading:u}=Yns(s||""),{data:h}=Sy(),{data:p}=YD(),{data:f}=pU(3650),{data:g}=I1e(365),{data:_}=NWs(s),{contactsWithScores:v}=Hye(),{data:j}=E1e(),b=g6e(),S=y6e(),A=fU(),T=Qmt(),[L,D]=N.useState(!1),[M,F]=N.useState({}),[z,V]=N.useState(!1),[W,Y]=N.useState(null),[K,J]=N.useState(""),[ne,ie]=N.useState(void 0),[he,ce]=N.useState(""),[pe,le]=N.useState(null),[ve,ge]=N.useState(!1),[Te,Me]=N.useState(null),[Ce,Ae]=N.useState(!1),{isGmailConnected:De,gmailEmail:Ie}=Oh(),{isReady:Fe}=bR(),qe=Fe||De,be=H_t(),[Ze,Ne]=N.useState(!1),{data:it}=ct({queryKey:["cma-eligible"],queryFn:async()=>{const{data:{user:Xt}}=await q.auth.getUser();if(!Xt)return!1;const{data:Js}=await q.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",Xt.id);return(Js||[]).some(Cs=>Cs.is_active&&Cs.mls_provider_id&&!Cs.no_mls_mode)}}),je=async()=>{var rn,tn,er,gn;if(!d)return;const Xt=(rn=d.address)==null?void 0:rn.trim(),Js=(tn=d.city)==null?void 0:tn.trim(),Cs=(er=d.state)==null?void 0:er.trim().toUpperCase(),As=((gn=d.zip_code)==null?void 0:gn.trim())||"";if(!Xt||!Js||!Cs){ae.error("Add a full address (street, city, state) before creating a CMA.");return}try{Ne(!0);const In=await be.mutateAsync({subject:{address:Xt,city:Js,state:Cs,zip:As},contactId:d.id,title:`${d.first_name||""} ${d.last_name||""}`.trim()+" — "+Xt});t(`/mission-control/cma/${In.id}`)}catch(In){ae.error("Could not create CMA: "+((In==null?void 0:In.message)||"unknown error"))}finally{Ne(!1)}},{data:Ge}=ct({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:Xt,error:Js}=await q.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(Js)throw Js;return Xt},enabled:!!s}),Be=Xt=>{if(!Xt)return null;const Js=Xt.match(/Video ID:\s*([a-f0-9-]+)/i);return Js?Js[1]:null},Ye=N.useMemo(()=>{if(!v)return[];const Xt=new Map;if(c.size>0&&j)for(const Cs of j)Xt.has(Cs.contact_id)||Xt.set(Cs.contact_id,new Set),Xt.get(Cs.contact_id).add(Cs.tag_id);let Js=v.filter(Cs=>{var er,gn,In;const As=r===""||`${Cs.first_name} ${Cs.last_name}`.toLowerCase().includes(r.toLowerCase())||((er=Cs.email)==null?void 0:er.toLowerCase().includes(r.toLowerCase()))||((gn=Cs.phone)==null?void 0:gn.includes(r)),rn=a==="all"||((In=Cs.tags)==null?void 0:In.some(Zn=>Zn.relationship_type_id===a));let tn=!0;if(c.size>0){const Zn=Xt.get(Cs.id)||new Set;o==="all"?tn=Array.from(c).every(ea=>Zn.has(ea)):tn=Array.from(c).some(ea=>Zn.has(ea))}return As&&rn&&tn});return i==="not-touched-90"?Js=Js.filter(Cs=>{const As=Cs.relationshipScore.daysSinceTouch;return As===null||As>90}):i==="at-risk"?Js=Js.filter(Cs=>Cs.relationshipScore.status==="at-risk"):i==="cooling"?Js=Js.filter(Cs=>Cs.relationshipScore.status==="cooling"):i==="warm"&&(Js=Js.filter(Cs=>Cs.relationshipScore.status==="warm")),Js.map(Cs=>Cs.id)},[v,r,a,i,c,o,j]),We=Ye.indexOf(s||""),rt=We>0?Ye[We-1]:null,tt=We1&&We!==-1,He=Xt=>{const Js=new URLSearchParams;r&&Js.set("search",r),a!=="all"&&Js.set("type",a),i!=="all"&&Js.set("status",i),c.size>0&&(Js.set("tags",Array.from(c).join(",")),Js.set("tagMode",o));const Cs=Js.toString();return`/mission-control/contacts/${Xt}${Cs?`?${Cs}`:""}`},dt=N.useMemo(()=>{const Xt=((f==null?void 0:f.filter(Cs=>Cs.contact_id===s))||[]).map(Cs=>{var er,gn,In;const As=Be(Cs.notes);let rn=((er=Cs.action_type)==null?void 0:er.name)||"Touch",tn=Cs.notes;if(rn==="Other"&&((gn=Cs.notes)!=null&&gn.startsWith("["))){const Zn=Cs.notes.indexOf("]");Zn>0&&(rn=Cs.notes.substring(1,Zn),tn=Cs.notes.substring(Zn+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:Cs.id,type:"touch",completed_at:Cs.completed_at,name:rn,color:((In=Cs.action_type)==null?void 0:In.color)||"#3B82F6",notes:tn,videoId:As}}),Js=((g==null?void 0:g.filter(Cs=>Cs.contact_id===s))||[]).map(Cs=>({id:Cs.id,type:"popby",completed_at:Cs.completed_at,name:"Pop-by",color:"#F97316",notes:Cs.notes,videoId:null}));return[...Xt,...Js].sort((Cs,As)=>new Date(As.completed_at).getTime()-new Date(Cs.completed_at).getTime())},[f,g,s]),bt=()=>{var Xt;d&&(F({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:((Xt=d.tags)==null?void 0:Xt.map(Js=>Js.relationship_type_id))||[]}),D(!0))},vt=async()=>{await b.mutateAsync({id:s,...M,lead_source_id:M.lead_source_id||null}),D(!1)},Bt=async()=>{confirm("Are you sure you want to delete this contact?")&&(await S.mutateAsync(s),t("/mission-control/contacts"))},Fs=((Pt=p==null?void 0:p.find(Xt=>Xt.id===W))==null?void 0:Pt.name)==="Other",Rs=async()=>{if(!W||Fs&&!he.trim())return;const Xt=ne?new Date(ne.getFullYear(),ne.getMonth(),ne.getDate(),12,0,0).toISOString():void 0,Js=Fs?`[${he.trim()}]${K?" — "+K:""}`:K;await A.mutateAsync({contactId:s,actionTypeId:W,notes:Js,completedAt:Xt}),V(!1),Y(null),J(""),ie(void 0),ce("")},ms=(Xt,Js)=>{qe&&d?(Me({email:Xt,name:Js||`${d.first_name} ${d.last_name||""}`.trim()}),ge(!0)):window.location.href=`mailto:${Xt}`};return u?e.jsx(Ts,{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(Ts,{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(pl,{className:"h-4 w-4 mr-1"}),"Back to Contacts"]}),at&&e.jsxs("div",{className:"flex items-center gap-1 ml-2 border-l pl-2",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>rt&&t(He(rt)),disabled:!rt,className:"px-2",children:[e.jsx(pl,{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:[We+1," of ",Ye.length]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>tt&&t(He(tt)),disabled:!tt,className:"px-2",children:[e.jsx("span",{className:"sr-only sm:not-sr-only sm:mr-1",children:"Next"}),e.jsx(xa,{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.email&&e.jsxs(B,{variant:"outline",onClick:()=>ms(d.email,`${d.first_name} ${d.last_name||""}`.trim()),children:[e.jsx(Vs,{className:"h-4 w-4 mr-1"}),"Email"]}),d.email&&e.jsxs(B,{variant:"outline",onClick:()=>Ae(!0),className:"border-primary/40 text-primary hover:bg-primary/10",children:[e.jsx(un,{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(br,{className:"h-4 w-4 mr-1"}),"Quick Video Touch"]}),e.jsxs(bs,{open:z,onOpenChange:V,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Log Action"]})}),e.jsxs(vs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{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:p==null?void 0:p.filter(Xt=>Xt.active).map(Xt=>e.jsxs("button",{onClick:()=>Y(Xt.id),className:` p-3 rounded-lg border text-left transition-all ${W===Xt.id?"border-primary bg-primary/10":"hover:bg-accent"} `,children:[e.jsx("div",{className:"font-medium",children:Xt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Xt.description})]},Xt.id))}),Fs&&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:he,onChange:Xt=>ce(Xt.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(el,{children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal mt-2",!ne&&"text-muted-foreground"),children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),ne?Ss(ne,"PPP"):"Today (default)"]})}),e.jsx(Ho,{className:"w-auto p-0",align:"start",children:e.jsx(Kg,{mode:"single",selected:ne,onSelect:ie,disabled:Xt=>Xt>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(Es,{id:"action-notes",value:K,onChange:Xt=>J(Xt.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs(B,{onClick:Rs,disabled:!W||Fs&&!he.trim()||A.isPending,className:"w-full",children:[e.jsx(Ir,{className:"h-4 w-4 mr-1"}),"Complete Action"]})]})]})]}),e.jsxs(B,{variant:"outline",onClick:bt,children:[e.jsx(ku,{className:"h-4 w-4 mr-1"}),"Edit"]}),e.jsx(B,{variant:"destructive",size:"icon",onClick:Bt,children:e.jsx(_n,{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(U_t,{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||""]}),(((Jt=d.lead_source_ref)==null?void 0:Jt.name)||d.lead_source)&&e.jsx(ze,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:((ft=d.lead_source_ref)==null?void 0:ft.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:()=>ms(d.email),className:"flex items-center gap-1 hover:text-primary transition-colors",children:[e.jsx(Vs,{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(Ar,{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(Fge,{contact:d}),(Vt=d.tags)==null?void 0:Vt.map(Xt=>{const Js=h==null?void 0:h.find(Cs=>Cs.id===Xt.relationship_type_id);return Js?e.jsx(ze,{variant:"secondary",className:"text-xs",children:Js.name},Xt.id):null})]}),e.jsx("div",{className:"mt-2",children:e.jsx(ZGs,{contactId:s})})]})}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"md:col-span-2",children:[e.jsx(Mt,{children:e.jsx(It,{children:"Contact Information"})}),e.jsx(Ee,{children:L?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:M.first_name,onChange:Xt=>F({...M,first_name:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"last_name",children:"Last Name"}),e.jsx(ye,{id:"last_name",value:M.last_name,onChange:Xt=>F({...M,last_name:Xt.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(ye,{id:"email",type:"email",value:M.email,onChange:Xt=>F({...M,email:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"phone",children:"Phone"}),e.jsx(ye,{id:"phone",value:M.phone,onChange:Xt=>F({...M,phone:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"address",children:"Street Address"}),e.jsx(ye,{id:"address",value:M.address,onChange:Xt=>F({...M,address:Xt.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:M.city,onChange:Xt=>F({...M,city:Xt.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"state",children:"State"}),e.jsx(ye,{id:"state",value:M.state,onChange:Xt=>F({...M,state:Xt.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:M.zip_code,onChange:Xt=>F({...M,zip_code:Xt.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:M.birthday,onChange:Xt=>F({...M,birthday:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(ye,{id:"home_anniversary",type:"date",value:M.home_anniversary,onChange:Xt=>F({...M,home_anniversary:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"wedding_anniversary",children:"Wedding Anniversary"}),e.jsx(ye,{id:"wedding_anniversary",type:"date",value:M.wedding_anniversary||"",onChange:Xt=>F({...M,wedding_anniversary:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"spouse_birthday",children:"Spouse Birthday"}),e.jsx(ye,{id:"spouse_birthday",type:"date",value:M.spouse_birthday,onChange:Xt=>F({...M,spouse_birthday:Xt.target.value})})]})]}),e.jsx(ll,{}),e.jsx(tTe,{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:Xt=>T.mutate({contactId:s,spouseContactId:Xt}),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:M.company_name,onChange:Xt=>F({...M,company_name:Xt.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:M.job_title,onChange:Xt=>F({...M,job_title:Xt.target.value}),placeholder:"Enter job title"})]})]}),e.jsx($_t,{value:M.lead_source_id||"",onChange:Xt=>F({...M,lead_source_id:Xt})}),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(Xt=>Xt.active).map(Xt=>{var Js;return e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(ui,{checked:(Js=M.tagIds)==null?void 0:Js.includes(Xt.id),onCheckedChange:Cs=>{var As;F(Cs?{...M,tagIds:[...M.tagIds||[],Xt.id]}:{...M,tagIds:(As=M.tagIds)==null?void 0:As.filter(rn=>rn!==Xt.id)})}}),e.jsx("span",{className:"text-sm",children:Xt.name})]},Xt.id)})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"notes",children:"Notes"}),e.jsx(Es,{id:"notes",value:M.notes,onChange:Xt=>F({...M,notes:Xt.target.value}),rows:4})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{onClick:vt,disabled:b.isPending,children:"Save Changes"}),e.jsx(B,{variant:"outline",onClick:()=>D(!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(yr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:"Last Contacted:"})," ",Ss(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(Vs,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("button",{onClick:()=>ms(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(Ar,{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})]})]}),(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(ka,{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}`]})]})]}),it&&d.address&&d.city&&d.state&&e.jsxs(B,{size:"sm",variant:"outline",onClick:je,disabled:Ze,children:[Ze?e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(fw,{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(yr,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Birthday: ",Ss(Cl(d.birthday),Cl(d.birthday).getFullYear()===1900?"MMMM d":"MMMM d, yyyy")]})]}),d.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Home Anniversary: ",Ss(Cl(d.home_anniversary),Cl(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(gi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Spouse Birthday: ",Ss(Cl(d.spouse_birthday),Cl(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(gi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Wedding Anniversary: ",Ss(Cl(d.wedding_anniversary),Cl(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(Is,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Date Added: ",Ss(new Date(d.created_at),"MMMM d, yyyy")]})]})]}),e.jsx(ll,{}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(tTe,{contactId:s,currentSpouseContactId:(d==null?void 0:d.spouse_contact_id)||null,currentSpouseName:d.spouse_name||null,currentSpouseEmail:d.spouse_email||null,onLink:Xt=>T.mutate({contactId:s,spouseContactId:Xt}),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(Va,{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(ll,{}),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:(Ms=d.tags)!=null&&Ms.length?d.tags.map(Xt=>{var Js;return e.jsx(ze,{variant:"secondary",children:(Js=Xt.relationship_type)==null?void 0:Js.name},Xt.id)}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No relationship types assigned"})})]}),d.notes&&e.jsxs(e.Fragment,{children:[e.jsx(ll,{}),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(eGs,{contact:d,onLogTouch:()=>V(!0)}),e.jsx(VWs,{contactId:s}),e.jsx(MWs,{contactId:s}),e.jsx(IWs,{contactId:s}),e.jsx(LWs,{contactId:s,contactName:d.first_name}),e.jsx(DWs,{contactId:s,contactName:d.first_name}),e.jsx(UWs,{contactId:s}),e.jsx(FWs,{contactId:s}),e.jsx(BWs,{contactId:s}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"Activity Log"})}),e.jsx(Ee,{children:dt.length>0?e.jsx("div",{className:"space-y-4",children:dt.map(Xt=>{var Js;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:Xt.color},children:Xt.type==="popby"?e.jsx(Oi,{className:"h-4 w-4"}):(Js=Xt.name)==null?void 0:Js.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:Xt.name}),Xt.videoId&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>le(Xt.videoId),children:[e.jsx(Al,{className:"h-3 w-3 mr-1"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ss(new Date(Xt.completed_at),"MMM d, yyyy h:mm a")}),Xt.notes&&!Xt.videoId&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Xt.notes})]})]},Xt.id)})}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"})})]}),_&&_.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Ei,{className:"h-5 w-5 text-primary"}),"Video Replies"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-4",children:_.map(Xt=>{var Js,Cs;return e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0",children:[(Js=Xt.video)!=null&&Js.thumbnail_url?e.jsx("img",{src:Xt.video.thumbnail_url,alt:Xt.video.title||"Video",className:"h-12 w-16 object-cover rounded cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>le(Xt.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:()=>le(Xt.video_id),children:e.jsx(br,{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: ",((Cs=Xt.video)==null?void 0:Cs.title)||"Untitled Video"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs flex-shrink-0",onClick:()=>le(Xt.video_id),children:[e.jsx(Al,{className:"h-3 w-3 mr-1"}),"Watch"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ss(new Date(Xt.created_at),"MMM d, yyyy h:mm a")}),Xt.message&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:['"',Xt.message,'"']})]})]},Xt.id)})})})]}),Ge&&Ge.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(cr,{className:"h-5 w-5 text-sky-500"}),"Sent Emails"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-3",children:Ge.map(Xt=>e.jsxs(bs,{children:[e.jsx(Ai,{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(Vs,{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:Xt.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",Xt.to_email," · ",Ss(new Date(Xt.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx(xa,{className:"h-4 w-4 text-muted-foreground mt-1 flex-shrink-0"})]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] flex flex-col",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5 text-sky-500"}),Xt.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",Xt.to_email," · ",Ss(new Date(Xt.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:Xt.body,className:"w-full h-[400px] border-0",sandbox:"",title:`Email: ${Xt.subject}`})})]})]},Xt.id))})})]})]}),e.jsx(bs,{open:!!pe,onOpenChange:Xt=>!Xt&&le(null),children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Video Preview"})}),pe&&e.jsx($Ws,{videoId:pe})]})})]})]})}),qe&&d&&Te&&e.jsx(t1,{open:ve,onOpenChange:ge,contact:{id:d.id,first_name:d.first_name,last_name:d.last_name,email:Te.email},gmailEmail:Ie}),d&&d.email&&e.jsx(fWs,{open:Ce,onOpenChange:Ae,contact:{id:d.id,first_name:d.first_name,last_name:d.last_name,email:d.email}})]}):e.jsx(Ts,{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 GWs({rangeDays:s}){const{user:t}=ys(),n=Ht(),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(!1),{data:d=[],isLoading:u}=ct({queryKey:["newsletter-campaigns",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let f=q.from("email_campaigns").select("id, name, subject, status, sent_at, scheduled_at, created_at, total_recipients, sent_count, open_count, click_count, bounce_count").eq("user_id",t.id).like("name","Newsletter:%").order("created_at",{ascending:!1}).limit(50);if(s){const v=new Date(Date.now()-s*864e5).toISOString();f=f.gte("created_at",v)}const{data:g,error:_}=await f;if(_)throw _;return g||[]}}),{data:h}=ct({queryKey:["newsletter-campaign-recipients",r],enabled:!!r,queryFn:async()=>{const{data:f,error:g}=await q.from("email_campaign_recipients").select("id, email, name, status, sent_at, opened_at, clicked_at, error_message").eq("campaign_id",r).order("sent_at",{ascending:!1}).limit(2e3);if(g)throw g;return f||[]}}),p=async()=>{if(!(!i||!t)){c(!0);try{const{data:f,error:g}=await q.from("email_campaign_recipients").select("email, name, contact_id").eq("campaign_id",i.id).eq("status","sent").is("opened_at",null).limit(5e3);if(g)throw g;if(!f||f.length===0){ae.info("All recipients opened — nothing to resend!"),l(null),c(!1);return}const{data:_}=await q.from("email_campaigns").select("subject, body_html, from_email, reply_to_email").eq("id",i.id).single();if(!_)throw new Error("Original campaign not found");const{data:v,error:j}=await q.from("email_campaigns").insert({user_id:t.id,name:`${i.name} (Resend to non-openers)`,subject:_.subject,body_html:_.body_html,from_email:_.from_email,reply_to_email:_.reply_to_email,total_recipients:f.length,status:"draft"}).select("id").single();if(j)throw j;const b=f.map(A=>({campaign_id:v.id,contact_id:A.contact_id,email:A.email,name:A.name,status:"pending"}));for(let A=0;A{const g=f.sent_count||0,_=g>0?f.open_count/g*100:0,v=g>0?f.click_count/g*100:0,j=f.sent_at?Wv(new Date,new Date(f.sent_at)):0,b=f.status==="sent"&&j>=3&&g>0&&f.open_counta(f.id),children:[e.jsx(Er,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),b&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>l(f),children:[e.jsx(zA,{className:"h-3.5 w-3.5 mr-1"})," Resend"]})]})]}),f.status==="sent"&&g>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mt-3",children:[e.jsx(yG,{icon:e.jsx(cr,{className:"h-3.5 w-3.5"}),label:"Sent",value:g,sub:`of ${f.total_recipients}`}),e.jsx(yG,{icon:e.jsx(Er,{className:"h-3.5 w-3.5 text-blue-600"}),label:"Opens",value:f.open_count,sub:`${_.toFixed(1)}%`,children:e.jsx(pi,{value:_,className:"h-1 mt-1"})}),e.jsx(yG,{icon:e.jsx(oc,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:f.click_count,sub:`${v.toFixed(1)}%`,children:e.jsx(pi,{value:v,className:"h-1 mt-1"})}),e.jsx(yG,{icon:e.jsx(cL,{className:"h-3.5 w-3.5 text-orange-600"}),label:"Bounces",value:f.bounce_count,sub:f.bounce_count>0?"review":"none"})]})]},f.id)})})]})}),e.jsx(cg,{open:!!r,onOpenChange:f=>!f&&a(null),children:e.jsxs(ix,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(n0,{children:e.jsx(r0,{children:"Recipient Activity"})}),e.jsx("div",{className:"mt-4 space-y-1",children:h?h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recipients yet."}):e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs uppercase text-muted-foreground border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2",children:"Recipient"}),e.jsx("th",{className:"text-left py-2",children:"Opened"}),e.jsx("th",{className:"text-left py-2",children:"Clicked"}),e.jsx("th",{className:"text-left py-2",children:"Status"})]})}),e.jsx("tbody",{children:h.map(f=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsxs("td",{className:"py-2",children:[e.jsx("div",{className:"font-medium truncate max-w-[180px]",children:f.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[180px]",children:f.email})]}),e.jsx("td",{className:"py-2 text-xs",children:f.opened_at?e.jsx(ze,{variant:"default",className:"text-xs",children:Ss(new Date(f.opened_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2 text-xs",children:f.clicked_at?e.jsx(ze,{variant:"default",className:"text-xs bg-purple-600",children:Ss(new Date(f.clicked_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"py-2 text-xs",children:[f.status==="sent"&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"sent"}),f.status==="pending"&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:"queued"}),f.status==="failed"&&e.jsx(ze,{variant:"destructive",className:"text-xs",title:f.error_message||"",children:"failed"}),f.status==="suppressed"&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"suppressed"})]})]},f.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})})]})}),e.jsx(Oo,{open:!!i,onOpenChange:f=>!f&&l(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Resend to non-openers?"}),e.jsxs(Mo,{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(Eo,{children:[e.jsx(Io,{disabled:o,children:"Cancel"}),e.jsx(jo,{onClick:p,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}),"Resending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(zA,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function yG({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]})}function WWs(){const{user:s}=ys(),t=Mn(),n=Ht(),{data:r=[],isLoading:a}=ct({queryKey:["scheduled-email-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("email_campaigns").select("id, name, subject, scheduled_at, total_recipients, status, created_at").eq("user_id",s.id).eq("status","scheduled").order("scheduled_at",{ascending:!0});if(u)throw u;return d||[]},refetchInterval:3e4}),i=async(d,u)=>{const{data:{session:h}}=await q.auth.getSession(),f=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-schedule-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h.access_token}`},body:JSON.stringify({action:d,campaign_id:u})})).json();if(!f.success)throw new Error(f.error||`Failed to ${d}`);return f},l=gt({mutationFn:d=>i("cancel",d),onSuccess:()=>{ae.success("Schedule cancelled — saved as draft"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ae.error(d.message)}),o=gt({mutationFn:d=>i("delete",d),onSuccess:()=>{ae.success("Scheduled email deleted"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ae.error(d.message)}),c=gt({mutationFn:async({id:d,iso:u})=>{const{error:h}=await q.from("email_campaigns").update({scheduled_at:u,status:"scheduled"}).eq("id",d);if(h)throw h;await i("schedule",d)},onSuccess:()=>{ae.success("Send time updated"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ae.error(d.message)});return a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading scheduled emails..."}):r.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(gr,{className:"h-12 w-12 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No scheduled emails."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Emails you schedule for the future will appear here."})]})}):e.jsx("div",{className:"space-y-3",children:r.map(d=>e.jsx(KWs,{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 KWs({campaign:s,onEdit:t,onCancel:n,onDelete:r,onReschedule:a,isBusy:i}){const l=s.scheduled_at?new Date(s.scheduled_at):null,[o,c]=N.useState(!1),[d,u]=N.useState(l||void 0),[h,p]=N.useState(l?`${String(l.getHours()).padStart(2,"0")}:${String(l.getMinutes()).padStart(2,"0")}`:"09:00"),f=()=>{if(!d)return ae.error("Pick a date");const g=new Date(`${Ss(d,"yyyy-MM-dd")}T${h}:00`).toISOString();if(new Date(g).getTime()gp(g.target.value)})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:f,disabled:i,children:[i&&e.jsx(ts,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save new time"]})]})]})]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",disabled:i,children:[e.jsx(Hc,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel Send"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Cancel this scheduled send?"}),e.jsxs(Mo,{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(Eo,{children:[e.jsx(Io,{children:"Keep scheduled"}),e.jsx(jo,{onClick:n,children:"Cancel send"})]})]})]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"ghost",className:"text-destructive hover:text-destructive",disabled:i,children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-1.5"})," Delete"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete this scheduled email?"}),e.jsx(Mo,{children:"This permanently removes the scheduled email and all its recipient records. This can't be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Keep"}),e.jsx(jo,{onClick:r,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete permanently"})]})]})]})]})]})})})}const qZe=["Gmail","Mass Email","Campaign","Client Portal Invite"],YWs={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 ZWs(){const{user:s}=ys(),[t,n]=gl(),{data:r=[],isLoading:a}=Z_t(),[i,l]=N.useState(""),[o,c]=N.useState("all"),[d,u]=N.useState("30"),[h,p]=N.useState(!1),[f,g]=N.useState(t.get("tab")==="scheduled"?"scheduled":"sent"),{gmailEmail:_}=Oh(),{data:v=0}=ct({queryKey:["scheduled-email-count",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{count:T}=await q.from("email_campaigns").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","scheduled");return T||0},refetchInterval:3e4});N.useEffect(()=>{const T=new URLSearchParams(t);f==="scheduled"?T.set("tab","scheduled"):T.delete("tab"),n(T,{replace:!0})},[f]);const j=N.useMemo(()=>Array.from(new Set(r.map(T=>T.contact_id).filter(Boolean))),[r]),{data:b}=ct({queryKey:["sent-emails-contact-names",s==null?void 0:s.id,j.length],enabled:j.length>0,queryFn:async()=>{const{data:T}=await q.from("innercircle_contacts").select("id, first_name, last_name").in("id",j),L=new Map;return(T||[]).forEach(D=>{L.set(D.id,[D.first_name,D.last_name].filter(Boolean).join(" ")||"Contact")}),L}}),S=N.useMemo(()=>{const T=d==="all"?null:Date.now()-parseInt(d)*864e5,L=i.trim().toLowerCase();return r.filter(D=>{if(o!=="all"&&D.channel!==o||T&&new Date(D.sent_at).getTime(){const T={};let L=0,D=0,M=0;return S.forEach(F=>{T[F.channel]=(T[F.channel]||0)+1,(F.channel==="Campaign"||F.channel==="Mass Email")&&(M++,F.opened_at&&L++,F.clicked_at&&D++)}),{byChannel:T,opened:L,clicked:D,trackable:M}},[S]);return e.jsx(Ts,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-start md: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(cr,{className:"h-6 w-6"})," Sent Emails"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"All emails you've sent through LevelUp — Gmail, mass emails, campaigns, and client portal invites."})]}),e.jsxs(B,{onClick:()=>p(!0),children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"})," Send Email"]})]}),e.jsxs(Br,{value:f,onValueChange:T=>g(T),className:"space-y-6",children:[e.jsxs(Fr,{children:[e.jsxs(Kt,{value:"sent",className:"gap-2",children:[e.jsx(cr,{className:"h-4 w-4"})," Sent"]}),e.jsxs(Kt,{value:"scheduled",className:"gap-2",children:[e.jsx(gr,{className:"h-4 w-4"})," Scheduled",v>0&&e.jsx(ze,{variant:"secondary",className:"ml-1 h-5 min-w-5 px-1.5 text-xs",children:v})]})]}),e.jsxs(is,{value:"sent",className:"space-y-6 mt-0",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"py-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:"Total Sent"}),e.jsx("p",{className:"text-2xl font-bold",children:S.length}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 truncate",children:qZe.map(T=>A.byChannel[T]?`${A.byChannel[T]} ${T}`:null).filter(Boolean).join(" · ")||"—"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"py-4",children:[e.jsxs("p",{className:"text-xs text-muted-foreground uppercase flex items-center gap-1",children:[e.jsx(xr,{className:"h-3 w-3"})," Delivered"]}),e.jsx("p",{className:"text-2xl font-bold",children:S.length}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"All sends completed"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"py-4",children:[e.jsxs("p",{className:"text-xs text-muted-foreground uppercase flex items-center gap-1",children:[e.jsx(Er,{className:"h-3 w-3"})," Opened"]}),e.jsx("p",{className:"text-2xl font-bold",children:A.opened}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:A.trackable>0?`${Math.round(A.opened/A.trackable*100)}% of ${A.trackable} tracked`:"No tracked emails"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"py-4",children:[e.jsxs("p",{className:"text-xs text-muted-foreground uppercase flex items-center gap-1",children:[e.jsx(oc,{className:"h-3 w-3"})," Clicked"]}),e.jsx("p",{className:"text-2xl font-bold",children:A.clicked}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:A.trackable>0?`${Math.round(A.clicked/A.trackable*100)}% of ${A.trackable} tracked`:"No tracked emails"})]})})]}),e.jsxs("p",{className:"text-xs text-muted-foreground -mt-2",children:[e.jsx(yw,{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.jsxs("div",{className:"flex flex-col md:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-md",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search subject, recipient, contact...",value:i,onChange:T=>l(T.target.value),className:"pl-9"})]}),e.jsxs(ds,{value:o,onValueChange:c,children:[e.jsx(ls,{className:"w-[200px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Channels"}),qZe.map(T=>e.jsx(Qe,{value:T,children:T},T))]})]}),e.jsxs(ds,{value:d,onValueChange:u,children:[e.jsx(ls,{className:"w-[160px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"7",children:"Last 7 days"}),e.jsx(Qe,{value:"30",children:"Last 30 days"}),e.jsx(Qe,{value:"90",children:"Last 90 days"}),e.jsx(Qe,{value:"365",children:"Last year"}),e.jsx(Qe,{value:"all",children:"All time"})]})]})]}),e.jsx(GWs,{rangeDays:d==="all"?null:parseInt(d)}),a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):S.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Vs,{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(fe,{children:e.jsx(Ee,{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(Ww,{children:e.jsxs(Ec,{children:[e.jsxs(Ac,{className:"inline-flex items-center gap-1",children:["Engagement ",e.jsx(yw,{className:"h-3 w-3"})]}),e.jsx(vc,{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:S.slice(0,500).map(T=>{const L=T.contact_id?b==null?void 0:b.get(T.contact_id):null,D=T.channel==="Campaign"||T.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:Ss(new Date(T.sent_at),"MMM d, yyyy h:mm a")}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(ze,{variant:"outline",className:YWs[T.channel],children:T.channel})}),e.jsx("td",{className:"py-3 px-4 max-w-xs truncate font-medium",children:T.subject}),e.jsx("td",{className:"py-3 px-4 text-muted-foreground",children:T.to_email}),e.jsx("td",{className:"py-3 px-4",children:T.contact_id&&L?e.jsx(Ln,{to:`/mission-control/contacts/${T.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:D?e.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.jsxs(ze,{variant:"outline",className:"bg-slate-50 text-slate-700 border-slate-200 gap-1",children:[e.jsx(xr,{className:"h-3 w-3"})," Delivered"]}),T.opened_at&&e.jsxs(ze,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200 gap-1",children:[e.jsx(Er,{className:"h-3 w-3"})," Opened"]}),T.clicked_at&&e.jsxs(ze,{variant:"outline",className:"bg-emerald-50 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(oc,{className:"h-3 w-3"})," Clicked"]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Not tracked"})})]},T.id)})})]}),S.length>500&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center py-3 border-t",children:["Showing first 500 of ",S.length," — narrow your filters to see more."]})]})})})]}),e.jsx(is,{value:"scheduled",className:"mt-0",children:e.jsx(WWs,{})})]}),e.jsx(t1,{open:h,onOpenChange:p,gmailEmail:_})]})})}const VZe={Crown:ff,FileText:Nr,Users:Nn,Globe:lc,Star:ca,Phone:Ar,MessageSquare:Ei,PenTool:r4,Video:br,Gift:Oi},vG=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function QWs(){var vt,Bt;const s=Mn(),{user:t}=ys(),{data:n}=Sy(),{data:r}=Qns(),{data:a}=rrs(),{data:i}=Zmt(),{data:l}=YD(),{data:o}=Zns(),c=ars(),d=Xns(),u=ers(),h=trs(),p=srs(),f=nrs(),g=Jns(),[_,v]=N.useState(null),[j,b]=N.useState(!1),[S,A]=N.useState(null),[T,L]=N.useState(""),[D,M]=N.useState(""),[F,z]=N.useState([]),[V,W]=N.useState(null),[Y,K]=N.useState(null),[J,ne]=N.useState(null),[ie,he]=N.useState(!1),[ce,pe]=N.useState(""),[le,ve]=N.useState(""),[ge,Te]=N.useState(""),[Me,Ce]=N.useState(""),Ae=(Zt,Fs)=>a==null?void 0:a.some(Rs=>Rs.plan_id===Zt&&Rs.relationship_type_id===Fs&&Rs.active),De=Zt=>a==null?void 0:a.find(Fs=>Fs.relationship_type_id===Zt&&Fs.active),Ie=async(Zt,Fs)=>{const Rs=Ae(Zt,Fs);await c.mutateAsync({planId:Zt,relationshipTypeId:Fs,active:!Rs})},Fe=(r==null?void 0:r.filter(Zt=>Zt.active&&!Zt.owner_user_id))||[],qe=(r==null?void 0:r.filter(Zt=>Zt.owner_user_id===(t==null?void 0:t.id)))||[],be=n==null?void 0:n.find(Zt=>Zt.id===_),Ze=_?De(_):null,Ne=r==null?void 0:r.find(Zt=>Zt.id===(Ze==null?void 0:Ze.plan_id)),it=async()=>{if(!T.trim())return;const Zt=await d.mutateAsync({name:T,description:D});Zt&&F.length>0&&await p.mutateAsync({planId:Zt.id,items:F}),Ye()},je=async()=>{!T.trim()||!S||(await u.mutateAsync({id:S,name:T,description:D}),await p.mutateAsync({planId:S,items:F}),Ye())},Ge=Zt=>{var Fs;A(Zt.id),L(Zt.name),M(Zt.description||""),z(((Fs=Zt.items)==null?void 0:Fs.map(Rs=>({month_number:Rs.month_number,action_type_id:Rs.action_type_id,default_script_id:Rs.default_script_id||void 0,notes:Rs.notes||void 0})))||[]),b(!0)},Be=async(Zt,Fs)=>{if(Zt.owner_user_id===(t==null?void 0:t.id)){Ge(Zt);return}try{const Rs=await g.mutateAsync({sourcePlanId:Zt.id,newName:`${Zt.name} (My Copy)`});if(!Rs)return;await c.mutateAsync({planId:Zt.id,relationshipTypeId:Fs,active:!1}),await c.mutateAsync({planId:Rs.id,relationshipTypeId:Fs,active:!0}),A(Rs.id),L(Rs.name),M(Rs.description||""),z((Zt.items||[]).map(ms=>({month_number:ms.month_number,action_type_id:ms.action_type_id,default_script_id:ms.default_script_id||void 0,notes:ms.notes||void 0}))),b(!0)}catch{}},Ye=()=>{b(!1),A(null),L(""),M(""),z([])},We=(Zt,Fs)=>{K(Fs)},rt=(Zt,Fs,Rs)=>{z(ms=>[...ms.filter(Jt=>Jt.month_number!==Zt),{month_number:Zt,action_type_id:Fs,default_script_id:Rs}]),W(null),K(null)},tt=Zt=>{z(Fs=>Fs.filter(Rs=>Rs.month_number!==Zt))},at=async()=>{if(!ce.trim()||!le.trim()||!Y)return;const Zt=await f.mutateAsync({actionTypeId:Y,title:ce,scriptBody:le,emailSubject:ge||void 0,tone:Me||void 0});Zt&&V!==null&&rt(V,Y,Zt.id),he(!1),pe(""),ve(""),Te(""),Ce("")},He=Y?o==null?void 0:o.filter(Zt=>Zt.action_type_id===Y&&Zt.active):[],dt=Zt=>VZe[Zt||"Phone"]||Ar,bt=Zt=>VZe[Zt||"Users"]||Nn;return e.jsxs(Ts,{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(pl,{className:"h-4 w-4 mr-1"}),"Back"]}),e.jsxs(B,{onClick:()=>b(!0),className:"w-full sm:w-auto",children:[e.jsx(Is,{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(Zt=>Zt.active).map(Zt=>{const Fs=bt(Zt.icon),Rs=(i==null?void 0:i[Zt.id])||0,ms=De(Zt.id),Pt=r==null?void 0:r.find(ft=>ft.id===(ms==null?void 0:ms.plan_id)),Jt=_===Zt.id;return e.jsxs("button",{onClick:()=>v(Zt.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${Jt?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[e.jsx(Fs,{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:Zt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Rs," contacts"]})]}),Pt?e.jsxs(ze,{variant:"secondary",className:"text-xs",children:[e.jsx(Ri,{className:"h-3 w-3 mr-1"}),Pt.name.split(" ")[0]]}):e.jsx(ze,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},Zt.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:_&&be?e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[(()=>{const Zt=bt(be.icon);return e.jsx(Zt,{className:"h-5 w-5"})})(),be.name," Touchpoint Plan"]}),e.jsxs(Vn,{children:["Choose a plan for your ",be.name," contacts"]})]}),e.jsxs(Ee,{className:"space-y-6",children:[Ne&&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(Ri,{className:"h-4 w-4 text-green-500"}),"Currently using: ",Ne.name]}),Ne.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ne.description})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",disabled:g.isPending||c.isPending,onClick:()=>Be(Ne,_),children:[e.jsx(wv,{className:"h-4 w-4 mr-1"}),"Edit Steps"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>Ie(Ne.id,_),children:"Disable"})]})]}),Ne.items&&Ne.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(yr,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:vG.map((Zt,Fs)=>{var Jt,ft;const Rs=((Jt=Ne.items)==null?void 0:Jt.filter(Vt=>Vt.month_number===Fs+1))||[],ms=(ft=Rs[0])==null?void 0:ft.action_type,Pt=ms?dt(ms.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${Rs.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:Zt}),Pt&&e.jsx(Pt,{className:"h-4 w-4 mx-auto mt-1",style:{color:(ms==null?void 0:ms.color)||"#3B82F6"}})]},Fs)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:Ne?"Switch to a Different Plan":"Choose a Plan"}),Fe.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"}),Fe.map(Zt=>{var Rs;const Fs=(Ne==null?void 0:Ne.id)===Zt.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Fs?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Zt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((Rs=Zt.items)==null?void 0:Rs.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>ne(Zt.id),children:e.jsx(Er,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:g.isPending,onClick:()=>{const ms=`${Zt.name} (Copy)`;g.mutate({sourcePlanId:Zt.id,newName:ms})},children:e.jsx(Xr,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:Fs?"outline":"default",disabled:Fs||c.isPending,onClick:()=>Ie(Zt.id,_),children:Fs?"Active":"Use This"})]})]},Zt.id)})]}),qe.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"My Custom Plans"}),qe.map(Zt=>{var Rs;const Fs=(Ne==null?void 0:Ne.id)===Zt.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Fs?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Zt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((Rs=Zt.items)==null?void 0:Rs.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>ne(Zt.id),children:e.jsx(Er,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>Ge(Zt),children:e.jsx(wv,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>h.mutate(Zt.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})}),e.jsx(B,{size:"sm",variant:Fs?"outline":"default",disabled:Fs||c.isPending,onClick:()=>Ie(Zt.id,_),children:Fs?"Active":"Use This"})]})]},Zt.id)})]}),Fe.length===0&&qe.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(fe,{children:e.jsxs(Ee,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(yr,{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(fe,{className:"bg-muted/50",children:e.jsx(Ee,{className:"py-4",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:"How it works:"})," When you assign a plan to a contact group, those contacts will appear in your daily suggested actions based on the plan's schedule."]})})})]}),e.jsx(bs,{open:j,onOpenChange:Zt=>{Zt?b(!0):Ye()},children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:S?"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:Zt=>L(Zt.target.value),placeholder:"e.g., My VIP Plan"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"plan-description",children:"Description (optional)"}),e.jsx(Es,{id:"plan-description",value:D,onChange:Zt=>M(Zt.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:vG.map((Zt,Fs)=>{const Rs=Fs+1,ms=F.find(ft=>ft.month_number===Rs),Pt=ms?l==null?void 0:l.find(ft=>ft.id===ms.action_type_id):null,Jt=Pt?dt(Pt.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>W(V===Rs?null:Rs),className:` w-full p-3 rounded-lg border text-center transition-all ${ms?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${V===Rs?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:Zt}),Jt?e.jsx(Jt,{className:"h-5 w-5 mx-auto mt-1",style:{color:(Pt==null?void 0:Pt.color)||"#3B82F6"}}):e.jsx(Is,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),ms&&e.jsx("button",{type:"button",onClick:ft=>{ft.stopPropagation(),tt(Rs)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx(Bn,{className:"h-3 w-3"})})]},Fs)})}),V!==null&&!Y&&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 ",vG[V-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(Zt=>Zt.active).map(Zt=>{const Fs=dt(Zt.icon);return e.jsxs("button",{type:"button",onClick:()=>We(V,Zt.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx(Fs,{className:"h-4 w-4",style:{color:Zt.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:Zt.name})]},Zt.id)})})]}),V!==null&&Y&&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:()=>K(null),children:[e.jsx(pl,{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:()=>rt(V,Y),className:"w-full flex items-center gap-3 p-3 rounded-lg border bg-background hover:bg-accent transition-colors text-left",children:e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"No Script"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Use without a predefined script"})]})}),He==null?void 0:He.map(Zt=>e.jsx("button",{type:"button",onClick:()=>rt(V,Y,Zt.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:Zt.title}),Zt.tone&&e.jsx(ze,{variant:"secondary",className:"text-xs mt-1",children:Zt.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[Zt.script_body.substring(0,100),"..."]})]})},Zt.id)),e.jsxs("button",{type:"button",onClick:()=>he(!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(Is,{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"})]})]})]})]})]}),F.length>0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[F.length," touchpoint",F.length!==1?"s":""," per year"]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:Ye,children:"Cancel"}),e.jsxs(B,{onClick:S?je:it,disabled:!T.trim()||d.isPending||u.isPending,children:[e.jsx(qo,{className:"h-4 w-4 mr-2"}),S?"Save Changes":"Create Plan"]})]})]})}),e.jsx(bs,{open:ie,onOpenChange:he,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{children:e.jsx(_s,{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:ce,onChange:Zt=>pe(Zt.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script-tone",children:"Tone (optional)"}),e.jsxs(ds,{value:Me,onValueChange:Ce,children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select tone..."})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"friendly",children:"Friendly"}),e.jsx(Qe,{value:"professional",children:"Professional"}),e.jsx(Qe,{value:"casual",children:"Casual"}),e.jsx(Qe,{value:"formal",children:"Formal"})]})]})]}),((Bt=(vt=l==null?void 0:l.find(Zt=>Zt.id===Y))==null?void 0:vt.name)==null?void 0:Bt.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:ge,onChange:Zt=>Te(Zt.target.value),placeholder:"e.g., Quick Hello!"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script-body",children:"Script Content"}),e.jsx(Es,{id:"script-body",value:le,onChange:Zt=>ve(Zt.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(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>he(!1),children:"Cancel"}),e.jsxs(B,{onClick:at,disabled:!ce.trim()||!le.trim()||f.isPending,children:[e.jsx(qo,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})}),e.jsx(bs,{open:!!J,onOpenChange:Zt=>{Zt||ne(null)},children:e.jsx(vs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:(()=>{const Zt=r==null?void 0:r.find(ms=>ms.id===J);if(!Zt)return null;const Fs=Zt.owner_user_id===(t==null?void 0:t.id),Rs=[...Zt.items||[]].sort((ms,Pt)=>ms.month_number-Pt.month_number);return e.jsxs(e.Fragment,{children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[Zt.name,!Fs&&e.jsx(ze,{variant:"secondary",children:"Template"})]}),Zt.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Zt.description})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Rs.length," touchpoint",Rs.length!==1?"s":""," per year"]}),e.jsx("div",{className:"space-y-2",children:Array.from({length:12},(ms,Pt)=>Pt+1).map(ms=>{const Pt=Rs.find(Ms=>Ms.month_number===ms),Jt=Pt?l==null?void 0:l.find(Ms=>Ms.id===Pt.action_type_id):null,ft=Pt!=null&&Pt.default_script_id?o==null?void 0:o.find(Ms=>Ms.id===Pt.default_script_id):null,Vt=Jt?dt(Jt.icon):null;return e.jsxs("div",{className:`p-3 rounded-lg border flex items-start gap-3 ${Pt?"bg-muted/30":"opacity-60"}`,children:[e.jsx("div",{className:"w-16 shrink-0 font-medium text-sm",children:vG[ms-1]}),Pt&&Jt?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Vt&&e.jsx(Vt,{className:"h-4 w-4",style:{color:Jt.color||"#3B82F6"}}),e.jsx("span",{className:"font-medium text-sm",children:Jt.name}),ft&&e.jsx(ze,{variant:"outline",className:"text-xs",children:ft.title})]}),ft&&e.jsx("div",{className:"mt-2 text-sm text-muted-foreground whitespace-pre-wrap bg-background p-2 rounded border",children:ft.script_body}),Pt.notes&&e.jsx("div",{className:"mt-1 text-xs text-muted-foreground italic",children:Pt.notes})]}):e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:"No touchpoint scheduled"})]},ms)})})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>ne(null),children:"Close"}),Fs?e.jsxs(B,{onClick:()=>{const ms=r==null?void 0:r.find(Pt=>Pt.id===J);ms&&(ne(null),Ge(ms))},children:[e.jsx(wv,{className:"h-4 w-4 mr-2"}),"Edit Plan"]}):e.jsxs(B,{disabled:g.isPending,onClick:()=>{g.mutate({sourcePlanId:Zt.id,newName:`${Zt.name} (Copy)`}),ne(null)},children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"}),"Duplicate to Edit"]})]})]})})()})})]})}const CNe="https://cma.relevelup.com";function Q_t({open:s,onOpenChange:t,cma:n}){var ne;const{user:r}=ys(),{toast:a}=Ba(),[i,l]=N.useState([]),[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,p]=N.useState(""),[f,g]=N.useState(""),[_,v]=N.useState(""),[j,b]=N.useState(!1),[S,A]=N.useState(null),[T,L]=N.useState(!1),[D,M]=N.useState(!1),[F,z]=N.useState(null);N.useEffect(()=>{!s||!r||(async()=>{var Te;const[ie,he,ce,pe,le]=await Promise.all([q.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",r.id).not("email","is",null).order("first_name"),q.from("profiles").select("name, email, phone, brokerage_name, avatar_url, email_signature").eq("id",r.id).maybeSingle(),q.from("gmail_integrations").select("id, is_active").eq("user_id",r.id).maybeSingle(),q.from("ses_verified_emails").select("email, status").eq("user_id",r.id).eq("status","Success").limit(1),q.from("mass_email_settings").select("*").eq("user_id",r.id).maybeSingle()]),ve=(ie.data||[]).filter(Me=>Me.email&&Me.email.includes("@"));l(ve),A(he.data||null),L(!!((Te=ce.data)!=null&&Te.is_active)),M(!!(pe.data&&pe.data.length>0)),z(le.data||null);const ge=n.contact_id?ve.find(Me=>Me.id===n.contact_id):null;ge&&(c(ge),p(ge.email))})()},[s,r,n.contact_id]),N.useEffect(()=>{var pe;if(!s)return;const ie=((pe=n.subject)==null?void 0:pe.address)||"your home",he=((S==null?void 0:S.name)||"").split(" ")[0]||"your agent",ce=(o==null?void 0:o.first_name)||"there";g(`Your home value report for ${ie}`),v(`Hi ${ce}, I put together a fresh market analysis for ${ie}. 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, ${(S==null?void 0:S.name)||he}`)},[s,o==null?void 0:o.id,S==null?void 0:S.name,(ne=n.subject)==null?void 0:ne.address]);const V=N.useMemo(()=>T?"Gmail (your inbox)":D?"Amazon SES":null,[T,D]),W=!!(h.trim()&&f.trim()&&_.trim()&&V&&!j),Y=ie=>{c(ie),p(ie.email||""),u(!1)},K=ie=>{const he=`${CNe}/${n.share_token}?e=${ie}`,le=_.replace(/&/g,"&").replace(//g,">").replace(/\{\{cma_link\}\}/g,`View Your Home Value Report`).split(/\n{2,}/).map(Te=>`

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

`).join(""),ve=S!=null&&S.use_email_signature&&(S!=null&&S.email_signature)?`
${S.email_signature}
`:`
${S!=null&&S.name?`
${S.name}
`:""} ${S!=null&&S.brokerage_name?`
${S.brokerage_name}
`:""} ${S!=null&&S.phone?`
${S.phone}
`:""} ${S!=null&&S.email?``:""}
`,ge=``;return`
${le} ${ve}
Prepared with LevelUp · ReLevelUp Real Estate
${ge}
`},J=async()=>{if(!(!r||!W)){b(!0);try{const{data:ie,error:he}=await q.from("cma_email_sends").insert({cma_id:n.id,agent_id:r.id,contact_id:(o==null?void 0:o.id)??null,recipient_email:h.trim(),subject:f.trim(),sent_via:T?"gmail":"ses"}).select("id").single();if(he)throw he;const ce=K(ie.id);if(T){const{data:pe,error:le}=await q.functions.invoke("gmail-send",{body:{to:h.trim(),subject:f.trim(),body:ce}});if(le)throw le;if(!(pe!=null&&pe.success))throw new Error((pe==null?void 0:pe.error)||"Gmail send failed")}else if(D){const pe=(F==null?void 0:F.display_name)||(S==null?void 0:S.name)||"ReLevelUp",le=`${pe.toLowerCase().replace(/[^a-z]/g,".").replace(/^\.+|\.+$/g,"")||"noreply"}@send.relevelup.com`,{data:ve,error:ge}=await q.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:h.trim(),from_email:`${pe} <${le}>`,subject:f.trim(),body_html:ce,reply_to:(F==null?void 0:F.reply_to_email)||(S==null?void 0:S.email)||void 0}});if(ge)throw ge;if(!(ve!=null&&ve.success))throw new Error((ve==null?void 0:ve.error)||"SES send failed")}o&&!n.contact_id&&await q.from("cmas").update({contact_id:o.id}).eq("id",n.id),a({title:"CMA sent",description:`Delivered to ${h.trim()}`}),t(!1)}catch(ie){console.error("Send CMA error:",ie),a({title:"Send failed",description:ie.message||"Could not send email",variant:"destructive"})}finally{b(!1)}}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"w-5 h-5"}),"Send CMA to contact"]})}),V?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:V})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Contact"}),e.jsxs(el,{open:d,onOpenChange:u,children:[e.jsx(tl,{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(qg,{className:"w-4 h-4 opacity-50"})]})}),e.jsx(Ho,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Qg,{children:[e.jsx(Xg,{placeholder:"Search contacts…"}),e.jsxs(Jg,{children:[e.jsx(e0,{children:"No contacts with email found."}),e.jsx(t0,{children:i.map(ie=>e.jsxs(Jf,{value:`${ie.first_name} ${ie.last_name||""} ${ie.email}`,onSelect:()=>Y(ie),children:[e.jsx(Ir,{className:Et("w-4 h-4 mr-2",(o==null?void 0:o.id)===ie.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium",children:[ie.first_name," ",ie.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:ie.email})]})]},ie.id))})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"To email"}),e.jsx(ye,{type:"email",value:h,onChange:ie=>p(ie.target.value),placeholder:"client@example.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Subject"}),e.jsx(ye,{value:f,onChange:ie=>g(ie.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Message"}),e.jsx(Es,{rows:10,value:_,onChange:ie=>v(ie.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:`${CNe}/${n.share_token}`,target:"_blank",rel:"noreferrer",children:`${CNe}/${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(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:J,disabled:!W,children:[j?e.jsx(ts,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(cr,{className:"w-4 h-4 mr-2"}),"Send CMA"]})]})]})})}function XWs({onCreated:s}){const[t,n]=N.useState(!1),[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),h=_Ws(),p=H_t(),{toast:f}=Ba(),[g,_]=N.useState([]),v=async()=>{var S;_([]);try{const A=await h.mutateAsync({address:r,city:i,state:o,zip:d});_(A.matches||[]),(S=A.matches)!=null&&S.length||f({title:"No MLS match",description:'Use "Create from manual entry" below.'})}catch(A){f({title:"Search failed",description:A.message,variant:"destructive"})}},j=async S=>{const A=await p.mutateAsync({subject:S});n(!1),s(A.id)},b=async()=>{if(!r||!i||!o){f({title:"Address, city, state required"});return}const S=await p.mutateAsync({subject:{address:r,city:i,state:o,zip:d}});n(!1),s(S.id)};return e.jsxs(bs,{open:t,onOpenChange:n,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"New CMA"]})}),e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Start a CMA"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2",children:[e.jsx(ye,{className:"md:col-span-2",placeholder:"Street address",value:r,onChange:S=>a(S.target.value)}),e.jsx(ye,{placeholder:"City",value:i,onChange:S=>l(S.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"ST",maxLength:2,value:o,onChange:S=>c(S.target.value.toUpperCase())}),e.jsx(ye,{placeholder:"ZIP",value:d,onChange:S=>u(S.target.value)})]})]}),e.jsxs(B,{onClick:v,disabled:!r||h.isPending,className:"w-full",children:[h.isPending?e.jsx(ts,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(vr,{className:"w-4 h-4 mr-2"}),"Find in MLS"]}),g.length>0&&e.jsxs("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[g.length," match(es) — pick the subject property:"]}),g.map((S,A)=>{var T;return e.jsxs("button",{onClick:()=>j(S),className:"w-full text-left p-3 border rounded hover:bg-accent transition",children:[e.jsx("div",{className:"font-medium",children:S.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[S.city,", ",S.state," ",S.zip," · ",S.bedrooms??"?"," bd / ",S.bathrooms??"?"," ba · ",((T=S.sqft)==null?void 0:T.toLocaleString())??"?"," sqft",S.mlsNumber?` · MLS# ${S.mlsNumber}`:""," · ",S.source_provider]})]},A)})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsxs(B,{variant:"outline",onClick:b,disabled:p.isPending,className:"w-full",children:[e.jsx(Or,{className:"w-4 h-4 mr-2"}),"Create from manual entry"]})})]})]})]})}function JWs(){const{data:s,isLoading:t}=xWs(),n=bWs(),r=Mn(),{toast:a}=Ba(),[i,l]=N.useState(null);return e.jsx(Ts,{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(Nr,{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(XWs,{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(fe,{className:"hover:shadow-md transition",children:e.jsxs(Ee,{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(ze,{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(Vs,{className:"w-4 h-4 mr-1"}),"Send"]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>{confirm("Delete this CMA?")&&n.mutate(o.id)},children:e.jsx(_n,{className:"w-4 h-4"})})]})]})},o.id)})}):e.jsx(fe,{children:e.jsx(Ee,{className:"py-12 text-center text-muted-foreground",children:"No CMAs yet. Start one above."})}),i&&e.jsx(Q_t,{open:!!i,onOpenChange:o=>!o&&l(null),cma:i})]})})}function eKs(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 HZe(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 tKs({subject:s,comps:t,radiusMiles:n,onMarkerClick:r}){const a=N.useRef(null),i=N.useRef(null),l=N.useRef([]),[o,c]=N.useState(null);N.useEffect(()=>{let u=!1;return(async()=>{const{data:h}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();!u&&(h!=null&&h.value)&&c(h.value)})(),()=>{u=!0}},[]);const d=N.useMemo(()=>{const u=Number(s==null?void 0:s.latitude),h=Number(s==null?void 0:s.longitude);return!Number.isFinite(u)||!Number.isFinite(h)?null:{lat:u,lng:h}},[s==null?void 0:s.latitude,s==null?void 0:s.longitude]);return N.useEffect(()=>{if(!o||!a.current||i.current||!d)return;hl.accessToken=o;const u=new hl.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[d.lng,d.lat],zoom:12});return u.addControl(new hl.NavigationControl({showCompass:!1}),"top-right"),u.on("load",()=>{u.addSource("radius",{type:"geojson",data:HZe(d.lat,d.lng,n)}),u.addLayer({id:"radius-fill",type:"fill",source:"radius",paint:{"fill-color":"#2563eb","fill-opacity":.08}}),u.addLayer({id:"radius-line",type:"line",source:"radius",paint:{"line-color":"#2563eb","line-width":2,"line-dasharray":[2,2],"line-opacity":.5}})}),i.current=u,()=>{u.remove(),i.current=null}},[o,d]),N.useEffect(()=>{const u=i.current;if(!u||!d)return;const h=()=>{const p=u.getSource("radius");p&&p.setData(HZe(d.lat,d.lng,n))};u.isStyleLoaded()?h():u.once("load",h)},[n,d]),N.useEffect(()=>{const u=i.current;if(!u||!d)return;l.current.forEach(v=>v.remove()),l.current=[];const h=document.createElement("div");h.style.cssText=` width: 28px; height: 28px; border-radius: 50%; background: hsl(222 47% 11%); border: 3px solid white; box-shadow: 0 4px 12px rgba(0,0,0,0.3); display: flex; align-items: center; justify-content: center; color: white; font-size: 12px; font-weight: 700; `,h.textContent="★";const p=new hl.Marker({element:h}).setLngLat([d.lng,d.lat]).setPopup(new hl.Popup({offset:18}).setHTML(`Subject
${s.address??""}`)).addTo(u);l.current.push(p);const f=new hl.LngLatBounds;f.extend([d.lng,d.lat]),t.forEach((v,j)=>{const b=Number(v.latitude),S=Number(v.longitude);if(!Number.isFinite(b)||!Number.isFinite(S))return;const A=eKs(v.status),T=document.createElement("div");T.style.cssText="width:22px;height:22px;";const L=document.createElement("div");L.style.cssText=` width: 22px; height: 22px; border-radius: 50%; background: ${A}; border: 2px solid white; box-shadow: 0 2px 6px rgba(0,0,0,0.25); cursor: pointer; opacity: ${v.selected===!1?.4:1}; transition: transform 0.15s; transform-origin: center; `,L.onmouseenter=()=>{L.style.transform="scale(1.25)"},L.onmouseleave=()=>{L.style.transform="scale(1)"},r&&(L.onclick=()=>r(j)),T.appendChild(L);const D=v.soldPrice||v.price,M=new hl.Popup({offset:14}).setHTML(`
${v.address??""}
${v.status??""}`+(D?` · $${D.toLocaleString()}`:"")+"
"),F=new hl.Marker({element:T}).setLngLat([S,b]).setPopup(M).addTo(u);l.current.push(F),f.extend([S,b])});const _=n*1.60934/110.574;f.extend([d.lng,d.lat+_]),f.extend([d.lng,d.lat-_]);try{u.fitBounds(f,{padding:60,maxZoom:14,duration:600})}catch{}},[t,d,n,s.address,r]),d?e.jsxs("div",{className:"relative w-full h-[420px] rounded-xl overflow-hidden border shadow-sm",children:[e.jsx("div",{ref:a,className:"absolute inset-0"}),!o&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-muted/40 text-sm text-muted-foreground",children:"Loading map…"}),e.jsxs("div",{className:"absolute bottom-3 left-3 bg-background/95 backdrop-blur rounded-lg shadow-md border px-3 py-2 text-xs space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"hsl(222 47% 11%)"}}),"Subject"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#2563eb"}}),"Active"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#f59e0b"}}),"Pending"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#16a34a"}}),"Closed"]})]})]}):e.jsx("div",{className:"w-full h-[420px] rounded-xl border bg-muted/30 flex items-center justify-center text-sm text-muted-foreground",children:"Subject property has no coordinates — map unavailable."})}let Ng=null;function sKs(){if(Ng)return Ng;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return Ng={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},Ng;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 Ng={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:r},Ng;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?(Ng={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:r},Ng):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?(Ng={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:r},Ng):(Ng={canRunVirtualBg:!0,renderer:r},Ng)}catch{return Ng={canRunVirtualBg:!0},Ng}}const nKs=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function rKs({value:s,onChange:t,isLoading:n=!1,disabled:r=!1,className:a}){const i=N.useRef(null),[l,o]=N.useState(!1),[c]=N.useState(()=>sKs()),d=!c.canRunVirtualBg,{data:u=[],refetch:h}=ct({queryKey:["video-backgrounds"],queryFn:async()=>{const{data:{user:v}}=await q.auth.getUser();if(!v)return[];const{data:j,error:b}=await q.from("video_backgrounds").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});return b?(console.error("Failed to load backgrounds:",b),[]):j||[]}}),p=u.map(v=>({type:"image",label:v.name,imageUrl:v.image_url,thumbnail:v.thumbnail_url||v.image_url})),f=[...nKs,...p],g=v=>v.type!==s.type?!1:v.type==="image"?v.imageUrl===s.imageUrl:!0,_=async v=>{var b;const j=(b=v.target.files)==null?void 0:b[0];if(j){if(!j.type.startsWith("image/")){ae.error("Please select an image file");return}if(j.size>5*1024*1024){ae.error("Image must be under 5MB");return}o(!0);try{const{data:{user:S}}=await q.auth.getUser();if(!S)throw new Error("Not authenticated");const A=j.name.split(".").pop()||"jpg",T=`${S.id}/${crypto.randomUUID()}.${A}`,{error:L}=await q.storage.from("video-backgrounds").upload(T,j,{contentType:j.type});if(L)throw L;const{data:D}=q.storage.from("video-backgrounds").getPublicUrl(T),M=D.publicUrl,{error:F}=await q.from("video_backgrounds").insert({name:j.name.replace(/\.[^.]+$/,""),image_url:M,thumbnail_url:M,category:"custom",is_stock:!1,user_id:S.id});if(F)throw F;await h(),t({type:"image",imageUrl:M,blurRadius:15}),ae.success("Background uploaded!")}catch(S){console.error("Upload error:",S),ae.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($l,{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(ts,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Loading…"})]}),f.map((v,j)=>{const b=g(v);return e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({type:v.type,imageUrl:v.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",b?"border-primary bg-primary/10":"border-transparent bg-muted/50",r&&"opacity-50 cursor-not-allowed"),children:[e.jsxs("div",{className:"w-12 h-8 rounded flex items-center justify-center overflow-hidden bg-muted",children:[v.type==="none"&&e.jsx(XP,{className:"h-4 w-4 text-muted-foreground"}),v.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"})}),v.type==="image"&&v.thumbnail&&e.jsx("img",{src:v.thumbnail,alt:v.label,className:"w-full h-full object-cover"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-14",children:v.label})]},`${v.type}-${v.imageUrl||j}`)}),e.jsxs("button",{type:"button",disabled:r||l,onClick:()=>{var v;return(v=i.current)==null?void 0:v.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(ts,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(Is,{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:_}),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(n9,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var lD=typeof self<"u"?self:{};function X_t(s,t){e:{for(var n=["CLOSURE_FLAGS"],r=lD,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 ewt(s){lD.setTimeout(()=>{throw s},0)}var sTe,lKs=X_t(610401301,!1),WZe=X_t(748402147,!0);function KZe(){var s=lD.navigator;return s&&(s=s.userAgent)?s:""}const YZe=lD.navigator;function R1e(s){return R1e[" "](s),s}sTe=YZe&&YZe.userAgentData||null,R1e[" "]=function(){};const twt={};let S7=null;function cKs(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),p!=64&&l(h<<6&192|p))}}(s,function(i){r[a++]=i}),a!==n?r.subarray(0,a):r}function swt(){if(!S7){S7={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const r=s.concat(t[n].split(""));twt[n]=r;for(let a=0;a0)&&(KZe().indexOf("Trident")!=-1||KZe().indexOf("MSIE")!=-1))&&typeof btoa=="function";const ZZe=/[-_.]/g,uKs={"-":"+",_:"/",".":"="};function hKs(s){return uKs[s]||""}function rwt(s){if(!nwt)return cKs(s);s=ZZe.test(s)?s.replace(ZZe,hKs):s,s=atob(s);const t=new Uint8Array(s.length);for(let n=0;n=t||(n[s]=r+1,iwt(s=Error(),"incident"),ewt(s))}}function NR(){return typeof BigInt=="function"}var kR=typeof Symbol=="function"&&typeof Symbol()=="symbol";function tj(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 fKs=tj("jas",void 0,!0),QZe=tj(void 0,"0di"),RF=tj(void 0,"1oa"),xy=tj(void 0,Symbol()),xKs=tj(void 0,"0ub"),gKs=tj(void 0,"0ubs"),rTe=tj(void 0,"0ubsb"),yKs=tj(void 0,"0actk"),uD=tj("m_m","Pa",!0),XZe=tj();const owt={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},lwt=Object.defineProperties,wi=kR?fKs:"Ga";var l6;const JZe=[];function BU(s,t){kR||wi in s||lwt(s,owt),s[wi]|=t}function Km(s,t){kR||wi in s||lwt(s,owt),s[wi]=t}function $U(s){return BU(s,34),s}function g$(s){return BU(s,8192),s}Km(JZe,7),l6=Object.freeze(JZe);var hD={};function by(s,t){return t===void 0?s.h!==RM&&!!(2&(0|s.v[wi])):!!(2&t)&&s.h!==RM}const RM={};function wLe(s,t){if(s!=null){if(typeof s=="string")s=s?new Ew(s,cD):DM();else if(s.constructor!==Ew)if(bLe(s))s=s.length?new Ew(new Uint8Array(s),cD):DM();else{if(!t)throw Error();s=void 0}}return s}class eQe{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 vKs=Object.freeze({});function cwt(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"),tQe=O1e(s=>typeof s=="string"),_Ks=O1e(s=>typeof s=="boolean"),F1e=typeof lD.BigInt=="function"&&typeof lD.BigInt(0)=="bigint";function gy(s){var t=s;if(tQe(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(bKs(t)&&!Number.isSafeInteger(t))throw Error(String(t));return F1e?BigInt(s):s=_Ks(s)?s?"1":"0":tQe(s)?s.trim()||"0":String(s)}var aTe=O1e(s=>F1e?s>=jKs&&s<=kKs:s[0]==="-"?sQe(s,wKs):sQe(s,NKs));const wKs=Number.MIN_SAFE_INTEGER.toString(),jKs=F1e?BigInt(Number.MIN_SAFE_INTEGER):void 0,NKs=Number.MAX_SAFE_INTEGER.toString(),kKs=F1e?BigInt(Number.MAX_SAFE_INTEGER):void 0;function sQe(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(r>>0;Cu=t,Qh=(s-t)/4294967296>>>0}function mD(s){if(s<0){nQe(-s);const[t,n]=kLe(Cu,Qh);Cu=t>>>0,Qh=n>>>0}else nQe(s)}function jLe(s){const t=CKs||(CKs=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),Qh=0,Cu=t.getUint32(0,!0)}function uwt(s,t){const n=4294967296*t+(s>>>0);return Number.isSafeInteger(n)?n:y$(s,t)}function TKs(s,t){return gy(NR()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):y$(s,t))}function hwt(s,t){return NR()?gy(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var n=""+(4294967296*t+s);else NR()?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+rQe(n)+rQe(s));return n}function rQe(s){return s=String(s),"0000000".slice(s.length)+s}function NLe(s,t){if(2147483648&t)if(NR())s=""+(BigInt(0|t)<>>0));else{const[n,r]=kLe(s,t);s="-"+y$(n,r)}else s=y$(s,t);return s}function z1e(s){if(s.length<16)mD(Number(s));else if(NR())s=BigInt(s),Cu=Number(s&BigInt(4294967295))>>>0,Qh=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");Qh=Cu=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));Qh*=1e6,Cu=1e6*Cu+i,Cu>=4294967296&&(Qh+=Math.trunc(Cu/4294967296),Qh>>>=0,Cu>>>=0)}if(t){const[r,a]=kLe(Cu,Qh);Cu=r,Qh=a}}}function kLe(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function kb(s){return Array.prototype.slice.call(s)}const UU=typeof BigInt=="function"?BigInt.asIntN:void 0,EKs=typeof BigInt=="function"?BigInt.asUintN:void 0,OM=Number.isSafeInteger,B1e=Number.isFinite,pD=Math.trunc,AKs=gy(0);function C7(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 ow(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function v$(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 mwt(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const MKs=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function qU(s){switch(typeof s){case"bigint":return!0;case"number":return B1e(s);case"string":return MKs.test(s);default:return!1}}function CR(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return B1e(s)?0|s:void 0}function pwt(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return B1e(s)?s>>>0:void 0}function fwt(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(z1e(s),NLe(Cu,Qh))}function SLe(s){if(s=pD(s),!OM(s)){mD(s);var t=Cu,n=Qh;(s=2147483648&n)&&(n=~n>>>0,(t=1+~t>>>0)==0&&(n=n+1>>>0)),s=typeof(t=uwt(t,n))=="number"?s?-t:t:s?"-"+t:t}return s}function xwt(s){var t=pD(Number(s));return OM(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),fwt(s))}function gwt(s){var t=pD(Number(s));return OM(t)?gy(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),NR()?gy(UU(64,BigInt(s))):gy(fwt(s)))}function ywt(s){return OM(s)?s=gy(SLe(s)):(s=pD(s),OM(s)?s=String(s):(mD(s),s=NLe(Cu,Qh)),s=gy(s)),s}function zge(s){const t=typeof s;return s==null?s:t==="bigint"?gy(UU(64,s)):qU(s)?t==="string"?gwt(s):ywt(s):void 0}function vwt(s){if(typeof s!="string")throw Error();return s}function VU(s){if(s!=null&&typeof s!="string")throw Error();return s}function wf(s){return s==null||typeof s=="string"?s:void 0}function CLe(s,t,n,r){return s!=null&&s[uD]===hD?s:Array.isArray(s)?((r=(n=0|s[wi])|32&r|2&r)!==n&&Km(s,r),new t(s)):(n?2&r?((s=t[QZe])||($U((s=new t).v),s=t[QZe]=s),t=s):t=new t:t=void 0,t)}function IKs(s,t,n){if(t)e:{if(!qU(t=s))throw nTe("int64");switch(typeof t){case"string":t=gwt(t);break e;case"bigint":t=gy(UU(64,t));break e;default:t=ywt(t)}}else t=zge(s);return(s=t)==null?n?AKs:void 0:s}const PKs={};let LKs=function(){try{return R1e(new class extends Map{constructor(){super()}}),!1}catch{return!0}}();class ENe{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 DKs=LKs?(Object.setPrototypeOf(ENe.prototype,Map.prototype),Object.defineProperties(ENe.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),ENe):class extends Map{constructor(){super()}};function aQe(s){return s}function ANe(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var yN=class extends DKs{constructor(s,t,n=aQe,r=aQe){super(),this.J=0|s[wi],this.K=t,this.S=n,this.fa=this.K?RKs:r;for(let a=0;a{s.call(t,a.get(r),r,a)}):super.forEach(s,t)}set(s,t){return ANe(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 RKs(s,t,n,r,a,i){return s=CLe(s,r,n,i),a&&(s=ELe(s)),s}function OKs(s){return[s,this.get(s)]}let FKs;function iQe(){return FKs||(FKs=new yN($U([]),void 0,void 0,void 0,PKs))}function $1e(s){return xy?s[xy]:void 0}function Bge(s,t){for(const n in s)!isNaN(n)&&t(s,+n,s[n])}yN.prototype.toJSON=void 0;var iTe=class{};const zKs={Ka:!0};function BKs(s,t){t<100||dD(gKs,1)}function U1e(s,t,n,r){const a=r!==void 0;r=!!r;var i,l=xy;!a&&kR&&l&&(i=s[l])&&Bge(i,BKs),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 p=0;p=i){const g=p-h;(t??(t={}))[g]=f}else l[p]=f}if(c)for(let f in c){if((o=c[f])==null||(o=n(o,r))==null)continue;let g;p=+f,u&&!Number.isNaN(p)&&(g=p+h){g[v]=kb(j)}),g.da=f.da,g}(s)),l}function $Ks(s){return s[0]=b$(s[0]),s[1]=b$(s[1]),s}function b$(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return aTe(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[wi];return s.length===0&&1&t?void 0:U1e(s,t,b$)}if(s!=null&&s[uD]===hD)return bwt(s);if(s instanceof Ew){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if(nwt){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 yN?s=s.size!==0?s.V($Ks):void 0:void 0}return s}let UKs,qKs;function bwt(s){return U1e(s=s.v,0|s[wi],b$)}function tM(s,t){return _wt(s,t[0],t[1])}function _wt(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[wi],WZe&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(WZe)throw Error("carr");dD(yKs,5)}(),256&a)throw Error("farr");if(64&a)return(a|r)!==a&&Km(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 Km(s,64|a|r),s}function VKs(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var n=0|s[wi];return s.length===0&&1&n?void 0:oQe(s,n,t)}if(s!=null&&s[uD]===hD)return lQe(s);if(s instanceof yN){if(2&(t=s.J))return s;if(!s.size)return;if(n=$U(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 Gc(s,t,n,r){AR(s),Hm(s=s.v,0|s[wi],t,n,r)}function Hm(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[wi]))>>14&1023||536870912)?r!=null&&(s[l+(a?0:-1)]={[n]:r}):s[i]=r),t)}function aA(){return vKs===void 0?2:4}function iA(s,t,n,r,a){let i=s.v,l=0|i[wi];r=by(s,l)?1:r,a=!!a||r===3,r===2&&ER(s)&&(i=s.v,l=0|i[wi]);let o=(s=MLe(i,t))===l6?7:0|s[wi],c=ILe(o,l);var d=!(4&c);if(d){4&c&&(s=kb(s),o=0,c=nM(c,l),l=Hm(i,l,t,s));let u=0,h=0;for(;u{const o=CLe(l,n,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!by(r)&&c6(s,t),r}function Yl(s,t,n,r){let a=s.v,i=0|a[wi];if((t=Cwt(a,i,t,n,r))==null)return t;if(i=0|a[wi],!by(s,i)){const l=ELe(t);l!==t&&(ER(s)&&(a=s.v,i=0|a[wi]),i=Hm(a,i,n,t=l,r),c6(a,i))}return t}function Twt(s,t,n,r,a,i,l,o){var c=by(s,n);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&ER(s)&&(n=0|(t=s.v)[wi]);var d=(s=MLe(t,a))===l6?7:0|s[wi],u=ILe(d,n);if(o=!(4&u)){var h=s,p=n;const f=!!(2&u);f&&(p|=2);let g=!f,_=!0,v=0,j=0;for(;v32)for(a|=(127&n)>>4,i=3;i<32&&128&n;i+=7)n=l[o++],a|=(127&n)<>>0,a>>>0);throw Error()}function zLe(s){let t=0,n=s.g;const r=n+10,a=s.h;for(;n>>0}function Uge(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],rM(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 HKs(s){return F4(s)}function rM(s,t){if(s.g=t,t>s.l)throw Error()}function Awt(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 Mwt(s,t){if(t==0)return DM();var n=Awt(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):SKs?s.slice(n,t):new Uint8Array(s.subarray(n,t))),n.length==0?DM():new Ew(n,cD)}var cQe=[];function Iwt(s,t,n,r){if(qge.length){const a=qge.pop();return a.o(r),a.g.init(s,t,n,r),a}return new GKs(s,t,n,r)}function Pwt(s){s.g.clear(),s.l=-1,s.h=-1,qge.length<100&&qge.push(s)}function Lwt(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var n=Uw(s.g);if(t=n>>>3,!((n&=7)>=0&&n<=5)||t<1)throw Error();return s.l=t,s.h=n,!0}function rpe(s){switch(s.h){case 0:s.h!=0?rpe(s):zLe(s.g);break;case 1:rM(s=s.g,s.g+8);break;case 2:if(s.h!=2)rpe(s);else{var t=Uw(s.g);rM(s=s.g,s.g+t)}break;case 5:rM(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!Lwt(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}rpe(s)}break;default:throw Error()}}function HU(s,t,n){const r=s.g.l;var a=Uw(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 BLe(s){var t=Uw(s.g),n=Awt(s=s.g,t);if(s=s.h,aKs){var r,a=s;(r=TNe)||(r=TNe=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(bG===void 0){try{r.decode(new Uint8Array([128]))}catch{}try{r.decode(new Uint8Array([97])),bG=!0}catch{bG=!1}}throw!bG&&(TNe=void 0),o}}else{t=(i=n)+t,n=[];let o,c=null;for(;i=t?x3():(o=s[i++],l<194||(192&o)!=128?(i--,x3()):n.push((31&l)<<6|63&o)):l<240?i>=t-1?x3():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(r=s[i++]))!=128?(i--,x3()):n.push((15&l)<<12|(63&o)<<6|63&r)):l<=244?i>=t-2?x3():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(r=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,x3()):(l=(7&l)<<18|(63&o)<<12|(63&r)<<6|63&a,l-=65536,n.push(55296+(l>>10&1023),56320+(1023&l)))):x3(),n.length>=8192&&(c=GZe(c,n),n.length=0)}i=GZe(c,n)}return i}function Dwt(s){const t=Uw(s.g);return Mwt(s.g,t)}function V1e(s,t,n){var r=Uw(s.g);for(r=s.g.g+r;s.g.g>>0,this.g=t>>>0}};let WKs;function uQe(s){return s?/^-?\d+$/.test(s)?(z1e(s),new lTe(Cu,Qh)):null:KKs||(KKs=new lTe(0,0))}var lTe=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let KKs;function qL(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 IR(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function H1e(s,t){if(t>=0)IR(s,t);else{for(let n=0;n<9;n++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function $Le(s){var t=Cu;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 fD(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function s1(s,t,n){IR(s.g,8*t+n)}function ULe(s,t){return s1(s,t,2),t=s.g.end(),fD(s,t),t.push(s.h),t}function qLe(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 G1e(s,t,n){s1(s,t,2),IR(s.g,n.length),fD(s,s.g.end()),fD(s,n)}function Vge(s,t,n,r){n!=null&&(t=ULe(s,t),r(n,s),qLe(s,t))}function sj(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var VLe=sj(),Rwt=sj(),HLe=sj(),GLe=sj(),WLe=sj(),Owt=sj(),YKs=sj(),W1e=sj(),Fwt=sj(),zwt=sj();function nj(s,t,n){var r=s.v;xy&&xy in r&&(r=r[xy])&&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 ji=class{constructor(s,t){this.v=_wt(s,t,void 0,2048)}toJSON(){return bwt(this)}j(){var a;var s=AYs,t=this.v,n=s.g,r=xy;if(kR&&r&&((a=t[r])==null?void 0:a[n])!=null&&dD(xKs,3),t=s.g,XZe&&xy&&XZe===void 0&&(r=(n=this.v)[xy])&&(r=r.da))try{r(n,t,zKs)}catch(i){ewt(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[wi];return ALe(this,s,t)?TLe(this,s,!0):new this.constructor(TR(s,t,!1))}};ji.prototype[uD]=hD,ji.prototype.toString=function(){return this.v.toString()};var PR=class{constructor(s,t,n){this.g=s,this.h=t,s=VLe,this.l=!!s&&n===s||!1}};function K1e(s,t){return new PR(s,t,VLe)}function Bwt(s,t,n,r,a){Vge(s,n,Vwt(t,r),a)}const ZKs=K1e(function(s,t,n,r,a){return s.h===2&&(HU(s,DLe(t,r,n),a),!0)},Bwt),QKs=K1e(function(s,t,n,r,a){return s.h===2&&(HU(s,DLe(t,r,n),a),!0)},Bwt);var Y1e=Symbol(),Z1e=Symbol(),cTe=Symbol(),hQe=Symbol(),mQe=Symbol();let $wt,Uwt;function d6(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 UKs||(UKs=[0,void 0,!0]);case"number":return h>0?void 0:h===0?qKs||(qKs=[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,$wt??($wt=i),Uwt??(Uwt=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 YLe(s,t,n,r,a){const i=n.g;let l,o;s[t]=(c,d,u)=>i(c,d,u,o||(o=d6(Z1e,KLe,YLe,r).T),l||(l=ZLe(r)),a)}function ZLe(s){let t=s[cTe];if(t!=null)return t;const n=d6(Z1e,KLe,YLe,s);return t=n.ma?(r,a)=>$wt(r,a,n):(r,a)=>{for(;Lwt(a)&&a.h!=4;){var i=a.l,l=n[i];if(l==null){var o=n.ba;o&&(o=o[i])&&(o=JKs(o))!=null&&(l=n[i]=o)}if(l==null||!l(a,r,i)){if(l=(o=a).m,rpe(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=Mwt(o.g,c);l=void 0,o=r,c&&((l=o[xy]??(o[xy]=new iTe))[i]??(l[i]=[])).push(c)}}return(r=$1e(r))&&(r.da=n.qa[mQe]),!0},s[cTe]=t,s[mQe]=XKs.bind(s),t}function XKs(s,t,n,r){var a=this[Z1e];const i=this[cTe],l=tM(void 0,a.T),o=$1e(s);if(o){var c=!1,d=a.ba;if(d){if(a=(u,h,p)=>{if(p.length!==0)if(d[h])for(const f of p){u=Iwt(f);try{c=!0,i(l,u)}finally{Pwt(u)}}else r==null||r(s,h,p)},t==null)Bge(o,a);else if(o!=null){const u=o[t];u&&a(o,t,u)}if(c){let u=0|s[wi];if(2&u&&2048&u&&!(n!=null&&n.Ka))throw Error();const h=SR(u),p=(f,g)=>{if(vN(s,f,h)!=null){if((n==null?void 0:n.Qa)===1)return;throw Error()}g!=null&&(u=Hm(s,u,f,g,h)),delete o[f]};t==null?cwt(l,0|l[wi],(f,g)=>{p(f,g)}):p(t,vN(l,t,h))}}}}function JKs(s){const t=(s=qwt(s))[0].g;if(s=s[1]){const n=ZLe(s),r=d6(Z1e,KLe,YLe,s).T;return(a,i,l)=>t(a,i,l,r,n)}return t}function Q1e(s,t,n){s[t]=n.h}function X1e(s,t,n,r){let a,i;const l=n.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=d6(Y1e,Q1e,X1e,r).T),a||(a=Hwt(r)))}function Hwt(s){let t=s[hQe];if(!t){const n=d6(Y1e,Q1e,X1e,s);t=(r,a)=>Gwt(r,a,n),s[hQe]=t}return t}function Gwt(s,t,n){cwt(s,0|s[wi],(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=qwt(c))[0].h;if(c=c[1]){const u=Hwt(c),h=d6(Y1e,Q1e,X1e,c).T;c=l.ma?Uwt(h,u):(p,f,g)=>d(p,f,g,h,u)}else c=d;return l[o]=c}}(n,r);i?i(t,a,r):r<500||dD(rTe,3)}}),(s=$1e(s))&&Bge(s,(r,a,i)=>{for(fD(t,t.g.end()),r=0;r{Vge(s,n,tM([l,i],r),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),qL(s.g,n.h,n.g);break;default:n=uQe(t),qL(s.g,n.h,n.g)}}function Ywt(s,t,n){(t=CR(t))!=null&&t!=null&&(s1(s,n,0),H1e(s.g,t))}function Zwt(s,t,n){(t=mwt(t))!=null&&(s1(s,n,0),s.g.g.push(t?1:0))}function Qwt(s,t,n){(t=wf(t))!=null&&G1e(s,n,J_t(t))}function Xwt(s,t,n,r,a){Vge(s,n,Vwt(t,r),a)}function Jwt(s,t,n){(t=t==null||typeof t=="string"||t instanceof Ew?t:void 0)!=null&&G1e(s,n,OLe(t,!0).buffer)}function ejt(s,t,n){(t=pwt(t))!=null&&t!=null&&(s1(s,n,0),IR(s.g,t))}function tjt(s,t,n){return(s.h===5||s.h===2)&&(t=MR(t,0|t[wi],n),s.h==2?V1e(s,Uge,t):t.push(Uge(s.g)),!0)}var sm=ux(function(s,t,n){return s.h===5&&(hx(t,n,Uge(s.g)),!0)},Wwt,W1e),sYs=DR(tjt,function(s,t,n){if((t=LR(ow,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"))||(z1e(r),r=y$(Cu,Qh))),r;if(a==="number")return(r=pD(r))>=0&&OM(r)||(mD(r),r=uwt(Cu,Qh)),r}}(t),t!=null&&(typeof t=="string"&&dQe(t),t!=null))switch(s1(s,n,0),typeof t){case"number":s=s.g,mD(t),qL(s,Cu,Qh);break;case"bigint":n=BigInt.asUintN(64,t),n=new oTe(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),qL(s.g,n.h,n.g);break;default:n=dQe(t),qL(s.g,n.h,n.g)}},YKs),Um=ux(function(s,t,n){return s.h===0&&(hx(t,n,F4(s.g)),!0)},Ywt,GLe),GU=DR(function(s,t,n){return(s.h===0||s.h===2)&&(t=MR(t,0|t[wi],n),s.h==2?V1e(s,F4,t):t.push(F4(s.g)),!0)},function(s,t,n){if((t=LR(CR,t))!=null&&t.length){n=ULe(s,n);for(let r=0;r{{const i={ea:!0};r&&Object.assign(i,r),n=Iwt(n,void 0,void 0,i);try{const l=new s,o=l.v;ZLe(t)(o,n);var a=l}finally{Pwt(n)}}return a}}function J1e(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}}}};Gwt(this.v,t,d6(Y1e,Q1e,X1e,s)),fD(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=xQe.createPolicy("goog#html",{createHTML:r,createScript:r,createScriptURL:r})}catch{}return n}()),s=(t=PNe)?t.createScriptURL(s):s,new class{constructor(n){this.g=n}toString(){return this.g+""}}(s)}function _G(s,...t){if(t.length===0)return gQe(s[0]);let n=s[0];for(let r=0;r({index:Iv(r,1)??0??-1,score:Sh(r,2)??0,categoryName:wf(Pu(r,3))??""??"",displayName:wf(Pu(r,4))??""??""})),headIndex:t,headName:n}}function LYs(s){const t={classifications:bN(s,fYs,1).map(n=>{var r;return a8e(((r=Yl(n,djt,4))==null?void 0:r.g())??[],Iv(n,2)??0,wf(Pu(n,3))??"")})};return function(n){return n==null?n:typeof n=="bigint"?(aTe(n)?n=Number(n):(n=UU(64,n),n=aTe(n)?Number(n):String(n)),n):qU(n)?typeof n=="number"?SLe(n):xwt(n):void 0}(Pu(s,2,void 0,void 0,zge))!=null&&(t.timestampMs=Ojt(Pu(s,2,void 0,void 0,zge)??wwt)),t}function Fjt(s){var l,o;var t=iA(s,3,ow,aA()),n=iA(s,2,CR,aA()),r=iA(s,1,wf,aA()),a=iA(s,9,wf,aA());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function EQe(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 AQe(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 $jt(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 ki(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 MQe(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]=$jt(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 IQe(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 E_(s,t,n){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=n}function Ak(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)}}dP.forVisionTasks=function(s,t=!1){return jG("vision",s??_G``,t)},dP.forTextTasks=function(s,t=!1){return jG("text",s??_G``,t)},dP.forGenAiTasks=function(s,t=!1){return jG("genai",s??_G``,t)},dP.forAudioTasks=function(s,t=!1){return jG("audio",s??_G``,t)},dP.isSimdSupported=function(s=!1){return zjt(s)};async function RYs(s,t,n,r){return s=await(async(a,i,l,o,c)=>{if(i&&await AQe(i),!self.ModuleFactory||l&&(await AQe(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 RNe(s,t){const n=Yl(s.baseOptions,Hge,1)||new Hge;typeof t=="string"?(Gc(n,2,VU(t)),Gc(n,1)):t instanceof Uint8Array&&(Gc(n,1,wLe(t,!1)),Gc(n,2)),Qi(s.baseOptions,0,1,n)}function PQe(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 di(s,t){s.C=Math.max(s.C,t)}function nbe(s,t){s.B=new l0,_y(s.B,2,"PassThroughCalculator"),hu(s.B,"free_memory"),Ll(s.B,"free_memory_unused_out"),Bu(t,"free_memory"),n1(t,s.B)}function xD(s,t){hu(s.B,t),Ll(s.B,t+"_unused_out")}function rbe(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var pTe=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=Yl(this.baseOptions,Hge,1))!=null&&a.g()||(i=Yl(this.baseOptions,Hge,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=Yl(d.baseOptions,NQe,3);if(!h){var p=h=new NQe,f=new yQe;Tz(p,4,ape,f)}"delegate"in u&&(u.delegate==="GPU"?(u=h,p=new lYs,Tz(u,2,ape,p)):(u=h,p=new yQe,Tz(u,4,ape,p))),Qi(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),RNe(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)RNe(this,c.modelAssetBuffer);else if(c.modelAssetBuffer)return async function(d){const u=[];for(var h=0;;){const{done:p,value:f}=await d.read();if(p)break;u.push(f),h+=f.length}if(u.length===0)return new Uint8Array(0);if(u.length===1)return u[0];d=new Uint8Array(h),h=0;for(const p of u)d.set(p,h),h+=p.length;return d}(c.modelAssetBuffer).then(d=>{RNe(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=cYs(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,PQe(this)}finishProcessing(){this.g.finishProcessing(),PQe(this)}close(){this.B=void 0,this.g.closeGraph()}};function w4(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}pTe.prototype.close=pTe.prototype.close;class OYs{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 LQe(s,t,n){const r=s.g;if(n=w4(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 DQe(s,t){const n=s.g,r=w4(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(r);const a=w4(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=w4(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 OYs(n,r,a,i)}function i8e(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function FYs(s,t,n,r){return i8e(s,t),s.h||(s.m(),s.D()),n?(s.u||(s.u=DQe(s,!0)),n=s.u):(s.A||(s.A=DQe(s,!1)),n=s.A),t.useProgram(s.h),n.bind(),s.l(),s=r(),n.g.bindVertexArray(null),s}function Ujt(s,t,n){return i8e(s,t),s=w4(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 qjt(s,t,n){i8e(s,t),s.B||(s.B=w4(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 zYs(s){var t;(t=s.g)==null||t.bindFramebuffer(s.g.FRAMEBUFFER,null)}var Vjt=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=w4(s.createProgram(),"Failed to create WebGL program"),this.X=LQe(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=LQe(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 P2(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 fTe(s){var t=P2(s,1);if(!t){if(t=P2(s,0))t=new Float32Array(t).map(r=>r/255);else{t=new Float32Array(s.width*s.height);const r=gD(s);var n=o8e(s);if(qjt(n,r,Hjt(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 fTe(this)}N(){return Hjt(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=gD(this),a=o8e(this);r.activeTexture(r.TEXTURE1),n=Ujt(a,r,this.m?r.LINEAR:r.NEAREST),r.bindTexture(r.TEXTURE_2D,n);const i=Gjt(this);r.texImage2D(r.TEXTURE_2D,0,i,this.width,this.height,0,r.RED,r.FLOAT,null),r.bindTexture(r.TEXTURE_2D,null),qjt(a,r,n),FYs(a,r,!1,()=>{Wjt(this),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLE_FAN,0,4),xTe(this)}),zYs(a),xTe(this)}}s.push(n)}return new gp(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&gD(this).deleteTexture(P2(this,2)),RQe=-1}};gp.prototype.close=gp.prototype.close,gp.prototype.clone=gp.prototype.clone,gp.prototype.getAsWebGLTexture=gp.prototype.N,gp.prototype.getAsFloat32Array=gp.prototype.ia,gp.prototype.getAsUint8Array=gp.prototype.ja,gp.prototype.hasWebGLTexture=gp.prototype.R,gp.prototype.hasFloat32Array=gp.prototype.ka,gp.prototype.hasUint8Array=gp.prototype.Fa;var RQe=250;function Bb(...s){return s.map(([t,n])=>({start:t,end:n}))}const BYs=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((OQe=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:Bjt()?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?'),ki(this,r||"input_audio",i=>{ki(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){E_(this,"__graph_config__",t=>{s(t)}),ki(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),ki(this,r,l=>{this.i._addAudioToInputStream(this.g,t,n,l,a)})}addGpuBufferToStream(s,t,n){ki(this,t,r=>{const[a,i]=MQe(this,s,r);this.i._addBoundTextureToStream(r,a,i,n)})}addBoolToStream(s,t,n){ki(this,t,r=>{this.i._addBoolToInputStream(s,r,n)})}addDoubleToStream(s,t,n){ki(this,t,r=>{this.i._addDoubleToInputStream(s,r,n)})}addFloatToStream(s,t,n){ki(this,t,r=>{this.i._addFloatToInputStream(s,r,n)})}addIntToStream(s,t,n){ki(this,t,r=>{this.i._addIntToInputStream(s,r,n)})}addUintToStream(s,t,n){ki(this,t,r=>{this.i._addUintToInputStream(s,r,n)})}addStringToStream(s,t,n){ki(this,t,r=>{ki(this,s,a=>{this.i._addStringToInputStream(a,r,n)})})}addStringRecordToStream(s,t,n){ki(this,t,r=>{IQe(this,Object.keys(s),a=>{IQe(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,r,n)})})})}addProtoToStream(s,t,n,r){ki(this,n,a=>{ki(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){ki(this,s,n=>{this.i._addEmptyPacketToInputStream(n,t)})}addBoolVectorToStream(s,t,n){ki(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){ki(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){ki(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){ki(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){ki(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){ki(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)ki(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,r,n)})}addBoolToInputSidePacket(s,t){ki(this,t,n=>{this.i._addBoolToInputSidePacket(s,n)})}addDoubleToInputSidePacket(s,t){ki(this,t,n=>{this.i._addDoubleToInputSidePacket(s,n)})}addFloatToInputSidePacket(s,t){ki(this,t,n=>{this.i._addFloatToInputSidePacket(s,n)})}addIntToInputSidePacket(s,t){ki(this,t,n=>{this.i._addIntToInputSidePacket(s,n)})}addUintToInputSidePacket(s,t){ki(this,t,n=>{this.i._addUintToInputSidePacket(s,n)})}addStringToInputSidePacket(s,t){ki(this,t,n=>{ki(this,s,r=>{this.i._addStringToInputSidePacket(r,n)})})}addProtoToInputSidePacket(s,t,n){ki(this,n,r=>{ki(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){ki(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){ki(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){ki(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){ki(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){ki(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){ki(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)ki(this,a,i=>{this.i._addStringVectorEntry(r,i)});this.i._addStringVectorToInputSidePacket(r,n)})}attachBoolListener(s,t){E_(this,s,t),ki(this,s,n=>{this.i._attachBoolListener(n)})}attachBoolVectorListener(s,t){Ak(this,s,t),ki(this,s,n=>{this.i._attachBoolVectorListener(n)})}attachIntListener(s,t){E_(this,s,t),ki(this,s,n=>{this.i._attachIntListener(n)})}attachIntVectorListener(s,t){Ak(this,s,t),ki(this,s,n=>{this.i._attachIntVectorListener(n)})}attachUintListener(s,t){E_(this,s,t),ki(this,s,n=>{this.i._attachUintListener(n)})}attachUintVectorListener(s,t){Ak(this,s,t),ki(this,s,n=>{this.i._attachUintVectorListener(n)})}attachDoubleListener(s,t){E_(this,s,t),ki(this,s,n=>{this.i._attachDoubleListener(n)})}attachDoubleVectorListener(s,t){Ak(this,s,t),ki(this,s,n=>{this.i._attachDoubleVectorListener(n)})}attachFloatListener(s,t){E_(this,s,t),ki(this,s,n=>{this.i._attachFloatListener(n)})}attachFloatVectorListener(s,t){Ak(this,s,t),ki(this,s,n=>{this.i._attachFloatVectorListener(n)})}attachStringListener(s,t){E_(this,s,t),ki(this,s,n=>{this.i._attachStringListener(n)})}attachStringVectorListener(s,t){Ak(this,s,t),ki(this,s,n=>{this.i._attachStringVectorListener(n)})}attachProtoListener(s,t,n){E_(this,s,t),ki(this,s,r=>{this.i._attachProtoListener(r,n||!1)})}attachProtoVectorListener(s,t,n){Ak(this,s,t),ki(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?'),E_(this,s,(r,a)=>{r=new Float32Array(r.buffer,r.byteOffset,r.length/4),t(r,a)}),ki(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 OQe{get ga(){return this.i}pa(s,t,n){ki(this,t,r=>{const[a,i]=MQe(this,s,r);this.ga._addBoundTextureAsImageToStream(r,a,i,n)})}Z(s,t){E_(this,s,t),ki(this,s,n=>{this.ga._attachImageListener(n)})}aa(s,t){Ak(this,s,t),ki(this,s,n=>{this.ga._attachImageVectorListener(n)})}}));var OQe,$b=class extends BYs{};async function Gl(s,t,n){return async function(r,a,i,l){return RYs(r,a,i,l)}(s,n.canvas??(Bjt()?void 0:document.createElement("canvas")),t,n)}function Kjt(s,t,n,r){if(s.U){const i=new fjt;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].");Pi(i,1,(a.left+a.right)/2),Pi(i,2,(a.top+a.bottom)/2),Pi(i,4,a.right-a.left),Pi(i,3,a.bottom-a.top)}else Pi(i,1,.5),Pi(i,2,.5),Pi(i,4,1),Pi(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(Pi(i,5,-Math.PI*n.rotationDegrees/180),(n==null?void 0:n.rotationDegrees)%180!=0){const[l,o]=$jt(t);n=Sh(i,3)*o/l,a=Sh(i,4)*l/o,Pi(i,4,n),Pi(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 Ub(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'.");Kjt(s,t,n,s.C+1)}function aj(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'.");Kjt(s,t,n,r)}function yD(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 gp([a],n,!1,s.g.i.canvas,s.P,i,t),r?s.clone():s}var wy=class extends pTe{constructor(s,t,n,r){super(s),this.g=s,this.X=t,this.U=n,this.oa=r,this.P=new Vjt}l(s,t=!0){if("runningMode"in s&&Gc(this.baseOptions,2,v$(!!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()}};wy.prototype.close=wy.prototype.close;var ov=class extends wy{constructor(s,t){super(new $b(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},Qi(s=this.h=new tbe,0,1,t=new fh),Pi(this.h,2,.5),Pi(this.h,3,.3)}get baseOptions(){return Yl(this.h,fh,1)}set baseOptions(s){Qi(this.h,0,1,s)}o(s){return"minDetectionConfidence"in s&&Pi(this.h,2,s.minDetectionConfidence??.5),"minSuppressionThreshold"in s&&Pi(this.h,3,s.minSuppressionThreshold??.3),this.l(s)}F(s,t){return this.j={detections:[]},Ub(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},aj(this,s,n,t),this.j}m(){var s=new Ty;Bu(s,"image_in"),Bu(s,"norm_rect_in"),ic(s,"detections");const t=new Cy;nj(t,_Ys,this.h);const n=new l0;_y(n,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),hu(n,"IMAGE:image_in"),hu(n,"NORM_RECT:norm_rect_in"),Ll(n,"DETECTIONS:detections"),n.o(t),n1(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=hjt(i),this.j.detections.push(Fjt(r));di(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{di(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};ov.prototype.detectForVideo=ov.prototype.G,ov.prototype.detect=ov.prototype.F,ov.prototype.setOptions=ov.prototype.o,ov.createFromModelPath=async function(s,t){return Gl(ov,s,{baseOptions:{modelAssetPath:t}})},ov.createFromModelBuffer=function(s,t){return Gl(ov,s,{baseOptions:{modelAssetBuffer:t}})},ov.createFromOptions=function(s,t){return Gl(ov,s,t)};var l8e=Bb([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]),c8e=Bb([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]),d8e=Bb([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),Yjt=Bb([474,475],[475,476],[476,477],[477,474]),u8e=Bb([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]),h8e=Bb([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),Zjt=Bb([469,470],[470,471],[471,472],[472,469]),m8e=Bb([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]),Qjt=[...l8e,...c8e,...d8e,...u8e,...h8e,...m8e],Xjt=Bb([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 FQe(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var Xu=class extends wy{constructor(s,t){super(new $b(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,Qi(s=this.h=new bjt,0,1,t=new fh),this.A=new vjt,Qi(this.h,0,3,this.A),this.u=new tbe,Qi(this.h,0,2,this.u),_N(this.u,4,1),Pi(this.u,2,.5),Pi(this.A,2,.5),Pi(this.h,4,.5)}get baseOptions(){return Yl(this.h,fh,1)}set baseOptions(s){Qi(this.h,0,1,s)}o(s){return"numFaces"in s&&_N(this.u,4,s.numFaces??1),"minFaceDetectionConfidence"in s&&Pi(this.u,2,s.minFaceDetectionConfidence??.5),"minTrackingConfidence"in s&&Pi(this.h,4,s.minTrackingConfidence??.5),"minFacePresenceConfidence"in s&&Pi(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 FQe(this),Ub(this,s,t),this.j}G(s,t,n){return FQe(this),aj(this,s,n,t),this.j}m(){var s=new Ty;Bu(s,"image_in"),Bu(s,"norm_rect"),ic(s,"face_landmarks");const t=new Cy;nj(t,jYs,this.h);const n=new l0;_y(n,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),hu(n,"IMAGE:image_in"),hu(n,"NORM_RECT:norm_rect"),Ll(n,"NORM_LANDMARKS:face_landmarks"),n.o(t),n1(s,n),this.g.attachProtoVectorListener("face_landmarks",(r,a)=>{for(const i of r)r=WU(i),this.j.faceLandmarks.push(sbe(r));di(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",r=>{di(this,r)}),this.outputFaceBlendshapes&&(ic(s,"blendshapes"),Ll(n,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(r,a)=>{if(this.outputFaceBlendshapes)for(const i of r)r=ebe(i),this.j.faceBlendshapes.push(a8e(r.g()??[]));di(this,a)}),this.g.attachEmptyPacketListener("blendshapes",r=>{di(this,r)})),this.outputFacialTransformationMatrixes&&(ic(s,"face_geometry"),Ll(n,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(r,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of r)(r=Yl(r=wYs(i),mYs,2))&&this.j.facialTransformationMatrixes.push({rows:Iv(r,1)??0??0,columns:Iv(r,2)??0??0,data:iA(r,3,ow,aA()).slice()??[]});di(this,a)}),this.g.attachEmptyPacketListener("face_geometry",r=>{di(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Xu.prototype.detectForVideo=Xu.prototype.G,Xu.prototype.detect=Xu.prototype.F,Xu.prototype.setOptions=Xu.prototype.o,Xu.createFromModelPath=function(s,t){return Gl(Xu,s,{baseOptions:{modelAssetPath:t}})},Xu.createFromModelBuffer=function(s,t){return Gl(Xu,s,{baseOptions:{modelAssetBuffer:t}})},Xu.createFromOptions=function(s,t){return Gl(Xu,s,t)},Xu.FACE_LANDMARKS_LIPS=l8e,Xu.FACE_LANDMARKS_LEFT_EYE=c8e,Xu.FACE_LANDMARKS_LEFT_EYEBROW=d8e,Xu.FACE_LANDMARKS_LEFT_IRIS=Yjt,Xu.FACE_LANDMARKS_RIGHT_EYE=u8e,Xu.FACE_LANDMARKS_RIGHT_EYEBROW=h8e,Xu.FACE_LANDMARKS_RIGHT_IRIS=Zjt,Xu.FACE_LANDMARKS_FACE_OVAL=m8e,Xu.FACE_LANDMARKS_CONTOURS=Qjt,Xu.FACE_LANDMARKS_TESSELATION=Xjt;var p8e=Bb([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 zQe(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function BQe(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 $Qe(s,t=!0){const n=[];for(const a of s){var r=ebe(a);s=[];for(const i of r.g())r=t&&Iv(i,1)!=null?Iv(i,1)??0:-1,s.push({score:Sh(i,2)??0,index:r,categoryName:wf(Pu(i,3))??""??"",displayName:wf(Pu(i,4))??""??""});n.push(s)}return n}var M0=class extends wy{constructor(s,t){super(new $b(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Qi(s=this.j=new jjt,0,1,t=new fh),this.u=new t8e,Qi(this.j,0,2,this.u),this.D=new e8e,Qi(this.u,0,3,this.D),this.A=new wjt,Qi(this.u,0,2,this.A),this.h=new NYs,Qi(this.j,0,3,this.h),Pi(this.A,2,.5),Pi(this.u,4,.5),Pi(this.D,2,.5)}get baseOptions(){return Yl(this.j,fh,1)}set baseOptions(s){Qi(this.j,0,1,s)}o(s){var a,i,l,o;if(_N(this.A,3,s.numHands??1),"minHandDetectionConfidence"in s&&Pi(this.A,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Pi(this.u,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Pi(this.D,2,s.minHandPresenceConfidence??.5),s.cannedGesturesClassifierOptions){var t=new BI,n=t,r=mTe(s.cannedGesturesClassifierOptions,(a=Yl(this.h,BI,3))==null?void 0:a.l());Qi(n,0,2,r),Qi(this.h,0,3,t)}else s.cannedGesturesClassifierOptions===void 0&&((i=Yl(this.h,BI,3))==null||i.g());return s.customGesturesClassifierOptions?(Qi(n=t=new BI,0,2,r=mTe(s.customGesturesClassifierOptions,(l=Yl(this.h,BI,4))==null?void 0:l.l())),Qi(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=Yl(this.h,BI,4))==null||o.g()),this.l(s)}Ha(s,t){return zQe(this),Ub(this,s,t),BQe(this)}Ia(s,t,n){return zQe(this),aj(this,s,n,t),BQe(this)}m(){var s=new Ty;Bu(s,"image_in"),Bu(s,"norm_rect"),ic(s,"hand_gestures"),ic(s,"hand_landmarks"),ic(s,"world_hand_landmarks"),ic(s,"handedness");const t=new Cy;nj(t,kYs,this.j);const n=new l0;_y(n,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),hu(n,"IMAGE:image_in"),hu(n,"NORM_RECT:norm_rect"),Ll(n,"HAND_GESTURES:hand_gestures"),Ll(n,"LANDMARKS:hand_landmarks"),Ll(n,"WORLD_LANDMARKS:world_hand_landmarks"),Ll(n,"HANDEDNESS:handedness"),n.o(t),n1(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r){r=WU(i);const l=[];for(const o of bN(r,pjt,1))l.push({x:Sh(o,1)??0,y:Sh(o,2)??0,z:Sh(o,3)??0,visibility:Sh(o,4)??0});this.landmarks.push(l)}di(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{di(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r){r=VL(i);const l=[];for(const o of bN(r,mjt,1))l.push({x:Sh(o,1)??0,y:Sh(o,2)??0,z:Sh(o,3)??0,visibility:Sh(o,4)??0});this.worldLandmarks.push(l)}di(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{di(this,r)}),this.g.attachProtoVectorListener("hand_gestures",(r,a)=>{this.gestures.push(...$Qe(r,!1)),di(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",r=>{di(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{this.handedness.push(...$Qe(r)),di(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{di(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function UQe(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}M0.prototype.recognizeForVideo=M0.prototype.Ia,M0.prototype.recognize=M0.prototype.Ha,M0.prototype.setOptions=M0.prototype.o,M0.createFromModelPath=function(s,t){return Gl(M0,s,{baseOptions:{modelAssetPath:t}})},M0.createFromModelBuffer=function(s,t){return Gl(M0,s,{baseOptions:{modelAssetBuffer:t}})},M0.createFromOptions=function(s,t){return Gl(M0,s,t)},M0.HAND_CONNECTIONS=p8e;var I0=class extends wy{constructor(s,t){super(new $b(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Qi(s=this.h=new t8e,0,1,t=new fh),this.u=new e8e,Qi(this.h,0,3,this.u),this.j=new wjt,Qi(this.h,0,2,this.j),_N(this.j,3,1),Pi(this.j,2,.5),Pi(this.u,2,.5),Pi(this.h,4,.5)}get baseOptions(){return Yl(this.h,fh,1)}set baseOptions(s){Qi(this.h,0,1,s)}o(s){return"numHands"in s&&_N(this.j,3,s.numHands??1),"minHandDetectionConfidence"in s&&Pi(this.j,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Pi(this.h,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Pi(this.u,2,s.minHandPresenceConfidence??.5),this.l(s)}F(s,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Ub(this,s,t),UQe(this)}G(s,t,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],aj(this,s,n,t),UQe(this)}m(){var s=new Ty;Bu(s,"image_in"),Bu(s,"norm_rect"),ic(s,"hand_landmarks"),ic(s,"world_hand_landmarks"),ic(s,"handedness");const t=new Cy;nj(t,SYs,this.h);const n=new l0;_y(n,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),hu(n,"IMAGE:image_in"),hu(n,"NORM_RECT:norm_rect"),Ll(n,"LANDMARKS:hand_landmarks"),Ll(n,"WORLD_LANDMARKS:world_hand_landmarks"),Ll(n,"HANDEDNESS:handedness"),n.o(t),n1(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r)r=WU(i),this.landmarks.push(sbe(r));di(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{di(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r)r=VL(i),this.worldLandmarks.push(Az(r));di(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{di(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{var i=this.handedness,l=i.push;const o=[];for(const c of r){r=ebe(c);const d=[];for(const u of r.g())d.push({score:Sh(u,2)??0,index:Iv(u,1)??0??-1,categoryName:wf(Pu(u,3))??""??"",displayName:wf(Pu(u,4))??""??""});o.push(d)}l.call(i,...o),di(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{di(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};I0.prototype.detectForVideo=I0.prototype.G,I0.prototype.detect=I0.prototype.F,I0.prototype.setOptions=I0.prototype.o,I0.createFromModelPath=function(s,t){return Gl(I0,s,{baseOptions:{modelAssetPath:t}})},I0.createFromModelBuffer=function(s,t){return Gl(I0,s,{baseOptions:{modelAssetBuffer:t}})},I0.createFromOptions=function(s,t){return Gl(I0,s,t)},I0.HAND_CONNECTIONS=p8e;var Jjt=Bb([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 qQe(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function VQe(s){try{if(!s.D)return s.h;s.D(s.h)}finally{rbe(s)}}function kG(s,t){s=WU(s),t.push(sbe(s))}var Jd=class extends wy{constructor(s,t){super(new $b(s,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,Qi(s=this.j=new Tjt,0,1,t=new fh),this.I=new e8e,Qi(this.j,0,2,this.I),this.W=new CYs,Qi(this.j,0,3,this.W),this.u=new tbe,Qi(this.j,0,4,this.u),this.O=new vjt,Qi(this.j,0,5,this.O),this.A=new Sjt,Qi(this.j,0,6,this.A),this.M=new Cjt,Qi(this.j,0,7,this.M),Pi(this.u,2,.5),Pi(this.u,3,.3),Pi(this.O,2,.5),Pi(this.A,2,.5),Pi(this.A,3,.3),Pi(this.M,2,.5),Pi(this.I,2,.5)}get baseOptions(){return Yl(this.j,fh,1)}set baseOptions(s){Qi(this.j,0,1,s)}o(s){return"minFaceDetectionConfidence"in s&&Pi(this.u,2,s.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in s&&Pi(this.u,3,s.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in s&&Pi(this.O,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"minPoseDetectionConfidence"in s&&Pi(this.A,2,s.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in s&&Pi(this.A,3,s.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in s&&Pi(this.M,2,s.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in s&&(this.outputPoseSegmentationMasks=!!s.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in s&&Pi(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,qQe(this),Ub(this,s,r),VQe(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.D=typeof n=="function"?n:r,qQe(this),aj(this,s,a,t),VQe(this)}m(){var s=new Ty;Bu(s,"input_frames_image"),ic(s,"pose_landmarks"),ic(s,"pose_world_landmarks"),ic(s,"face_landmarks"),ic(s,"left_hand_landmarks"),ic(s,"left_hand_world_landmarks"),ic(s,"right_hand_landmarks"),ic(s,"right_hand_world_landmarks");const t=new Cy,n=new pQe;_y(n,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(a,i){if(i!=null)if(Array.isArray(i))Gc(a,2,U1e(i,0,b$));else{if(!(typeof i=="string"||i instanceof Ew||bLe(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");rS(a,2,wLe(i,!1),DM())}}(n,this.j.g());const r=new l0;_y(r,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),RLe(r,8,pQe,n),hu(r,"IMAGE:input_frames_image"),Ll(r,"POSE_LANDMARKS:pose_landmarks"),Ll(r,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),Ll(r,"FACE_LANDMARKS:face_landmarks"),Ll(r,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),Ll(r,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),Ll(r,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),Ll(r,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),r.o(t),n1(s,r),nbe(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{kG(a,this.h.poseLandmarks),di(this,i)}),this.g.attachEmptyPacketListener("pose_landmarks",a=>{di(this,a)}),this.g.attachProtoListener("pose_world_landmarks",(a,i)=>{var l=this.h.poseWorldLandmarks;a=VL(a),l.push(Az(a)),di(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{di(this,a)}),this.outputPoseSegmentationMasks&&(Ll(r,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),xD(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[yD(this,a,!0,!this.D)],di(this,i)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",a=>{this.h.poseSegmentationMasks=[],di(this,a)})),this.g.attachProtoListener("face_landmarks",(a,i)=>{kG(a,this.h.faceLandmarks),di(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{di(this,a)}),this.outputFaceBlendshapes&&(ic(s,"extra_blendshapes"),Ll(r,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=ebe(a),l.push(a8e(a.g()??[]))),di(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{di(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{kG(a,this.h.leftHandLandmarks),di(this,i)}),this.g.attachEmptyPacketListener("left_hand_landmarks",a=>{di(this,a)}),this.g.attachProtoListener("left_hand_world_landmarks",(a,i)=>{var l=this.h.leftHandWorldLandmarks;a=VL(a),l.push(Az(a)),di(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{di(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{kG(a,this.h.rightHandLandmarks),di(this,i)}),this.g.attachEmptyPacketListener("right_hand_landmarks",a=>{di(this,a)}),this.g.attachProtoListener("right_hand_world_landmarks",(a,i)=>{var l=this.h.rightHandWorldLandmarks;a=VL(a),l.push(Az(a)),di(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{di(this,a)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Jd.prototype.detectForVideo=Jd.prototype.G,Jd.prototype.detect=Jd.prototype.F,Jd.prototype.setOptions=Jd.prototype.o,Jd.createFromModelPath=function(s,t){return Gl(Jd,s,{baseOptions:{modelAssetPath:t}})},Jd.createFromModelBuffer=function(s,t){return Gl(Jd,s,{baseOptions:{modelAssetBuffer:t}})},Jd.createFromOptions=function(s,t){return Gl(Jd,s,t)},Jd.HAND_CONNECTIONS=p8e,Jd.POSE_CONNECTIONS=Jjt,Jd.FACE_LANDMARKS_LIPS=l8e,Jd.FACE_LANDMARKS_LEFT_EYE=c8e,Jd.FACE_LANDMARKS_LEFT_EYEBROW=d8e,Jd.FACE_LANDMARKS_LEFT_IRIS=Yjt,Jd.FACE_LANDMARKS_RIGHT_EYE=u8e,Jd.FACE_LANDMARKS_RIGHT_EYEBROW=h8e,Jd.FACE_LANDMARKS_RIGHT_IRIS=Zjt,Jd.FACE_LANDMARKS_FACE_OVAL=m8e,Jd.FACE_LANDMARKS_CONTOURS=Qjt,Jd.FACE_LANDMARKS_TESSELATION=Xjt;var lv=class extends wy{constructor(s,t){super(new $b(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},Qi(s=this.h=new Ejt,0,1,t=new fh)}get baseOptions(){return Yl(this.h,fh,1)}set baseOptions(s){Qi(this.h,0,1,s)}o(s){return Qi(this.h,0,2,mTe(s,Yl(this.h,XLe,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},Ub(this,s,t),this.j}ta(s,t,n){return this.j={classifications:[]},aj(this,s,n,t),this.j}m(){var s=new Ty;Bu(s,"input_image"),Bu(s,"norm_rect"),ic(s,"classifications");const t=new Cy;nj(t,TYs,this.h);const n=new l0;_y(n,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),hu(n,"IMAGE:input_image"),hu(n,"NORM_RECT:norm_rect"),Ll(n,"CLASSIFICATIONS:classifications"),n.o(t),n1(s,n),this.g.attachProtoListener("classifications",(r,a)=>{this.j=LYs(xYs(r)),di(this,a)}),this.g.attachEmptyPacketListener("classifications",r=>{di(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};lv.prototype.classifyForVideo=lv.prototype.ta,lv.prototype.classify=lv.prototype.sa,lv.prototype.setOptions=lv.prototype.o,lv.createFromModelPath=function(s,t){return Gl(lv,s,{baseOptions:{modelAssetPath:t}})},lv.createFromModelBuffer=function(s,t){return Gl(lv,s,{baseOptions:{modelAssetBuffer:t}})},lv.createFromOptions=function(s,t){return Gl(lv,s,t)};var P0=class extends wy{constructor(s,t){super(new $b(s,t),"image_in","norm_rect",!0),this.h=new Ajt,this.embeddings={embeddings:[]},Qi(s=this.h,0,1,t=new fh)}get baseOptions(){return Yl(this.h,fh,1)}set baseOptions(s){Qi(this.h,0,1,s)}o(s){var t=this.h,n=Yl(this.h,jQe,2);return n=n?n.clone():new jQe,s.l2Normalize!==void 0?Gc(n,1,v$(s.l2Normalize)):"l2Normalize"in s&&Gc(n,1),s.quantize!==void 0?Gc(n,2,v$(s.quantize)):"quantize"in s&&Gc(n,2),Qi(t,0,2,n),this.l(s)}za(s,t){return Ub(this,s,t),this.embeddings}Aa(s,t,n){return aj(this,s,n,t),this.embeddings}m(){var s=new Ty;Bu(s,"image_in"),Bu(s,"norm_rect"),ic(s,"embeddings_out");const t=new Cy;nj(t,EYs,this.h);const n=new l0;_y(n,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),hu(n,"IMAGE:image_in"),hu(n,"NORM_RECT:norm_rect"),Ll(n,"EMBEDDINGS:embeddings_out"),n.o(t),n1(s,n),this.g.attachProtoListener("embeddings_out",(r,a)=>{r=vYs(r),this.embeddings=function(i){return{embeddings:bN(i,yYs,1).map(l=>{var d,u;const o={headIndex:Iv(l,3)??0??-1,headName:wf(Pu(l,4))??""??""};var c=l.v;return Cwt(c,0|c[wi],wQe,MNe(l,1))!==void 0?(l=iA(l=Yl(l,wQe,MNe(l,1),void 0),1,ow,aA()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((u=(d=Yl(l,gYs,MNe(l,2),void 0))==null?void 0:d.na())==null?void 0:u.h())??c),o}),timestampMs:Ojt(Pu(i,2,void 0,void 0,zge)??wwt)}}(r),di(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",r=>{di(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};P0.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=EQe(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=EQe(TQe(s.quantizedEmbedding),TQe(t.quantizedEmbedding))}return s},P0.prototype.embedForVideo=P0.prototype.Aa,P0.prototype.embed=P0.prototype.za,P0.prototype.setOptions=P0.prototype.o,P0.createFromModelPath=function(s,t){return Gl(P0,s,{baseOptions:{modelAssetPath:t}})},P0.createFromModelBuffer=function(s,t){return Gl(P0,s,{baseOptions:{modelAssetBuffer:t}})},P0.createFromOptions=function(s,t){return Gl(P0,s,t)};var gTe=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 $Ys(s){var n,r;const t=function(a){return bN(a,l0,1)}(s.ca()).filter(a=>(wf(Pu(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=Yl(t[0],Cy,7))==null?void 0:n.j())==null?void 0:r.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=wf(Pu(a,1))??""})}function HQe(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function GQe(s){try{const t=new gTe(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{rbe(s)}}gTe.prototype.close=gTe.prototype.close;var Fx=class extends wy{constructor(s,t){super(new $b(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new r8e,this.A=new Mjt,Qi(this.h,0,3,this.A),Qi(s=this.h,0,1,t=new fh)}get baseOptions(){return Yl(this.h,fh,1)}set baseOptions(s){Qi(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?Gc(this.h,2,VU(s.displayNamesLocale)):"displayNamesLocale"in s&&Gc(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){$Ys(this)}segment(s,t,n){const r=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:n,HQe(this),Ub(this,s,r),GQe(this)}La(s,t,n,r){const a=typeof n!="function"?n:{};return this.j=typeof n=="function"?n:r,HQe(this),aj(this,s,a,t),GQe(this)}Da(){return this.u}m(){var s=new Ty;Bu(s,"image_in"),Bu(s,"norm_rect");const t=new Cy;nj(t,Pjt,this.h);const n=new l0;_y(n,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),hu(n,"IMAGE:image_in"),hu(n,"NORM_RECT:norm_rect"),n.o(t),n1(s,n),nbe(this,s),this.outputConfidenceMasks&&(ic(s,"confidence_masks"),Ll(n,"CONFIDENCE_MASKS:confidence_masks"),xD(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>yD(this,i,!0,!this.j)),di(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],di(this,r)})),this.outputCategoryMask&&(ic(s,"category_mask"),Ll(n,"CATEGORY_MASK:category_mask"),xD(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=yD(this,r,!1,!this.j),di(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,di(this,r)})),ic(s,"quality_scores"),Ll(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,di(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,di(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Fx.prototype.getLabels=Fx.prototype.Da,Fx.prototype.segmentForVideo=Fx.prototype.La,Fx.prototype.segment=Fx.prototype.segment,Fx.prototype.setOptions=Fx.prototype.o,Fx.createFromModelPath=function(s,t){return Gl(Fx,s,{baseOptions:{modelAssetPath:t}})},Fx.createFromModelBuffer=function(s,t){return Gl(Fx,s,{baseOptions:{modelAssetBuffer:t}})},Fx.createFromOptions=function(s,t){return Gl(Fx,s,t)};var yTe=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()}};yTe.prototype.close=yTe.prototype.close;var A_=class extends wy{constructor(s,t){super(new $b(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new r8e,this.u=new Mjt,Qi(this.h,0,3,this.u),Qi(s=this.h,0,1,t=new fh)}get baseOptions(){return Yl(this.h,fh,1)}set baseOptions(s){Qi(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 Ljt,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new DNe;rS(i,3,v$(!0),!1),rS(i,1,C7(t.keypoint.x),0),rS(i,2,C7(t.keypoint.y),0),Tz(r,1,hTe,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new MYs;for(i of t.scribble)rS(t=new DNe,3,v$(!0),!1),rS(t,1,C7(i.x),0),rS(t,2,C7(i.y),0),RLe(o,1,DNe,t);Tz(r,2,hTe,o)}}this.g.addProtoToStream(r.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",n),Ub(this,s,a);e:{try{const o=new yTe(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{rbe(this)}l=void 0}return l}m(){var s=new Ty;Bu(s,"image_in"),Bu(s,"roi_in"),Bu(s,"norm_rect_in");const t=new Cy;nj(t,Pjt,this.h);const n=new l0;_y(n,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),hu(n,"IMAGE:image_in"),hu(n,"ROI:roi_in"),hu(n,"NORM_RECT:norm_rect_in"),n.o(t),n1(s,n),nbe(this,s),this.outputConfidenceMasks&&(ic(s,"confidence_masks"),Ll(n,"CONFIDENCE_MASKS:confidence_masks"),xD(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>yD(this,i,!0,!this.j)),di(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],di(this,r)})),this.outputCategoryMask&&(ic(s,"category_mask"),Ll(n,"CATEGORY_MASK:category_mask"),xD(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=yD(this,r,!1,!this.j),di(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,di(this,r)})),ic(s,"quality_scores"),Ll(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,di(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,di(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};A_.prototype.segment=A_.prototype.segment,A_.prototype.setOptions=A_.prototype.o,A_.createFromModelPath=function(s,t){return Gl(A_,s,{baseOptions:{modelAssetPath:t}})},A_.createFromModelBuffer=function(s,t){return Gl(A_,s,{baseOptions:{modelAssetBuffer:t}})},A_.createFromOptions=function(s,t){return Gl(A_,s,t)};var cv=class extends wy{constructor(s,t){super(new $b(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},Qi(s=this.h=new Djt,0,1,t=new fh)}get baseOptions(){return Yl(this.h,fh,1)}set baseOptions(s){Qi(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?Gc(this.h,2,VU(s.displayNamesLocale)):"displayNamesLocale"in s&&Gc(this.h,2),s.maxResults!==void 0?_N(this.h,3,s.maxResults):"maxResults"in s&&Gc(this.h,3),s.scoreThreshold!==void 0?Pi(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&Gc(this.h,4),s.categoryAllowlist!==void 0?$ge(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&Gc(this.h,5),s.categoryDenylist!==void 0?$ge(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&Gc(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},Ub(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},aj(this,s,n,t),this.j}m(){var s=new Ty;Bu(s,"input_frame_gpu"),Bu(s,"norm_rect"),ic(s,"detections");const t=new Cy;nj(t,IYs,this.h);const n=new l0;_y(n,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),hu(n,"IMAGE:input_frame_gpu"),hu(n,"NORM_RECT:norm_rect"),Ll(n,"DETECTIONS:detections"),n.o(t),n1(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=hjt(i),this.j.detections.push(Fjt(r));di(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{di(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};cv.prototype.detectForVideo=cv.prototype.G,cv.prototype.detect=cv.prototype.F,cv.prototype.setOptions=cv.prototype.o,cv.createFromModelPath=async function(s,t){return Gl(cv,s,{baseOptions:{modelAssetPath:t}})},cv.createFromModelBuffer=function(s,t){return Gl(cv,s,{baseOptions:{modelAssetBuffer:t}})},cv.createFromOptions=function(s,t){return Gl(cv,s,t)};var vTe=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 WQe(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function KQe(s){try{const t=new vTe(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{rbe(s)}}vTe.prototype.close=vTe.prototype.close;var L0=class extends wy{constructor(s,t){super(new $b(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,Qi(s=this.h=new Rjt,0,1,t=new fh),this.A=new Cjt,Qi(this.h,0,3,this.A),this.j=new Sjt,Qi(this.h,0,2,this.j),_N(this.j,4,1),Pi(this.j,2,.5),Pi(this.A,2,.5),Pi(this.h,4,.5)}get baseOptions(){return Yl(this.h,fh,1)}set baseOptions(s){Qi(this.h,0,1,s)}o(s){return"numPoses"in s&&_N(this.j,4,s.numPoses??1),"minPoseDetectionConfidence"in s&&Pi(this.j,2,s.minPoseDetectionConfidence??.5),"minTrackingConfidence"in s&&Pi(this.h,4,s.minTrackingConfidence??.5),"minPosePresenceConfidence"in s&&Pi(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,WQe(this),Ub(this,s,r),KQe(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.u=typeof n=="function"?n:r,WQe(this),aj(this,s,a,t),KQe(this)}m(){var s=new Ty;Bu(s,"image_in"),Bu(s,"norm_rect"),ic(s,"normalized_landmarks"),ic(s,"world_landmarks"),ic(s,"segmentation_masks");const t=new Cy;nj(t,PYs,this.h);const n=new l0;_y(n,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),hu(n,"IMAGE:image_in"),hu(n,"NORM_RECT:norm_rect"),Ll(n,"NORM_LANDMARKS:normalized_landmarks"),Ll(n,"WORLD_LANDMARKS:world_landmarks"),n.o(t),n1(s,n),nbe(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(r,a)=>{this.landmarks=[];for(const i of r)r=WU(i),this.landmarks.push(sbe(r));di(this,a)}),this.g.attachEmptyPacketListener("normalized_landmarks",r=>{this.landmarks=[],di(this,r)}),this.g.attachProtoVectorListener("world_landmarks",(r,a)=>{this.worldLandmarks=[];for(const i of r)r=VL(i),this.worldLandmarks.push(Az(r));di(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",r=>{this.worldLandmarks=[],di(this,r)}),this.outputSegmentationMasks&&(Ll(n,"SEGMENTATION_MASK:segmentation_masks"),xD(this,"segmentation_masks"),this.g.aa("segmentation_masks",(r,a)=>{this.segmentationMasks=r.map(i=>yD(this,i,!0,!this.u)),di(this,a)}),this.g.attachEmptyPacketListener("segmentation_masks",r=>{this.segmentationMasks=[],di(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};L0.prototype.detectForVideo=L0.prototype.G,L0.prototype.detect=L0.prototype.F,L0.prototype.setOptions=L0.prototype.o,L0.createFromModelPath=function(s,t){return Gl(L0,s,{baseOptions:{modelAssetPath:t}})},L0.createFromModelBuffer=function(s,t){return Gl(L0,s,{baseOptions:{modelAssetBuffer:t}})},L0.createFromOptions=function(s,t){return Gl(L0,s,t)},L0.POSE_CONNECTIONS=Jjt;let oA=null,T7=null;async function UYs(){return oA||T7||(T7=(async()=>{const s=await dP.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return oA=await Fx.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}),oA})(),T7)}function qYs(s,t,n,r,a){const i=new Float32Array(s.length);for(let l=0;l=0&&(o-=s[c+u]);const p=Math.min(h,n-1)-Math.max(u+1,0)+1;i[c+d]=o/p}}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 VYs(){oA&&(oA.close(),oA=null,T7=null)}function HYs(s,t){const n=N.useRef(null),r=N.useRef(null),a=N.useRef(null),i=N.useRef(null),l=N.useRef(0);N.useRef(0);const[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,p]=N.useState(null),f=t.type!=="none"&&s!==null;return N.useEffect(()=>{if(t.type==="image"&&t.imageUrl){const g=new Image;g.crossOrigin="anonymous",g.src=t.imageUrl,g.onload=()=>{i.current=g}}else i.current=null},[t.type,t.imageUrl]),N.useEffect(()=>{if(!f||!s){a.current&&(a.current.srcObject=null,a.current=null);return}const g=document.createElement("video");return g.srcObject=s,g.muted=!0,g.playsInline=!0,g.autoplay=!0,g.play().catch(()=>{}),a.current=g,()=>{g.srcObject=null,a.current=null}},[f,s]),N.useEffect(()=>{if(!f){c(null),p(null);return}let g=!1;return(async()=>{u(!0),p(null);try{const v=await UYs();if(g)return;u(!1);const j=a.current;if(!j||(await new Promise(Ae=>{if(j.videoWidth>0)return Ae();j.onloadedmetadata=()=>Ae(),setTimeout(Ae,2e3)}),g))return;const b=j.videoWidth||640,S=j.videoHeight||480,A=n.current;if(!A)return;A.width=b,A.height=S;const T=A.getContext("2d",{willReadFrequently:!1,alpha:!1});r.current||(r.current=document.createElement("canvas"));const L=r.current;L.width=b,L.height=S;const D=L.getContext("2d",{willReadFrequently:!1}),M=document.createElement("canvas");M.width=b,M.height=S;const F=M.getContext("2d",{alpha:!1}),z=document.createElement("canvas");z.width=b,z.height=S;const V=z.getContext("2d",{willReadFrequently:!1}),W=V.createImageData(b,S),Y=W.data;for(let Ae=0;AeK.addTrack(Ae)),g||c(K);const ne=t.blurRadius??15,ie=t.mirror??!1,he=new Float32Array(b*S),ce=new Float32Array(b*S),pe=new Float32Array(b*S);let le=!1;const ve=4,ge=.35,Te=typeof j.requestVideoFrameCallback=="function",Me=()=>{if(g||!a.current)return;const Ae=a.current;if(Ae.readyState<2){Ce(Ae);return}try{const De=performance.now(),Fe=v.segmentForVideo(Ae,De).confidenceMasks;if(Fe&&Fe.length>0){ce.fill(0);for(let qe=1;qe1?1:it}}if(qYs(ce,he,b,S,ve),le)for(let qe=0;qe=1?255:Ze*255|0}if(V.putImageData(W,0,0),t.type==="blur")F.filter=`blur(${ne}px)`,F.drawImage(Ae,0,0,b,S),F.filter="none",T.drawImage(M,0,0);else if(t.type==="image"&&i.current){const qe=i.current,be=qe.width/qe.height,Ze=b/S;let Ne=0,it=0,je=qe.width,Ge=qe.height;be>Ze?(je=qe.height*Ze,Ne=(qe.width-je)/2):(Ge=qe.width/Ze,it=(qe.height-Ge)/2),T.drawImage(qe,Ne,it,je,Ge,0,0,b,S)}else T.fillStyle="#000",T.fillRect(0,0,b,S);D.globalCompositeOperation="source-over",D.clearRect(0,0,b,S),D.drawImage(Ae,0,0,b,S),D.globalCompositeOperation="destination-in",D.drawImage(z,0,0),D.globalCompositeOperation="source-over",ie?(T.save(),T.translate(b,0),T.scale(-1,1),T.drawImage(L,0,0),T.restore()):T.drawImage(L,0,0);for(const qe of Fe)qe.close()}else T.drawImage(Ae,0,0,b,S)}catch{T.drawImage(Ae,0,0,b,S)}Ce(Ae)},Ce=Ae=>{g||(Te?Ae.requestVideoFrameCallback(()=>Me()):l.current=requestAnimationFrame(Me))};Ce(j)}catch(v){console.error("[useVirtualBackground] init error:",v),g||(u(!1),p(v.message||"Failed to initialize virtual background"))}})(),()=>{g=!0,l.current&&cancelAnimationFrame(l.current),c(null)}},[f,t.type,t.blurRadius,t.imageUrl,s]),N.useEffect(()=>()=>{VYs()},[]),{canvasRef:n,compositedStream:o,isLoading:d,isActive:f,error:h}}function u6({maxDurationSeconds:s=600,onRecordingComplete:t,onError:n,onRecordingStateChange:r,className:a,teleprompterContent:i}){const l=N.useRef(null),o=N.useRef(null),c=N.useRef(null),[d,u]=N.useState(null),h=N.useRef([]),p=N.useRef(null),f=N.useRef(null),g=N.useRef(null),_=N.useRef(null),v=wR(),[j,b]=N.useState("camera"),S=N.useRef(null),A=N.useRef(null),T=N.useRef(null),L=N.useRef(null),D=N.useRef(null),M=N.useRef(null),[F,z]=N.useState(!0),[V,W]=N.useState(!0),[Y,K]=N.useState(null),[J,ne]=N.useState(!1),[ie,he]=N.useState(!1),[ce,pe]=N.useState(null),[le,ve]=N.useState(null),[ge,Te]=N.useState(0),[Me,Ce]=N.useState("user"),[Ae,De]=N.useState(0),[Ie,Fe]=N.useState(!1),[qe,be]=N.useState(!0),[Ze,Ne]=N.useState(null),[it,je]=N.useState(!1),[Ge,Be]=N.useState(null),Ye=N.useRef(null),[We,rt]=N.useState(()=>{try{const Jn=localStorage.getItem("video-bg-config");if(Jn)return JSON.parse(Jn)}catch{}return{type:"none"}});N.useEffect(()=>{try{localStorage.setItem("video-bg-config",JSON.stringify(We))}catch{}},[We]);const[tt,at]=N.useState([]),[He,dt]=N.useState([]),[bt,vt]=N.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[Bt,Zt]=N.useState(()=>{try{return localStorage.getItem("video-cam-id")||""}catch{return""}});N.useEffect(()=>{try{localStorage.setItem("video-mic-id",bt)}catch{}},[bt]),N.useEffect(()=>{try{localStorage.setItem("video-cam-id",Bt)}catch{}},[Bt]),N.useEffect(()=>{var js,Dn,wr;if(!((js=navigator.mediaDevices)!=null&&js.enumerateDevices))return;const Jn=async()=>{try{const $r=await navigator.mediaDevices.enumerateDevices();at($r.filter(ss=>ss.kind==="audioinput")),dt($r.filter(ss=>ss.kind==="videoinput"))}catch($r){console.warn("[VideoRecorder] enumerateDevices failed",$r)}};return Jn(),(wr=(Dn=navigator.mediaDevices).addEventListener)==null||wr.call(Dn,"devicechange",Jn),()=>{var $r,ss;return(ss=($r=navigator.mediaDevices).removeEventListener)==null?void 0:ss.call($r,"devicechange",Jn)}},[Y]);const{canvasRef:Fs,compositedStream:Rs,isLoading:ms,isActive:Pt,error:Jt}=HYs(d,We),ft=N.useRef(n);ft.current=n;const Vt=N.useCallback(Jn=>{z(Jn)},[]),Ms=N.useRef(F),Xt=N.useCallback(()=>{T.current&&(cancelAnimationFrame(T.current),T.current=null),L.current&&(L.current.terminate(),L.current=null),S.current&&(S.current.getTracks().forEach(Jn=>Jn.stop()),S.current=null),D.current&&(D.current.getTracks().forEach(Jn=>Jn.stop()),D.current=null),M.current&&(M.current.srcObject=null,M.current=null)},[]),Js=N.useCallback(async()=>{var Jn;try{const js=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1920},height:{ideal:1080}},audio:!0});S.current=js;let Dn=null;try{Dn=await navigator.mediaDevices.getUserMedia({video:Bt?{deviceId:{exact:Bt},width:{ideal:320},height:{ideal:240}}:{width:{ideal:320},height:{ideal:240}},audio:!1})}catch{console.warn("[VideoRecorder] No webcam for PiP overlay")}let wr=null;try{wr=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,...bt?{deviceId:{exact:bt}}:{}}}),console.log("[VideoRecorder] mic acquired for screen recording",wr.getAudioTracks().map(nr=>nr.label))}catch(nr){console.warn("[VideoRecorder] No mic audio for screen recording",nr);try{wr=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{}}const $r=js.getVideoTracks()[0],ss=$r.getSettings(),Oe=ss.width||1920,Xe=ss.height||1080,ot=document.createElement("canvas");ot.width=Oe,ot.height=Xe,A.current=ot;const Nt=ot.getContext("2d");let Rt=null;Dn&&(Rt=document.createElement("video"),Rt.srcObject=Dn,Rt.muted=!0,Rt.playsInline=!0,Rt.autoplay=!0,await Rt.play(),M.current=Rt);const qt=document.createElement("video");qt.srcObject=js,qt.muted=!0,qt.playsInline=!0,qt.autoplay=!0,await qt.play();const xs=()=>{if(Nt.drawImage(qt,0,0,Oe,Xe),Rt&&Rt.readyState>=2){const nr=Math.round(Oe*.2),Ot=Math.round(nr*(Rt.videoHeight/Rt.videoWidth||.75)),fn=Oe-nr-20,sr=Xe-Ot-20,Hn=12;Nt.save(),Nt.beginPath(),Nt.moveTo(fn+Hn,sr),Nt.lineTo(fn+nr-Hn,sr),Nt.quadraticCurveTo(fn+nr,sr,fn+nr,sr+Hn),Nt.lineTo(fn+nr,sr+Ot-Hn),Nt.quadraticCurveTo(fn+nr,sr+Ot,fn+nr-Hn,sr+Ot),Nt.lineTo(fn+Hn,sr+Ot),Nt.quadraticCurveTo(fn,sr+Ot,fn,sr+Ot-Hn),Nt.lineTo(fn,sr+Hn),Nt.quadraticCurveTo(fn,sr,fn+Hn,sr),Nt.closePath(),Nt.clip(),Nt.translate(fn+nr,sr),Nt.scale(-1,1),Nt.drawImage(Rt,0,0,nr,Ot),Nt.restore(),Nt.strokeStyle="rgba(255,255,255,0.6)",Nt.lineWidth=2,Nt.beginPath(),Nt.moveTo(fn+Hn,sr),Nt.lineTo(fn+nr-Hn,sr),Nt.quadraticCurveTo(fn+nr,sr,fn+nr,sr+Hn),Nt.lineTo(fn+nr,sr+Ot-Hn),Nt.quadraticCurveTo(fn+nr,sr+Ot,fn+nr-Hn,sr+Ot),Nt.lineTo(fn+Hn,sr+Ot),Nt.quadraticCurveTo(fn,sr+Ot,fn,sr+Ot-Hn),Nt.lineTo(fn,sr+Hn),Nt.quadraticCurveTo(fn,sr,fn+Hn,sr),Nt.closePath(),Nt.stroke()}},rs="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}}",ks=new Blob([rs],{type:"application/javascript"}),ln=new Worker(URL.createObjectURL(ks));L.current=ln,ln.onmessage=()=>xs(),ln.postMessage({type:"start",fps:30}),xs();const Gs=ot.captureStream(30),Un=[],jr=js.getAudioTracks();jr.length&&Un.push(...jr),wr&&Un.push(...wr.getAudioTracks());const Sr=new MediaStream([...Gs.getVideoTracks(),...Un]);return D.current=Sr,$r.onended=()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),Xt()},Sr}catch(js){return console.error("[VideoRecorder] Screen capture error:",js),js.name!=="NotAllowedError"&&((Jn=ft.current)==null||Jn.call(ft,"Failed to start screen capture: "+(js.message||"Unknown error"))),null}},[Xt]),Cs=N.useCallback(async()=>{var js,Dn;W(!0),Ne(null);const Jn=v&&F;console.log("[VideoRecorder] initCamera start",{isMobile:v,usePortraitMode:F,shouldBePortrait:Jn,facingMode:Me});try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Camera not available in this browser or context. Try opening in a new tab.");c.current&&(console.log("[VideoRecorder] stopping existing stream"),c.current.getTracks().forEach(Nt=>Nt.stop()));const wr=v&&Jn?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},$r=Bt?{...wr,deviceId:{exact:Bt}}:{...wr,facingMode:{ideal:Me}},ss={echoCancellation:!0,noiseSuppression:!0,...bt?{deviceId:{exact:bt}}:{}};console.log("[VideoRecorder] requesting getUserMedia",$r);const Oe=await navigator.mediaDevices.getUserMedia({video:$r,audio:ss});if(console.log("[VideoRecorder] getUserMedia success"),Oe.getVideoTracks().length===0)throw new Error("Camera stream started but no video track was provided.");c.current=Oe,u(Oe),K(!0);const ot=Oe.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",ot.width,"x",ot.height),l.current){const Nt=l.current;Nt.srcObject=Oe,Nt.muted=!0,Nt.playsInline=!0,Nt.autoplay=!0,Nt.setAttribute("muted",""),Nt.setAttribute("playsinline",""),Nt.setAttribute("autoplay","");try{(js=Nt.load)==null||js.call(Nt)}catch(qt){console.warn("[VideoRecorder] videoEl.load failed",qt)}const Rt=async()=>{try{return await Nt.play(),console.log("[VideoRecorder] preview play ok"),je(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:Nt.readyState,videoWidth:Nt.videoWidth,videoHeight:Nt.videoHeight})},300),!0}catch(qt){return console.warn("[VideoRecorder] preview play blocked",qt),je(!0),!1}};await new Promise(qt=>{let xs=!1;const rs=()=>{xs||(xs=!0,qt())},ks=()=>{Rt().finally(rs)};Nt.onloadedmetadata=ks,Nt.onloadeddata=ks,setTimeout(rs,1500)})}try{f.current=new AudioContext;const Nt=f.current.createMediaStreamSource(Oe);g.current=f.current.createAnalyser(),g.current.fftSize=256,Nt.connect(g.current);const Rt=()=>{if(g.current){const qt=new Uint8Array(g.current.frequencyBinCount);g.current.getByteFrequencyData(qt);const xs=qt.reduce((rs,ks)=>rs+ks)/qt.length;De(Math.min(100,xs/128*100))}_.current=requestAnimationFrame(Rt)};Rt()}catch(Nt){console.warn("Audio context not available:",Nt)}}catch(wr){console.error("Camera initialization error:",wr),K(!1);let $r="Failed to access camera or microphone.";wr.name==="NotAllowedError"?$r="Camera permission denied. Please allow camera access in your browser settings.":wr.name==="NotFoundError"?$r="No camera found. Please connect a camera and try again.":wr.name==="NotReadableError"?$r="Camera is in use by another application. Please close other apps using the camera.":wr.message&&($r=wr.message),Ne($r),(Dn=ft.current)==null||Dn.call(ft,$r)}finally{W(!1)}},[Me,v,F,bt,Bt]);N.useEffect(()=>{Ms.current!==F&&Y&&!J&&!le&&(Ms.current=F,Cs())},[F,Y,J,le,Cs]),N.useEffect(()=>(Cs(),()=>{c.current&&c.current.getTracks().forEach(Jn=>Jn.stop()),p.current&&clearInterval(p.current),_.current&&cancelAnimationFrame(_.current),f.current&&f.current.close(),Ye.current&&clearInterval(Ye.current),le&&URL.revokeObjectURL(le),Xt()}),[Cs,le]),N.useEffect(()=>{if(V||Y!==!0||le)return;const Jn=c.current,js=l.current;!Jn||!js||Pt||(js.srcObject!==Jn&&(js.srcObject=Jn,js.muted=!0,js.playsInline=!0,js.autoplay=!0,js.setAttribute("muted",""),js.setAttribute("playsinline",""),js.setAttribute("autoplay","")),js.play().then(()=>je(!1)).catch(Dn=>{je(!0),console.warn("Live preview play blocked on mount:",Dn)}))},[Y,V,le,Pt]),N.useEffect(()=>{r==null||r(J)},[J,r]);const As=N.useCallback(async()=>{if(le)return;const Jn=l.current;if(Jn)try{await Jn.play(),je(!1)}catch(js){je(!0),console.warn("Live preview still blocked (needs user gesture):",js)}},[le]),rn=N.useCallback(()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),p.current&&(clearInterval(p.current),p.current=null),Xt(),ne(!1),he(!1)},[Xt]),tn=N.useCallback(async()=>{let Jn=null;if(j==="screen"){if(Jn=await Js(),!Jn)return}else Jn=Pt&&Rs?Rs:c.current;if(!Jn)return;As(),h.current=[],Te(0);const Dn=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].find($r=>MediaRecorder.isTypeSupported($r)),wr=new MediaRecorder(Jn,Dn?{mimeType:Dn,videoBitsPerSecond:j==="screen"?4e6:25e5}:{videoBitsPerSecond:j==="screen"?4e6:25e5});wr.ondataavailable=$r=>{$r.data.size>0&&h.current.push($r.data)},wr.onstop=()=>{var Xe;const $r=wr.mimeType||Dn||((Xe=h.current[0])==null?void 0:Xe.type)||"video/webm",ss=new Blob(h.current,{type:$r});pe(ss);const Oe=URL.createObjectURL(ss);ve(Oe)},o.current=wr,wr.start(100),ne(!0),p.current=setInterval(()=>{Te($r=>$r>=s-1?(rn(),s):$r+1)},1e3)},[As,s,rn,Pt,Rs,j,Js]),er=N.useCallback(()=>{Ye.current&&(clearInterval(Ye.current),Ye.current=null),Be(3);let Jn=3;Ye.current=setInterval(()=>{Jn-=1,Jn<=0?(Ye.current&&clearInterval(Ye.current),Ye.current=null,Be(null),tn()):Be(Jn)},1e3)},[tn]),gn=N.useCallback(()=>{o.current&&o.current.state==="recording"&&(o.current.pause(),he(!0),p.current&&clearInterval(p.current))},[]),In=N.useCallback(()=>{o.current&&o.current.state==="paused"&&(o.current.resume(),he(!1),p.current=setInterval(()=>{Te(Jn=>Jn>=s-1?(rn(),s):Jn+1)},1e3))},[s,rn]),Zn=N.useCallback(()=>{le&&URL.revokeObjectURL(le),pe(null),ve(null),Te(0),Fe(!1),be(!0),l.current&&c.current&&!Pt&&(l.current.srcObject=c.current,l.current.muted=!0,As())},[As,le,Pt]),ea=N.useCallback(()=>{Ce(Jn=>Jn==="user"?"environment":"user")},[]),vi=N.useCallback(()=>{ce&&t(ce,ge)},[ce,ge,t]),Ls=N.useCallback(()=>{l.current&&le&&(Ie?l.current.pause():(be(!1),l.current.muted=!1,l.current.play()),Fe(!Ie))},[le,Ie]);N.useEffect(()=>{if(!le)return;const Jn=l.current;if(!Jn)return;be(!1),Jn.pause(),Jn.removeAttribute("src"),Jn.srcObject=null,Jn.load(),Jn.src=le,Jn.currentTime=0,Jn.playsInline=!0,Jn.muted=!1,Jn.onended=()=>Fe(!1);const js=()=>{var $r;const Dn=Jn.error,wr=Dn?`Recorded video failed to play (code ${Dn.code}). Likely unsupported format/codec in this browser.`:"Recorded video failed to play.";console.warn("[VideoRecorder] recorded playback error",Dn),($r=ft.current)==null||$r.call(ft,wr)};return Jn.addEventListener("error",js),Jn.load(),()=>{Jn.removeEventListener("error",js)}},[le]);const fi=Jn=>{const js=Math.floor(Jn/60),Dn=Jn%60;return`${js}:${Dn.toString().padStart(2,"0")}`},Lr=j==="screen"?"aspect-video":v&&F?"aspect-[9/16]":"aspect-video";return V?e.jsx("div",{className:Et("flex items-center justify-center bg-black rounded-lg",Lr,a),children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(ts,{className:"h-12 w-12 animate-spin mx-auto mb-4"}),e.jsx("p",{children:"Initializing camera..."})]})}):Y===!1?e.jsx("div",{className:Et("flex items-center justify-center bg-black rounded-lg",Lr,a),children:e.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[e.jsx(Gi,{className:"h-12 w-12 mx-auto mb-4 text-destructive"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Camera Access Required"}),e.jsx("p",{className:"text-gray-400 mb-4 text-sm",children:Ze||"Please allow camera and microphone access to record videos."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(B,{onClick:()=>Cs(),variant:"secondary",className:"w-full",children:[e.jsx(Ti,{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:[!J&&!le&&e.jsxs("div",{className:"flex items-center justify-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs(B,{variant:j==="camera"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>b("camera"),children:[e.jsx(mf,{className:"h-4 w-4"}),"Camera"]}),e.jsxs(B,{variant:j==="screen"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>b("screen"),children:[e.jsx(OA,{className:"h-4 w-4"}),"Screen"]})]}),j==="camera"&&!J&&!le&&e.jsx(rKs,{value:We,onChange:rt,isLoading:ms,disabled:J}),!J&&!le&&(tt.length>0||He.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-3 py-2 bg-muted/40 rounded-lg",children:[tt.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(Fv,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(ds,{value:bt||"default",onValueChange:Jn=>vt(Jn==="default"?"":Jn),children:[e.jsx(ls,{className:"h-8 text-xs",children:e.jsx(us,{placeholder:"Default microphone"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"default",children:"Default microphone"}),tt.map(Jn=>e.jsx(Qe,{value:Jn.deviceId,children:Jn.label||`Microphone ${Jn.deviceId.slice(0,6)}`},Jn.deviceId))]})]})]}),He.length>1&&j==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(mf,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(ds,{value:Bt||"default",onValueChange:Jn=>Zt(Jn==="default"?"":Jn),children:[e.jsx(ls,{className:"h-8 text-xs",children:e.jsx(us,{placeholder:"Default camera"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"default",children:"Default camera"}),He.map(Jn=>e.jsx(Qe,{value:Jn.deviceId,children:Jn.label||`Camera ${Jn.deviceId.slice(0,6)}`},Jn.deviceId))]})]})]})]}),j==="camera"&&v&&!J&&!le&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(xb,{className:Et("h-4 w-4",F?"text-muted-foreground":"text-primary")}),e.jsx(se,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),e.jsx(bn,{id:"orientation-toggle",checked:F,onCheckedChange:Vt}),e.jsx(se,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx(ng,{className:Et("h-4 w-4",F?"text-primary":"text-muted-foreground")})]}),j==="screen"&&!J&&!le&&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(OA,{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:()=>{As()},children:[e.jsx("video",{ref:l,src:le??void 0,className:Et("w-full bg-black",F&&!le?"object-contain":"object-cover",Lr,!le&&Me==="user"!==(We.mirror??!1)&&"scale-x-[-1]",Pt&&!le&&"hidden"),playsInline:!0,controls:!!le,muted:le?qe:!0,autoPlay:!le},le??"live"),Pt&&!le&&e.jsx("canvas",{ref:Fs,className:Et("w-full bg-black",F?"object-contain":"object-cover",Lr,Me==="user"!==(We.mirror??!1)&&"scale-x-[-1]")}),Pt&&ms&&!le&&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(ts,{className:"h-8 w-8 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm",children:"Loading virtual background…"})]})}),!le&&it&&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 As(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),i&&!le&&e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:i}),Ge!==null&&!le&&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:Ge},Ge),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),J&&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",ie?"bg-yellow-500":"bg-red-500 animate-pulse")}),e.jsxs("span",{className:"text-white text-sm font-medium",children:[fi(ge)," / ",fi(s)]})]}),J&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(pi,{value:ge/s*100,className:"h-1 rounded-none"})}),!le&&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(Fv,{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:`${Ae}%`}})})]}),e.jsx("div",{className:"absolute bottom-4 left-0 right-0 flex justify-center gap-3 px-4",children:le?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"secondary",size:"lg",className:"bg-white/20 hover:bg-white/30 text-white",onClick:Zn,children:[e.jsx(Ti,{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:Ls,children:Ie?e.jsx(bf,{className:"h-5 w-5"}):e.jsx(Al,{className:"h-5 w-5"})}),e.jsxs(B,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:vi,children:[e.jsx(Ir,{className:"h-5 w-5 mr-2"}),"Use This Video"]})]}):e.jsxs(e.Fragment,{children:[j==="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:ea,disabled:J||Ge!==null,children:e.jsx(cm,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!J&&Ge===null?e.jsx(B,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:j==="screen"?tn:er,children:j==="screen"?e.jsx(OA,{className:"h-6 w-6"}):e.jsx(br,{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:ie?In:gn,children:ie?e.jsx(Al,{className:"h-5 w-5"}):e.jsx(bf,{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:rn,children:e.jsx(ly,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}function GYs({open:s,onOpenChange:t,onUploaded:n}){const{user:r}=ys(),{toast:a}=Ba(),[i,l]=N.useState(!1),o=async(c,d)=>{if(r){l(!0);try{const u=c.type.includes("mp4")?"mp4":"webm",h=`${r.id}/${crypto.randomUUID()}.${u}`,{error:p}=await q.storage.from("cma-videos").upload(h,c,{contentType:c.type||"video/webm",upsert:!1});if(p)throw p;const{data:f,error:g}=await q.storage.from("cma-videos").createSignedUrl(h,60*60*24*365*5);if(g||!(f!=null&&f.signedUrl))throw g||new Error("Could not sign video URL");n(f.signedUrl,Math.round(d)),a({title:"Video added to your CMA"}),t(!1)}catch(u){a({title:"Upload failed",description:u==null?void 0:u.message,variant:"destructive"})}finally{l(!1)}}};return e.jsx(bs,{open:s,onOpenChange:c=>!i&&t(c),children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Record a personal message"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"A 30-second hello goes a long way. Welcome your client, explain the price, and invite their reply."})]}),i?e.jsxs("div",{className:"py-12 flex flex-col items-center gap-3",children:[e.jsx(ts,{className:"w-8 h-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading your video…"})]}):e.jsx(u6,{maxDurationSeconds:180,onRecordingComplete:o})]})})}function WYs({value:s,onChange:t}){const{user:n}=ys(),[r,a]=N.useState(!1);return e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(br,{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(Ee,{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(Bn,{className:"w-3.5 h-3.5"})})]}),e.jsxs("p",{className:"text-xs text-emerald-700 flex items-center gap-1",children:[e.jsx(Al,{className:"w-3 h-3"})," Video attached"]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(a6,{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(br,{className:"w-4 h-4"}),"Record New"]})]}),e.jsx(GYs,{open:r,onOpenChange:a,onUploaded:i=>t({url:i,label:"Personal message"})})]})]})}function J1(s){const t=Number(String(s).replace(/[^0-9.]/g,""));return Number.isFinite(t)&&t>0?t:null}function KYs({open:s,onOpenChange:t,subject:n,onSave:r,isSaving:a}){const[i,l]=N.useState({bedrooms:"",bathrooms:"",sqft:"",yearBuilt:"",propertyType:"",propertySubType:""});N.useEffect(()=>{s&&l({bedrooms:(n==null?void 0:n.bedrooms)!=null?String(n.bedrooms):"",bathrooms:(n==null?void 0:n.bathrooms)!=null?String(n.bathrooms):"",sqft:(n==null?void 0:n.sqft)!=null?String(n.sqft):"",yearBuilt:(n==null?void 0:n.yearBuilt)!=null?String(n.yearBuilt):"",propertyType:(n==null?void 0:n.propertyType)||"Residential",propertySubType:(n==null?void 0:n.propertySubType)||"Single Family"})},[s,n]);const o=async()=>{await r({bedrooms:J1(i.bedrooms),bathrooms:J1(i.bathrooms),sqft:J1(i.sqft),yearBuilt:J1(i.yearBuilt),propertyType:i.propertyType||null,propertySubType:i.propertySubType||null}),t(!1)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Fill in the subject property basics"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"When the MLS feed does not return the home details, add the basics here and LevelUp will keep the CMA moving."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(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(ts,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(qo,{className:"w-4 h-4 mr-2"}),"Save subject details"]})]})]})})}function YYs({open:s,onOpenChange:t,subject:n,onAdd:r}){const[a,i]=N.useState({address:"",city:"",state:"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""});N.useEffect(()=>{s&&i({address:"",city:(n==null?void 0:n.city)||"",state:(n==null?void 0:n.state)||"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""})},[s,n]);const l=()=>{const o=J1(a.price),c=J1(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:J1(a.bedrooms),bathrooms:J1(a.bathrooms),sqft:c,yearBuilt:J1(a.yearBuilt),photos:[]}),t(!1))};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Add a comparable manually"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Use this when the MLS feed misses a property or you already know the best comp. Add at least the address, price, and square footage."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(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()||!J1(a.price)||!J1(a.sqft),children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Add comp to CMA"]})]})]})})}function ZYs(){var Ce,Ae,De,Ie,Fe,qe,be;const{id:s}=bi(),t=Mn(),{toast:n}=Ba(),{data:r,isLoading:a}=gWs(s),{data:i}=yWs(s),l=vWs(),o=wWs(),c=jWs(),{leadSite:d,isLoading:u}=Ip(),[h,p]=N.useState([]),[f,g]=N.useState({sqftPct:.2,monthsBack:6,maxMiles:5,statuses:["Active","Pending","Closed"]}),[_,v]=N.useState(null),[j,b]=N.useState(!1),[S,A]=N.useState({low:"",likely:"",high:"",note:""}),[T,L]=N.useState(!1),[D,M]=N.useState(!1),[F,z]=N.useState(!1),[V,W]=N.useState(null),Y=async Ze=>{var Ye,We;if(!r||!(Ze!=null&&Ze.address)||!(Ze!=null&&Ze.city)||!(Ze!=null&&Ze.state))return Ze;let Ne={...Ze};const it=async rt=>{const{data:tt,error:at}=await q.functions.invoke("cma-subject-lookup",{body:{address:rt.address,city:rt.city,state:rt.state,zip:rt.zip,latitude:rt.latitude,longitude:rt.longitude,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id}});if(at)throw at;return(tt==null?void 0:tt.matches)||[]},je=rt=>{const at=rt.find(vt=>Number.isFinite(Number(vt.latitude))&&Number.isFinite(Number(vt.longitude)))||rt[0];if(!at)return;const He=typeof at.match_type=="string"&&at.match_type.startsWith("nearby-"),dt=He&&Number.isFinite(Number(Ne.latitude))&&Number.isFinite(Number(Ne.longitude)),bt=vt=>at[vt]!==void 0&&at[vt]!==null&&at[vt]!==""&&at[vt]!==0?at[vt]:Ne[vt];Ne={...Ne,bedrooms:bt("bedrooms"),bathrooms:bt("bathrooms"),sqft:bt("sqft"),yearBuilt:bt("yearBuilt"),lotSize:bt("lotSize"),propertyType:bt("propertyType"),propertySubType:bt("propertySubType"),source_provider:at.source_provider??Ne.source_provider,match_type:at.match_type??Ne.match_type,matched_mls_address:He?at.address:Ne.matched_mls_address,latitude:dt?Ne.latitude:at.latitude??Ne.latitude,longitude:dt?Ne.longitude:at.longitude??Ne.longitude,mlsNumber:He?Ne.mlsNumber:at.mlsNumber??Ne.mlsNumber,photos:!He&&Array.isArray(at.photos)&&at.photos.length?at.photos:Ne.photos}};je(await it(Ne));const Ge=()=>Number.isFinite(Number(Ne.latitude))&&Number.isFinite(Number(Ne.longitude));if(!Ge()){const{data:rt}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle(),tt=rt==null?void 0:rt.value;if(tt){const at=encodeURIComponent(`${Ne.address}, ${Ne.city}, ${Ne.state} ${Ne.zip||""}`.trim()),dt=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${at}.json?access_token=${tt}&limit=1&country=us`)).json(),bt=(We=(Ye=dt==null?void 0:dt.features)==null?void 0:Ye[0])==null?void 0:We.center;Array.isArray(bt)&&bt.length===2&&(Ne.longitude=bt[0],Ne.latitude=bt[1])}}if((!Ne.bedrooms||!Ne.bathrooms||!Ne.sqft||!Ne.yearBuilt)&&Ge())try{je(await it(Ne))}catch(rt){console.warn("second-pass subject lookup failed",rt)}return JSON.stringify(Ne)!==JSON.stringify(Ze)&&await l.mutateAsync({id:r.id,patch:{subject:Ne}}),Ne};N.useEffect(()=>{var it,je;r!=null&&r.settings&&g({sqftPct:r.settings.sqftPct??.2,monthsBack:r.settings.monthsBack??6,maxMiles:r.settings.maxMiles??5,statuses:r.settings.statuses??["Active","Pending","Closed"]});const Ze=(it=r==null?void 0:r.settings)==null?void 0:it.priceOverride;Ze!=null&&Ze.enabled&&(b(!0),A({low:Ze.low!=null?String(Ze.low):"",likely:Ze.likely!=null?String(Ze.likely):"",high:Ze.high!=null?String(Ze.high):"",note:Ze.note??""}));const Ne=(je=r==null?void 0:r.settings)==null?void 0:je.personalVideo;Ne!=null&&Ne.url&&W({url:Ne.url,thumb:Ne.thumb,label:Ne.label})},[r==null?void 0:r.id]);const K=N.useRef(!1);N.useEffect(()=>{K.current||i!=null&&i.length&&(p(i.map(Ze=>({...Ze.snapshot,selected:Ze.selected,manual:Ze.manual,score:Ze.score}))),K.current=!0)},[i]);const J=N.useRef(null);N.useEffect(()=>{if(!r||u)return;const Ze=r.subject||{},Ne=Number.isFinite(Number(Ze.latitude))&&Number.isFinite(Number(Ze.longitude)),it=!!(Number(Ze.bedrooms)||Number(Ze.bathrooms)||Number(Ze.sqft)||Number(Ze.yearBuilt));if(Ne&&it)return;const je=`${r.id}:${(d==null?void 0:d.id)??r.lead_site_id??"no-site"}`;J.current!==je&&(!Ze.address||!Ze.city||!Ze.state||(J.current=je,(async()=>{try{await Y(Ze)}catch(Ge){console.warn("subject enrich failed",Ge)}})()))},[r==null?void 0:r.id,r==null?void 0:r.lead_site_id,d==null?void 0:d.id,u]);const ne=N.useMemo(()=>r?BZe(r.subject,h):null,[r,h]),ie=async()=>{if(r)try{const Ze=await Y(r.subject),Ne=await o.mutateAsync({subject:Ze,filters:f,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id});p(Ne.comps.map(it=>({...it,selected:!0})).slice(0,12)),n({title:`Found ${Ne.comps.length} comps`,description:`Top ${Math.min(12,Ne.comps.length)} auto-selected.`})}catch(Ze){n({title:"Search failed",description:Ze.message,variant:"destructive"})}},he=Ze=>{p(Ne=>Ne.map((it,je)=>je===Ze?{...it,selected:!it.selected}:it))},ce=Ze=>{p(Ne=>Ne.filter((it,je)=>je!==Ze))},pe=async Ze=>{if(!r)return;const Ne=Object.fromEntries(Object.entries(Ze).filter(([,je])=>je!=null&&je!=="")),it={...r.subject,...Ne,manually_enriched:!0};await l.mutateAsync({id:r.id,patch:{subject:it}}),n({title:"Subject details saved",description:it.sqft?"You can now find comps or add your own.":"Add square footage to unlock suggested pricing."})},le=Ze=>{p(Ne=>[{...Ze,selected:!0,manual:!0},...Ne]),n({title:"Manual comp added"})},ve=async(Ze=!1)=>{if(!r)return;const Ne=BZe(r.subject,h),it=We=>{const rt=Number(String(We).replace(/[^0-9.]/g,""));return Number.isFinite(rt)&&rt>0?Math.round(rt):null},je=j?it(S.likely):null,Ge=j?it(S.low):null,Be=j?it(S.high):null,Ye=j&&je;await l.mutateAsync({id:r.id,patch:{settings:{...f,priceOverride:{enabled:j,low:Ge,likely:je,high:Be,note:S.note||null},personalVideo:V},price_low:Ye?Ge??je:Ne.low??null,price_likely:Ye?je:Ne.likely??null,price_high:Ye?Be??je:Ne.high??null,status:Ze?"shared":r.status}}),await c.mutateAsync({cmaId:r.id,comps:h}),n({title:Ze?"CMA published":"CMA saved"})},ge=r?`https://cma.relevelup.com/${r.share_token}`:"";if(a||!r)return e.jsx(Ts,{children:e.jsx("div",{className:"p-6",children:e.jsx(ts,{className:"w-6 h-6 animate-spin"})})});const Te=h.filter(Ze=>Ze.selected).length,Me=!((Ce=r.subject)!=null&&Ce.bedrooms)||!((Ae=r.subject)!=null&&Ae.bathrooms)||!((De=r.subject)!=null&&De.sqft)||!((Ie=r.subject)!=null&&Ie.yearBuilt);return e.jsx(Ts,{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(Hr,{className:"w-4 h-4 mr-1"})," All CMAs"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>ve(!1),disabled:l.isPending,children:[e.jsx(qo,{className:"w-4 h-4 mr-1"}),"Save"]}),e.jsxs(B,{onClick:()=>ve(!0),disabled:l.isPending,children:[e.jsx(Hl,{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(ge),n({title:"Link copied"})},children:[e.jsx(tr,{className:"w-4 h-4 mr-1"}),"Copy Link"]}),e.jsxs(B,{onClick:()=>L(!0),children:[e.jsx(Vs,{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(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Subject Property"})}),e.jsxs(Ee,{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:"})," ",((Fe=r.subject.sqft)==null?void 0:Fe.toLocaleString())??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Year:"})," ",r.subject.yearBuilt??"—"]})]}),Me&&e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 p-3 text-amber-950 space-y-2",children:[e.jsx("p",{className:"font-medium",children:"No panic — we can still build this."}),e.jsx("p",{className:"text-xs leading-relaxed",children:"If the MLS/feed does not return beds, baths, sqft, or year, add them manually and LevelUp will use them for comps and pricing."}),e.jsxs(B,{size:"sm",variant:"outline",className:"bg-white",onClick:()=>M(!0),children:[e.jsx(_a,{className:"w-3.5 h-3.5 mr-1"}),"Fill in property details"]})]}),!Me&&e.jsxs(B,{size:"sm",variant:"ghost",className:"px-0",onClick:()=>M(!0),children:[e.jsx(_a,{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 Ze=>{const Ne=Number(Ze.target.value);Ne>0&&await l.mutateAsync({id:r.id,patch:{subject:{...r.subject,sqft:Ne}}})}})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(fw,{className:"w-4 h-4"}),"Suggested Price"]})}),e.jsxs(Ee,{className:"space-y-3",children:[ne!=null&&ne.likely?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-3xl font-bold",children:["$",(j&&Number(S.likely)>0?Number(S.likely):ne.likely).toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Comps suggest: $",(qe=ne.low)==null?void 0:qe.toLocaleString()," – $",(be=ne.high)==null?void 0:be.toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",ne.ppsf,"/sqft median · ",Te," 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(bn,{id:"override-toggle",checked:j,onCheckedChange:b})]}),j&&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:S.likely,onChange:Ze=>A(Ne=>({...Ne,likely:Ze.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:S.low,onChange:Ze=>A(Ne=>({...Ne,low:Ze.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Range high"}),e.jsx(ye,{type:"number",placeholder:"optional",value:S.high,onChange:Ze=>A(Ne=>({...Ne,high:Ze.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Why this price (optional)"}),e.jsx(Es,{rows:2,maxLength:500,placeholder:"Notes shown to your client",value:S.note,onChange:Ze=>A(Ne=>({...Ne,note:Ze.target.value}))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Save to apply. Your price will replace the comp-based number on the shared report."})]})]})]})]}),e.jsx(WYs,{value:V,onChange:W}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Filters"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs",children:["SqFt tolerance: ±",Math.round(f.sqftPct*100),"%"]}),e.jsx(Bm,{value:[f.sqftPct*100],min:5,max:50,step:5,onValueChange:([Ze])=>g(Ne=>({...Ne,sqftPct:Ze/100}))})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs",children:["Search radius: ",f.maxMiles," mi"]}),e.jsx(Bm,{value:[f.maxMiles],min:1,max:25,step:1,onValueChange:([Ze])=>g(Ne=>({...Ne,maxMiles:Ze}))})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs",children:["Sold within: ",f.monthsBack," months"]}),e.jsx(Bm,{value:[f.monthsBack],min:1,max:24,step:1,onValueChange:([Ze])=>g(Ne=>({...Ne,monthsBack:Ze}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Status"}),["Active","Pending","Closed"].map(Ze=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ui,{checked:f.statuses.includes(Ze),onCheckedChange:Ne=>g(it=>({...it,statuses:Ne?[...it.statuses,Ze]:it.statuses.filter(je=>je!==Ze)}))})," ",Ze]},Ze))]}),e.jsxs(B,{className:"w-full",onClick:ie,disabled:o.isPending,children:[o.isPending?e.jsx(ts,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(un,{className:"w-4 h-4 mr-2"}),"Find Comps"]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:()=>z(!0),children:[e.jsx(Is,{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(tKs,{subject:r.subject,comps:h,radiusMiles:f.maxMiles,onMarkerClick:Ze=>v(Ze)}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"text-lg font-semibold",children:["Comparables (",h.length,")"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Te," selected"]})]}),h.length?e.jsx("div",{className:"space-y-2",children:h.map((Ze,Ne)=>{var it;return e.jsx(fe,{className:Ze.selected?"":"opacity-50",children:e.jsxs(Ee,{className:"p-3 flex gap-3 items-center",children:[e.jsx(ui,{checked:Ze.selected,onCheckedChange:()=>he(Ne)}),e.jsxs("button",{type:"button",onClick:()=>v(Ne),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(Sfe,{photos:Ze.photos,className:"w-20 h-16 rounded flex-none"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate hover:underline",children:Ze.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Ze.city,", ",Ze.state," · ",Ze.bedrooms??"?","bd/",Ze.bathrooms??"?","ba · ",((it=Ze.sqft)==null?void 0:it.toLocaleString())??"?"," sqft",Ze.yearBuilt?` · ${Ze.yearBuilt}`:""]}),e.jsxs("div",{className:"text-xs mt-0.5",children:[e.jsx(ze,{variant:"outline",className:"mr-1",children:Ze.status}),Ze.score!=null&&e.jsxs("span",{className:"text-muted-foreground",children:["Score ",Ze.score]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"font-semibold",children:["$",(Ze.soldPrice||Ze.price||0).toLocaleString()]}),Ze.sqft&&(Ze.soldPrice||Ze.price)?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Math.round((Ze.soldPrice||Ze.price)/Ze.sqft),"/sqft"]}):null]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>v(Ne),title:"View details",children:e.jsx(Er,{className:"w-4 h-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ce(Ne),title:"Remove",children:e.jsx(_n,{className:"w-4 h-4"})})]})},Ne)})}):e.jsx(fe,{children:e.jsx(Ee,{className:"py-12 text-center text-muted-foreground",children:e.jsxs("div",{className:"max-w-md mx-auto space-y-3",children:[e.jsxs("p",{children:["Click ",e.jsx("strong",{children:"Find Comps"})," to auto-pull from your MLS."]}),e.jsx("p",{className:"text-sm",children:"If nothing comes back, you are not stuck — use LevelUp's fallback template: enter the subject details, add 2–3 known comps, then set your suggested price."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[Me&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>M(!0),children:"Fill subject details"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>z(!0),children:"Add manual comp"})]})]})})})]})]}),e.jsx(Uht,{comp:_!=null?h[_]:null,open:_!=null,onClose:()=>v(null)}),e.jsx(KYs,{open:D,onOpenChange:M,subject:r.subject,onSave:pe,isSaving:l.isPending}),e.jsx(YYs,{open:F,onOpenChange:z,subject:r.subject,onAdd:le}),e.jsx(Q_t,{open:T,onOpenChange:L,cma:r})]})})}function QYs(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 e2t="popby_geocode_cache_v1";function XYs(){try{return JSON.parse(localStorage.getItem(e2t)||"{}")}catch{return{}}}function JYs(s){try{localStorage.setItem(e2t,JSON.stringify(s))}catch{}}function eZs({contacts:s,onLogPopby:t}){const[n,r]=N.useState(null),[a,i]=N.useState("idle"),[l,o]=N.useState(5),[c,d]=N.useState(""),[u,h]=N.useState(new Map),[p,f]=N.useState(!1);N.useEffect(()=>{(async()=>{const{data:b}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();b!=null&&b.value&&d(b.value)})()},[]);const g=N.useMemo(()=>s.filter(b=>b.isDue&&(b.address||b.city&&b.state||b.zip)),[s]),_=()=>{if(!("geolocation"in navigator)){i("unavailable");return}i("loading"),navigator.geolocation.getCurrentPosition(b=>{r({lat:b.coords.latitude,lng:b.coords.longitude}),i("ok")},()=>{i("denied")},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})};N.useEffect(()=>{if(!c||!n||g.length===0)return;let b=!1;const S=XYs(),A=new Map;g.forEach(L=>{const D=[L.address,L.city,L.state,L.zip].filter(Boolean).join("|").toLowerCase();S[D]&&A.set(L.id,S[D])}),h(new Map(A));const T=g.filter(L=>!([L.address,L.city,L.state,L.zip].filter(Boolean).join("|").toLowerCase()in S));if(T.length!==0)return f(!0),(async()=>{const L=[...T],D=async()=>{var M,F;for(;L.length&&!b;){const z=L.shift(),V=[z.address,z.city,z.state,z.zip].filter(Boolean),W=V.join("|").toLowerCase(),Y=V.join(", ");try{const J=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(Y)}.json?limit=1&access_token=${c}`)).json();if((F=(M=J==null?void 0:J.features)==null?void 0:M[0])!=null&&F.center){const[ne,ie]=J.features[0].center;S[W]={lat:ie,lng:ne},A.set(z.id,{lat:ie,lng:ne})}else S[W]=null}catch{}}};await Promise.all([D(),D(),D(),D()]),b||(JYs(S),h(new Map(A)),f(!1))})(),()=>{b=!0}},[c,n,g]);const v=N.useMemo(()=>{if(!n)return[];const b=[];return g.forEach(S=>{const A=u.get(S.id);if(!A)return;const T=QYs(n.lat,n.lng,A.lat,A.lng);T<=l&&b.push({...S,distanceMiles:T,lat:A.lat,lng:A.lng})}),b.sort((S,A)=>S.distanceMiles-A.distanceMiles)},[n,g,u,l]),j=b=>{const A=/iPad|iPhone|iPod/.test(navigator.userAgent)?`https://maps.apple.com/?daddr=${b.lat},${b.lng}`:`https://www.google.com/maps/dir/?api=1&destination=${b.lat},${b.lng}`;window.open(A,"_blank","noopener")};return e.jsxs(fe,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2 text-lg",children:[e.jsx(iL,{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(ds,{value:String(l),onValueChange:b=>o(Number(b)),children:[e.jsx(ls,{className:"w-[110px] h-9",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"2",children:"2 miles"}),e.jsx(Qe,{value:"5",children:"5 miles"}),e.jsx(Qe,{value:"10",children:"10 miles"}),e.jsx(Qe,{value:"25",children:"25 miles"})]})]}),e.jsxs(B,{size:"sm",variant:a==="ok"?"outline":"default",onClick:_,disabled:a==="loading",children:[a==="loading"?e.jsx(Ti,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(iL,{className:"h-4 w-4 mr-1"}),a==="ok"?"Refresh":"Use my location"]})]})]})}),e.jsxs(Ee,{className:"space-y-3",children:[a==="idle"&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(ka,{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(Gi,{className:"h-6 w-6"}),"Location access was blocked. Enable it in your browser to use Nearby Now."]}),a==="unavailable"&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"Geolocation isn't available on this device."}),a==="ok"&&!c&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"Mapping isn't configured yet — ask an admin to add the Mapbox token."}),a==="ok"&&c&&g.length===0&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"No due contacts have addresses yet. Add street addresses to your sphere to power this."}),a==="ok"&&c&&g.length>0&&p&&v.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ws,{className:"h-14 w-full"}),e.jsx(Ws,{className:"h-14 w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Locating contacts…"})]}),a==="ok"&&c&&!p&&v.length===0&&g.length>0&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:["No due contacts within ",l," miles. Try widening the radius."]}),v.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ze,{variant:"secondary",className:"font-medium",children:[v.length," nearby"]}),p&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ti,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:v.map(b=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg bg-card border hover:border-primary/40 transition-colors",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"font-medium truncate",children:[b.first_name," ",b.last_name]}),e.jsx(ze,{variant:"outline",className:"text-xs",children:b.distanceMiles<1?`${(b.distanceMiles*5280).toFixed(0)} ft`:`${b.distanceMiles.toFixed(1)} mi`}),b.daysOverdue>0&&e.jsxs(ze,{variant:"destructive",className:"text-xs",children:[b.daysOverdue,"d overdue"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:[b.address,b.city,b.state].filter(Boolean).join(", ")})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b.phone&&e.jsx(B,{size:"icon",variant:"ghost",asChild:!0,className:"h-9 w-9",title:"Call",children:e.jsx("a",{href:`tel:${b.phone}`,children:e.jsx(Ar,{className:"h-4 w-4"})})}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>j(b),className:"h-9 w-9",title:"Directions",children:e.jsx(p9,{className:"h-4 w-4"})}),e.jsxs(B,{size:"sm",onClick:()=>t(b),children:[e.jsx(Oi,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},b.id))})]})]})]})}const tZs="0dde5abb-0005-4c8c-a471-30d0cbc9e280",sZs=[{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 nZs(){const s=Mn(),t=T_t(),{data:n}=WHs(),{data:r}=Sy(),{data:a}=gLe(),{data:i}=I1e(90),{data:l}=ox(),o=XHs(),c=ZHs(),d=YHs(),u=QHs(),{data:h=[],isLoading:p}=ct({queryKey:["popby-templates"],queryFn:async()=>{const{data:J,error:ne}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",tZs).order("publish_date",{ascending:!1});if(ne)throw ne;const{data:ie}=await q.from("template_likes").select("template_id"),{data:he}=await q.from("template_comments").select("template_id"),ce=new Map;ie==null||ie.forEach(le=>{ce.set(le.template_id,(ce.get(le.template_id)||0)+1)});const pe=new Map;return he==null||he.forEach(le=>{pe.set(le.template_id,(pe.get(le.template_id)||0)+1)}),(J||[]).map(le=>({...le,likesCount:ce.get(le.id)||0,commentsCount:pe.get(le.id)||0}))}}),f=J=>{const ne=l==null?void 0:l.find(ie=>ie.id===J);return ne?`${ne.first_name} ${ne.last_name||""}`.trim():"Unknown"},g=J=>{if(!J)return null;const ne=n==null?void 0:n.find(ie=>ie.id===J);return(ne==null?void 0:ne.name)||null},[_,v]=N.useState(null),[j,b]=N.useState(!1),[S,A]=N.useState(!1),[T,L]=N.useState(!1),[D,M]=N.useState({popby_item_id:"",notes:""}),[F,z]=N.useState({name:"",description:""}),V=async()=>{_&&(await c.mutateAsync({contact_id:_.id,popby_item_id:D.popby_item_id||void 0,notes:D.notes||void 0}),b(!1),v(null),M({popby_item_id:"",notes:""}))},W=async()=>{F.name.trim()&&(await d.mutateAsync({name:F.name.trim(),description:F.description.trim()||void 0}),L(!1),z({name:"",description:""}))},Y=async(J,ne)=>{await u.mutateAsync({relationship_type_id:J,frequency_days:parseInt(ne)})},K=J=>{var ie;const ne=a==null?void 0:a.find(he=>he.relationship_type_id===J);return((ie=ne==null?void 0:ne.frequency_days)==null?void 0:ie.toString())||"90"};return e.jsx(Ts,{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(fe,{children:e.jsxs(Ee,{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(fe,{children:e.jsxs(Ee,{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(fe,{children:e.jsxs(Ee,{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(ka,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs(B,{variant:"outline",onClick:()=>A(!0),children:[e.jsx(Xo,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs(B,{variant:"outline",onClick:()=>L(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs(Br,{defaultValue:"due",children:[e.jsxs(Fr,{children:[e.jsx(Kt,{value:"due",children:"Due for Popby"}),e.jsx(Kt,{value:"activity",children:"Recent Activity"}),e.jsx(Kt,{value:"library",children:"Popby Library"}),e.jsx(Kt,{value:"templates",children:"Popby Templates"})]}),e.jsxs(is,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(eZs,{contacts:t||[],onLogPopby:J=>{v(J),b(!0)}}),!t||t.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Oi,{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(J=>e.jsx(fe,{className:"hover:shadow-md transition-shadow",children:e.jsx(Ee,{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:[J.first_name," ",J.last_name]}),J.daysOverdue>0&&e.jsxs(ze,{variant:"destructive",className:"text-xs",children:[J.daysOverdue,"+ days overdue"]}),J.daysSinceLastPopby===null&&e.jsx(ze,{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:[J.address&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ka,{className:"h-3 w-3"}),J.city||J.address]}),J.tags&&J.tags.length>0&&e.jsx("span",{children:J.tags.map(ne=>{var ie;return(ie=ne.relationship_type)==null?void 0:ie.name}).join(", ")})]}),J.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",Ss(new Date(J.lastPopby),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[J.phone&&e.jsx(B,{size:"sm",variant:"ghost",asChild:!0,children:e.jsx("a",{href:`tel:${J.phone}`,children:e.jsx(Ar,{className:"h-4 w-4"})})}),e.jsxs(B,{size:"sm",onClick:()=>{v(J),b(!0)},children:[e.jsx(Ri,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},J.id))})]}),e.jsx(is,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(gr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No popby activity yet!"}),e.jsx("p",{className:"text-sm mt-1",children:"Start logging popbys to see your history here."})]})}):e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(Ee,{className:"space-y-3",children:i.map(J=>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(Oi,{className:"h-5 w-5 text-orange-500"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium",children:f(J.contact_id)}),g(J.popby_item_id)&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:g(J.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Ss(new Date(J.completed_at),"MMM d, yyyy h:mm a")}),J.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:J.notes})]})]},J.id))})]})}),e.jsx(is,{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(J=>e.jsx(fe,{children:e.jsx(Ee,{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(Oi,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-medium",children:J.name}),J.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:J.description}),!J.owner_user_id&&e.jsx(ze,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},J.id)),e.jsx(fe,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>L(!0),children:e.jsx(Ee,{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(Is,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(is,{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"]}),p&&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((J,ne)=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx(Ws,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(Ws,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ws,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ws,{className:"h-5 w-16"}),e.jsx(Ws,{className:"h-5 w-20"})]})]})},ne))}),!p&&h.length===0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Rc,{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."})]})}),!p&&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(J=>e.jsxs(fe,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer",onClick:()=>s(`/templates/${J.id}`),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",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 text-muted-foreground",children:"No Preview"})}),e.jsxs(Ee,{className:"p-4 flex flex-col",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:J.name}),J.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:Xz(J.description)}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:e.jsx(ze,{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(Vm,{className:"h-3.5 w-3.5"}),J.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"}),J.commentsCount]})]}),e.jsxs(B,{size:"sm",className:"w-full gap-2",onClick:ne=>{ne.stopPropagation(),s(`/templates/${J.id}`)},children:[e.jsx(tr,{className:"h-4 w-4"}),"View Template"]})]})]},J.id))})]})]}),e.jsx(bs,{open:j,onOpenChange:b,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Log Popby for ",_==null?void 0:_.first_name," ",_==null?void 0:_.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(ds,{value:D.popby_item_id,onValueChange:J=>M(ne=>({...ne,popby_item_id:J})),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select a popby item..."})}),e.jsx(cs,{children:n==null?void 0:n.map(J=>e.jsx(Qe,{value:J.id,children:J.name},J.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Notes (optional)"}),e.jsx(Es,{placeholder:"Any notes about this popby...",value:D.notes,onChange:J=>M(ne=>({...ne,notes:J.target.value}))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(B,{onClick:V,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(bs,{open:S,onOpenChange:A,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Popby Frequency Settings"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set default popby frequency for each relationship type. You can override these per-contact."}),r==null?void 0:r.map(J=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(se,{className:"font-medium",children:J.name}),e.jsxs(ds,{value:K(J.id),onValueChange:ne=>Y(J.id,ne),children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(us,{})}),e.jsx(cs,{children:sZs.map(ne=>e.jsx(Qe,{value:ne.value,children:ne.label},ne.value))})]})]},J.id))]}),e.jsx(Xn,{children:e.jsx(B,{onClick:()=>A(!1),children:"Done"})})]})}),e.jsx(bs,{open:T,onOpenChange:L,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Add Popby Idea"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Name *"}),e.jsx(ye,{placeholder:"e.g., Homemade cookies",value:F.name,onChange:J=>z(ne=>({...ne,name:J.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Es,{placeholder:"Optional description...",value:F.description,onChange:J=>z(ne=>({...ne,description:J.target.value}))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>L(!1),children:"Cancel"}),e.jsx(B,{onClick:W,disabled:!F.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const rZs=Yw({property_address:go().min(1,"Property address is required"),city:go().optional(),state:go().optional(),zip:go().optional(),transaction_type:yMe(["buyer","seller"]),close_date:go().min(1,"Close date is required"),sale_price:Y9().min(0,"Sale price must be positive"),commission_amount:Y9().optional(),lead_source_id:go().optional(),client_type_id:go().optional(),contact_id:go().optional(),notes:go().optional(),is_win:dWt()});function t2t({open:s,onOpenChange:t,transaction:n}){const[r,a]=N.useState(!1),[i,l]=N.useState(""),[o,c]=N.useState(!1),[d,u]=N.useState(""),h=qye(),p=Grs(),{data:f}=ZD(),{data:g}=Sy(),{data:_}=ox(),v=Uye(),j=_6e(),{data:b}=Vye(),S=(b==null?void 0:b.show_commission)??!0,A=Dye({resolver:Rye(rZs),defaultValues:{property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1}});N.useEffect(()=>{n?A.reset({property_address:n.property_address,city:n.city||"",state:n.state||"",zip:n.zip||"",transaction_type:n.transaction_type,close_date:n.close_date,sale_price:Number(n.sale_price),commission_amount:n.commission_amount?Number(n.commission_amount):void 0,lead_source_id:n.lead_source_id||void 0,client_type_id:n.client_type_id||void 0,contact_id:n.contact_id||void 0,notes:n.notes||"",is_win:n.is_win}):A.reset({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1})},[n,A]);const T=async F=>{const z={property_address:F.property_address,transaction_type:F.transaction_type,close_date:F.close_date,sale_price:F.sale_price,is_win:F.is_win,commission_amount:F.commission_amount||null,lead_source_id:F.lead_source_id||null,client_type_id:F.client_type_id||null,contact_id:F.contact_id||null,city:F.city||null,state:F.state||null,zip:F.zip||null,notes:F.notes||null};n?await p.mutateAsync({id:n.id,...z}):await h.mutateAsync(z),t(!1)},L=async()=>{if(!i.trim())return;const[F,...z]=i.trim().split(" "),V=z.join(" ")||null,W=await v.mutateAsync({first_name:F,last_name:V,tagIds:[]});W&&(A.setValue("contact_id",W.id),l(""),c(!1),a(!1))},D=async()=>{if(!d.trim())return;const F=await j.mutateAsync(d.trim());F&&(A.setValue("lead_source_id",F.id),u(""))},M=_==null?void 0:_.find(F=>F.id===A.watch("contact_id"));return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh]",children:[e.jsx(ws,{children:e.jsx(_s,{children:n?"Edit Transaction":"Add Transaction"})}),e.jsx(hi,{className:"max-h-[70vh] pr-4",children:e.jsx(Oye,{...A,children:e.jsxs("form",{onSubmit:A.handleSubmit(T),className:"space-y-4",children:[e.jsx(Nu,{control:A.control,name:"property_address",render:({field:F})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Property Address *"}),e.jsx(au,{children:e.jsx(ye,{placeholder:"123 Main St",...F})}),e.jsx(Yx,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(Nu,{control:A.control,name:"city",render:({field:F})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"City"}),e.jsx(au,{children:e.jsx(ye,{placeholder:"City",...F})})]})}),e.jsx(Nu,{control:A.control,name:"state",render:({field:F})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"State"}),e.jsx(au,{children:e.jsx(ye,{placeholder:"TX",...F})})]})}),e.jsx(Nu,{control:A.control,name:"zip",render:({field:F})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Zip"}),e.jsx(au,{children:e.jsx(ye,{placeholder:"75001",...F})})]})})]}),e.jsx(Nu,{control:A.control,name:"transaction_type",render:({field:F})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Transaction Type *"}),e.jsxs(ds,{onValueChange:F.onChange,value:F.value,children:[e.jsx(au,{children:e.jsx(ls,{children:e.jsx(us,{placeholder:"Select type"})})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"buyer",children:"Buyer"}),e.jsx(Qe,{value:"seller",children:"Seller"})]})]}),e.jsx(Yx,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Nu,{control:A.control,name:"close_date",render:({field:F})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Close Date *"}),e.jsx(au,{children:e.jsx(ye,{type:"date",...F})}),e.jsx(Yx,{})]})}),e.jsx(Nu,{control:A.control,name:"sale_price",render:({field:F})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Sale Price *"}),e.jsx(au,{children:e.jsx(ye,{type:"number",placeholder:"0",...F,onChange:z=>F.onChange(Number(z.target.value))})}),e.jsx(Yx,{})]})})]}),S&&e.jsx(Nu,{control:A.control,name:"commission_amount",render:({field:F})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Commission"}),e.jsx(au,{children:e.jsx(ye,{type:"number",placeholder:"0",...F,value:F.value??"",onChange:z=>F.onChange(z.target.value?Number(z.target.value):void 0)})})]})}),e.jsx(Nu,{control:A.control,name:"lead_source_id",render:({field:F})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Lead Source"}),e.jsxs(ds,{onValueChange:F.onChange,value:F.value||"",children:[e.jsx(au,{children:e.jsx(ls,{children:e.jsx(us,{placeholder:"Select source"})})}),e.jsx(cs,{children:f==null?void 0:f.map(z=>e.jsx(Qe,{value:z.id,children:z.name},z.id))})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"Add custom source...",value:d,onChange:F=>u(F.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:D,disabled:!d.trim(),children:e.jsx(Is,{className:"h-4 w-4"})})]}),e.jsx(Nu,{control:A.control,name:"client_type_id",render:({field:F})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Client Type"}),e.jsxs(ds,{onValueChange:F.onChange,value:F.value||"",children:[e.jsx(au,{children:e.jsx(ls,{children:e.jsx(us,{placeholder:"Select client type"})})}),e.jsx(cs,{children:g==null?void 0:g.map(z=>e.jsx(Qe,{value:z.id,children:z.name},z.id))})]})]})}),e.jsx(Nu,{control:A.control,name:"contact_id",render:({field:F})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Client Contact"}),e.jsxs(el,{open:r,onOpenChange:a,children:[e.jsx(tl,{asChild:!0,children:e.jsx(au,{children:e.jsxs(B,{variant:"outline",role:"combobox",className:Et("w-full justify-between",!F.value&&"text-muted-foreground"),children:[M?`${M.first_name} ${M.last_name||""}`.trim():"Select contact",e.jsx(qg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(Ho,{className:"w-full p-0",align:"start",children:[e.jsxs(Qg,{children:[e.jsx(Xg,{placeholder:"Search contacts..."}),e.jsxs(Jg,{children:[e.jsx(e0,{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(Is,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx(t0,{children:_==null?void 0:_.map(z=>e.jsxs(Jf,{value:`${z.first_name} ${z.last_name||""}`,onSelect:()=>{F.onChange(z.id),a(!1)},children:[e.jsx(Ir,{className:Et("mr-2 h-4 w-4",z.id===F.value?"opacity-100":"opacity-0")}),z.first_name," ",z.last_name||""]},z.id))})]})]}),o&&e.jsxs("div",{className:"p-2 border-t space-y-2",children:[e.jsx(ye,{placeholder:"Enter contact name...",value:i,onChange:z=>l(z.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",onClick:L,disabled:!i.trim()||v.isPending,children:"Add Contact"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(Nu,{control:A.control,name:"notes",render:({field:F})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Notes"}),e.jsx(au,{children:e.jsx(Es,{placeholder:"Any notes about this transaction...",...F})})]})}),e.jsx(Nu,{control:A.control,name:"is_win",render:({field:F})=>e.jsxs(nu,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ru,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx(au,{children:e.jsx(bn,{checked:F.value,onCheckedChange:F.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||p.isPending,children:[n?"Update":"Add"," Transaction"]})]})]})})})]})})}function f8e({transactions:s,showCommission:t,isLoading:n,agentNameMap:r,readOnly:a}){const[i,l]=N.useState(null),[o,c]=N.useState(null),[d,u]=N.useState(""),[h,p]=N.useState("all"),[f,g]=N.useState("all"),[_,v]=N.useState("all"),[j,b]=N.useState(!1),S=Wrs(),A=qye(),{data:T}=ZD();Sy();const L=wR(),D=z=>{const{id:V,created_at:W,updated_at:Y,lead_source:K,client_type:J,contact:ne,...ie}=z;A.mutate(ie)},M=()=>{o&&(S.mutate(o),c(null))},F=s.filter(z=>{var ne,ie,he,ce;const V=d===""||z.property_address.toLowerCase().includes(d.toLowerCase())||((ie=(ne=z.contact)==null?void 0:ne.first_name)==null?void 0:ie.toLowerCase().includes(d.toLowerCase()))||((ce=(he=z.contact)==null?void 0:he.last_name)==null?void 0:ce.toLowerCase().includes(d.toLowerCase())),W=h==="all"||z.transaction_type===h,Y=f==="all"||z.lead_source_id===f,K=_==="all"||z.client_type_id===_,J=!j||z.is_win;return V&&W&&Y&&K&&J});return n?e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 space-y-4",children:[1,2,3].map(z=>e.jsx(Ws,{className:"h-16 w-full"},z))})}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs(It,{children:["Transactions (",F.length,")"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search...",value:d,onChange:z=>u(z.target.value),className:"pl-8 w-[150px]"})]}),e.jsxs(ds,{value:h,onValueChange:p,children:[e.jsx(ls,{className:"w-[100px]",children:e.jsx(us,{placeholder:"Type"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Types"}),e.jsx(Qe,{value:"buyer",children:"Buyer"}),e.jsx(Qe,{value:"seller",children:"Seller"})]})]}),e.jsxs(ds,{value:f,onValueChange:g,children:[e.jsx(ls,{className:"w-[130px]",children:e.jsx(us,{placeholder:"Lead Source"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Sources"}),T==null?void 0:T.map(z=>e.jsx(Qe,{value:z.id,children:z.name},z.id))]})]}),e.jsxs(B,{variant:j?"default":"outline",size:"sm",onClick:()=>b(!j),children:[e.jsx(bc,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(Ee,{children:F.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):L?e.jsx("div",{className:"space-y-3",children:F.map(z=>e.jsxs(fe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium truncate",children:z.property_address}),z.is_win&&e.jsx(bc,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[z.city,z.state?`, ${z.state}`:""]})]}),e.jsx(ze,{variant:z.transaction_type==="buyer"?"default":"secondary",children:z.transaction_type})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Close Date: "}),Q9e(z.close_date)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price: "}),yc(z.sale_price)]}),t&&z.commission_amount&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),yc(z.commission_amount)]}),z.lead_source&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Source: "}),z.lead_source.name]}),z.contact&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Client: "}),z.contact.first_name," ",z.contact.last_name]}),r&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),r[z.owner_user_id]||"Unknown"]})]}),!a&&e.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>l(z),children:e.jsx(ku,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>D(z),children:e.jsx(Xr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(z.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})]},z.id))}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[r&&e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Property"}),e.jsx(Ct,{children:"Type"}),e.jsx(Ct,{children:"Close Date"}),e.jsx(Ct,{children:"Sale Price"}),t&&e.jsx(Ct,{children:"Commission"}),e.jsx(Ct,{children:"Lead Source"}),e.jsx(Ct,{children:"Client"}),!a&&e.jsx(Ct,{className:"w-[50px]"})]})}),e.jsx(ha,{children:F.map(z=>{var V;return e.jsxs(Hs,{children:[r&&e.jsx(ut,{className:"font-medium text-sm",children:r[z.owner_user_id]||"Unknown"}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[z.is_win&&e.jsx(bc,{className:"h-4 w-4 text-yellow-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:z.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[z.city,z.state?`, ${z.state}`:""]})]})]})}),e.jsx(ut,{children:e.jsx(ze,{variant:z.transaction_type==="buyer"?"default":"secondary",children:z.transaction_type})}),e.jsx(ut,{children:Q9e(z.close_date)}),e.jsx(ut,{children:yc(z.sale_price)}),t&&e.jsx(ut,{children:z.commission_amount?yc(z.commission_amount):"-"}),e.jsx(ut,{children:((V=z.lead_source)==null?void 0:V.name)||"-"}),e.jsx(ut,{children:z.contact?`${z.contact.first_name} ${z.contact.last_name||""}`.trim():"-"}),!a&&e.jsx(ut,{children:e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",children:e.jsx(Ig,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",children:[e.jsxs(Qr,{onClick:()=>l(z),children:[e.jsx(ku,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Qr,{onClick:()=>D(z),children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(Qr,{onClick:()=>c(z.id),className:"text-destructive",children:[e.jsx(_n,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},z.id)})})]})})})]}),e.jsx(t2t,{open:!!i,onOpenChange:z=>!z&&l(null),transaction:i||void 0}),e.jsx(Oo,{open:!!o,onOpenChange:z=>!z&&c(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Transaction?"}),e.jsx(Mo,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:M,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function s2t({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=(p,f)=>{if(!f||f===0)return null;const g=Math.min(p/f*100,100),_=Math.max(f-p,0),v=l>0?_/l:0,j=i/12*100,b=g>=j?"ahead":g>=j*.8?"on-track":"behind";return{percent:g,remaining:_,pace:v,status:b}},c=o(t.totalTransactions,s.transactions_goal),d=o(t.totalVolume,s.volume_goal),u=r?o(t.totalCommission,s.gci_goal):null,h=p=>{switch(p){case"ahead":return e.jsxs(ze,{className:"bg-green-500 text-white",children:[e.jsx(mo,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return e.jsxs(ze,{variant:"secondary",children:[e.jsx(fb,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs(ze,{variant:"destructive",children:[e.jsx(vb,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!s.transactions_goal&&!s.volume_goal&&!s.gci_goal?null:e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oc,{className:"h-5 w-5 text-primary"}),e.jsxs(It,{children:[n," Goals Progress"]})]})}),e.jsx(Ee,{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(pi,{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(pi,{value:d.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[yc(t.totalVolume,!0)," of ",yc(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 ",yc(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(pi,{value:u.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[yc(t.totalCommission,!0)," of ",yc(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 ",yc(u.pace,!0),"/month"]})]})]})})]})}const aZs={light:"",dark:".dark"},n2t=N.createContext(null);function r2t(){const s=N.useContext(n2t);if(!s)throw new Error("useChart must be used within a ");return s}const a2t=N.forwardRef(({id:s,className:t,children:n,config:r,...a},i)=>{const l=N.useId(),o=`chart-${s||l.replace(/:/g,"")}`;return e.jsx(n2t.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(iZs,{id:o,config:r}),e.jsx(kw,{children:n})]})})});a2t.displayName="Chart";const iZs=({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(aZs).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},i2t=N.forwardRef(({active:s,payload:t,className:n,indicator:r="dot",hideLabel:a=!1,hideIndicator:i=!1,label:l,labelFormatter:o,labelClassName:c,formatter:d,color:u,nameKey:h,labelKey:p},f)=>{const{config:g}=r2t(),_=N.useMemo(()=>{var T;if(a||!(t!=null&&t.length))return null;const[j]=t,b=`${p||j.dataKey||j.name||"value"}`,S=bTe(g,j,b),A=!p&&typeof l=="string"?((T=g[l])==null?void 0:T.label)||l:S==null?void 0:S.label;return o?e.jsx("div",{className:Et("font-medium",c),children:o(A,t)}):A?e.jsx("div",{className:Et("font-medium",c),children:A}):null},[l,o,t,a,c,g,p]);if(!s||!(t!=null&&t.length))return null;const v=t.length===1&&r!=="dot";return e.jsxs("div",{ref:f,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:[v?null:_,e.jsx("div",{className:"grid gap-1.5",children:t.map((j,b)=>{const S=`${h||j.name||j.dataKey||"value"}`,A=bTe(g,j,S),T=u||j.payload.fill||j.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&&(j==null?void 0:j.value)!==void 0&&j.name?d(j.value,j.name,j,b,j.payload):e.jsxs(e.Fragment,{children:[A!=null&&A.icon?e.jsx(A.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":v&&r==="dashed"}),style:{"--color-bg":T,"--color-border":T}}),e.jsxs("div",{className:Et("flex flex-1 justify-between leading-none",v?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[v?_:null,e.jsx("span",{className:"text-muted-foreground",children:(A==null?void 0:A.label)||j.name})]}),j.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:j.value.toLocaleString()})]})]})},j.dataKey)})})]})});i2t.displayName="ChartTooltip";const oZs=N.forwardRef(({className:s,hideIcon:t=!1,payload:n,verticalAlign:r="bottom",nameKey:a},i)=>{const{config:l}=r2t();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=bTe(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});oZs.displayName="ChartLegend";function bTe(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 SG=["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 x8e({stats:s,year:t}){const n=s.transactionsByMonth.some(a=>a.count>0),r=s.leadSourceBreakdown.length>0;return!n&&!r?e.jsx(fe,{children:e.jsx(Ee,{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(fe,{className:"overflow-hidden",children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Transactions by Month"})}),e.jsx(Ee,{className:"overflow-hidden",children:e.jsx(a2t,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(kw,{width:"100%",height:"100%",children:e.jsxs(hLe,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(cLe,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(zw,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx(Bw,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(Np,{content:e.jsx(i2t,{})}),e.jsx(Fw,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),r&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Ee,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(kw,{width:"100%",height:"100%",children:e.jsxs(mLe,{children:[e.jsx(zb,{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(pR,{fill:SG[i%SG.length]},`cell-${i}`))}),e.jsx(Np,{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:SG[i%SG.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function lZs(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=cMe(t,r,new Date);if(L4e(a))return Ss(a,"yyyy-MM-dd")}catch{}try{const r=new Date(t);if(L4e(r))return Ss(r,"yyyy-MM-dd")}catch{}return null}const cZs=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function dZs({open:s,onOpenChange:t}){const[n,r]=N.useState([]),[a,i]=N.useState(!1),[l,o]=N.useState(0),{data:c}=ZD(),{data:d}=Sy(),u=qye(),h=()=>{const j=cZs.join(","),b=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),S=`${j} ${b}`,A=new Blob([S],{type:"text/csv"}),T=URL.createObjectURL(A),L=document.createElement("a");L.href=T,L.download="transaction-import-template.csv",L.click(),URL.revokeObjectURL(T)},p=j=>{const b=j.split(` `).filter(A=>A.trim());if(b.length<2)return[];const S=b[0].split(",").map(A=>A.trim().toLowerCase().replace(/['"]/g,""));return b.slice(1).map((A,T)=>{var ie,he,ce,pe;const L=[];let D="",M=!1;for(const le of A)le==='"'?M=!M:le===","&&!M?(L.push(D.trim()),D=""):D+=le;L.push(D.trim());const F=le=>{var ge;const ve=S.indexOf(le);return ve>=0?(ge=L[ve])==null?void 0:ge.replace(/^["']|["']$/g,"").trim():""},z=(ie=F("transaction_type"))==null?void 0:ie.toLowerCase(),V=(he=F("sale_price"))==null?void 0:he.replace(/[$,]/g,""),W=(ce=F("commission_amount"))==null?void 0:ce.replace(/[$,]/g,""),Y=(pe=F("is_win"))==null?void 0:pe.toLowerCase(),K=F("close_date"),J=lZs(K);let ne;return F("property_address")?["buyer","seller"].includes(z)?J?(!V||isNaN(Number(V)))&&(ne="Invalid sale price"):ne=`Invalid date format: "${K}" - use MM/DD/YYYY or YYYY-MM-DD`:ne='Transaction type must be "buyer" or "seller"':ne="Missing property address",{property_address:F("property_address"),city:F("city"),state:F("state"),zip:F("zip"),transaction_type:z==="seller"?"seller":"buyer",close_date:J||"",sale_price:Number(V)||0,commission_amount:W?Number(W):null,lead_source_name:F("lead_source"),client_type_name:F("client_type"),is_win:["yes","true","1"].includes(Y),notes:F("notes"),error:ne}})},f=j=>{var A;const b=(A=j.target.files)==null?void 0:A[0];if(!b)return;const S=new FileReader;S.onload=T=>{var M;const L=(M=T.target)==null?void 0:M.result,D=p(L);r(D)},S.readAsText(b)},g=async()=>{const j=n.filter(A=>!A.error);if(j.length===0){ae.error("No valid transactions to import");return}i(!0),o(0);let b=0,S=0;for(let A=0;AM.name.toLowerCase()===T.lead_source_name.toLowerCase()),D=d==null?void 0:d.find(M=>M.name.toLowerCase()===T.client_type_name.toLowerCase());await u.mutateAsync({property_address:T.property_address,city:T.city||null,state:T.state||null,zip:T.zip||null,transaction_type:T.transaction_type,close_date:T.close_date,sale_price:T.sale_price,commission_amount:T.commission_amount,lead_source_id:(L==null?void 0:L.id)||null,client_type_id:(D==null?void 0:D.id)||null,contact_id:null,notes:T.notes||null,is_win:T.is_win}),b++}catch(L){S++,console.error("Failed to import transaction:",L)}o(Math.round((A+1)/j.length*100))}i(!1),b>0&&ae.success(`Imported ${b} transaction${b>1?"s":""}`),S>0&&ae.error(`Failed to import ${S} transaction${S>1?"s":""}`),r([]),t(!1)},_=n.filter(j=>!j.error).length,v=n.filter(j=>j.error).length;return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Import Transactions"}),e.jsx(Qn,{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(Pa,{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:f})]}),n.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ze,{variant:"outline",children:[n.length," rows found"]}),_>0&&e.jsxs(ze,{className:"bg-green-500 text-white",children:[e.jsx(Ir,{className:"h-3 w-3 mr-1"}),_," valid"]}),v>0&&e.jsxs(ze,{variant:"destructive",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"}),v," errors"]})]}),e.jsx(hi,{className:"h-[200px] border rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-2",children:[n.slice(0,10).map((j,b)=>e.jsxs("div",{className:`p-2 rounded text-sm ${j.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:j.property_address||"(no address)"}),e.jsx(ze,{variant:j.transaction_type==="buyer"?"default":"secondary",children:j.transaction_type})]}),e.jsxs("div",{className:"text-muted-foreground",children:[j.close_date," • $",j.sale_price.toLocaleString()]}),j.error&&e.jsx(TIe,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(EIe,{className:"text-xs",children:j.error})})]},b)),n.length>10&&e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",n.length-10," more"]})]})}),a&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${l}%`}})}),e.jsxs("p",{className:"text-sm text-center text-muted-foreground",children:["Importing... ",l,"%"]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:g,disabled:_===0||a,children:[e.jsx(Na,{className:"h-4 w-4 mr-2"}),"Import ",_," Transaction",_!==1?"s":""]})]})]})]})})}const uZs=Yw({transactions_goal:Y9().min(0).optional(),volume_goal:Y9().min(0).optional(),gci_goal:Y9().min(0).optional()});function hZs({open:s,onOpenChange:t,year:n,existingGoals:r}){const a=Krs(),{data:i}=Vye(),l=(i==null?void 0:i.show_commission)??!0,o=Dye({resolver:Rye(uZs),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});N.useEffect(()=>{r?o.reset({transactions_goal:r.transactions_goal??void 0,volume_goal:r.volume_goal?Number(r.volume_goal):void 0,gci_goal:r.gci_goal?Number(r.gci_goal):void 0}):o.reset({transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0})},[r,o,s]);const c=async d=>{await a.mutateAsync({year:n,transactions_goal:d.transactions_goal??null,volume_goal:d.volume_goal??null,gci_goal:l?d.gci_goal??null:null}),t(!1)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:[n," Goals"]}),e.jsx(Qn,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx(Oye,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(Nu,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Transactions Goal"}),e.jsx(au,{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(Vme,{children:"Total number of deals you want to close"}),e.jsx(Yx,{})]})}),e.jsx(Nu,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"Volume Goal ($)"}),e.jsx(au,{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(Vme,{children:"Total sales volume you want to achieve"}),e.jsx(Yx,{})]})}),l&&e.jsx(Nu,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs(nu,{children:[e.jsx(ru,{children:"GCI Goal ($)"}),e.jsx(au,{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(Vme,{children:"Gross commission income target"}),e.jsx(Yx,{})]})}),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 g8e({transactions:s,isLoading:t}){const n=N.useRef(null),r=N.useRef(null),a=N.useRef([]),i=N.useRef(null),{isAdmin:l}=ys(),[o,c]=N.useState(""),[d,u]=N.useState(!0),[h,p]=N.useState(0),[f,g]=N.useState(!1),_=s.filter(j=>j.latitude!=null&&j.longitude!=null),v=s.filter(j=>j.latitude==null||j.longitude==null);return N.useEffect(()=>{(async()=>{u(!0);try{const{data:b}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();b!=null&&b.value&&c(b.value)}catch(b){console.error("Error fetching mapbox token:",b)}u(!1)})()},[]),N.useEffect(()=>{if(!o||v.length===0||f)return;(async()=>{var S;g(!0);let b=0;for(const A of v){const T=[A.property_address,A.city,A.state,A.zip].filter(Boolean).join(", ");if(T)try{const D=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(T)}.json?access_token=${o}&limit=1`)).json();if((S=D.features)!=null&&S[0]){const[M,F]=D.features[0].center;await q.from("scorecard_transactions").update({latitude:F,longitude:M}).eq("id",A.id),A.latitude=F,A.longitude=M,b++}}catch(L){console.error("Geocode error:",L)}}p(b),g(!1)})()},[o,s]),N.useEffect(()=>{if(!n.current||!o||r.current)return;hl.accessToken=o;const j=s.filter(A=>A.latitude!=null&&A.longitude!=null);let b=[-98.5795,39.8283],S=4;if(j.length>0){const A=j.reduce((L,D)=>L+D.longitude,0)/j.length,T=j.reduce((L,D)=>L+D.latitude,0)/j.length;b=[A,T],S=j.length===1?12:10}return r.current=new hl.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:S,center:b}),r.current.addControl(new hl.NavigationControl,"top-right"),()=>{var A;(A=r.current)==null||A.remove(),r.current=null}},[o]),N.useEffect(()=>{var b;if(!r.current||!o)return;a.current.forEach(S=>S.remove()),a.current=[],(b=i.current)==null||b.remove();const j=s.filter(S=>S.latitude!=null&&S.longitude!=null);if(j.forEach(S=>{var F;const A=S.transaction_type==="buyer",T=A?"#3B82F6":"#10B981",L=document.createElement("div");L.className="cursor-pointer",L.innerHTML=`
${A?'':''}
`;const D=new hl.Popup({offset:25,closeButton:!0}).setHTML(`
${S.property_address}
${S.city?`
${S.city}${S.state?", "+S.state:""} ${S.zip||""}
`:""}
${A?"Buyer":"Seller"} $${Number(S.sale_price).toLocaleString()}
Closed: ${Cl(S.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(F=S.lead_source)!=null&&F.name?" · "+S.lead_source.name:""}
${S.contact?`
Client: ${S.contact.first_name} ${S.contact.last_name||""}
`:""}
`),M=new hl.Marker(L).setLngLat([S.longitude,S.latitude]).setPopup(D).addTo(r.current);a.current.push(M)}),j.length>1){const S=new hl.LngLatBounds;j.forEach(A=>S.extend([A.longitude,A.latitude])),r.current.fitBounds(S,{padding:60,maxZoom:13})}else j.length===1&&r.current.flyTo({center:[j[0].longitude,j[0].latitude],zoom:12})},[s,o,f]),d||t?e.jsx(fe,{children:e.jsx(Ee,{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(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(ka,{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:[_.length," of ",s.length," mapped",f&&" · Geocoding..."]})]}),e.jsx("div",{ref:n,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(Gi,{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 o2t=()=>{const{data:s}=Zv();return ct({queryKey:["team-scorecard-members",s==null?void 0:s.teamId],queryFn:async()=>{const{data:t,error:n}=await q.from("team_members").select("user_id").eq("team_id",s.teamId);if(n)throw n;const r=t.map(l=>l.user_id),{data:a,error:i}=await q.from("profiles").select("id, name, email, avatar_url").in("id",r);if(i)throw i;return a||[]},enabled:!!(s!=null&&s.teamId)&&(s==null?void 0:s.role)==="team_leader"})},mZs=s=>{const{data:t}=Zv(),{data:n}=o2t();return ct({queryKey:["team-scorecard-transactions",t==null?void 0:t.teamId,s],queryFn:async()=>{const r=n.map(o=>o.id);let a=q.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).in("owner_user_id",r).order("close_date",{ascending:!1});s&&(a=a.gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`));const{data:i,error:l}=await a;if(l)throw l;return i},enabled:!!n&&n.length>0})};function pZs(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 fZs(s,t){return s?s.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function xZs({year:s}){var p;const{data:t,isLoading:n}=o2t(),{data:r,isLoading:a}=mZs(s),i=Mn(),l=n||a,{aggregate:o,memberStats:c,topPerformer:d,agentNameMap:u,teamChartStats:h}=N.useMemo(()=>{if(!t||!r)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const f=t.map(z=>pZs(z,r));f.sort((z,V)=>V.totalVolume-z.totalVolume);const g={};t.forEach(z=>{g[z.id]=z.name||z.email});const _=r.length,v=r.reduce((z,V)=>z+Number(V.sale_price),0),j=r.reduce((z,V)=>z+(Number(V.commission_amount)||0),0),b=r.filter(z=>z.transaction_type==="buyer").length,S=r.filter(z=>z.transaction_type==="seller").length,A={};r.forEach(z=>{var W;const V=((W=z.lead_source)==null?void 0:W.name)||"Unknown";A[V]=(A[V]||0)+1});const T=Object.entries(A).sort((z,V)=>V[1]-z[1])[0],L={};r.forEach(z=>{const V=Cl(z.close_date).toLocaleString("default",{month:"short"});L[V]=(L[V]||0)+1});const M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(z=>({month:z,count:L[z]||0})),F=Object.entries(A).map(([z,V])=>({name:z,count:V})).sort((z,V)=>V.count-z.count);return{aggregate:{totalTxns:_,buyerCount:b,sellerCount:S,totalVolume:v,avgPrice:_>0?v/_:0,totalGCI:j,topSource:T?{name:T[0],count:T[1]}:null,memberCount:t.length},memberStats:f,topPerformer:f[0]||null,agentNameMap:g,teamChartStats:{transactionsByMonth:M,leadSourceBreakdown:F}}},[t,r]);return l?e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[1,2,3,4].map(f=>e.jsx(Ws,{className:"h-24"},f))}),e.jsx(Ws,{className:"h-64"})]}):!o||c.length===0?e.jsx(fe,{className:"py-12",children:e.jsxs(Ee,{className:"text-center space-y-2",children:[e.jsx(Nn,{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(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Nn,{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(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Or,{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(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zl,{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:yc(o.totalVolume,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(mo,{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:yc(o.avgPrice,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zl,{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:yc(o.totalGCI,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(bc,{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:((p=o.topSource)==null?void 0:p.name)||"-"}),o.topSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.topSource.count," deals"]})]})})]}),d&&d.totalTransactions>0&&e.jsx(fe,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Ee,{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(vo,{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:yc(d.totalVolume,!0)})]})]})}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-lg",children:"Member Performance"})}),e.jsx(Ee,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{className:"text-center",children:"Transactions"}),e.jsx(Ct,{className:"text-center",children:"B / S"}),e.jsx(Ct,{className:"text-right",children:"Volume"}),e.jsx(Ct,{className:"text-right",children:"Avg Price"}),e.jsx(Ct,{className:"text-right",children:"GCI"}),e.jsx(Ct,{className:"text-right"})]})}),e.jsx(ha,{children:c.map((f,g)=>e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[g===0&&f.totalTransactions>0&&e.jsx(vo,{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(ni,{src:f.member.avatar_url||void 0}),e.jsx(aa,{className:"text-xs",children:fZs(f.member.name,f.member.email)})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:f.member.name||f.member.email}),f.member.name&&e.jsx("p",{className:"text-xs text-muted-foreground",children:f.member.email})]})]})}),e.jsx(ut,{className:"text-center font-semibold",children:f.totalTransactions}),e.jsxs(ut,{className:"text-center text-sm",children:[f.buyerCount," / ",f.sellerCount]}),e.jsx(ut,{className:"text-right font-medium",children:yc(f.totalVolume,!0)}),e.jsx(ut,{className:"text-right text-sm",children:yc(f.averagePrice,!0)}),e.jsx(ut,{className:"text-right font-medium",children:yc(f.totalGCI,!0)}),e.jsx(ut,{className:"text-right",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>i(`/mission-control/scorecard/${f.member.id}`),children:e.jsx(Er,{className:"h-4 w-4"})})})]},f.member.id))})]})})})]}),e.jsxs(Br,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Fr,{children:[e.jsxs(Kt,{value:"transactions",children:[e.jsx(Tp,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(Kt,{value:"charts",children:[e.jsx(yo,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(Kt,{value:"map",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(is,{value:"transactions",children:e.jsx(f8e,{transactions:r||[],showCommission:!0,isLoading:a,agentNameMap:u,readOnly:!0})}),e.jsx(is,{value:"charts",children:h&&e.jsx(x8e,{stats:h,year:s})}),e.jsx(is,{value:"map",children:e.jsx(g8e,{transactions:r||[],isLoading:a})})]})]})}const ipe=new Date().getFullYear(),YQe=Array.from({length:10},(s,t)=>ipe-t),CG="all";function gZs(){var W;const[s,t]=N.useState(ipe),n=s===null?CG:String(s),r=Y=>t(Y===CG?null:Number(Y)),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[p,f]=N.useState("my"),{data:g}=Zv(),_=(g==null?void 0:g.role)==="team_leader",{data:v,isLoading:j}=w6e(s??void 0),{yearStats:b,lifetimeStats:S,isLoading:A,showCommission:T}=ppt(s??void 0),{data:L,isLoading:D}=mpt(s??ipe),{data:M}=Vye(),F=Yrs(),z=()=>{if(!v||v.length===0)return;const Y=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...T?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],K=v.map(ce=>{var pe,le;return[ce.property_address,ce.city||"",ce.state||"",ce.zip||"",ce.transaction_type,ce.close_date,ce.sale_price,...T?[ce.commission_amount||""]:[],((pe=ce.lead_source)==null?void 0:pe.name)||"",((le=ce.client_type)==null?void 0:le.name)||"",ce.contact?`${ce.contact.first_name} ${ce.contact.last_name||""}`.trim():"",ce.is_win?"Yes":"No",ce.notes||""]}),J=[Y,...K].map(ce=>ce.map(pe=>`"${String(pe).replace(/"/g,'""')}"`).join(",")).join(` `),ne=new Blob([J],{type:"text/csv"}),ie=URL.createObjectURL(ne),he=document.createElement("a");he.href=ie,he.download=s===null?"transactions-all.csv":`transactions-${s}.csv`,he.click(),URL.revokeObjectURL(ie)},V=!v||v.length===0;return e.jsxs(Ts,{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"})]}),_&&e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[e.jsx(B,{variant:p==="my"?"default":"ghost",size:"sm",onClick:()=>f("my"),className:"h-8",children:"My Scorecard"}),e.jsxs(B,{variant:p==="team"?"default":"ghost",size:"sm",onClick:()=>f("team"),className:"h-8",children:[e.jsx(Nn,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),p==="team"&&_?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(ds,{value:n,onValueChange:r,children:[e.jsx(ls,{className:"w-[140px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:CG,children:"All Years"}),YQe.map(Y=>e.jsx(Qe,{value:String(Y),children:Y},Y))]})]})]}),e.jsx(xZs,{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(ds,{value:n,onValueChange:r,children:[e.jsx(ls,{className:"w-[140px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:CG,children:"All Years"}),YQe.map(Y=>e.jsx(Qe,{value:String(Y),children:Y},Y))]})]}),e.jsx(B,{variant:"outline",size:"icon",onClick:()=>h(!u),children:e.jsx(Xo,{className:"h-4 w-4"})})]})]}),u&&e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsx(It,{className:"text-lg",children:"Settings"})}),e.jsx(Ee,{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(bn,{checked:(M==null?void 0:M.show_commission)??!0,onCheckedChange:Y=>F.mutate({show_commission:Y})})]})})]}),V&&!j?e.jsx(fe,{className:"py-12",children:e.jsxs(Ee,{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(yo,{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(Is,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(Na,{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(Pa,{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(Is,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs(B,{variant:"outline",onClick:()=>d(!0),children:[e.jsx(Oc,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(Na,{className:"h-4 w-4 mr-2"}),"Import"]}),e.jsxs(B,{variant:"outline",onClick:z,disabled:V,children:[e.jsx(Pa,{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(Pa,{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(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Or,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:b.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[S.totalTransactions," lifetime"]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Nn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[b.buyerCount,"/",b.sellerCount]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"B/S split"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:yc(b.totalVolume,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[yc(S.totalVolume,!0)," lifetime"]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(mo,{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:yc(b.averagePrice,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(bc,{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:((W=b.topLeadSource)==null?void 0:W.name)||"-"}),b.topLeadSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.topLeadSource.count," deals"]})]})}),T&&e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:yc(b.totalCommission,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[yc(S.totalCommission,!0)," lifetime"]})]})}),T&&b.totalNetToAgent>0&&b.totalNetToAgent!==b.totalCommission&&e.jsx(fe,{children:e.jsxs(Ee,{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(Zl,{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:yc(b.totalNetToAgent,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[yc(S.totalNetToAgent,!0)," lifetime"]})]})})]}),s!==null&&L&&e.jsx(s2t,{goals:L,stats:b,year:s,showCommission:T}),e.jsxs(Br,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Fr,{children:[e.jsx(Kt,{value:"transactions",children:"Transactions"}),e.jsx(Kt,{value:"charts",children:"Charts"}),e.jsxs(Kt,{value:"map",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(is,{value:"transactions",children:e.jsx(f8e,{transactions:v||[],showCommission:T,isLoading:j})}),e.jsx(is,{value:"charts",children:e.jsx(x8e,{stats:b,year:s??void 0})}),e.jsx(is,{value:"map",children:e.jsx(g8e,{transactions:v||[],isLoading:j})})]})]})]})]}),e.jsx(t2t,{open:a,onOpenChange:i}),e.jsx(dZs,{open:l,onOpenChange:o}),e.jsx(hZs,{open:c,onOpenChange:d,year:s??ipe,existingGoals:L})]})}function l2t({open:s,onOpenChange:t,listingId:n,listingSlug:r,listingTitle:a}){const{user:i}=ys(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(!1);N.useEffect(()=>{(async()=>{if(!(!s||!i)){d(!0);try{const{data:v,error:j}=await q.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(j)throw j;if(v&&v.share_token)o(v);else if(v&&!v.share_token){const{data:b,error:S}=await q.from("listing_shares").update({share_type:"referral_link"}).eq("id",v.id).select("id, share_token, click_count, lead_count").single();if(S)throw S;o(b)}else{const{data:b,error:S}=await q.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(S)throw S;o(b)}}catch(v){console.error("Error creating share link:",v),ae.error("Failed to generate share link")}finally{d(!1)}}})()},[s,i,n]);const p=l!=null&&l.share_token?`https://listings.relevelup.com/${r||n}?ref=${l.share_token}`:"",f=async()=>{try{await navigator.clipboard.writeText(p),h(!0),ae.success("Link copied to clipboard!"),setTimeout(()=>h(!1),2e3)}catch{ae.error("Failed to copy link")}},g=_=>{const v=encodeURIComponent(p),j=encodeURIComponent(`Check out this listing: ${a}`);switch(_){case"email":window.open(`mailto:?subject=${j}&body=${v}`);break;case"text":window.open(`sms:?body=${j}%20${v}`);break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${v}`,"_blank");break}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-amber-500"}),"Share & Earn Leads"]}),e.jsx(Qn,{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...":p,readOnly:!0,className:"font-mono text-sm"}),e.jsx(B,{onClick:f,disabled:c||!p,variant:u?"default":"outline",children:u?e.jsx(Ir,{className:"h-4 w-4"}):e.jsx(Xr,{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:()=>g("email"),disabled:c,children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>g("text"),disabled:c,children:[e.jsx(Ei,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>g("facebook"),disabled:c,children:[e.jsx(Lh,{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(Er,{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(Nn,{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 yZs={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"},vZs={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},bZs={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function _Zs({listing:s,onClick:t,onEdit:n,onDelete:r,onCreateMusicVideo:a,showActions:i}){var v,j;const{user:l}=ys(),{data:o}=opt(s.id),c=ipt(),[d,u]=N.useState(!1),h=b=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(b),p=((v=s.photos)==null?void 0:v.find(b=>b.is_primary))||((j=s.photos)==null?void 0:j[0]),f=(l==null?void 0:l.id)===s.agent_id,g=async b=>{b.stopPropagation();try{const S=await c.mutateAsync(s.id);ae.success(S.saved?"Listing saved!":"Listing removed from saved")}catch{ae.error("Failed to save listing")}},_=b=>{if(b.stopPropagation(),l)u(!0);else{const S=`https://listings.relevelup.com/${s.slug||s.id}`;navigator.clipboard.writeText(S),ae.success("Link copied to clipboard!")}};return e.jsxs(fe,{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:[p?e.jsx("img",{src:p.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(ly,{className:"h-12 w-12"})}),e.jsx(ze,{className:`absolute top-2 left-2 ${yZs[s.status]} text-white border-0`,children:vZs[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(ca,{className:"h-4 w-4 text-white fill-white"})}),e.jsxs("div",{className:"absolute bottom-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(B,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:g,children:e.jsx(gi,{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:_,title:f?"Copy link":"Share & earn leads",children:f?e.jsx(Hl,{className:"h-4 w-4"}):e.jsx(un,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(l2t,{open:d,onOpenChange:u,listingId:s.id,listingSlug:s.slug||null,listingTitle:s.property_address||`${s.city}, ${s.state}`}),e.jsxs(Ee,{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(ze,{variant:"outline",className:"text-xs",children:[e.jsx(Nn,{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(ka,{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(sy,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Cp,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ly,{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(ze,{variant:"secondary",className:"text-xs",children:bZs[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(Er,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hl,{className:"h-3 w-3"}),s.share_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gi,{className:"h-3 w-3"}),s.save_count]})]}),i&&(n||r||a)&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[a&&e.jsxs(B,{variant:"outline",size:"sm",className:"flex-1 min-w-[140px] gap-1.5 border-violet-500/60 text-violet-600 hover:bg-violet-50",onClick:b=>{b.stopPropagation(),a()},children:[e.jsx(pL,{className:"h-4 w-4"}),"Music Video"]}),n&&e.jsxs(B,{variant:"outline",size:"sm",className:"flex-1",onClick:b=>{b.stopPropagation(),n()},children:[e.jsx(ku,{className:"h-4 w-4 mr-2"}),"Edit"]}),r&&e.jsx(B,{variant:"destructive",size:"sm",onClick:b=>{b.stopPropagation(),r()},children:e.jsx(_n,{className:"h-4 w-4"})})]})]})]})}const y8e="lu_listing_selection_v1",Gge=24,Wge=new Set;function c2t(){try{return JSON.parse(sessionStorage.getItem(y8e)||"{}")}catch{return{}}}function ONe(s){try{sessionStorage.setItem(y8e,JSON.stringify(s))}catch{}Wge.forEach(t=>t())}let v2=c2t();function wZs(){v2=c2t(),Wge.forEach(s=>s())}typeof window<"u"&&window.addEventListener("storage",s=>{s.key===y8e&&wZs()});const aS={getSnapshot:()=>v2,subscribe(s){return Wge.add(s),()=>Wge.delete(s)},toggle(s){const t={...v2};if(t[s.mlsNumber])delete t[s.mlsNumber];else{if(Object.keys(t).length>=Gge)return!1;t[s.mlsNumber]=s}return v2=t,ONe(t),!0},remove(s){const t={...v2};delete t[s],v2=t,ONe(t)},clear(){v2={},ONe({})},has(s){return!!v2[s]},all(){return Object.values(v2)}};function d2t(){const s=N.useSyncExternalStore(aS.subscribe,aS.getSnapshot,aS.getSnapshot);return{selected:Object.values(s),selectedIds:new Set(Object.keys(s)),count:Object.keys(s).length,has:t=>!!s[t],toggle:aS.toggle,remove:aS.remove,clear:aS.clear}}const jZs=new Set(["office_exclusive","coming_soon","pre_market"]);function NZs(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=jZs.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 TG(s){const{has:t}=d2t(),n=`lx-${s.listing.id}`,r=t(n);return e.jsxs("div",{className:"relative",children:[e.jsx(_Zs,{...s}),e.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),aS.toggle(NZs(s.listing))||ae.error(`You can select up to ${Gge} 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(Ir,{className:"h-4 w-4"}):e.jsx(Vs,{className:"h-4 w-4"})})]})}function kZs({open:s,onOpenChange:t,listings:n}){const{user:r}=ys(),{leadSite:a}=Ip(),[i,l]=N.useState("grid"),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(new Set),[_,v]=N.useState(!1),[j,b]=N.useState(!1),{data:S}=C1e(),[A,T]=N.useState(!1);N.useEffect(()=>{!s||!(r!=null&&r.id)||q.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle().then(({data:J})=>b(!!(J!=null&&J.gmail_email)))},[s,r==null?void 0:r.id]),N.useEffect(()=>{if(s){if(!o){const J=Array.from(new Set(n.map(ie=>ie.city).filter(Boolean))),ne=J.length===1?` in ${J[0]}`:"";c(n.length===1?`New listing for you${ne}`:`${n.length} hand-picked listings${ne}`)}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:L=[],isLoading:D}=ct({queryKey:["send-listings-contacts",r==null?void 0:r.id],queryFn:async()=>{const{data:J}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, city").eq("owner_user_id",r.id).not("email","is",null).neq("email","").order("first_name");return J||[]},enabled:!!(r!=null&&r.id)&&s}),{data:M}=ct({queryKey:["send-listings-suggestions",n.map(J=>J.mlsNumber).join(",")],queryFn:async()=>{const{data:J,error:ne}=await q.functions.invoke("listing-email-suggestions",{body:{listings:n.map(ie=>({mlsNumber:ie.mlsNumber,city:ie.city,state:ie.state,price:ie.price,bedrooms:ie.bedrooms,bathrooms:ie.bathrooms}))}});if(ne)throw ne;return J},enabled:s&&n.length>0}),F=(M==null?void 0:M.suggestions)||[],z=N.useMemo(()=>{const J=h.trim().toLowerCase();return J?L.filter(ne=>`${ne.first_name??""} ${ne.last_name??""} ${ne.email} ${ne.city??""}`.toLowerCase().includes(J)):L},[L,h]),V=J=>{g(ne=>{const ie=new Set(ne);return ie.has(J)?ie.delete(J):ie.add(J),ie})},W=()=>{g(J=>{const ne=new Set(J);return F.forEach(ie=>ne.add(ie.contact_id)),ne})},Y=n.length>0&&n.every(J=>J.mlsNumber.startsWith("lx-")),K=async()=>{if(!Y&&!(a!=null&&a.id)){ae.error("You need an active lead site to send listings.");return}if(!o.trim())return ae.error("Subject is required");if(f.size===0)return ae.error("Pick at least one recipient");if(!j&&S&&!S.hasVerifiedSes){T(!0);return}const J=L.filter(ne=>f.has(ne.id)).map(ne=>({contact_id:ne.id,email:ne.email,first_name:ne.first_name,last_name:ne.last_name}));v(!0);try{const{data:ne,error:ie}=await q.functions.invoke("listing-email-send",{body:{lead_site_id:(a==null?void 0:a.id)||null,layout:i,subject:o.trim(),intro_message:d.trim()||null,listings:n.map(he=>({mlsNumber:he.mlsNumber,address:he.address,city:he.city,state:he.state,zip:he.zip,price:he.price,bedrooms:he.bedrooms,bathrooms:he.bathrooms,sqft:he.sqft,status:he.status,photos:(he.photos||[]).slice(0,1),description:he.description||"",external_url:he.externalUrl||null,is_private:he.is_private===!0})),recipients:J}});if(ie)throw ie;if(!(ne!=null&&ne.success))throw new Error((ne==null?void 0:ne.error)||"Send failed");ae.success(`Sent ${ne.sent}/${J.length} via ${j?"Gmail":"Amazon SES"}${ne.failed?` · ${ne.failed} failed`:""}`),aS.clear(),g(new Set),t(!1)}catch(ne){ae.error((ne==null?void 0:ne.message)||"Failed to send")}finally{v(!1)}};return e.jsxs(bs,{open:s,onOpenChange:t,children:[e.jsxs(vs,{className:"max-w-5xl max-h-[92vh] overflow-hidden p-0 flex flex-col",children:[e.jsxs(ws,{className:"px-6 pt-6 pb-2",children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5 text-primary"}),"Email ",n.length," ",n.length===1?"Listing":"Listings"]}),e.jsx(Qn,{children:Y?"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(J=>{var ne;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:((ne=J.photos)==null?void 0:ne[0])&&e.jsx("img",{src:J.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:["$",(J.price/1e3).toFixed(0),"k"]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground truncate",children:[J.city,", ",J.state]})]})]},J.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(yf,{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(nl,{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:J=>c(J.target.value),placeholder:"Subject line",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"intro",children:"Personal message"}),e.jsx(Es,{id:"intro",value:d,onChange:J=>u(J.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:j?"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:[F.length>0&&e.jsxs(fe,{className:"p-3 bg-amber-50/50 border-amber-200",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-amber-600"}),e.jsxs("div",{className:"text-sm font-medium",children:[F.length," smart ",F.length===1?"match":"matches"]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:W,children:"Add all"})]}),e.jsx(hi,{className:"max-h-32 mt-2",children:e.jsx("div",{className:"space-y-1",children:F.slice(0,12).map(J=>{const ne=f.has(J.contact_id);return e.jsxs("label",{className:"flex items-start gap-2 text-xs py-1 cursor-pointer",children:[e.jsx(ui,{checked:ne,onCheckedChange:()=>V(J.contact_id),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[J.first_name," ",J.last_name??""," ",e.jsxs("span",{className:"text-muted-foreground font-normal",children:["· ",J.email]})]}),e.jsx("div",{className:"text-muted-foreground truncate",children:J.reason})]})]},J.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 (",z.length,")"]}),f.size>0&&e.jsxs(ze,{variant:"secondary",children:[f.size," selected"]})]}),e.jsx(ye,{placeholder:"Search contacts…",value:h,onChange:J=>p(J.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(hi,{className:"h-full",children:D?e.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading…"}):z.length===0?e.jsx("div",{className:"p-4 text-sm text-muted-foreground text-center",children:"No contacts found"}):e.jsx("div",{className:"divide-y",children:z.map(J=>{const ne=f.has(J.id);return e.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-muted/40",children:[e.jsx(ui,{checked:ne,onCheckedChange:()=>V(J.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[J.first_name," ",J.last_name??""]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[J.email,J.city&&e.jsxs(e.Fragment,{children:[" · ",J.city]})]})]})]},J.id)})})})})}),e.jsxs("div",{className:"px-6 py-2 text-xs text-muted-foreground border-t flex items-center justify-between",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-foreground",children:f.size})," recipients"]}),f.size>0&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>g(new Set),children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),"Clear"]})]})]})]}),e.jsxs(Xn,{className:"px-6 py-4 border-t bg-muted/30",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:_,children:"Cancel"}),e.jsx(B,{onClick:K,disabled:_||f.size===0,children:_?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Send to ",f.size," ",f.size===1?"contact":"contacts"]})})]})]}),e.jsx(T1e,{open:A,onOpenChange:T,hasPending:!!(S!=null&&S.hasPendingSes),pendingEmails:S==null?void 0:S.pendingEmails})]})}function SZs(){const{selected:s,count:t,remove:n,clear:r}=d2t(),[a,i]=N.useState(!1);return t===0?null:e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed bottom-4 left-1/2 -translate-x-1/2 z-50 w-[min(96vw,820px)]",children:e.jsxs("div",{className:"rounded-2xl border bg-background/95 backdrop-blur shadow-2xl p-3 flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-primary/10 text-primary flex items-center justify-center font-semibold",children:t}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium leading-tight",children:[t," listing",t===1?"":"s"," selected"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t>=Gge?"Max reached":`Pick up to ${Gge}`})]})]}),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(Bn,{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(_n,{className:"h-4 w-4"})," Clear"]}),e.jsxs(B,{size:"sm",className:"gap-1.5",onClick:()=>i(!0),children:[e.jsx(cr,{className:"h-4 w-4"}),"Email these ",t===1?"listing":"listings"]})]})]})}),e.jsx(kZs,{open:a,onOpenChange:i,listings:s})]})}const CZs=[{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"}],TZs=[{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 EZs({filters:s,onFiltersChange:t,onClose:n}){const r=()=>{t({sortBy:"newest"})};return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(It,{className:"text-lg",children:"Filters"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:r,children:"Clear All"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(Bn,{className:"h-4 w-4"})})]})]}),e.jsxs(Ee,{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(ds,{value:s.status||"all",onValueChange:a=>t({...s,status:a==="all"?void 0:a}),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"All statuses"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Statuses"}),CZs.map(a=>e.jsx(Qe,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Property Type"}),e.jsxs(ds,{value:s.propertyType||"all",onValueChange:a=>t({...s,propertyType:a==="all"?void 0:a}),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"All types"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Types"}),TZs.map(a=>e.jsx(Qe,{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(bn,{checked:s.openToReferrals||!1,onCheckedChange:a=>t({...s,openToReferrals:a||void 0})})]})]})]})}function AZs({leaderboard:s}){const t=r=>{switch(r){case 0:return e.jsx(vo,{className:"h-5 w-5 text-amber-500"});case 1:return e.jsx(Q2,{className:"h-5 w-5 text-gray-400"});case 2:return e.jsx(bc,{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(ze,{variant:l===0?"default":"secondary",children:[i.count," ",a]})]},i.agentId))});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(vo,{className:"h-5 w-5 text-amber-500"}),"Community Badges"]})}),e.jsx(Ee,{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(Hl,{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(Or,{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(Q2,{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(vo,{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(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"Community Leaderboard"})}),e.jsx(Ee,{children:e.jsxs(Br,{defaultValue:"sharers",children:[e.jsxs(Fr,{className:"w-full",children:[e.jsxs(Kt,{value:"sharers",className:"flex-1",children:[e.jsx(Hl,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(Kt,{value:"listers",className:"flex-1",children:[e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(is,{value:"sharers",className:"mt-4",children:n(s==null?void 0:s.topSharers,"shares")}),e.jsx(is,{value:"listers",className:"mt-4",children:n(s==null?void 0:s.topListers,"listings")})]})})]})]})}const ZQe={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},QQe={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 MZs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function IZs({listings:s,isLoading:t}){const n=Mn(),r=N.useRef(null),a=N.useRef(null),i=N.useRef([]),{isAdmin:l}=ys(),[o,c]=N.useState(""),[d,u]=N.useState(!0),[h,p]=N.useState(!1),f=s.filter(_=>_.latitude!=null&&_.longitude!=null),g=s.filter(_=>(_.latitude==null||_.longitude==null)&&(_.property_address||_.city));return N.useEffect(()=>{(async()=>{u(!0);try{const{data:v}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();v!=null&&v.value&&c(v.value)}catch(v){console.error("Error fetching mapbox token:",v)}u(!1)})()},[]),N.useEffect(()=>{if(!o||g.length===0||h)return;(async()=>{var v;p(!0);for(const j of g){const b=[j.property_address,j.city,j.state].filter(Boolean).join(", ");if(b)try{const A=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(b)}.json?access_token=${o}&limit=1`)).json();if((v=A.features)!=null&&v[0]){const[T,L]=A.features[0].center;await q.from("listings").update({latitude:L,longitude:T}).eq("id",j.id),j.latitude=L,j.longitude=T}}catch(S){console.error("Geocode error:",S)}}p(!1)})()},[o,s]),N.useEffect(()=>{if(!r.current||!o||a.current)return;hl.accessToken=o;const _=s.filter(b=>b.latitude!=null&&b.longitude!=null);let v=[-98.5795,39.8283],j=4;if(_.length>0){const b=_.reduce((A,T)=>A+T.longitude,0)/_.length,S=_.reduce((A,T)=>A+T.latitude,0)/_.length;v=[b,S],j=_.length===1?12:10}return a.current=new hl.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:j,center:v}),a.current.addControl(new hl.NavigationControl,"top-right"),()=>{var b;(b=a.current)==null||b.remove(),a.current=null}},[o]),N.useEffect(()=>{if(!a.current||!o)return;i.current.forEach(v=>v.remove()),i.current=[];const _=s.filter(v=>v.latitude!=null&&v.longitude!=null);if(_.forEach(v=>{var L,D,M;const j=ZQe[v.status]||"#10B981",b=((L=v.photos)==null?void 0:L.find(F=>F.is_primary))||((D=v.photos)==null?void 0:D[0]),S=document.createElement("div");S.className="cursor-pointer",S.innerHTML=`
`;const A=new hl.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${b!=null&&b.photo_url?``:""}
${MZs(v.price)}
${v.property_address||""}
${v.city}, ${v.state}
${QQe[v.status]||v.status} ${v.bedrooms?`${v.bedrooms} bed`:""} ${v.bathrooms?`${v.bathrooms} bath`:""}
${(M=v.agent)!=null&&M.name?`
Listed by ${v.agent.name}
`:""}
Click to view details →
`),T=new hl.Marker(S).setLngLat([v.longitude,v.latitude]).setPopup(A).addTo(a.current);i.current.push(T)}),_.length>1){const v=new hl.LngLatBounds;_.forEach(j=>v.extend([j.longitude,j.latitude])),a.current.fitBounds(v,{padding:60,maxZoom:13})}else _.length===1&&a.current.flyTo({center:[_[0].longitude,_[0].latitude],zoom:12})},[s,o,h]),N.useEffect(()=>(window.__navigateToListing__=_=>{n(`/mission-control/listings/${_}`)},()=>{delete window.__navigateToListing__}),[n]),d||t?e.jsx(fe,{children:e.jsx(Ee,{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(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(ka,{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(ZQe).map(([_,v])=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:v}}),e.jsx("span",{className:"text-xs",children:QQe[_]})]},_)),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[f.length," of ",s.length," mapped",h&&" · Geocoding..."]})]}),e.jsx("div",{ref:r,className:"w-full h-[60vh] rounded-lg shadow-lg border"})]}):e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(Gi,{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 _Te="homereel_mv_prefill",wTe="homereel_mv_badge_default";function u2t(s){try{sessionStorage.setItem(_Te,JSON.stringify(s)),s.badge&&s.badge.type!=="none"&&sessionStorage.setItem(wTe,JSON.stringify(s.badge))}catch{}}function fgn(){try{const s=sessionStorage.getItem(_Te);return s?(sessionStorage.removeItem(_Te),JSON.parse(s)):null}catch{return null}}function xgn(){try{const s=sessionStorage.getItem(wTe);return s?(sessionStorage.removeItem(wTe),JSON.parse(s)):null}catch{return null}}function h2t(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 PZs(){var F,z,V,W,Y,K,J,ne;const s=Mn(),{brokerageId:t}=ys(),{data:n,isLoading:r}=spt(),[a,i]=N.useState("feed"),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState({sortBy:"newest"}),{data:p,isLoading:f}=npt({...u,city:c||u.city}),{data:g,isLoading:_}=Mrs(),{data:v,isLoading:j}=rpt(),{data:b,isLoading:S}=Drs(),{data:A,isLoading:T}=Frs(),{data:L}=Ors(),D=apt(),M=async ie=>{if(confirm("Are you sure you want to delete this listing? This action cannot be undone."))try{await D.mutateAsync(ie),ae.success("Listing deleted successfully")}catch{ae.error("Failed to delete listing")}};return r?e.jsx(Ts,{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(Ts,{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(Is,{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(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Or,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(p==null?void 0:p.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active Listings"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-pink-500/10 rounded-lg",children:e.jsx(gi,{className:"h-5 w-5 text-pink-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(g==null?void 0:g.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-emerald-500/10 rounded-lg",children:e.jsx(jA,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(v==null?void 0:v.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"My Listings"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-sky-500/10 rounded-lg",children:e.jsx(Nn,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((F=b==null?void 0:b.sent)==null?void 0:F.length)||0)+(((z=b==null?void 0:b.received)==null?void 0:z.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs(Br,{value:a,onValueChange:i,children:[e.jsxs(Fr,{className:"w-full justify-start overflow-x-auto",children:[e.jsx(Kt,{value:"feed",children:"Community Feed"}),t&&e.jsx(Kt,{value:"brokerage",children:"Brokerage"}),e.jsx(Kt,{value:"my-listings",children:"My Listings"}),e.jsx(Kt,{value:"saved",children:"Saved"}),e.jsx(Kt,{value:"referrals",children:"Referrals"}),e.jsx(Kt,{value:"map",children:"Map"}),e.jsx(Kt,{value:"leaderboard",children:"Leaderboard"})]}),e.jsxs(is,{value:"feed",className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by city or neighborhood...",value:c,onChange:ie=>d(ie.target.value),className:"pl-9"})]}),e.jsxs(ds,{value:u.sortBy,onValueChange:ie=>h({...u,sortBy:ie}),children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(us,{placeholder:"Sort by"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"newest",children:"Newest First"}),e.jsx(Qe,{value:"updated",children:"Recently Updated"}),e.jsx(Qe,{value:"price_asc",children:"Price: Low to High"}),e.jsx(Qe,{value:"price_desc",children:"Price: High to Low"})]})]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!l),children:[e.jsx(Rv,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx(EZs,{filters:u,onFiltersChange:h,onClose:()=>o(!1)}),f?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((ie,he)=>e.jsxs(fe,{children:[e.jsx(Ws,{className:"h-48 w-full"}),e.jsxs(Ee,{className:"p-4 space-y-2",children:[e.jsx(Ws,{className:"h-5 w-3/4"}),e.jsx(Ws,{className:"h-4 w-1/2"}),e.jsx(Ws,{className:"h-4 w-1/4"})]})]},he))}):(p==null?void 0:p.length)===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(Or,{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(Is,{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:p==null?void 0:p.map(ie=>e.jsx(TG,{listing:ie,onClick:()=>s(`/mission-control/listings/${ie.id}`)},ie.id))})]}),e.jsx(is,{value:"my-listings",className:"space-y-4",children:j?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ie,he)=>e.jsxs(fe,{children:[e.jsx(Ws,{className:"h-48 w-full"}),e.jsxs(Ee,{className:"p-4 space-y-2",children:[e.jsx(Ws,{className:"h-5 w-3/4"}),e.jsx(Ws,{className:"h-4 w-1/2"})]})]},he))}):(v==null?void 0:v.length)===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(jA,{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(Is,{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:v==null?void 0:v.map(ie=>e.jsx(TG,{listing:ie,showActions:!0,onClick:()=>s(`/mission-control/listings/${ie.id}`),onEdit:()=>s(`/mission-control/listings/${ie.id}/edit`),onDelete:()=>M(ie.id),onCreateMusicVideo:()=>{const he=(ie.photos??[]).slice().sort((ce,pe)=>(pe.is_primary?1:0)-(ce.is_primary?1:0)||(ce.sort_order??0)-(pe.sort_order??0)).map(ce=>ce.photo_url).filter(Boolean);if(he.length===0){ae.error("Add photos to this listing first.");return}u2t({photos:he,details:{address:ie.property_address||`${ie.city??""} ${ie.state??""}`.trim(),beds:ie.bedrooms?String(ie.bedrooms):"",baths:ie.bathrooms?String(ie.bathrooms):"",sqft:ie.square_footage?String(ie.square_footage):"",price:ie.price?String(ie.price):"",highlights:ie.description||""},sourceLabel:"My Listings",badge:h2t(ie.status,ie.price)}),s("/admin/beta/homereel?tab=music-video")}},ie.id))})}),e.jsx(is,{value:"saved",className:"space-y-4",children:_?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ie,he)=>e.jsxs(fe,{children:[e.jsx(Ws,{className:"h-48 w-full"}),e.jsxs(Ee,{className:"p-4 space-y-2",children:[e.jsx(Ws,{className:"h-5 w-3/4"}),e.jsx(Ws,{className:"h-4 w-1/2"})]})]},he))}):(g==null?void 0:g.length)===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(gi,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No saved listings"}),e.jsx("p",{className:"text-muted-foreground",children:"Save listings to quickly access them later"})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:g==null?void 0:g.map(ie=>e.jsx(TG,{listing:ie.listing,onClick:()=>s(`/mission-control/listings/${ie.listing.id}`)},ie.id))})}),e.jsx(is,{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(Hl,{className:"h-4 w-4"}),"Referrals Sent (",((V=b==null?void 0:b.sent)==null?void 0:V.length)||0,")"]}),((W=b==null?void 0:b.sent)==null?void 0:W.length)===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-8 text-center text-muted-foreground",children:"No referrals sent yet"})}):e.jsx("div",{className:"space-y-3",children:(Y=b==null?void 0:b.sent)==null?void 0:Y.map(ie=>{var he,ce;return e.jsx(fe,{children:e.jsx(Ee,{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:ie.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((he=ie.listing)==null?void 0:he.property_address)||((ce=ie.listing)==null?void 0:ce.city)})]}),e.jsx(ze,{variant:ie.status==="closed"?"default":"secondary",children:ie.status.replace("_"," ")})]})})},ie.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Referrals Received (",((K=b==null?void 0:b.received)==null?void 0:K.length)||0,")"]}),((J=b==null?void 0:b.received)==null?void 0:J.length)===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-8 text-center text-muted-foreground",children:"No referrals received yet"})}):e.jsx("div",{className:"space-y-3",children:(ne=b==null?void 0:b.received)==null?void 0:ne.map(ie=>{var he;return e.jsx(fe,{children:e.jsxs(Ee,{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:ie.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(he=ie.sender)==null?void 0:he.name]})]}),e.jsx(ze,{variant:ie.status==="closed"?"default":"secondary",children:ie.status.replace("_"," ")})]}),e.jsx(B,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>s(`/mission-control/listings/${ie.listing_id}`),children:"View Listing"})]})},ie.id)})})]})]})}),t&&e.jsx(is,{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((ie,he)=>e.jsxs(fe,{children:[e.jsx(Ws,{className:"h-48 w-full"}),e.jsxs(Ee,{className:"p-4 space-y-2",children:[e.jsx(Ws,{className:"h-5 w-3/4"}),e.jsx(Ws,{className:"h-4 w-1/2"})]})]},he))}):(A==null?void 0:A.length)===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(jA,{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(Is,{className:"h-4 w-4 mr-2"}),"Add a Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:A==null?void 0:A.map(ie=>e.jsx(TG,{listing:ie,onClick:()=>s(`/mission-control/listings/${ie.id}`)},ie.id))})}),e.jsx(is,{value:"map",children:e.jsx(IZs,{listings:p||[],isLoading:f})}),e.jsx(is,{value:"leaderboard",children:e.jsx(AZs,{leaderboard:L})})]})]}),e.jsx(SZs,{})]}):e.jsx(Ts,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(Or,{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 m2t(s){return ct({queryKey:["listing-documents",s],queryFn:async()=>{const{data:t,error:n}=await q.from("listing_documents").select("*").eq("listing_id",s).order("sort_order",{ascending:!0}).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function LZs(){const{user:s}=ys(),t=Ht();return gt({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 q.storage.from("listing-documents").upload(i,r,{contentType:r.type||void 0});if(l)throw l;const{data:o,error:c}=await q.from("listing_documents").insert({listing_id:n,owner_user_id:s.id,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["listing-documents",r.listingId]})}})}function DZs(){const s=Ht();return gt({mutationFn:async({id:t,storage_path:n,listingId:r})=>{await q.storage.from("listing-documents").remove([n]);const{error:a}=await q.from("listing_documents").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function RZs(){const s=Ht();return gt({mutationFn:async({id:t,visible:n,listingId:r})=>{const{error:a}=await q.from("listing_documents").update({visible_on_exchange:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}async function p2t(s){const{data:t,error:n}=await q.storage.from("listing-documents").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const OZs=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function FZs({listingId:s,ownerOnly:t=!1}){const{data:n=[]}=m2t(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 p2t(i);window.open(l,"_blank")}catch{ae.error("Failed to open document")}};return e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"text-lg flex items-center gap-2",children:[e.jsx(Nr,{className:"h-5 w-5"}),"Documents & Disclosures (",r.length,")"]})}),e.jsx(Ee,{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(Nr,{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:OZs(i.file_size)})]}),e.jsx(Pa,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}const zZs=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)}`},XQe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),g3="#D4AF37",JQe="#0F172A",eXe=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}),tXe=(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)},E7=(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()}…`},BZs=(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},UZs=s=>s instanceof DOMException||s instanceof Error?s.name:null;function f2t({listingId:s,open:t,onOpenChange:n}){var T,L;const{data:r}=b6e(s||""),[a,i]=N.useState(null),[l,o]=N.useState(!1),[c,d]=N.useState(null),[u,h]=N.useState(null),p=((r==null?void 0:r.photos)||[]).slice().sort((D,M)=>D.is_primary&&!M.is_primary?-1:!D.is_primary&&M.is_primary?1:(D.sort_order??0)-(M.sort_order??0));N.useEffect(()=>{var M;if(!t)return;const D=((M=p[0])==null?void 0:M.photo_url)||null;h(F=>F||D)},[t,r==null?void 0:r.id,p.length]),N.useEffect(()=>{let D=!1;if(!(!t||!(r!=null&&r.agent_id)))return(async()=>{var V,W,Y,K;const{data:M}=await q.from("profiles").select("name, phone, phone_e164, avatar_url, brokerage:brokerages!profiles_brokerage_id_fkey(name)").eq("id",r.agent_id).maybeSingle();if(D)return;const F=M,z=((V=F==null?void 0:F.brokerage)==null?void 0:V.name)||((Y=(W=r.agent)==null?void 0:W.brokerage)==null?void 0:Y.name)||null;i({name:(F==null?void 0:F.name)||((K=r.agent)==null?void 0:K.name)||"Agent",phone:(F==null?void 0:F.phone)||(F==null?void 0:F.phone_e164)||null,avatar_url:(F==null?void 0:F.avatar_url)||null,brokerage:z})})(),()=>{D=!0}},[t,r==null?void 0:r.agent_id]),N.useEffect(()=>{if(!t){d(null),h(null);return}if(!r||!a)return;const D=setTimeout(()=>{f()},350);return()=>clearTimeout(D)},[t,r==null?void 0:r.id,a==null?void 0:a.name,u]);const f=async()=>{if(!(!r||!a)){o(!0);try{const D=document.createElement("canvas");D.width=1080,D.height=1080;const M=D.getContext("2d");if(!M)throw new Error("Canvas unavailable");if(M.fillStyle=JQe,M.fillRect(0,0,1080,1080),b){const K=await eXe(b);tXe(M,K,0,0,1080,1080)}const F=M.createLinearGradient(0,0,0,1080);F.addColorStop(0,"rgba(15,23,42,0.58)"),F.addColorStop(.34,"rgba(15,23,42,0.16)"),F.addColorStop(.62,"rgba(15,23,42,0.48)"),F.addColorStop(1,"rgba(15,23,42,0.98)"),M.fillStyle=F,M.fillRect(0,0,1080,1080),M.fillStyle=g3,M.fillRect(56,62,72,2),M.font="600 22px Arial, sans-serif",$Zs(M,"JUST LISTED",146,72,8),M.save(),M.shadowColor="rgba(0,0,0,0.55)",M.shadowBlur=24,M.shadowOffsetY=4,M.fillStyle="#F8FAFC",M.font="600 64px Georgia, serif",M.textBaseline="top";const z=BZs(M,r.property_address||`${r.city||""}, ${r.state||""}`.trim(),952,2);let V=z.length>1?590:654;z.forEach(K=>{M.fillText(K,64,V),V+=70}),M.restore();const W=[r.city,r.state].filter(Boolean).join(", ")+(r.neighborhood?` · ${r.neighborhood}`:"");M.fillStyle="rgba(248,250,252,0.9)",M.font="600 26px Arial, sans-serif",M.fillText(E7(M,W.toUpperCase(),952),64,V+8),M.fillStyle=g3,M.font="700 56px Arial, sans-serif",M.fillText(XQe(r.price),64,V+58),A.length>0&&(M.fillStyle="rgba(248,250,252,0.86)",M.font="600 22px Arial, sans-serif",M.fillText(E7(M,A.join(" · "),430),360,V+78));const Y=M.createLinearGradient(0,880,0,1080);if(Y.addColorStop(0,"rgba(15,23,42,0.96)"),Y.addColorStop(1,"#0B1322"),M.fillStyle=Y,M.fillRect(0,880,1080,200),M.fillStyle=g3,M.fillRect(0,880,1080,2),M.save(),M.beginPath(),M.arc(124,980,60,0,Math.PI*2),M.closePath(),M.fillStyle="#1E293B",M.fill(),M.lineWidth=6,M.strokeStyle=g3,M.stroke(),M.clip(),a.avatar_url)try{const K=await eXe(a.avatar_url);tXe(M,K,64,920,120,120)}catch{M.fillStyle=g3,M.font="700 48px Arial, sans-serif",M.textAlign="center",M.textBaseline="middle",M.fillText(a.name.charAt(0).toUpperCase(),124,982)}else M.fillStyle=g3,M.font="700 48px Arial, sans-serif",M.textAlign="center",M.textBaseline="middle",M.fillText(a.name.charAt(0).toUpperCase(),124,982);M.restore(),M.textAlign="left",M.textBaseline="alphabetic",M.fillStyle="#F8FAFC",M.font="600 38px Georgia, serif",M.fillText(E7(M,a.name,S?430:820),212,970),a.brokerage&&(M.fillStyle=g3,M.font="600 20px Arial, sans-serif",M.fillText(E7(M,a.brokerage.toUpperCase(),S?430:820),212,1008)),S&&(M.textAlign="right",M.fillStyle="rgba(212,175,55,0.86)",M.font="600 16px Arial, sans-serif",M.fillText("CALL · TEXT",1016,958),M.fillStyle="#F8FAFC",M.font="600 38px Arial, sans-serif",M.fillText(S,1016,1008)),d(D.toDataURL("image/png"))}catch(D){console.error("Generate graphic error",D),ae.error("Could not generate graphic")}finally{o(!1)}}},g=async D=>(await fetch(D)).blob(),_=async()=>{if(!c)return;const D=document.createElement("a");D.href=c,D.download=`just-listed-${(r==null?void 0:r.slug)||(r==null?void 0:r.id)||"graphic"}.png`,D.click(),ae.success("Downloaded!")},v=async()=>{if(c)try{const D=await g(c);await navigator.clipboard.write([new ClipboardItem({"image/png":D})]),ae.success("Copied to clipboard")}catch{ae.error("Copy not supported in this browser")}},j=async()=>{if(c)try{const D=await g(c),M=new File([D],"just-listed.png",{type:"image/png"});navigator.canShare&&navigator.canShare({files:[M]})?await navigator.share({files:[M],title:"Just Listed"}):_()}catch(D){UZs(D)!=="AbortError"&&ae.error("Share failed")}},b=u||((T=p[0])==null?void 0:T.photo_url)||null,S=zZs(a==null?void 0:a.phone),A=[r!=null&&r.bedrooms?`${r.bedrooms} BD`:null,r!=null&&r.bathrooms?`${r.bathrooms} BA`:null,r!=null&&r.square_footage?`${r.square_footage.toLocaleString()} SF`:null].filter(Boolean);return e.jsx(bs,{open:t,onOpenChange:n,children:e.jsx(vs,{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(ws,{className:"px-5 pt-5 pb-3 shrink-0",children:[e.jsxs(_s,{className:"flex items-center gap-2 pr-8",children:[e.jsx(un,{className:"h-5 w-5 text-amber-500 shrink-0"}),e.jsx("span",{className:"truncate",children:"Your Just Listed Graphic"})]}),e.jsx(Qn,{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:JQe},children:[b&&e.jsx("img",{src:b,alt:"Selected property",className:"absolute inset-0 h-full w-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-slate-950/65 via-slate-950/25 to-slate-950"}),e.jsxs("div",{className:"absolute left-4 right-4 top-4 flex items-center gap-2",children:[e.jsx("span",{className:"h-px w-6 bg-amber-400"}),e.jsx("span",{className:"text-[9px] font-semibold uppercase tracking-[0.28em] text-amber-300",children:"Just Listed"})]}),e.jsxs("div",{className:"absolute left-4 right-4 bottom-[64px] text-white",children:[e.jsx("div",{className:"line-clamp-2 font-serif text-[18px] font-semibold leading-[1.05] drop-shadow-lg",children:(r==null?void 0:r.property_address)||`${(r==null?void 0:r.city)||""}, ${(r==null?void 0:r.state)||""}`}),e.jsxs("div",{className:"mt-1 truncate text-[9px] font-semibold uppercase tracking-[0.18em] text-white/85",children:[[r==null?void 0:r.city,r==null?void 0:r.state].filter(Boolean).join(", "),r!=null&&r.neighborhood?` · ${r.neighborhood}`:""]}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[e.jsx("span",{className:"text-[16px] font-bold text-amber-300",children:r?XQe(r.price):""}),A.length>0&&e.jsx("span",{className:"truncate text-[8px] font-semibold uppercase tracking-[0.14em] text-white/80",children:A.join(" · ")})]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 flex h-[52px] items-center border-t border-amber-400 bg-slate-950/95 px-4",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full border-2 border-amber-400 bg-slate-800 text-xs font-bold text-amber-300",children:a!=null&&a.avatar_url?e.jsx("img",{src:a.avatar_url,alt:"",className:"h-full w-full object-cover"}):(L=a==null?void 0:a.name)==null?void 0:L.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})]}),S&&e.jsx("div",{className:"ml-2 shrink-0 text-[9px] font-semibold text-white",children:S})]}),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(ts,{className:"h-7 w-7 animate-spin"}),e.jsx("p",{className:"text-xs",children:"Crafting your graphic…"})]})]}),p.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:p.map(D=>{const M=u===D.photo_url;return e.jsx("button",{type:"button",onClick:()=>h(D.photo_url),className:`relative shrink-0 h-14 w-14 rounded-md overflow-hidden border-2 transition ${M?"border-amber-500 ring-2 ring-amber-500/30":"border-transparent hover:border-muted-foreground/40"}`,children:e.jsx("img",{src:D.photo_url,alt:"",className:"w-full h-full object-cover"})},D.id)})})]})]}),e.jsxs("div",{className:"px-5 pb-5 pt-2 shrink-0 border-t bg-background flex flex-wrap justify-end gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>void f(),disabled:l||!r||!a,children:"Regenerate"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:v,disabled:!c,className:"gap-1.5",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"})," Copy"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:j,disabled:!c,className:"gap-1.5",children:[e.jsx(Hl,{className:"h-3.5 w-3.5"})," Share"]}),e.jsxs(B,{size:"sm",onClick:_,disabled:!c,className:"gap-1.5",children:[e.jsx(Pa,{className:"h-3.5 w-3.5"})," Download"]})]})]})})})}function qZs(s){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}const VZs={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function HZs({open:s,onOpenChange:t,listing:n}){const{user:r}=ys(),{data:a=[],isLoading:i}=ox(),{data:l=[]}=Sy(),[o,c]=N.useState(""),[d,u]=N.useState("all"),[h,p]=N.useState(new Set),[f,g]=N.useState(!1),[_,v]=N.useState(null);N.useEffect(()=>{s||(c(""),u("all"),p(new Set),g(!1))},[s]),N.useEffect(()=>{!s||!r||(async()=>{const{data:M}=await q.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle();v((M==null?void 0:M.gmail_email)||null)})()},[s,r]);const j=N.useMemo(()=>a.filter(M=>M.email),[a]),b=N.useMemo(()=>{let M=j;if(d!=="all"&&(M=M.filter(F=>{var z;return(z=F.tags)==null?void 0:z.some(V=>V.relationship_type_id===d)})),o.trim()){const F=o.toLowerCase();M=M.filter(z=>`${z.first_name||""} ${z.last_name||""}`.toLowerCase().includes(F)||(z.email||"").toLowerCase().includes(F))}return M},[j,o,d]),S=()=>{h.size===b.length?p(new Set):p(new Set(b.map(M=>M.id)))},A=M=>{const F=new Set(h);F.has(M)?F.delete(M):F.add(M),p(F)},T=N.useMemo(()=>j.filter(M=>h.has(M.id)).map(M=>({id:M.id,first_name:M.first_name||"there",last_name:M.last_name,email:M.email})),[j,h]),{defaultSubject:L,defaultBody:D}=N.useMemo(()=>{var le,ve,ge,Te;const M=n.property_address||`${n.city}, ${n.state}`,F=qZs(n.price),z=VZs[n.property_type]||"home",V=n.bedrooms?`${n.bedrooms} bed`:"",W=n.bathrooms?`${n.bathrooms} bath`:"",Y=n.square_footage?`${n.square_footage.toLocaleString()} sqft`:"",K=[V,W,Y].filter(Boolean).join(" • "),J=`https://listings.relevelup.com/${n.slug||n.id}`,ne=((ve=(le=n.photos)==null?void 0:le.find(Me=>Me.is_primary))==null?void 0:ve.photo_url)||((Te=(ge=n.photos)==null?void 0:ge[0])==null?void 0:Te.photo_url)||"",he={active:"Just Listed",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"}[n.status]||"New Listing",ce=`${he}: ${M} — ${F}`,pe=`

Hi {{first_name}},

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

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

${F}

${M}

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

${K?`

${K} • ${z}

`:""} View Photos & Details →

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

Talk soon,

`;return{defaultSubject:ce,defaultBody:pe}},[n]);return f?e.jsx(t1,{open:f,onOpenChange:M=>{g(M),M||t(!1)},bulkContacts:T,defaultSubject:L,defaultBody:D,gmailEmail:_}):e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[640px] max-h-[90vh] flex flex-col",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-amber-500"}),"Email this listing to your sphere"]}),e.jsx(Qn,{children:"Pick which contacts should hear about this property. We'll personalize each email with their name."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search contacts...",value:o,onChange:M=>c(M.target.value),className:"pl-9"})]}),e.jsxs(ds,{value:d,onValueChange:u,children:[e.jsx(ls,{className:"sm:w-[180px]",children:e.jsx(us,{placeholder:"Filter by tag"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All contacts"}),l.map(M=>e.jsx(Qe,{value:M.id,children:M.name},M.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm border-y py-2",children:[e.jsxs("button",{type:"button",onClick:S,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(ui,{checked:b.length>0&&h.size===b.length,className:"pointer-events-none"}),e.jsx("span",{children:h.size===b.length&&b.length>0?"Deselect all":`Select all (${b.length})`})]}),e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"}),h.size," selected"]})]}),e.jsx(hi,{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(ts,{className:"h-5 w-5 animate-spin mr-2"}),"Loading your contacts..."]}):b.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:j.length===0?"No contacts with email addresses yet.":"No contacts match your search."}):e.jsx("div",{className:"space-y-1 py-2",children:b.map(M=>e.jsxs("label",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 cursor-pointer",children:[e.jsx(ui,{checked:h.has(M.id),onCheckedChange:()=>A(M.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[M.first_name," ",M.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:M.email})]}),M.tags&&M.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap justify-end max-w-[40%]",children:M.tags.slice(0,2).map(F=>{var z;return e.jsx(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:(z=F.relationship_type)==null?void 0:z.name},F.id)})})]},M.id))})}),e.jsx(ll,{}),e.jsxs("div",{className:"flex justify-between items-center gap-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:_?`Sending from ${_}`:"Connect Gmail in Settings to send"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>g(!0),disabled:h.size===0,className:"gap-2",children:[e.jsx(Vs,{className:"h-4 w-4"}),"Compose Email (",h.size,")"]})]})]})]})})}function Cv(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 KU(){const s=ma();return ct({queryKey:["deal-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function x2t(){const s=ma(),t=Ht();return gt({mutationFn:async()=>{if(!s)throw new Error("Not authenticated");const{error:n}=await q.rpc("initialize_deal_pipeline_stages",{p_user_id:s});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function abe(){const s=ma();return ct({queryKey:["deal-pipeline-deals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at) `).eq("owner_user_id",s).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function g2t(){const s=ma(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("deal_pipeline").insert({deal_name:n.deal_name,deal_type:n.deal_type,stage_id:n.stage_id||null,contact_id:n.contact_id||null,listing_id:n.listing_id||null,property_address:n.property_address||null,city:n.city||null,state:n.state||null,zip_code:n.zip_code||null,expected_price:n.expected_price||null,expected_commission:n.expected_commission||null,commission_percentage:n.commission_percentage||3,target_close_date:n.target_close_date||null,contract_date:n.contract_date||null,listing_date:n.listing_date||null,priority:n.priority||"medium",probability:n.probability||50,notes:n.notes||null,owner_user_id:s}).select().single();if(a)throw a;return await q.from("deal_activities").insert([{deal_id:r.id,activity_type:"system",title:"Deal created",description:`Deal "${n.deal_name}" was created`}]),r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function y2t(){const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("deal_pipeline").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function GZs(){const s=Ht();return gt({mutationFn:async({dealId:t,stageId:n,stageName:r})=>{const{data:a,error:i}=await q.from("deal_pipeline").update({stage_id:n}).eq("id",t).select().single();if(i)throw i;return await q.from("deal_activities").insert({deal_id:t,activity_type:"stage_change",title:`Moved to ${r}`,metadata:{new_stage_id:n,new_stage_name:r}}),a},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-activities"]})}})}function WZs(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("deal_pipeline").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function KZs(s){return ct({queryKey:["deal-activities",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_activities").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function YZs(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("deal_activities").insert([{deal_id:t.deal_id,activity_type:t.activity_type,title:t.title,description:t.description||null}]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-activities",n.deal_id]})}})}function ZZs(s){return ct({queryKey:["deal-checklist",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_checklist_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function QZs(){const s=Ht();return gt({mutationFn:async({id:t,is_completed:n,deal_id:r})=>{const{data:a,error:i}=await q.from("deal_checklist_items").update({is_completed:n,completed_at:n?new Date().toISOString():null}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-checklist",n.deal_id]})}})}function XZs(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("deal_checklist_items").insert([{deal_id:t.deal_id,title:t.title,description:t.description||null,due_date:t.due_date||null,sort_order:t.sort_order||0}]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-checklist",n.deal_id]})}})}function JZs(){const s=ma();return ct({queryKey:["deal-pipeline-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("deal_pipeline").select("*, deal_pipeline_stages(name, is_won_stage, is_lost_stage)").eq("owner_user_id",s);if(n)throw n;const r=(t==null?void 0:t.filter(o=>{var c,d,u;return!((c=o.deal_pipeline_stages)!=null&&c.is_won_stage)&&!((d=o.deal_pipeline_stages)!=null&&d.is_lost_stage)&&((u=o.deal_pipeline_stages)==null?void 0:u.name)!=="Cancelled"}))||[],a=(t==null?void 0:t.filter(o=>{var c;return(c=o.deal_pipeline_stages)==null?void 0:c.is_won_stage}))||[],i=new Date().getFullYear(),l=a.filter(o=>{const c=o.actual_close_date;return c?new Date(c).getFullYear()===i:!0});return{totalDeals:(t==null?void 0:t.length)||0,activeDeals:r.length,wonDeals:a.length,pipelineValue:r.reduce((o,c)=>o+(c.expected_price||0),0),expectedCommission:r.reduce((o,c)=>o+(c.expected_commission||0),0),expectedNetToAgent:r.reduce((o,c)=>o+(Cv(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+(Cv(c)||0)*d},0),ytdWonDeals:l.length,ytdWonGCI:l.reduce((o,c)=>o+(c.expected_commission||0),0),ytdWonNet:l.reduce((o,c)=>o+(Cv(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(Cv(c)||0),0)+r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(Cv(c)||0)*d},0)}},enabled:!!s})}function eQs(s){const t=ma();return ct({queryKey:["deal-by-listing",s,t],queryFn:async()=>{if(!t||!s)return null;const{data:n,error:r}=await q.from("deal_pipeline").select(` *, deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("listing_id",s).maybeSingle();if(r)throw r;return n},enabled:!!t&&!!s})}function tQs(){const s=Ht();return gt({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await q.from("deal_pipeline").update({listing_id:n}).eq("id",t).select().single();if(a)throw a;return await q.from("deal_activities").insert({deal_id:t,activity_type:"system",title:"Linked to Listing Exchange",description:"This deal is now synced with Listing Exchange",metadata:{listing_id:n}}),r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",n.listingId]})}})}function sQs(){const s=Ht();return gt({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await q.from("deal_pipeline").update({listing_id:null}).eq("id",t).select().single();if(a)throw a;return{data:r,listingId:n}},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",t.listingId]})}})}function nQs({listing:s}){const t=Mn(),[n,r]=N.useState(""),[a,i]=N.useState(!1),{data:l,isLoading:o}=eQs(s.id),{data:c,isLoading:d}=KU(),{data:u,isLoading:h}=abe(),p=x2t(),f=tQs(),g=sQs(),_=g2t(),v=(u==null?void 0:u.filter(T=>!T.listing_id))||[],j=T=>{if(!(c!=null&&c.length))return null;switch(T){case"coming_soon":case"active":case"price_improvement":return c.find(L=>L.name==="Active");case"under_contract":return c.find(L=>L.name==="Under Contract");case"sold":return c.find(L=>L.is_won_stage);default:return c.find(L=>L.name==="Active")}},b=async()=>{i(!0);try{c!=null&&c.length||await p.mutateAsync();const T=j(s.status);await _.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}),ae.success("Deal created and linked to listing!")}catch(T){console.error("Failed to create deal:",T),ae.error("Failed to create deal")}finally{i(!1)}},S=async()=>{if(!n){ae.error("Please select a deal");return}try{await f.mutateAsync({dealId:n,listingId:s.id}),ae.success("Listing linked to deal!"),r("")}catch{ae.error("Failed to link listing")}},A=async()=>{if(l)try{await g.mutateAsync({dealId:l.id,listingId:s.id}),ae.success("Listing unlinked from deal")}catch{ae.error("Failed to unlink listing")}};return o||d?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(Z2,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ts,{className:"h-5 w-5 animate-spin text-muted-foreground"})})})]}):l?e.jsxs(fe,{className:"border-primary/20 bg-primary/5",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(El,{className:"h-4 w-4 text-primary"}),"Linked to Pipeline"]})}),e.jsxs(Ee,{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(ze,{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(Oa,{className:"h-3 w-3 ml-1"})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:A,disabled:g.isPending,children:g.isPending?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(qA,{className:"h-4 w-4"})})]})]})]}):e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(Z2,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Link this listing to your pipeline to track the deal and sync status changes."}),e.jsxs(B,{onClick:b,disabled:a||_.isPending,className:"w-full",size:"sm",children:[a||_.isPending?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Create New Deal"]}),v.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-card px-2 text-muted-foreground",children:"or"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ds,{value:n,onValueChange:r,children:[e.jsx(ls,{className:"flex-1 text-sm",children:e.jsx(us,{placeholder:"Link to existing deal..."})}),e.jsx(cs,{children:v.map(T=>e.jsx(Qe,{value:T.id,children:T.deal_name},T.id))})]}),e.jsx(B,{variant:"secondary",size:"icon",onClick:S,disabled:!n||f.isPending,children:f.isPending?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(El,{className:"h-4 w-4"})})]})]})]})]})}const rQs={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"},aQs={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},sXe={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function iQs(){var ie,he,ce,pe,le,ve,ge,Te,Me;const{listingId:s}=bi(),t=Mn(),{user:n}=ys(),{data:r,isLoading:a}=b6e(s||""),{data:i}=opt(s||""),{data:l}=Prs(s||""),o=ipt(),c=Irs(),d=Lrs(),u=apt(),h=Rrs(),[p,f]=N.useState(!1),[g,_]=N.useState(!1),[v,j]=N.useState(!1),[b,S]=N.useState(!1),[A,T]=N.useState(!1),[L,D]=N.useState(null),[M,F]=N.useState({buyerName:"",buyerType:"",notes:""}),z=(n==null?void 0:n.id)===(r==null?void 0:r.agent_id),V=Ce=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ce),W=async Ce=>{const Ae=`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:Ce});try{switch(Ce){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Ae)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(Ae),ae.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${De} ${Ae}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(De)}&body=${encodeURIComponent(`Check out this listing: ${Ae}`)}`);break}}catch(Ie){console.error("Share error:",Ie),ae.error("Failed to share")}},Y=async()=>{try{await u.mutateAsync(r.id),ae.success("Listing deleted"),t("/mission-control/listings")}catch{ae.error("Failed to delete listing")}},K=async()=>{if(!M.buyerName.trim()){ae.error("Please enter buyer name");return}try{await h.mutateAsync({listingId:r.id,listingAgentId:r.agent_id,buyerName:M.buyerName,buyerType:M.buyerType||void 0,notes:M.notes||void 0}),ae.success("Referral sent successfully!"),_(!1),F({buyerName:"",buyerType:"",notes:""})}catch{ae.error("Failed to send referral")}},J=Ce=>{var Ze,Ne;const Ae=(r==null?void 0:r.property_address)||`${r==null?void 0:r.city}, ${r==null?void 0:r.state}`,De=V((r==null?void 0:r.price)||0),Ie=r!=null&&r.bedrooms?`${r.bedrooms}BD`:"",Fe=r!=null&&r.bathrooms?`${r.bathrooms}BA`:"",qe=r!=null&&r.square_footage?`${r.square_footage.toLocaleString()}SF`:"",be=[Ie,Fe,qe].filter(Boolean).join(" | ");switch(Ce){case"just_listed":return`🏡 JUST LISTED! ${Ae} ${De} ${be} ${(r==null?void 0:r.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(Ze=r==null?void 0:r.city)==null?void 0:Ze.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${Ae} Now ${De}! ${be} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${sXe[(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! ${be} DM me for details! 📩 #ComingSoon #RealEstate #${(Ne=r==null?void 0:r.city)==null?void 0:Ne.replace(/\s/g,"")}`;default:return""}};if(a)return e.jsx(Ts,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-10 w-32"}),e.jsx(Ws,{className:"h-[400px] w-full"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsx(Ws,{className:"h-48"}),e.jsx(Ws,{className:"h-48"}),e.jsx(Ws,{className:"h-48"})]})]})});if(!r)return e.jsx(Ts,{title:"Listing Not Found",description:"",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing could not be found."}),e.jsx(B,{onClick:()=>t("/mission-control/listings"),children:"Back to Listings"})]})})});const ne=((ie=r.photos)==null?void 0:ie.find(Ce=>Ce.is_primary))||((he=r.photos)==null?void 0:he[0]);return e.jsxs(Ts,{title:"",description:"",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/mission-control/listings"),children:[e.jsx(Hr,{className:"h-4 w-4 mr-2"}),"Back to Listings"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsx("div",{className:"aspect-[16/10] rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>ne&&D(ne.photo_url),children:ne?e.jsx("img",{src:ne.photo_url,alt:"Primary",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No photos"})})}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:(ce=r.photos)==null?void 0:ce.slice(1,5).map((Ce,Ae)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>D(Ce.photo_url),children:e.jsx("img",{src:Ce.photo_url,alt:`Photo ${Ae+2}`,className:"w-full h-full object-cover"})},Ce.id))})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsx(fe,{children:e.jsxs(Ee,{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(ze,{className:`${rQs[r.status]} text-white border-0`,children:aQs[r.status]}),r.is_featured&&e.jsxs(ze,{variant:"outline",className:"border-amber-500 text-amber-500",children:[e.jsx(ca,{className:"h-3 w-3 mr-1 fill-amber-500"}),"Featured"]}),r.open_to_referrals&&e.jsxs(ze,{variant:"outline",children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),e.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:V(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(ka,{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(gi,{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(pw,{className:"h-4 w-4"}):e.jsx(im,{className:"h-4 w-4"})}),!z&&e.jsxs(B,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>j(!0),children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(Hl,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(cc,{children:[e.jsxs(Qr,{onClick:()=>W("copy"),children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(Qr,{onClick:()=>W("facebook"),children:[e.jsx(Lh,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(Qr,{onClick:()=>W("text"),children:[e.jsx(Ei,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(Qr,{onClick:()=>W("email"),children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),z&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",onClick:()=>{const Ce=(r.photos??[]).slice().sort((Ae,De)=>(De.is_primary?1:0)-(Ae.is_primary?1:0)||(Ae.sort_order??0)-(De.sort_order??0)).map(Ae=>Ae.photo_url).filter(Boolean);if(Ce.length===0){ae.error("Add photos to this listing first.");return}u2t({photos:Ce,details:{address:r.property_address||`${r.city??""} ${r.state??""}`.trim(),beds:r.bedrooms?String(r.bedrooms):"",baths:r.bathrooms?String(r.bathrooms):"",sqft:r.square_footage?String(r.square_footage):"",price:r.price?String(r.price):"",highlights:r.description||""},sourceLabel:"Listing Exchange",badge:h2t(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(pL,{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(un,{className:"h-4 w-4"}),"Just Listed Graphic"]}),e.jsxs(B,{variant:"outline",onClick:()=>S(!0),className:"gap-2",children:[e.jsx(Vs,{className:"h-4 w-4"}),"Email My Sphere"]}),e.jsxs(B,{onClick:()=>t(`/mission-control/listings/${r.id}/customize`),className:"gap-2 bg-gradient-to-r from-primary to-primary/80 hover:opacity-95 text-primary-foreground shadow-md",children:[e.jsx(un,{className:"h-4 w-4"}),"Customize Public Page"]}),e.jsxs(B,{variant:"outline",onClick:()=>t(`/mission-control/listings/${r.id}/edit`),children:[e.jsx(ku,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx(B,{variant:"destructive",size:"icon",onClick:()=>f(!0),children:e.jsx(_n,{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(sy,{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(Cp,{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(ly,{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(yr,{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(ze,{variant:"secondary",children:[e.jsx(Va,{className:"h-3 w-3 mr-1"}),sXe[r.property_type]]}),r.lot_size&&e.jsxs(ze,{variant:"secondary",children:["Lot: ",r.lot_size]}),r.has_hoa&&e.jsx(ze,{variant:"secondary",children:"HOA"})]}),r.description&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Description"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})]}),r.agent_notes&&r.agent_notes_public&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.agent_notes})]}),r.mls_link&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:r.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"View on MLS"]})})]}),e.jsxs("div",{className:"flex items-center gap-4 pt-4 mt-4 border-t text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Er,{className:"h-4 w-4"}),r.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hl,{className:"h-4 w-4"}),r.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gi,{className:"h-4 w-4"}),r.save_count," saves"]})]})]})}),r.allow_sharing&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-lg",children:"Share Content"})}),e.jsx(Ee,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(Ce=>e.jsxs("div",{className:"p-3 bg-muted rounded-lg",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("p",{className:"font-medium text-sm capitalize",children:[Ce.replace("_"," ")," Caption"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(J(Ce)),ae.success("Caption copied!")},children:e.jsx(Xr,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:J(Ce)})]},Ce))})]}),e.jsx(FZs,{listingId:r.id,ownerOnly:z})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-lg",children:"Listing Agent"})}),e.jsxs(Ee,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx("span",{className:"text-lg font-semibold text-primary",children:((le=(pe=r.agent)==null?void 0:pe.name)==null?void 0:le.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((ve=r.agent)==null?void 0:ve.name)||"Unknown"}),((Te=(ge=r.agent)==null?void 0:ge.brokerage)==null?void 0:Te.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r.agent.brokerage.name})]})]}),!z&&e.jsx("div",{className:"space-y-2",children:((Me=r.agent)==null?void 0:Me.email)&&e.jsx(B,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${r.agent.email}`,children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),z&&e.jsx(nQs,{listing:r}),!z&&r.open_to_referrals&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"text-lg flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5"}),"Send a Buyer"]})}),e.jsxs(Ee,{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:()=>_(!0),children:"Send Referral"})]})]})]})]})]}),e.jsx(bs,{open:!!L,onOpenChange:()=>D(null),children:e.jsx(vs,{className:"max-w-4xl",children:e.jsx("img",{src:L||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(bs,{open:p,onOpenChange:f,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Delete Listing"}),e.jsx(Qn,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Y,disabled:u.isPending,children:u.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(bs,{open:g,onOpenChange:_,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Send Buyer Referral"}),e.jsx(Qn,{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:M.buyerName,onChange:Ce=>F({...M,buyerName:Ce.target.value}),placeholder:"Enter buyer's name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Buyer Type"}),e.jsxs(ds,{value:M.buyerType,onValueChange:Ce=>F({...M,buyerType:Ce}),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select type"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"first_time",children:"First-Time Buyer"}),e.jsx(Qe,{value:"investor",children:"Investor"}),e.jsx(Qe,{value:"relocating",children:"Relocating"}),e.jsx(Qe,{value:"upgrade",children:"Upgrading"}),e.jsx(Qe,{value:"downsize",children:"Downsizing"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Notes"}),e.jsx(Es,{value:M.notes,onChange:Ce=>F({...M,notes:Ce.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),e.jsx(B,{onClick:K,disabled:h.isPending,children:h.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(l2t,{open:v,onOpenChange:j,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(HZs,{open:b,onOpenChange:S,listing:r}),e.jsx(f2t,{listingId:(r==null?void 0:r.id)||null,open:A,onOpenChange:T})]})}function oQs({onImport:s}){const[t,n]=N.useState(""),[r,a]=N.useState([]),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(null),h=N.useRef(),p=N.useRef(null);N.useEffect(()=>{const b=S=>{p.current&&!p.current.contains(S.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const f=async b=>{if(b.trim().length<3){a([]),c(!1);return}l(!0);try{const{data:S,error:A}=await q.functions.invoke("mls-listing-search",{body:{query:b}});if(A)throw A;a((S==null?void 0:S.listings)||[]),c(!0)}catch(S){console.error("MLS search error:",S),a([])}finally{l(!1)}},g=b=>{n(b),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>f(b),400)},_=b=>{u(b.mlsNumber),s(b),c(!1),n(`${b.address}, ${b.city}`),ae.success(`Imported: ${b.address}`,{description:"Property details and photos have been auto-filled."}),u(null)},v=b=>b?`$${b.toLocaleString()}`:"",j=b=>{const S=(b||"").toLowerCase();return S.includes("single")||S.includes("detached")?"Single Family":S.includes("condo")?"Condo":S.includes("town")?"Townhouse":S.includes("land")||S.includes("lot")?"Land":S.includes("multi")?"Multi-Family":S.includes("commercial")?"Commercial":b||"Other"};return e.jsxs(fe,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Mt,{className:"pb-3",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Pa,{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(Ee,{children:e.jsxs("div",{ref:p,className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:t,onChange:b=>g(b.target.value),onFocus:()=>r.length>0&&c(!0),placeholder:"Start typing a property address...",className:"pl-9 pr-9"}),i&&e.jsx(ts,{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(Bn,{className:"h-4 w-4"})})]}),o&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-popover border rounded-lg shadow-lg max-h-[400px] overflow-y-auto",children:r.length===0&&!i?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No properties found. Try a different address."}):r.map(b=>e.jsxs("button",{type:"button",onClick:()=>_(b),disabled:d===b.mlsNumber,className:"w-full text-left p-3 hover:bg-accent/50 transition-colors border-b last:border-0 flex items-start gap-3",children:[b.photos[0]?e.jsx("img",{src:b.photos[0],alt:"",className:"w-16 h-12 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-16 h-12 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(ka,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:b.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.city,", ",b.state," ",b.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground",children:v(b.price)}),b.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(sy,{className:"h-3 w-3"})," ",b.bedrooms]}),b.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Cp,{className:"h-3 w-3"})," ",b.bathrooms]}),b.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(J2,{className:"h-3 w-3"})," ",b.sqft.toLocaleString()]})]})]}),e.jsxs("div",{className:"flex-shrink-0 flex flex-col items-end gap-1",children:[e.jsx(ze,{variant:"outline",className:"text-[10px]",children:j(b.propertyType)}),b.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[b.photos.length," photos"]})]})]},b.mlsNumber))})]})})]})}function lQs({photo:s,onRemove:t,onSetPrimary:n}){const{attributes:r,listeners:a,setNodeRef:i,transform:l,transition:o,isDragging:c}=Lve({id:s.id}),d={transform:O4.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(Fu,{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(Bn,{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(ca,{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 cQs({photos:s,uploading:t,onUpload:n,onRemove:r,onReorder:a,onSetPrimary:i}){const l=kve(R8(rR,{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 p=o.findIndex(j=>j.id===u.id),f=o.findIndex(j=>j.id===h.id),g=[...o],[_]=g.splice(p,1);g.splice(f,0,_);const v=g.map((j,b)=>({...j,sort_order:b}));a(v)};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(Mve,{sensors:l,collisionDetection:Sve,onDragEnd:c,children:e.jsx(Pve,{items:o.map(d=>d.id),strategy:AU,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(d=>e.jsx(lQs,{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(ts,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Na,{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 dQs({selectedVideoId:s,onVideoSelect:t,listingId:n}){const r=Mn(),{user:a}=ys(),[i,l]=N.useState(!1),[o,c]=N.useState([]),[d,u]=N.useState(!1),[h,p]=N.useState(null),[f,g]=N.useState({});N.useEffect(()=>{s&&a?_():p(null)},[s,a]);const _=async()=>{if(!s)return;const{data:F,error:z}=await q.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("id",s).eq("is_deleted",!1).single();!z&&F&&(p(F),v(F))},v=async F=>{try{const{data:z,error:V}=await q.functions.invoke("bunny-upload",{body:{action:"asset-urls",videoId:F.bunny_video_id,isAgentVideo:!0}});!V&&(z!=null&&z.thumbnailUrl)&&g(W=>({...W,[F.id]:{thumbnailUrl:z.thumbnailUrl}}))}catch(z){console.warn("Failed to get signed URL",z)}},j=async()=>{if(a){u(!0);try{const{data:F,error:z}=await q.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("owner_user_id",a.id).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(z)throw z;c(F||[]),F!=null&&F.length&&b(F)}catch(F){console.error("Error fetching videos:",F),ae.error("Failed to load videos")}finally{u(!1)}}},b=async F=>{var z;try{const V=F.map(ne=>ne.bunny_video_id),{data:W,error:Y}=await q.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:V,isAgentVideo:!0}});if(Y)throw Y;const K=(W==null?void 0:W.assets)||{},J={};for(const ne of F)(z=K[ne.bunny_video_id])!=null&&z.thumbnailUrl&&(J[ne.id]={thumbnailUrl:K[ne.bunny_video_id].thumbnailUrl});g(ne=>({...ne,...J}))}catch(V){console.warn("Failed to bulk-fetch signed URLs",V)}},S=()=>{l(!0),j()},A=F=>{t(F.id),p(F),l(!1),ae.success("Video selected")},T=()=>{t(null),p(null)},L=()=>{const F=n?`/mission-control/listings/${n}/edit`:"/mission-control/listings/new";r(`/mission-control/video?returnUrl=${encodeURIComponent(F)}`)},D=F=>{if(!F)return"0:00";const z=Math.floor(F/60),V=F%60;return`${z}:${V.toString().padStart(2,"0")}`},M=F=>{var z;return((z=f[F.id])==null?void 0:z.thumbnailUrl)||F.thumbnail_url};return e.jsxs("div",{className:"space-y-3",children:[h?e.jsx(fe,{className:"overflow-hidden",children:e.jsx(Ee,{className:"p-0",children:e.jsxs("div",{className:"flex items-start gap-4 p-4",children:[e.jsxs("div",{className:"relative w-32 h-20 bg-muted rounded-lg overflow-hidden flex-shrink-0",children:[M(h)?e.jsx("img",{src:M(h),alt:h.title||"Video thumbnail",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(br,{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(Al,{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:D(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:S,children:"Change"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:T,className:"text-destructive hover:text-destructive",children:e.jsx(Bn,{className:"h-4 w-4"})})]})]})})}):e.jsx(fe,{className:"border-dashed",children:e.jsx(Ee,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(br,{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:S,className:"gap-2",children:[e.jsx(Hg,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs(B,{type:"button",variant:"outline",onClick:L,className:"gap-2",children:[e.jsx(mf,{className:"h-4 w-4"}),"Record New Video"]})]})]})})}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Hg,{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(ts,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):o.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(br,{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:L,className:"gap-2",children:[e.jsx(mf,{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(F=>e.jsxs("button",{type:"button",onClick:()=>A(F),className:`group relative rounded-lg overflow-hidden border-2 transition-all text-left ${s===F.id?"border-primary ring-2 ring-primary/20":"border-transparent hover:border-muted-foreground/30"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[M(F)?e.jsx("img",{src:M(F),alt:F.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(br,{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(Al,{className:"h-8 w-8 text-white opacity-0 group-hover:opacity-100 transition-opacity"})}),F.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:D(F.duration_seconds)})]}),e.jsx("div",{className:"p-2 bg-card",children:e.jsx("p",{className:"text-xs font-medium truncate",children:F.title||"Untitled Video"})})]},F.id))})}),e.jsxs("div",{className:"flex justify-between items-center pt-4 border-t",children:[e.jsxs(B,{type:"button",variant:"ghost",onClick:L,className:"gap-2",children:[e.jsx(mf,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const uQs=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function hQs({listingId:s}){const t=N.useRef(null),{data:n=[],isLoading:r}=m2t(s),a=LZs(),i=DZs(),l=RZs(),o=async d=>{if(!(!d||d.length===0)){for(const u of Array.from(d)){if(u.size>25*1024*1024){ae.error(`${u.name} exceeds 25MB limit`);continue}try{await a.mutateAsync({listingId:s,file:u})}catch(h){ae.error(`Failed to upload ${u.name}: ${h.message}`)}}t.current&&(t.current.value=""),ae.success("Documents uploaded")}},c=async d=>{try{const u=await p2t(d);window.open(u,"_blank")}catch{ae.error("Failed to open document")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{ref:t,type:"file",multiple:!0,accept:".pdf,application/pdf",className:"hidden",onChange:d=>o(d.target.files)}),e.jsxs(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(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Na,{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(fe,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Nr,{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:uQs(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(Er,{className:"h-3 w-3"}):e.jsx(xf,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(bn,{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(Pa,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>{confirm(`Delete ${d.file_name}?`)&&i.mutate({id:d.id,storage_path:d.storage_path,listingId:s})},children:e.jsx(Bn,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const mQs=[{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"}],pQs=[{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 fQs({id:s,url:t,index:n,onRemove:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=Lve({id:s}),u={transform:O4.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(Fu,{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(Bn,{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(ca,{className:"h-2.5 w-2.5 fill-current"})," Primary"]})]})}function xQs({photoUrls:s,pendingPhotos:t,onRemove:n,onReorder:r,uploading:a,onUpload:i}){const l=kve(R8(rR,{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 p=o.indexOf(u.id),f=o.indexOf(h.id),g=[...s],_=[...t],[v]=g.splice(p,1),[j]=_.splice(p,1);g.splice(f,0,v),_.splice(f,0,j),r(g,_)};return e.jsxs("div",{className:"space-y-2",children:[s.length>1&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Drag photos to reorder. First photo will be primary."}),e.jsx(Mve,{sensors:l,collisionDetection:Sve,onDragEnd:c,children:e.jsx(Pve,{items:o,strategy:AU,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,u)=>e.jsx(fQs,{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(ts,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Na,{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 nXe(){const{listingId:s}=bi(),[t]=gl(),n=t.get("brokerage"),r=Mn(),{user:a}=ys(),{hasLeadSite:i}=Ip(),l=!!s&&s!=="new",o=!!n&&!l,[c,d]=N.useState([]),[u,h]=N.useState({open:!1,listingId:null,nextPath:"/mission-control/listings"}),{data:p,isLoading:f}=b6e(l?s:""),g=Nrs(),_=krs(),v=Srs(),j=Crs(),b=Trs(),S=Ers(),A=Ars(),{data:T=[]}=ct({queryKey:["brokerage-agents",n],queryFn:async()=>{if(!n)return[];const{data:ge,error:Te}=await q.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name");if(Te)throw Te;return ge||[]},enabled:o}),[L,D]=N.useState(""),[M,F]=N.useState(!1),[z,V]=N.useState([]),[W,Y]=N.useState([]),[K,J]=N.useState({property_address:"",city:"",state:"",neighborhood:"",price:"",property_type:"single_family",status:"active",bedrooms:"",bathrooms:"",square_footage:"",lot_size:"",year_built:"",has_hoa:!1,description:"",agent_notes:"",agent_notes_public:!1,mls_link:"",video_link:"",video_id:null,allow_sharing:!0,open_to_referrals:!0,open_to_social_promotion:!0,share_with_brokerage:!1,is_public:!0});N.useEffect(()=>{var ge,Te,Me,Ce,Ae;p&&l&&J({property_address:p.property_address||"",city:p.city||"",state:p.state||"",neighborhood:p.neighborhood||"",price:((ge=p.price)==null?void 0:ge.toString())||"",property_type:p.property_type,status:p.status,bedrooms:((Te=p.bedrooms)==null?void 0:Te.toString())||"",bathrooms:((Me=p.bathrooms)==null?void 0:Me.toString())||"",square_footage:((Ce=p.square_footage)==null?void 0:Ce.toString())||"",lot_size:p.lot_size||"",year_built:((Ae=p.year_built)==null?void 0:Ae.toString())||"",has_hoa:p.has_hoa,description:p.description||"",agent_notes:p.agent_notes||"",agent_notes_public:p.agent_notes_public,mls_link:p.mls_link||"",video_link:p.video_link||"",video_id:p.video_id||null,allow_sharing:p.allow_sharing,open_to_referrals:p.open_to_referrals,open_to_social_promotion:p.open_to_social_promotion,share_with_brokerage:p.share_with_brokerage??!1,is_public:p.is_public})},[p,l]);const ne=ge=>{var Ae,De;const Te={"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"},Me=(ge.propertyType||"").toLowerCase(),Ce=((Ae=Object.entries(Te).find(([Ie])=>Me.includes(Ie)))==null?void 0:Ae[1])||"other";J(Ie=>({...Ie,property_address:ge.address||Ie.property_address,city:ge.city||Ie.city,state:ge.state||Ie.state,price:ge.price?String(ge.price):Ie.price,property_type:Ce,bedrooms:ge.bedrooms?String(ge.bedrooms):Ie.bedrooms,bathrooms:ge.bathrooms?String(ge.bathrooms):Ie.bathrooms,square_footage:ge.sqft?String(ge.sqft):Ie.square_footage,lot_size:ge.lotSize?String(ge.lotSize):Ie.lot_size,year_built:ge.yearBuilt?String(ge.yearBuilt):Ie.year_built,description:ge.description||Ie.description})),((De=ge.photos)==null?void 0:De.length)>0&&(d(ge.photos),W.forEach(Ie=>URL.revokeObjectURL(Ie)),V([]),Y([]))},ie=ge=>{if(!ge)return;const Te=Array.from(ge);V(Ce=>[...Ce,...Te]);const Me=Te.map(Ce=>URL.createObjectURL(Ce));Y(Ce=>[...Ce,...Me])},he=ge=>{URL.revokeObjectURL(W[ge]),V(Te=>Te.filter((Me,Ce)=>Ce!==ge)),Y(Te=>Te.filter((Me,Ce)=>Ce!==ge))},ce=async ge=>{var Te;if(!(!ge||!p)){F(!0);try{for(const Me of Array.from(ge)){const Ce=Me.name.split(".").pop(),Ae=`${a==null?void 0:a.id}/${p.id}/${Date.now()}.${Ce}`,{error:De}=await q.storage.from("listing-photos").upload(Ae,Me);if(De)throw De;const{data:{publicUrl:Ie}}=q.storage.from("listing-photos").getPublicUrl(Ae);await j.mutateAsync({listingId:p.id,photoUrl:Ie,isPrimary:!((Te=p.photos)!=null&&Te.length)})}ae.success("Photos uploaded!")}catch(Me){console.error("Upload error:",Me),ae.error("Failed to upload photos")}finally{F(!1)}}},pe=async ge=>{for(let Te=0;Te{if(p)try{await b.mutateAsync({photoId:ge,listingId:p.id}),ae.success("Photo removed")}catch{ae.error("Failed to remove photo")}},ve=async ge=>{if(ge.preventDefault(),!K.city.trim()||!K.state.trim()||!K.price){ae.error("Please fill in required fields (City, State, Price)");return}if(o&&!L){ae.error("Please select an agent to assign this listing to");return}try{const Te={property_address:K.property_address||null,city:K.city,state:K.state,neighborhood:K.neighborhood||null,price:Number(K.price),property_type:K.property_type,status:K.status,bedrooms:K.bedrooms?Number(K.bedrooms):null,bathrooms:K.bathrooms?Number(K.bathrooms):null,square_footage:K.square_footage?Number(K.square_footage):null,lot_size:K.lot_size||null,year_built:K.year_built?Number(K.year_built):null,has_hoa:K.has_hoa,description:K.description||null,agent_notes:K.agent_notes||null,agent_notes_public:K.agent_notes_public,mls_link:K.mls_link||null,video_link:K.video_link||null,video_id:K.video_id||null,allow_sharing:K.allow_sharing,open_to_referrals:K.open_to_referrals,open_to_social_promotion:K.open_to_social_promotion,share_with_brokerage:K.share_with_brokerage,is_public:K.is_public};if(l)await v.mutateAsync({id:s,...Te}),ae.success("Listing updated!"),r(`/mission-control/listings/${s}`);else{F(!0);let Me;if(o&&L?Me=await _.mutateAsync({agentId:L,...Te}):Me=await g.mutateAsync(Te),z.length>0)try{await pe(Me.id),W.forEach(Ae=>URL.revokeObjectURL(Ae)),V([]),Y([])}catch(Ae){console.error("Photo upload error:",Ae),ae.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let Ae=0;Aer(o?"/my-brokerage":"/mission-control/listings"),children:[e.jsx(Hr,{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(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"Assign to Agent *"})}),e.jsxs(Ee,{children:[e.jsxs(ds,{value:L,onValueChange:D,children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select an agent..."})}),e.jsx(cs,{children:T.map(ge=>e.jsx(Qe,{value:ge.id,children:ge.name||ge.email},ge.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(oQs,{onImport:ne}),c.length>0&&e.jsxs(fe,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Mt,{className:"pb-3",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Pa,{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(Ee,{children:[e.jsxs("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:[c.slice(0,12).map((ge,Te)=>e.jsx("div",{className:"aspect-square rounded overflow-hidden bg-muted",children:e.jsx("img",{src:ge,alt:"",className:"w-full h-full object-cover"})},Te)),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(Bn,{className:"h-3 w-3 mr-1"})," Clear MLS photos"]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"Property Details"})}),e.jsx(Ee,{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:K.property_address,onChange:ge=>J({...K,property_address:ge.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"City *"}),e.jsx(ye,{value:K.city,onChange:ge=>J({...K,city:ge.target.value}),placeholder:"City",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"State *"}),e.jsx(ye,{value:K.state,onChange:ge=>J({...K,state:ge.target.value}),placeholder:"State",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Neighborhood"}),e.jsx(ye,{value:K.neighborhood,onChange:ge=>J({...K,neighborhood:ge.target.value}),placeholder:"Neighborhood"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Price *"}),e.jsx(ye,{type:"number",value:K.price,onChange:ge=>J({...K,price:ge.target.value}),placeholder:"500000",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Property Type"}),e.jsxs(ds,{value:K.property_type,onValueChange:ge=>J({...K,property_type:ge}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:pQs.map(ge=>e.jsx(Qe,{value:ge.value,children:ge.label},ge.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Status"}),e.jsxs(ds,{value:K.status,onValueChange:ge=>J({...K,status:ge}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:mQs.map(ge=>e.jsx(Qe,{value:ge.value,children:ge.label},ge.value))})]})]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"Property Specs (Optional)"})}),e.jsx(Ee,{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:K.bedrooms,onChange:ge=>J({...K,bedrooms:ge.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:K.bathrooms,onChange:ge=>J({...K,bathrooms:ge.target.value}),placeholder:"2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Sq Ft"}),e.jsx(ye,{type:"number",value:K.square_footage,onChange:ge=>J({...K,square_footage:ge.target.value}),placeholder:"2000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Lot Size"}),e.jsx(ye,{value:K.lot_size,onChange:ge=>J({...K,lot_size:ge.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:K.year_built,onChange:ge=>J({...K,year_built:ge.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(bn,{checked:K.has_hoa,onCheckedChange:ge=>J({...K,has_hoa:ge})}),e.jsx(se,{children:"Has HOA"})]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"Description & Links"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Es,{value:K.description,onChange:ge=>J({...K,description:ge.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(Es,{value:K.agent_notes,onChange:ge=>J({...K,agent_notes:ge.target.value}),placeholder:"Notes for other agents...",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bn,{checked:K.agent_notes_public,onCheckedChange:ge=>J({...K,agent_notes_public:ge})}),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:K.mls_link,onChange:ge=>J({...K,mls_link:ge.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Video Link"}),e.jsx(ye,{value:K.video_link,onChange:ge=>J({...K,video_link:ge.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(br,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(Ee,{children:e.jsx(dQs,{selectedVideoId:K.video_id,onVideoSelect:ge=>J({...K,video_id:ge}),listingId:l?s:void 0})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"Photos"})}),e.jsx(Ee,{children:l&&(p!=null&&p.photos)?e.jsx(cQs,{photos:p.photos,uploading:M,onUpload:ge=>ce(ge),onRemove:ge=>le(ge),onReorder:ge=>{S.mutate({photos:ge.map(Te=>({id:Te.id,sort_order:Te.sort_order,is_primary:Te.is_primary}))})},onSetPrimary:ge=>{p&&A.mutate({photoId:ge,listingId:p.id})}}):e.jsx(xQs,{photoUrls:W,onRemove:he,onReorder:(ge,Te)=>{Y(ge),V(Te)},pendingPhotos:z,uploading:M,onUpload:ie})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Pa,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(Ee,{children:l&&s?e.jsx(hQs,{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(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"Sharing & Collaboration"})}),e.jsxs(Ee,{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(bn,{checked:K.allow_sharing,onCheckedChange:ge=>J({...K,allow_sharing:ge})})]}),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(bn,{checked:K.open_to_referrals,onCheckedChange:ge=>J({...K,open_to_referrals:ge})})]}),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(bn,{checked:K.open_to_social_promotion,onCheckedChange:ge=>J({...K,open_to_social_promotion:ge})})]}),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(bn,{checked:K.share_with_brokerage,onCheckedChange:ge=>J({...K,share_with_brokerage:ge})})]}),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(bn,{checked:K.is_public,onCheckedChange:ge=>J({...K,is_public:ge})})]})]})]}),e.jsx(B,{type:"submit",className:"w-full",size:"lg",disabled:g.isPending||v.isPending,children:g.isPending||v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]}),e.jsx(f2t,{listingId:u.listingId,open:u.open,onOpenChange:ge=>{if(!ge){const{nextPath:Te}=u;h({open:!1,listingId:null,nextPath:Te}),r(Te)}}})]})}const jTe=[{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"}],v2t=[{type:"extra_video",label:"Extra Video / Reel",icon:br,desc:"Add a YouTube, Vimeo, or MP4 embed",accent:"from-rose-500/20 to-rose-500/5"},{type:"tour_3d",label:"3D Tour",icon:G7,desc:"Matterport, iGuide, or Kuula embed",accent:"from-indigo-500/20 to-indigo-500/5"},{type:"floor_plans",label:"Floor Plans",icon:nl,desc:"Upload floor plan images",accent:"from-sky-500/20 to-sky-500/5"},{type:"testimonial",label:"Testimonial",icon:gb,desc:"A quote from a past client",accent:"from-amber-500/20 to-amber-500/5"},{type:"countdown",label:"Offer Countdown",icon:gr,desc:'"Offers due Friday 5pm"',accent:"from-emerald-500/20 to-emerald-500/5"},{type:"custom_cta",label:"Custom CTA Button",icon:Jo,desc:"Link to a brochure or booking page",accent:"from-violet-500/20 to-violet-500/5"}],gQs=["#0f172a","#406E71","#c9a84c","#b91c1c","#0d7a5f","#4f46e5","#e85d3a","#111827"],FNe={sections:Object.fromEntries(jTe.map(s=>[s.key,!0])),hero_style:"photo",accent_color:null,custom_note:"",addons:[]},yQs=()=>Math.random().toString(36).slice(2,10);function vQs(){const{listingId:s}=bi(),t=Mn(),{user:n}=ys(),r=Ht(),[a,i]=N.useState("desktop"),[l,o]=N.useState(FNe),[c,d]=N.useState(!1),[u,h]=N.useState(0),{data:p,isLoading:f}=ct({queryKey:["listing-customize",s],queryFn:async()=>{const{data:z,error:V}=await q.from("listings").select("id, agent_id, slug, property_address, city, state, price, page_config, page_theme").eq("id",s).single();if(V)throw V;return z},enabled:!!s});N.useEffect(()=>{var z,V;p!=null&&p.page_config&&o({...FNe,...p.page_config||{},sections:{...FNe.sections,...((z=p.page_config)==null?void 0:z.sections)||{}},addons:((V=p.page_config)==null?void 0:V.addons)||[]})},[p==null?void 0:p.id]);const g=!!n&&!!p&&n.id===p.agent_id,_=N.useMemo(()=>p?`/public/listing/${p.slug||p.id}?preview=1&t=${u}`:"",[p,u]),v=N.useMemo(()=>p?`https://listings.relevelup.com/${p.slug||p.id}`:"",[p]),j=gt({mutationFn:async()=>{const{error:z}=await q.from("listings").update({page_config:l}).eq("id",s);if(z)throw z},onSuccess:()=>{ae.success("Saved. Your public page is live."),d(!1),r.invalidateQueries({queryKey:["listing-customize",s]}),r.invalidateQueries({queryKey:["public-listing"]}),h(z=>z+1)},onError:z=>ae.error(`Save failed: ${z.message||"Try again"}`)}),b=z=>{o(V=>({...V,...z})),d(!0)},S=(z,V)=>b({sections:{...l.sections||{},[z]:V}}),A=z=>b({addons:[...l.addons||[],{id:yQs(),type:z,data:{}}]}),T=(z,V)=>b({addons:(l.addons||[]).map(W=>W.id===z?{...W,data:{...W.data,...V}}:W)}),L=z=>b({addons:(l.addons||[]).filter(V=>V.id!==z)}),D=(z,V)=>{const W=[...l.addons||[]],Y=W.findIndex(J=>J.id===z);if(Y<0)return;const K=Y+V;K<0||K>=W.length||([W[Y],W[K]]=[W[K],W[Y]],b({addons:W}))};if(f)return e.jsx(Ts,{title:"",description:"",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading…"})});if(!p)return e.jsx(Ts,{title:"",description:"",children:e.jsx("div",{className:"p-8",children:"Listing not found."})});if(!g)return e.jsx(Ts,{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/${p.id}`),children:"Back"})]})});const M=(l.addons||[]).length,F=Object.values(l.sections||{}).filter(Boolean).length;return e.jsxs(Ts,{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/${p.id}`),children:[e.jsx(Hr,{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:p.property_address||`${p.city}, ${p.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(xb,{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(ng,{className:"h-3.5 w-3.5"})," Mobile"]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>h(z=>z+1),children:[e.jsx(Ti,{className:"h-3.5 w-3.5 mr-1.5"})," Refresh"]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:v,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1.5"})," Open live"]})}),e.jsx(B,{size:"sm",onClick:()=>j.mutate(),disabled:!c||j.isPending,children:j.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(qo,{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(hi,{className:"lg:h-[calc(100vh-140px)] pr-2",children:e.jsxs("div",{className:"space-y-6 pb-16",children:[e.jsx(OF,{icon:e.jsx(un,{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(z=>e.jsx("button",{onClick:()=>b({hero_style:z}),className:`text-xs rounded-lg border py-3 capitalize transition ${l.hero_style===z?"border-primary bg-primary/5 text-primary font-medium":"border-border hover:bg-muted"}`,children:z},z))})]})}),e.jsx(OF,{icon:e.jsx(fl,{className:"h-4 w-4"}),title:"Accent color",desc:"Highlights on the public page",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("button",{onClick:()=>b({accent_color:null}),className:`h-9 px-3 rounded-full text-xs border ${l.accent_color?"border-border hover:bg-muted":"border-primary bg-primary/5 text-primary"}`,children:"Default"}),gQs.map(z=>e.jsx("button",{onClick:()=>b({accent_color:z}),className:`h-9 w-9 rounded-full border-2 transition ${l.accent_color===z?"ring-2 ring-offset-2 ring-primary border-white":"border-white/20"}`,style:{background:z},"aria-label":z},z))]})}),e.jsx(OF,{icon:e.jsx(Dm,{className:"h-4 w-4"}),title:"Personal note",desc:"Shows in a beautiful callout on the public page",children:e.jsx(Es,{value:l.custom_note||"",onChange:z=>b({custom_note:z.target.value}),placeholder:"Why we love this home… (optional)",rows:3})}),e.jsx(OF,{icon:e.jsx(T2,{className:"h-4 w-4"}),title:"Page sections",desc:"Toggle any default section on or off",rightLabel:`${F} of ${jTe.length} on`,children:e.jsx("div",{className:"divide-y rounded-xl border",children:jTe.map(z=>{var W;const V=((W=l.sections)==null?void 0:W[z.key])!==!1;return e.jsxs("div",{className:"flex items-center justify-between p-3.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:z.label}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:z.hint})]}),e.jsx(bn,{checked:V,onCheckedChange:Y=>S(z.key,Y)})]},z.key)})})}),e.jsxs(OF,{icon:e.jsx(Is,{className:"h-4 w-4"}),title:"Add-on modules",desc:"Drop in extras to make this page unique",rightLabel:M?`${M} added`:void 0,children:[e.jsx("div",{className:"grid grid-cols-2 gap-2",children:v2t.map(z=>e.jsxs("button",{onClick:()=>A(z.type),className:`group text-left rounded-xl border p-3 hover:shadow-md transition bg-gradient-to-br ${z.accent}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"h-7 w-7 rounded-md bg-background border flex items-center justify-center",children:e.jsx(z.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-sm font-medium",children:z.label})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:z.desc})]},z.type))}),(l.addons||[]).length>0&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-muted-foreground",children:"On this page · drag to reorder"}),(l.addons||[]).map((z,V)=>e.jsx(bQs,{addon:z,onChange:W=>T(z.id,W),onRemove:()=>L(z.id),onMoveUp:V>0?()=>D(z.id,-1):void 0,onMoveDown:VD(z.id,1):void 0},z.id))]})]}),e.jsx("div",{className:"lg:hidden",children:e.jsx(B,{className:"w-full",onClick:()=>j.mutate(),disabled:!c||j.isPending,children:j.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(qo,{className:"h-4 w-4 mr-1.5"})," Save & Publish"]})})})]})}),e.jsx("div",{className:"lg:h-[calc(100vh-140px)]",children:e.jsxs(fe,{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(Er,{className:"h-3.5 w-3.5"}),"Live preview",c&&e.jsx(ze,{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(Ir,{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(xb,{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(ng,{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:_,title:"Preview",className:"w-full h-full border-0"},u)})})]})})]})]})}function OF({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 bQs({addon:s,onChange:t,onRemove:n,onMoveUp:r,onMoveDown:a}){const i=v2t.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(Fu,{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(Fu,{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(_n,{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(Es,{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(Es,{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 b2t="teleprompter_settings",zNe={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function _Qs(){try{const s=localStorage.getItem(b2t);return s?{...zNe,...JSON.parse(s)}:zNe}catch{return zNe}}function wQs(s){try{localStorage.setItem(b2t,JSON.stringify(s))}catch{}}function v8e({text:s,isVisible:t,onToggleVisibility:n,isRecording:r=!1,startCountdown:a=!1,onCountdownComplete:i,className:l}){const o=N.useRef(null),c=N.useRef(null),d=N.useRef(0),u=N.useRef(0),[h,p]=N.useState(_Qs),{scrollSpeed:f,fontSize:g,lineHeight:_,opacity:v,position:j,isMirrored:b}=h,S=N.useCallback((W,Y)=>{p(K=>{const J={...K,[W]:Y};return wQs(J),J})},[]),[A,T]=N.useState(!1),[L,D]=N.useState(null),M=N.useCallback(W=>{if(!o.current)return;d.current===0&&(d.current=W);const Y=W-d.current;d.current=W,u.current+=f*Y/1e3;const K=Math.floor(u.current);K>0&&(o.current.scrollTop+=K,u.current-=K);const{scrollTop:J,scrollHeight:ne,clientHeight:ie}=o.current;if(J+ie>=ne){T(!1);return}c.current=requestAnimationFrame(M)},[f]);N.useEffect(()=>(A?(d.current=0,u.current=0,c.current=requestAnimationFrame(M)):c.current&&cancelAnimationFrame(c.current),()=>{c.current&&cancelAnimationFrame(c.current)}),[A,M]),N.useEffect(()=>{if(r&&t)if(o.current&&(o.current.scrollTop=0),a){D(3);let W=3;const Y=setInterval(()=>{W-=1,W<=0?(clearInterval(Y),D(null),i==null||i(),T(!0)):D(W)},1e3);return()=>clearInterval(Y)}else setTimeout(()=>T(!0),100);else r||(T(!1),D(null))},[r,t,a,i]);const F=N.useCallback(()=>{o.current&&(o.current.scrollTop=0),T(!1)},[]),z=N.useCallback(()=>{T(W=>!W)},[]);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(Er,{className:"h-4 w-4 mr-2"}),"Show Script"]})});const V={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:[L!==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:L},L),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",V[j],L!==null&&"opacity-30"),style:{opacity:L!==null?.3:v},children:e.jsxs("div",{ref:o,className:Et("mx-auto max-w-2xl px-6 overflow-y-auto scrollbar-hide h-full",b&&"scale-x-[-1]"),style:{maskImage:"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)",WebkitMaskImage:"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)"},children:[e.jsx("div",{className:"h-full",style:{minHeight:"100%"}}),e.jsx("p",{className:"text-white text-center font-medium drop-shadow-lg",style:{fontSize:`${g}px`,lineHeight:_,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(el,{children:[e.jsx(tl,{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(Xo,{className:"h-4 w-4"})})}),e.jsx(Ho,{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:f})]}),e.jsx(Bm,{value:[f],onValueChange:([W])=>S("scrollSpeed",W),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:[g,"px"]})]}),e.jsx(Bm,{value:[g],onValueChange:([W])=>S("fontSize",W),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:_.toFixed(1)})]}),e.jsx(Bm,{value:[_*10],onValueChange:([W])=>S("lineHeight",W/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(v*100),"%"]})]}),e.jsx(Bm,{value:[v*100],onValueChange:([W])=>S("opacity",W/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:j==="top"?"default":"outline",size:"sm",onClick:()=>S("position","top"),children:e.jsx(tx,{className:"h-4 w-4"})}),e.jsx(B,{variant:j==="center"?"default":"outline",size:"sm",onClick:()=>S("position","center"),children:e.jsx(fb,{className:"h-4 w-4"})}),e.jsx(B,{variant:j==="bottom"?"default":"outline",size:"sm",onClick:()=>S("position","bottom"),children:e.jsx(io,{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(bn,{checked:b,onCheckedChange:W=>S("isMirrored",W)})]})]})})]}),e.jsx(B,{variant:"secondary",size:"icon",onClick:z,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:A?e.jsx(bf,{className:"h-4 w-4"}):e.jsx(Al,{className:"h-4 w-4"})}),e.jsx(B,{variant:"secondary",size:"icon",onClick:F,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(cm,{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(xf,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function jQs({onSelectScript:s,onCreateNew:t,selectedScriptId:n,className:r}){const{toast:a}=Ba(),[i,l]=N.useState(""),[o,c]=N.useState(null),[d,u]=N.useState("levelup"),{data:h,isLoading:p}=kGs(),{data:f,isLoading:g}=SGs(),{data:_,isLoading:v}=CGs(),j=TGs(),b=N.useMemo(()=>f?f.filter(D=>{const M=!i||D.title.toLowerCase().includes(i.toLowerCase())||D.script_text.toLowerCase().includes(i.toLowerCase())||D.tags.some(z=>z.toLowerCase().includes(i.toLowerCase())),F=!o||D.category_id===o;return M&&F}):[],[f,i,o]),S=N.useMemo(()=>_?_.filter(D=>!i||D.title.toLowerCase().includes(i.toLowerCase())||D.script_text.toLowerCase().includes(i.toLowerCase())):[],[_,i]),A=D=>{s({title:D.title,text:D.script_text})},T=async D=>{try{await j.mutateAsync(D),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},L=p||g||v;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(vr,{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:D=>l(D.target.value),className:"pl-9"})]})}),e.jsxs(Br,{value:d,onValueChange:D=>u(D),className:"flex-1 flex flex-col",children:[e.jsxs(Fr,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(Kt,{value:"levelup",children:[e.jsx(Nr,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(Kt,{value:"my-scripts",children:[e.jsx(Lv,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(is,{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(ze,{variant:o?"outline":"default",className:"cursor-pointer",onClick:()=>c(null),children:"All"}),h==null?void 0:h.map(D=>e.jsx(ze,{variant:o===D.id?"default":"outline",className:"cursor-pointer",onClick:()=>c(D.id),children:D.name},D.id))]}),e.jsx(hi,{className:"flex-1 max-h-[50vh]",children:L?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Nr,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No scripts found"})]}):e.jsx("div",{className:"space-y-2",children:b.map(D=>e.jsxs(fe,{className:Et("cursor-pointer hover:bg-accent/50 transition-colors",n===D.id&&"ring-2 ring-primary"),onClick:()=>A(D),children:[e.jsx(Mt,{className:"p-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(It,{className:"text-sm font-medium truncate",children:D.title}),D.category&&e.jsx(ze,{variant:"secondary",className:"mt-1 text-xs",children:D.category.name})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:M=>{M.stopPropagation(),T(D)},children:e.jsx(Lv,{className:"h-4 w-4"})}),e.jsx(xa,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(Ee,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:D.script_text})})]},D.id))})})]}),e.jsxs(is,{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(Is,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(hi,{className:"flex-1 max-h-[50vh]",children:v?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):S.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Lv,{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:S.map(D=>e.jsxs(fe,{className:Et("cursor-pointer hover:bg-accent/50 transition-colors",n===D.id&&"ring-2 ring-primary"),onClick:()=>A(D),children:[e.jsx(Mt,{className:"p-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(It,{className:"text-sm font-medium truncate",children:D.title}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:D.is_custom?e.jsx(ze,{variant:"outline",className:"text-xs",children:"Custom"}):e.jsx(ze,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),e.jsx(xa,{className:"h-4 w-4 text-muted-foreground ml-2"})]})}),e.jsx(Ee,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:D.script_text})})]},D.id))})})]})]})]})}function NQs({selectedTemplate:s,onSelect:t,contactName:n,saving:r=!1}){const[a,i]=N.useState(()=>{const o=IL(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(ts,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),e.jsx("div",{className:"space-y-3",children:Tns.map(o=>{const c=Ens(o.id),d=a.has(o.id),u=c.some(h=>h.id===s);return e.jsxs(dy,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(uy,{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(io,{className:Et("h-4 w-4 text-muted-foreground transition-transform",d&&"rotate-180")})]}),e.jsx(hy,{className:"pt-2",children:e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:c.map(h=>{const p=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",p?"border-primary ring-1 ring-primary/20 bg-primary/5":"border-muted hover:border-muted-foreground/30"),children:[p&&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(Ir,{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: "',IL(s).headerText(n),'"']})]})}function _2t({open:s,onOpenChange:t,video:n,contactName:r,onTemplateUpdated:a}){const[i,l]=N.useState(n.page_template||"default"),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState(n.page_template||"default"),[f,g]=N.useState([]),[_,v]=N.useState(n.contact_id&&r?{id:n.contact_id,name:r,email:null}:null),[j,b]=N.useState(!1),[S,A]=N.useState(!1),T=n.share_token?`https://video.relevelup.com/${n.share_token}`:"";N.useEffect(()=>{s&&f.length===0&&L()},[s]);const L=async()=>{A(!0);try{const{data:J,error:ne}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(ne)throw ne;const ie=(J||[]).map(he=>({id:he.id,name:[he.first_name,he.last_name].filter(Boolean).join(" ")||"Unnamed",email:he.email||null}));g(ie)}catch(J){console.error("Failed to fetch contacts:",J)}finally{A(!1)}},D=async J=>{v(J),b(!1),c(!0);try{const{error:ne}=await q.from("agent_videos").update({contact_id:(J==null?void 0:J.id)||null,recipient_name:(J==null?void 0:J.name)||null}).eq("id",n.id);if(ne)throw ne;ae.success(J?`Assigned to ${J.name}`:"Contact removed"),a==null||a()}catch(ne){console.error("Failed to update contact:",ne),ae.error("Failed to update contact")}finally{c(!1)}},M=async J=>{l(J),c(!0);try{const{error:ne}=await q.from("agent_videos").update({page_template:J}).eq("id",n.id);if(ne)throw ne;p(J),ae.success("Template saved!"),a==null||a()}catch(ne){console.error("Failed to save template:",ne),ae.error("Failed to save template"),l(h)}finally{c(!1)}},F=(_==null?void 0:_.name)||null,z=()=>{const J=n.title||"Video Message",ne=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:n.thumbnail_url||"";return``},V=async()=>{if(!n.thumbnail_url){ae.error("Video thumbnail not available yet");return}const J=z(),ne=`Watch: ${n.title||"Video Message"} ${T}`;try{const ie=new Blob([J],{type:"text/html"}),he=new Blob([ne],{type:"text/plain"}),ce=new ClipboardItem({"text/html":ie,"text/plain":he});await navigator.clipboard.write([ce]),ae.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(ne+` `+J),ae.success("Copied! Paste into your email.")}},W=async()=>{await navigator.clipboard.writeText(T),u(!0),ae.success("Share link copied!"),setTimeout(()=>u(!1),2e3)},Y=()=>{const ne=IL(i).headerText(F),ie=i==="default"?`Check out this video: ${T}`:`${ne} Check out this special video: ${T}`;window.open(`sms:?body=${encodeURIComponent(ie)}`,"_self")},K=()=>{const J=IL(i),ne=J.headerText(F),ie=i==="default"?n.title||"Video Message":ne,he=`${J.subText} Watch the video: ${T}`,ce=_!=null&&_.email?encodeURIComponent(_.email):"";window.open(`mailto:${ce}?subject=${encodeURIComponent(ie)}&body=${encodeURIComponent(he)}`,"_self")};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Jo,{className:"h-5 w-5"}),"Share Video"]}),e.jsx(Qn,{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(el,{open:j,onOpenChange:b,children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":j,className:"flex-1 justify-between",disabled:o,children:[_?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Xi,{className:"h-4 w-4 text-muted-foreground"}),_.name]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(qg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ho,{className:"w-[300px] p-0",align:"start",children:e.jsxs(Qg,{children:[e.jsx(Xg,{placeholder:"Search contacts..."}),e.jsxs(Jg,{children:[e.jsx(e0,{children:S?"Loading...":"No contacts found."}),e.jsx(t0,{children:f.map(J=>e.jsxs(Jf,{value:J.name,onSelect:()=>D(J),children:[e.jsx(Ir,{className:Et("mr-2 h-4 w-4",(_==null?void 0:_.id)===J.id?"opacity-100":"opacity-0")}),J.name]},J.id))})]})]})})]}),_&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>D(null),disabled:o,className:"shrink-0",children:e.jsx(Bn,{className:"h-4 w-4"})})]}),_&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',IL(i).headerText(_.name),'"']})]}),e.jsx(NQs,{selectedTemplate:i,onSelect:M,contactName:F,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:W,variant:d?"default":"outline",className:"shrink-0 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Ir,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Xr,{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:V,children:[e.jsx(nl,{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:Y,children:[e.jsx(Ei,{className:"h-4 w-4"}),"Text"]}),e.jsxs(B,{variant:"outline",className:"flex-1 gap-2",onClick:K,children:[e.jsx(Vs,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(Xn,{children:e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function kQs(){var Be;const s=Mn(),[t]=gl(),{toast:n}=Ba(),r=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c,storage:d}=O_t(),{data:u}=ox(),h=IN(),p=PGs(),[f,g]=N.useState("record"),[_,v]=N.useState(""),[j,b]=N.useState(!1),[S,A]=N.useState(!1),[T,L]=N.useState(!1),[D,M]=N.useState(null),[F,z]=N.useState(0),[V,W]=N.useState(0),[Y,K]=N.useState(null),[J,ne]=N.useState(null),[ie,he]=N.useState(r||""),[ce,pe]=N.useState(""),[le,ve]=N.useState(""),[ge,Te]=N.useState(null),[Me,Ce]=N.useState(null),[Ae,De]=N.useState(null),[Ie,Fe]=N.useState(!1),qe=N.useCallback(async(Ye,We)=>{M(Ye),g("uploading");try{const{videoId:rt,uploadUrl:tt}=await i6(ce||"Quick Video Touch");K(rt);const{apiKey:at}=await o6(rt),He=new XMLHttpRequest;He.upload.onprogress=Bt=>{Bt.lengthComputable&&z(Bt.loaded/Bt.total*100)},await new Promise((Bt,Zt)=>{He.onload=()=>{He.status>=200&&He.status<300?Bt():Zt(new Error(`Upload failed: ${He.status}`))},He.onerror=()=>Zt(new Error("Upload failed")),He.open("PUT",tt),He.setRequestHeader("AccessKey",at),He.send(Ye)}),g("processing");let dt=0;const bt=Date.now(),vt=90*1e3;for(;dt<4;){if(await new Promise(Zt=>setTimeout(Zt,3e3)),Date.now()-bt>vt){const Zt=Ye.size/1048576,Fs=`https://iframe.mediadelivery.net/play/${rt}/${rt}`;await h.mutateAsync({bunny_video_id:rt,playback_url:Fs,file_size_mb:Zt,title:ce||"Quick Video Touch",notes:le||void 0,contact_id:ie&&ie!=="none"?ie: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 Bt=await $w(rt);if(dt=Bt.status,W(Bt.encodeProgress||0),dt===4)ne({playbackUrl:Bt.directPlayUrl,thumbnailUrl:Bt.thumbnailUrl,previewUrl:Bt.previewUrl||null,duration:Bt.length||We,fileSizeMb:(Bt.storageSize||Ye.size)/(1024*1024)});else if(dt===5||dt===6)throw new Error("Video processing failed")}g("details")}catch(rt){console.error("Upload error:",rt),n({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),g("record")}},[ce,n]),be=async()=>{if(!(!Y||!J))try{const Ye=ie&&ie!=="none"?ie:null,We=await h.mutateAsync({bunny_video_id:Y,contact_id:Ye,playback_url:J.playbackUrl,thumbnail_url:J.thumbnailUrl,preview_url:J.previewUrl,duration_seconds:J.duration,file_size_mb:J.fileSizeMb,title:ce||"Quick Video Touch",notes:le,task_id:a||null,status:"ready"});Te(We.id),Ce(We.share_token||null),Ye&&await p.mutateAsync({contactId:Ye,videoId:We.id,notes:le}),n({title:"Video saved successfully!"}),g("share")}catch(Ye){console.error("Save video error:",Ye),n({title:"Failed to save video",description:(Ye==null?void 0:Ye.message)||"Please try again.",variant:"destructive"})}},Ze=(Ye,We)=>{navigator.clipboard.writeText(We),De(Ye),setTimeout(()=>De(null),2e3),n({title:"Copied to clipboard!"})},Ne=()=>Me?`https://video.relevelup.com/${Me}`:(J==null?void 0:J.playbackUrl)||"",it=()=>{const Ye=u==null?void 0:u.find(He=>He.id===ie),We=Ye?`${Ye.first_name}`:"",rt=(Ye==null?void 0:Ye.phone)||"",tt=(Ye==null?void 0:Ye.email)||"",at=Ne();return{text:`Hey${We?` ${We}`:""}! I recorded a quick video for you: ${at}`,link:at,contactPhone:rt,contactEmail:tt}},je=()=>{const{text:Ye,contactPhone:We}=it(),rt=We?`sms:${We}?body=${encodeURIComponent(Ye)}`:`sms:?body=${encodeURIComponent(Ye)}`;window.open(rt,"_self")},Ge=()=>{const{link:Ye,contactEmail:We}=it(),rt="Check out this video",tt=`I recorded a quick video for you: ${Ye}`,at=We?`mailto:${We}?subject=${encodeURIComponent(rt)}&body=${encodeURIComponent(tt)}`:`mailto:?subject=${encodeURIComponent(rt)}&body=${encodeURIComponent(tt)}`;window.open(at,"_self")};return i?e.jsx(Ts,{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(Hr,{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(Nr,{className:"h-4 w-4"}),"Video Library"]}),c&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm text-warning",children:["Storage: ",o.toFixed(0),"% used"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l.toFixed(0)," MB remaining"]})]})]})]}),f==="record"&&e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2",children:[e.jsx(u6,{maxDurationSeconds:600,onRecordingComplete:qe,onRecordingStateChange:L,className:"w-full",teleprompterContent:j&&_&&e.jsx(v8e,{text:_,isVisible:j,onToggleVisibility:()=>b(!1),isRecording:T,startCountdown:!1})}),!j&&_&&e.jsxs(B,{variant:"outline",className:"mt-4",onClick:()=>b(!0),children:[e.jsx(Nr,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(fe,{className:"lg:col-span-1",children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-lg",children:"Teleprompter Script"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx(Es,{placeholder:"Type or paste your script here...",value:_,onChange:Ye=>v(Ye.target.value),rows:6}),e.jsxs(cg,{open:S,onOpenChange:A,children:[e.jsx(rU,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full",children:[e.jsx(Nr,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(ix,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(n0,{className:"p-4 border-b",children:e.jsx(r0,{children:"Select a Script"})}),e.jsx(jQs,{onSelectScript:Ye=>{v(Ye.text),A(!1),b(!0)},className:"h-[calc(100vh-80px)]"})]})]}),_&&e.jsx(B,{className:"w-full",onClick:()=>b(!0),children:"Use Script"})]})]})]}),f==="uploading"&&e.jsx(fe,{className:"max-w-md mx-auto",children:e.jsxs(Ee,{className:"pt-6 text-center",children:[e.jsx(Na,{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(pi,{value:F,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[F.toFixed(0),"%"]})]})}),f==="processing"&&e.jsx(fe,{className:"max-w-md mx-auto",children:e.jsxs(Ee,{className:"pt-6 text-center space-y-4",children:[e.jsx(ts,{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(pi,{value:V,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[V.toFixed(0),"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:`This usually takes 30-60 seconds. If it takes longer, we'll auto-save your video and you can find it in your Video Library — look for the "processing" badge.`})]})}),f==="details"&&e.jsxs(fe,{className:"max-w-lg mx-auto",children:[e.jsx(Mt,{children:e.jsx(It,{children:"Video Details"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:ce,onChange:Ye=>pe(Ye.target.value),placeholder:"Quick Video Touch"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Attach to Contact (Optional)"}),e.jsxs(ds,{value:ie,onValueChange:he,children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"No contact - use anywhere"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Jo,{className:"h-4 w-4"}),"No contact - use anywhere"]})}),u==null?void 0:u.map(Ye=>e.jsx(Qe,{value:Ye.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xi,{className:"h-4 w-4"}),Ye.first_name," ",Ye.last_name]})},Ye.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Es,{value:le,onChange:Ye=>ve(Ye.target.value),placeholder:"Add notes about this video...",rows:3})]}),e.jsxs(B,{className:"w-full",onClick:be,disabled:h.isPending,children:[h.isPending&&e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),f==="share"&&e.jsxs(fe,{className:"max-w-lg mx-auto",children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"h-5 w-5 text-green-500"}),"Video Saved!"]})}),e.jsxs(Ee,{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:je,children:[e.jsx(Ei,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:Ge,children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>Ze("link",it().link),children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),"Copy Video Link",Ae==="link"&&e.jsx(Ir,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>Fe(!0),children:[e.jsx(fl,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx(B,{variant:"outline",onClick:()=>s("/mission-control/video-library"),children:"View Library"}),e.jsx(B,{onClick:()=>{g("record"),M(null),K(null),ne(null)},children:"Record Another"})]})]})]}),ge&&Me&&e.jsx(_2t,{open:Ie,onOpenChange:Fe,video:{id:ge,share_token:Me,title:ce||null,contact_id:ie||null,thumbnail_url:(J==null?void 0:J.thumbnailUrl)||null},contactName:((Be=u==null?void 0:u.find(Ye=>Ye.id===ie))==null?void 0:Be.first_name)||null})]})}):e.jsx(Ts,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center py-12",children:[e.jsx($l,{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 SQs({open:s,onOpenChange:t,video:n,gmailEmail:r,signedThumbnailUrl:a,onSendComplete:i}){const[l,o]=N.useState([]),[c,d]=N.useState(null),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[g,_]=N.useState(""),[v,j]=N.useState(""),[b,S]=N.useState(""),[A,T]=N.useState(!1),L=A_t(),D=n.share_token?`https://video.relevelup.com/share/video/${n.share_token}`:"",M=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:a||n.thumbnail_url||"",F=n.title||"Video Message";N.useEffect(()=>{s&&l.length===0&&z()},[s]),N.useEffect(()=>{if(s&&(j(`I recorded a video for you — ${F}`),S("Hey! I recorded a quick video just for you. Click below to watch it:"),d(null),_(""),n.contact_id)){const ne=l.find(ie=>ie.id===n.contact_id);ne&&(d(ne),_(ne.email||""))}},[s,n.contact_id,l]);const z=async()=>{f(!0);try{const{data:ne,error:ie}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(ie)throw ie;o(ne||[])}catch{console.error("Failed to fetch contacts")}finally{f(!1)}},V=ne=>{d(ne),h(!1),_(ne.email||""),S(`Hey ${ne.first_name}! I recorded a quick video just for you. Click below to watch it:`),j(`I recorded a video for you — ${F}`)},W=()=>{d(null),_(""),S("Hey! I recorded a quick video just for you. Click below to watch it:")},Y=ne=>`${ne.first_name} ${ne.last_name||""}`.trim(),K=ne=>{const ie=b.split(/\n\n+/).map(pe=>`

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

`).join(""),he=ne?I_t(ne):D,ce=ne?``:"";return`
${ie}

▶ Watch Video

${ce}
`},J=async()=>{var ne;if(!g){ae.error("Please enter a recipient email");return}if(!D){ae.error("Video does not have a share link");return}T(!0);try{let ie;try{const ve=c?Y(c):g.split("@")[0];ie=(await L.mutateAsync({video_id:n.id,recipient_email:g,recipient_name:ve,contact_id:(c==null?void 0:c.id)||null,sent_via:"gmail"})).share_token}catch(ve){console.warn("Failed to create tracking record, sending without tracking:",ve)}const he=K(ie),{data:ce,error:pe}=await q.functions.invoke("gmail-send",{body:{to:g,subject:v,body:he,contactId:(c==null?void 0:c.id)||null}});let le=null;if(pe&&((ne=pe.context)!=null&&ne.json))try{le=await pe.context.json()}catch{}if((le==null?void 0:le.error)==="insufficient_scope"||(ce==null?void 0:ce.error)==="insufficient_scope"){ae.error((le==null?void 0:le.message)||"Gmail is missing send permission. Please disconnect and reconnect Gmail, allowing 'Send email on your behalf'.",{duration:1e4});return}if(pe)throw new Error((le==null?void 0:le.message)||pe.message);if(!(ce!=null&&ce.success))throw new Error((ce==null?void 0:ce.error)||"Failed to send");ae.success("Video email sent!"),t(!1),i==null||i()}catch(ie){console.error("Gmail send error:",ie),ae.error("Failed to send: "+(ie instanceof Error?ie.message:"Unknown error"))}finally{T(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[560px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Vs,{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(el,{open:u,onOpenChange:h,children:[e.jsx(tl,{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(Xi,{className:"h-4 w-4 text-muted-foreground"}),Y(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(qg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ho,{className:"w-[350px] p-0",align:"start",children:e.jsxs(Qg,{children:[e.jsx(Xg,{placeholder:"Search contacts..."}),e.jsxs(Jg,{children:[e.jsx(e0,{children:p?"Loading...":"No contacts found."}),e.jsx(t0,{children:l.filter(ne=>ne.email).map(ne=>e.jsxs(Jf,{value:`${ne.first_name} ${ne.last_name||""} ${ne.email||""}`,onSelect:()=>V(ne),children:[e.jsx(Ir,{className:Et("mr-2 h-4 w-4",(c==null?void 0:c.id)===ne.id?"opacity-100":"opacity-0")}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Y(ne)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ne.email})]})]},ne.id))})]})]})})]}),c&&e.jsx(B,{variant:"ghost",size:"icon",onClick:W,className:"shrink-0",children:e.jsx(Bn,{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:g,onChange:ne=>_(ne.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(ll,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"video-subject",children:"Subject"}),e.jsx(ye,{id:"video-subject",value:v,onChange:ne=>j(ne.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"video-message",children:"Personal Message"}),e.jsx(Es,{id:"video-message",value:b,onChange:ne=>S(ne.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Video Preview (embedded in email)"}),e.jsxs("div",{className:"relative rounded-lg overflow-hidden bg-black",style:{maxWidth:320},children:[M?e.jsx("img",{src:M,alt:F,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(Al,{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(Al,{className:"h-5 w-5 text-primary ml-0.5"})})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recipients will see the thumbnail with a play button. Clicking opens the video page."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:A,children:"Cancel"}),e.jsxs(B,{onClick:J,disabled:A||!g||!v,className:"gap-2",children:[A?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"}),A?"Sending...":"Send Video Email"]})]})]})]})})}const CQs=()=>{const{user:s}=ys();return ct({queryKey:["team-videos",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.rpc("get_team_videos",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})};function TQs({recipient:s}){return s.watched_at?e.jsxs(ze,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(Al,{className:"h-2.5 w-2.5 mr-0.5"}),"Watched"]}):s.clicked_at?e.jsxs(ze,{className:"bg-blue-100 text-blue-800 text-[10px]",children:[e.jsx(Om,{className:"h-2.5 w-2.5 mr-0.5"}),"Clicked"]}):s.opened_at?e.jsxs(ze,{className:"bg-amber-100 text-amber-800 text-[10px]",children:[e.jsx(Er,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs(ze,{variant:"outline",className:"text-[10px]",children:[e.jsx(cr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function EQs({open:s,onOpenChange:t,videoId:n,videoTitle:r}){const{data:a=[],isLoading:i}=cGs(n);return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(yo,{className:"h-5 w-5"}),"Send Analytics: ",r]})}),i?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((l,o)=>e.jsx(Ws,{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(hi,{className:"h-[400px]",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Recipient"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Sent"}),e.jsx(Ct,{children:"Last Activity"})]})}),e.jsx(ha,{children:a.map(l=>e.jsxs(Hs,{children:[e.jsx(ut,{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(ut,{children:e.jsx(TQs,{recipient:l})}),e.jsx(ut,{className:"text-xs text-muted-foreground",children:Ss(new Date(l.sent_at),"MMM d, h:mm a")}),e.jsx(ut,{className:"text-xs text-muted-foreground",children:l.last_activity_at?Vo(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function AQs(){const{data:s,isLoading:t}=dGs(),{data:n=[],isLoading:r}=uGs(),[a,i]=N.useState(null),l=t||r,o=n.reduce((c,d)=>{const u=d.agent_videos,h=(u==null?void 0:u.id)||d.video_id;return c[h]||(c[h]={videoId:h,title:(u==null?void 0:u.title)||"Untitled",thumbnailUrl:u==null?void 0:u.thumbnail_url,recipients:[]}),c[h].recipients.push(d),c},{});return l?e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[...Array(4)].map((c,d)=>e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Ws,{className:"h-4 w-20"})}),e.jsx(Ee,{children:e.jsx(Ws,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total Sent"}),e.jsx(cr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:(s==null?void 0:s.totalSent)||0})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Open Rate"}),e.jsx(Er,{className:"h-4 w-4 text-amber-500"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(Om,{className:"h-4 w-4 text-blue-500"})]}),e.jsxs(Ee,{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(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(Vn,{children:"Click a video to see individual recipient tracking"})]}),e.jsx(Ee,{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 p=h.currentTarget;p.style.display="none",p.parentElement.innerHTML='
'}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(br,{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(cr,{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(Er,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(Om,{className:"h-3 w-3"})," ",u]})]})]}),e.jsx(mo,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx(EQs,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function MQs({previewSrc:s,thumbnailSrc:t,alt:n,isHovered:r}){const[a,i]=N.useState(!1),[l,o]=N.useState(!1),c=r&&s&&!a,d=t&&!l;return!d&&!c?e.jsx("div",{className:"w-full h-full flex items-center justify-center absolute inset-0 bg-muted",children:e.jsx(br,{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 IQs({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:p,getContactName:f,getShareUrl:g,copyToClipboard:_,formatDuration:v}){const[j,b]=N.useState(!1);return e.jsxs(fe,{className:"overflow-hidden group cursor-pointer",onClick:r,onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),children:[e.jsxs("div",{className:"relative aspect-video bg-muted overflow-hidden",children:[e.jsx(MQs,{previewSrc:t,thumbnailSrc:n,alt:s.title||"Video preview",isHovered:j}),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(Al,{className:"h-6 w-6 text-primary ml-1"})})}),e.jsx("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:v(s.duration_seconds)}),s.status!=="ready"&&e.jsx(ze,{variant:s.status==="processing"?"secondary":"destructive",className:"absolute top-2 left-2",children:s.status})]}),e.jsx(Ee,{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(Xi,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f(s.contact_id)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),e.jsx("span",{children:Ss(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(Er,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]}),p&&s.share_token&&e.jsxs(B,{variant:"outline",size:"sm",className:"mt-2 gap-1.5 text-xs h-7",onClick:S=>{S.stopPropagation(),h==null||h()},children:[e.jsx(Vs,{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(Xi,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f(s.contact_id)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),e.jsx("span",{children:Ss(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(Er,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:S=>S.stopPropagation(),children:e.jsx(Ig,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",className:"bg-popover",children:[e.jsxs(Qr,{onClick:S=>{S.stopPropagation(),r()},children:[e.jsx(Er,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(Zg,{}),e.jsxs(Qr,{onClick:S=>{S.stopPropagation(),u()},children:[e.jsx(fl,{className:"h-4 w-4 mr-2"}),"Share with Template"]}),e.jsxs(Qr,{onClick:S=>{S.stopPropagation(),_(g(s),"Share link")},children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(Qr,{onClick:S=>{S.stopPropagation(),o()},children:[e.jsx(kA,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(Qr,{onClick:S=>{S.stopPropagation(),c()},children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(Qr,{onClick:S=>{S.stopPropagation(),d()},children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),p&&s.share_token&&e.jsxs(Qr,{onClick:S=>{S.stopPropagation(),h==null||h()},children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]}),e.jsxs(Qr,{onClick:S=>{S.stopPropagation(),i()},children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Rename"]}),e.jsx(Zg,{}),s.contact_id&&e.jsxs(Qr,{onClick:S=>{S.stopPropagation(),l()},children:[e.jsx(Xi,{className:"h-4 w-4 mr-2"}),"View Contact"]}),e.jsxs(Qr,{onClick:S=>{S.stopPropagation(),a()},className:"text-destructive",children:[e.jsx(_n,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function PQs(){var Fs,Rs;const s=Mn(),{data:t,isLoading:n,refetch:r}=EGs(),{data:a}=D1e(),{data:i}=ox(),l=IGs(),o=MGs(),{isGmailConnected:c,gmailEmail:d}=Oh(),{data:u}=Zv(),{data:h=[],isLoading:p}=CQs(),[f,g]=N.useState("my"),[_,v]=N.useState(""),[j,b]=N.useState(null),[S,A]=N.useState(!1),[T,L]=N.useState(!1),[D,M]=N.useState(!1),[F,z]=N.useState(!1),[V,W]=N.useState(!1),[Y,K]=N.useState(""),[J,ne]=N.useState(!1),[ie,he]=N.useState(!1),[ce,pe]=N.useState(!1),[le,ve]=N.useState(!1),[ge,Te]=N.useState(""),[Me,Ce]=N.useState({}),Ae=ms=>{if(!ms)return"Unassigned";const Pt=i==null?void 0:i.find(Jt=>Jt.id===ms);return Pt?`${Pt.first_name} ${Pt.last_name||""}`.trim():"Unknown"},De=ms=>{if(!ms)return"0:00";const Pt=Math.floor(ms/60),Jt=ms%60;return`${Pt}:${Jt.toString().padStart(2,"0")}`},[Ie,Fe]=N.useState("all"),qe=t==null?void 0:t.filter(ms=>{const Pt=ms.category||"general";if(Ie==="general"&&Pt!=="general"||Ie==="open_house"&&Pt!=="open_house")return!1;if(!_)return!0;const Jt=Ae(ms.contact_id).toLowerCase(),ft=(ms.title||"").toLowerCase(),Vt=(ms.notes||"").toLowerCase();return Jt.includes(_.toLowerCase())||ft.includes(_.toLowerCase())||Vt.includes(_.toLowerCase())}),be=(t==null?void 0:t.filter(ms=>(ms.category||"general")==="open_house").length)||0,Ze=(t==null?void 0:t.filter(ms=>(ms.category||"general")==="general").length)||0,Ne=(t||[]).filter(ms=>ms.status==="processing"&&ms.bunny_video_id).map(ms=>ms.id).join(",");N.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const Pt=t.filter(ft=>ft.status==="processing"&&ft.bunny_video_id);if(!Pt.length)return;let Jt=!1;for(const ft of Pt)try{const{data:Vt,error:Ms}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:ft.bunny_video_id,isAgentVideo:!0}});if(Ms||!Vt)continue;Vt.status===4&&(await q.from("agent_videos").update({status:"ready",playback_url:Vt.directPlayUrl,thumbnail_url:Vt.thumbnailUrl,preview_url:Vt.previewUrl,duration_seconds:Vt.length||ft.duration_seconds,updated_at:new Date().toISOString()}).eq("id",ft.id),Jt=!0)}catch(Vt){console.warn("Reconcile check failed for video",ft.id,Vt)}Jt&&r()})()},[Ne,r]),N.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const Pt=t.filter(Xt=>(Xt==null?void 0:Xt.bunny_video_id)&&!Me[Xt.id]);if(!Pt.length)return;const Jt=Pt.map(Xt=>Xt.bunny_video_id),{data:ft,error:Vt}=await q.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:Jt,isAgentVideo:!0}});if(Vt)throw Vt;const Ms=(ft==null?void 0:ft.assets)||{};Ce(Xt=>{const Js={...Xt};for(const Cs of Pt)Ms[Cs.bunny_video_id]&&(Js[Cs.id]={previewUrl:Ms[Cs.bunny_video_id].previewUrl,thumbnailUrl:Ms[Cs.bunny_video_id].thumbnailUrl});return Js})})().catch(Pt=>console.warn("Failed to load signed Bunny asset URLs",Pt))},[t,Me]);const it=(a==null?void 0:a.total_storage_mb)||0,je=(a==null?void 0:a.max_storage_mb)||1024,Ge=it/je*100,Be=Ge>=80,Ye=Ge>=100,We=async(ms,Pt)=>{await navigator.clipboard.writeText(ms),ae.success(`${Pt} copied to clipboard`)},rt=ms=>ms.share_token?`https://video.relevelup.com/${ms.share_token}`:ms.playback_url||"",tt=ms=>{const Pt=rt(ms),Jt=i==null?void 0:i.find(Cs=>Cs.id===ms.contact_id),ft=Ae(ms.contact_id),Vt=ft!=="Unassigned"?ft.split(" ")[0]:"",Ms=(Jt==null?void 0:Jt.phone)||"",Xt=`Hey${Vt?` ${Vt}`:""}! I recorded a quick video message for you. Check it out: ${Pt}`,Js=Ms?`sms:${Ms}?body=${encodeURIComponent(Xt)}`:`sms:?body=${encodeURIComponent(Xt)}`;window.open(Js,"_self")},at=ms=>{const Pt=i==null?void 0:i.find(Js=>Js.id===ms.contact_id),Jt=(Pt==null?void 0:Pt.email)||"",ft=rt(ms),Vt="Check out this video",Ms=`I recorded a quick video for you: ${ft}`,Xt=Jt?`mailto:${Jt}?subject=${encodeURIComponent(Vt)}&body=${encodeURIComponent(Ms)}`:`mailto:?subject=${encodeURIComponent(Vt)}&body=${encodeURIComponent(Ms)}`;window.open(Xt,"_self")},He=ms=>{var Vt;const Pt=rt(ms),Jt=ms.title||"Video Message",ft=ms.share_token?`https://video.relevelup.com/thumb/${ms.share_token}`:((Vt=Me[ms.id])==null?void 0:Vt.thumbnailUrl)||ms.thumbnail_url||"";return``},dt=async ms=>{if(!ms.thumbnail_url&&!ms.share_token){ae.error("Video thumbnail not available yet");return}const Pt=He(ms),Jt=rt(ms),ft=`Watch: ${ms.title||"Video Message"} ${Jt}`;try{const Vt=new Blob([Pt],{type:"text/html"}),Ms=new Blob([ft],{type:"text/plain"}),Xt=new ClipboardItem({"text/html":Vt,"text/plain":Ms});await navigator.clipboard.write([Xt]),ae.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(ft+` `+Pt),ae.success("Copied! Paste into your email.")}},bt=async ms=>{try{ae.loading("Preparing download...",{id:"download"});const{data:Pt,error:Jt}=await q.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:ms.bunny_video_id,isAgentVideo:!0}});if(Jt||!(Pt!=null&&Pt.downloadUrl))throw new Error((Jt==null?void 0:Jt.message)||"Failed to get download URL");const Vt=`${((ms.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,Ms=await fetch(Pt.downloadUrl);if(!Ms.ok)throw new Error("Failed to fetch video file");const Xt=await Ms.blob(),Js=URL.createObjectURL(Xt),Cs=document.createElement("a");Cs.href=Js,Cs.download=Vt,Cs.rel="noreferrer",document.body.appendChild(Cs),Cs.click(),Cs.remove(),URL.revokeObjectURL(Js),ae.success("Download started",{id:"download"})}catch(Pt){console.error("Download error:",Pt),ae.error("Could not force download (your browser may block it).",{id:"download"})}},vt=async ms=>{b(ms),ne(!0),K(""),W(!0);try{const{data:Pt,error:Jt}=await q.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:ms.bunny_video_id,title:ms.title,isAgentVideo:!0,shareToken:ms.share_token}});if(Jt||!(Pt!=null&&Pt.html))throw new Error("Failed to generate CRM embed code");K(Pt.html)}catch(Pt){console.error("CRM embed error:",Pt),ae.error("Failed to generate CRM embed code"),W(!1)}finally{ne(!1)}},Bt=ms=>{b(ms),A(!0)},Zt=async()=>{if(j)try{await l.mutateAsync({id:j.id,bunnyVideoId:j.bunny_video_id,hardDelete:!0}),L(!1),b(null),ae.success("Video deleted successfully")}catch{ae.error("Failed to delete video")}};return e.jsx(Ts,{title:"Video Library",description:"Manage your video touches",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Video Library"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage and share your video touches"})]}),e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5 ml-2",children:[e.jsx("button",{onClick:()=>g("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${f==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Videos"}),u&&((Fs=u.team)==null?void 0:Fs.shared_videos_enabled)&&e.jsxs("button",{onClick:()=>g("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${f==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Nn,{className:"h-3.5 w-3.5"}),"Team"]}),e.jsxs("button",{onClick:()=>g("analytics"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${f==="analytics"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(yo,{className:"h-3.5 w-3.5"}),"Analytics"]})]})]}),f==="my"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>M(!0),children:[e.jsx(Na,{className:"h-4 w-4 mr-2"}),"Upload Video"]}),e.jsxs(B,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),f==="team"?e.jsx(LQs,{videos:h,isLoading:p,searchTerm:_,setSearchTerm:v}):f==="analytics"?e.jsx(AQs,{}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:Be?"border-amber-500":Ye?"border-destructive":"",children:e.jsxs(Ee,{className:"py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(i9,{className:`h-5 w-5 ${Ye?"text-destructive":Be?"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:[it.toFixed(1)," MB / ",je>=1024?`${(je/1024).toFixed(0)} GB`:`${je} MB`]})]}),e.jsx(pi,{value:Math.min(Ge,100),className:`h-2 ${Ye?"[&>div]:bg-destructive":Be?"[&>div]:bg-amber-500":""}`})]}),Be&&!Ye&&e.jsxs(ze,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),Ye&&e.jsxs(ze,{variant:"destructive",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"}),"At Limit"]})]}),Ye&&e.jsx("p",{className:"text-sm text-destructive mt-2",children:"You've reached your storage limit. Delete videos to record more."})]})}),e.jsx("div",{className:"flex gap-1 p-1 bg-muted rounded-lg w-fit",children:[{id:"all",label:"All",count:(t||[]).length},{id:"general",label:"My Videos",count:Ze},{id:"open_house",label:"Open House Tours",count:be}].map(ms=>e.jsxs("button",{onClick:()=>Fe(ms.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Ie===ms.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[ms.label," ",e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:ms.count})]},ms.id))}),e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search videos by contact, title, or notes...",value:_,onChange:ms=>v(ms.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"})}):(qe==null?void 0:qe.length)===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(br,{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(Is,{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:qe==null?void 0:qe.map(ms=>{var Pt,Jt;return e.jsx(IQs,{video:ms,previewSrc:(Pt=Me[ms.id])==null?void 0:Pt.previewUrl,thumbnailSrc:(Jt=Me[ms.id])==null?void 0:Jt.thumbnailUrl,onOpen:()=>Bt(ms),onDelete:()=>{b(ms),L(!0)},onRename:()=>{b(ms),Te(ms.title||""),ve(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${ms.contact_id}`),onGetEmbedCode:()=>{b(ms),z(!0)},onCopyEmailHtml:()=>dt(ms),onEmbedToCrm:()=>vt(ms),onShareWithTemplate:()=>{b(ms),he(!0)},onSendViaGmail:()=>{b(ms),pe(!0)},isGmailConnected:c,getContactName:Ae,getShareUrl:rt,copyToClipboard:We,formatDuration:De},ms.id)})}),e.jsx(bs,{open:S,onOpenChange:A,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:(j==null?void 0:j.title)||"Video Preview"}),e.jsx(Qn,{children:(j==null?void 0:j.contact_id)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xi,{className:"h-3 w-3"}),Ae(j.contact_id)]})})]}),j&&e.jsxs("div",{className:"space-y-4",children:[j.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(ts,{className:"h-8 w-8 text-primary animate-spin"})})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Video is still processing"}),e.jsx("p",{className:"text-muted-foreground text-sm max-w-sm",children:"Your video is being encoded and will be ready shortly. This usually takes 1–3 minutes. Check back soon!"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{A(!1),r()},children:[e.jsx(Ti,{className:"h-4 w-4 mr-2"}),"Refresh Library"]})]}):e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:j.playback_url?(()=>{let ms=j.playback_url;return ms.includes("iframe.mediadelivery.net/play/")&&(ms=ms.replace("/play/","/embed/"),ms+=(ms.includes("?")?"&":"?")+"autoplay=false&responsive=true"),ms.includes("iframe.mediadelivery.net")?e.jsx("iframe",{src:ms,title:j.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:j.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:j.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>ae.error("Video preview failed to load")},j.playback_url)})():e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-muted rounded-lg",children:[e.jsx(br,{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:()=>tt(j),children:[e.jsx(Ei,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs(B,{variant:"outline",onClick:()=>at(j),children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(B,{variant:"outline",onClick:()=>We(rt(j),"Share link"),children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(B,{variant:"outline",onClick:()=>dt(j),children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(B,{variant:"outline",onClick:()=>bt(j),children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs(B,{variant:"outline",onClick:()=>{A(!1),vt(j)},children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),e.jsxs(B,{variant:"outline",onClick:()=>{A(!1),he(!0)},children:[e.jsx(fl,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]}),c&&(j==null?void 0:j.share_token)&&e.jsxs(B,{variant:"outline",onClick:()=>{A(!1),pe(!0)},children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]})]}),e.jsx("div",{className:"flex justify-end pt-2 border-t",children:e.jsxs(B,{variant:"destructive",onClick:()=>{A(!1),L(!0)},children:[e.jsx(_n,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(bs,{open:T,onOpenChange:L,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Delete Video"}),e.jsx(Qn,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>L(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Zt,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(F_t,{open:D,onOpenChange:M}),e.jsx(bs,{open:F,onOpenChange:z,children:e.jsxs(vs,{className:"sm:max-w-lg",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Embed Video"}),e.jsx(Qn,{children:"Copy this code to embed the video on your website."})]}),j&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Embed Code"}),e.jsx(Es,{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 ms=``;We(ms,"Embed code")},children:[e.jsx(Xr,{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."})]})]})}),j&&e.jsx(_2t,{open:ie,onOpenChange:he,video:j,contactName:Ae(j.contact_id)}),j&&e.jsx(SQs,{open:ce,onOpenChange:pe,video:j,gmailEmail:d,signedThumbnailUrl:(Rs=Me[j.id])==null?void 0:Rs.thumbnailUrl}),e.jsx(bs,{open:le,onOpenChange:ve,children:e.jsxs(vs,{className:"max-w-sm",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Rename Video"}),e.jsx(Qn,{children:"Enter a new title for this video."})]}),e.jsx(ye,{value:ge,onChange:ms=>Te(ms.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:ms=>{ms.key==="Enter"&&ge.trim()&&o.mutate({id:j.id,title:ge.trim()},{onSuccess:()=>{ae.success("Video renamed"),ve(!1)}})}}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>ve(!1),children:"Cancel"}),e.jsx(B,{disabled:!ge.trim()||o.isPending,onClick:()=>{o.mutate({id:j.id,title:ge.trim()},{onSuccess:()=>{ae.success("Video renamed"),ve(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(bs,{open:V,onOpenChange:W,children:e.jsxs(vs,{className:"sm:max-w-lg",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(tr,{className:"h-5 w-5"}),"Embed to CRM"]}),e.jsx(Qn,{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."})]}),J?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ts,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):Y?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(Es,{readOnly:!0,rows:12,value:Y,className:"font-mono text-xs"})]}),e.jsxs(B,{className:"w-full",onClick:()=>{We(Y,"CRM embed code")},children:[e.jsx(Xr,{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 LQs({videos:s,isLoading:t,searchTerm:n,setSearchTerm:r}){const a=N.useMemo(()=>{if(!n)return s;const o=n.toLowerCase();return s.filter(c=>(c.title||"").toLowerCase().includes(o)||(c.owner_name||"").toLowerCase().includes(o)||(c.recipient_name||"").toLowerCase().includes(o))},[s,n]),i=N.useMemo(()=>{const o=new Map;return a.forEach(c=>{const d=o.get(c.owner_user_id);d?d.videos.push(c):o.set(c.owner_user_id,{name:c.owner_name,avatar:c.owner_avatar_url,videos:[c]})}),Array.from(o.entries())},[a]),l=o=>{if(!o)return"0:00";const c=Math.floor(o/60),d=o%60;return`${c}:${d.toString().padStart(2,"0")}`};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(vr,{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(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(Nn,{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(ni,{src:c.avatar||""}),e.jsx(aa,{children:(c.name||"?").charAt(0).toUpperCase()})]}),e.jsx("h3",{className:"font-semibold text-sm",children:c.name}),e.jsx(ze,{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(fe,{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(br,{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(Ee,{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(Xi,{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(Er,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),Ss(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const DQs=()=>{const{user:s}=ys();return ct({queryKey:["team-deals",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.rpc("get_team_deals",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},rXe=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function RQs({open:s,onOpenChange:t}){const{data:n,isLoading:r}=DQs(),[a,i]=N.useState(""),[l,o]=N.useState("all"),c=N.useMemo(()=>{if(!n)return new Map;const g=new Map;let _=0;return n.forEach(v=>{g.has(v.owner_user_id)||(g.set(v.owner_user_id,{name:v.owner_name||"Unknown",avatar:v.owner_avatar_url,color:rXe[_%rXe.length]}),_++)}),g},[n]),d=N.useMemo(()=>Array.from(c.entries()).map(([g,_])=>({id:g,..._})),[c]),u=N.useMemo(()=>{if(!n)return[];let g=n;if(l!=="all"&&(g=g.filter(_=>_.owner_user_id===l)),a.trim()){const _=a.toLowerCase();g=g.filter(v=>{var j,b,S,A;return v.deal_name.toLowerCase().includes(_)||((j=v.contact_name)==null?void 0:j.toLowerCase().includes(_))||((b=v.property_address)==null?void 0:b.toLowerCase().includes(_))||((S=v.city)==null?void 0:S.toLowerCase().includes(_))||((A=v.owner_name)==null?void 0:A.toLowerCase().includes(_))})}return g},[n,a,l]),h=N.useMemo(()=>{const g=new Map;return u.forEach(_=>{const v=_.stage_name||"Unknown";g.has(v)||g.set(v,{name:v,color:_.stage_color,icon:_.stage_icon,deals:[],totalValue:0});const j=g.get(v);j.deals.push(_),j.totalValue+=_.sale_price||0}),Array.from(g.values())},[u]),p=g=>g>=1e6?`$${(g/1e6).toFixed(1)}M`:g>=1e3?`$${(g/1e3).toFixed(0)}K`:`$${g.toFixed(0)}`,f=g=>g?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(g):null;return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-[95vw] w-full max-h-[90vh] flex flex-col",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5"}),"Team Pipeline"]})}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("div",{className:"relative flex-1 max-w-xs",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search deals...",value:a,onChange:g=>i(g.target.value),className:"pl-9"})]}),e.jsxs(ds,{value:l,onValueChange:o,children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(us,{placeholder:"All Members"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Members"}),d.map(g=>e.jsx(Qe,{value:g.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full inline-block",style:{backgroundColor:g.color}}),g.name]})},g.id))]})]}),e.jsxs("div",{className:"hidden md:flex items-center gap-3 ml-auto text-xs text-muted-foreground",children:[d.slice(0,6).map(g=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:g.color}}),g.name.split(" ")[0]]},g.id)),d.length>6&&e.jsxs("span",{children:["+",d.length-6," more"]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden mt-2",children:r?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(g=>e.jsxs("div",{className:"min-w-[260px] flex-1",children:[e.jsx(Ws,{className:"h-12 w-full mb-2 rounded-lg"}),e.jsx(Ws,{className:"h-24 w-full mb-2 rounded-lg"}),e.jsx(Ws,{className:"h-24 w-full rounded-lg"})]},g))}):h.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Nn,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No team deals found"}),e.jsx("p",{className:"text-sm",children:"Team members' deals will appear here."})]})}):e.jsx("div",{className:"flex gap-3 h-full overflow-x-auto pb-2",children:h.map(g=>{const _=g.icon&&T0e[g.icon]||lm;return e.jsxs("div",{className:"flex flex-col h-full min-w-[260px] max-w-[300px] flex-1 bg-muted/30 rounded-xl border border-border/50",children:[e.jsxs("div",{className:"p-3 border-b border-border/50 shrink-0",style:{borderTopColor:g.color||"hsl(var(--border))",borderTopWidth:3},children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-md flex items-center justify-center",style:{backgroundColor:g.color?`${g.color}20`:void 0},children:e.jsx(_,{className:"h-3.5 w-3.5",style:{color:g.color||void 0}})}),e.jsx("h3",{className:"font-semibold text-sm",children:g.name})]}),e.jsx(ze,{variant:"secondary",className:"text-xs px-2",children:g.deals.length})]}),g.totalValue>0&&e.jsx("p",{className:"text-xs text-muted-foreground ml-8",children:p(g.totalValue)})]}),e.jsx(hi,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:g.deals.map(v=>{const j=c.get(v.owner_user_id);return e.jsx(OQs,{deal:v,ownerColor:(j==null?void 0:j.color)||"#888",ownerName:(j==null?void 0:j.name)||"Unknown",ownerAvatar:(j==null?void 0:j.avatar)||null,formatPrice:f},v.id)})})})]},g.name)})})}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center pt-2 border-t shrink-0",children:[u.length," deal",u.length!==1?"s":""," across ",h.length," stage",h.length!==1?"s":""," from ",d.length," member",d.length!==1?"s":""]})]})})}function OQs({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(ni,{src:r||""}),e.jsx(aa,{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(ze,{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(Or,{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(Zl,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function FQs({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(Nn,{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(pl,{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(hi,{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(ni,{src:l.avatar_url||""}),e.jsx(aa,{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(bn,{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(ni,{src:l.avatar_url||""}),e.jsx(aa,{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 aXe=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function zQs(){const s=ma(),{data:t}=Zv(),n=(t==null?void 0:t.role)==="team_leader",r=t==null?void 0:t.teamId,a=ct({queryKey:["team-pipeline-members",r,s],queryFn:async()=>{const{data:i,error:l}=await q.from("team_members").select("user_id, role").eq("team_id",r).neq("user_id",s);if(l)throw l;if(!i||i.length===0)return[];const o=i.map(u=>u.user_id),{data:c,error:d}=await q.from("profiles").select("id, name, avatar_url").in("id",o);if(d)throw d;return(c||[]).map((u,h)=>({id:u.id,name:u.name||"Unknown",avatar_url:u.avatar_url,color:aXe[h%aXe.length]}))},enabled:!!r&&!!s&&n,staleTime:5*60*1e3});return{isTeamLeader:n,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function BQs(s){return ct({queryKey:["team-member-deals",s],queryFn:async()=>{if(s.length===0)return[];const{data:t,error:n}=await q.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at), deal_pipeline_stages(name) `).in("owner_user_id",s).order("updated_at",{ascending:!1});if(n)throw n;return(t||[]).map(r=>{var a;return{...r,_stage_name:((a=r.deal_pipeline_stages)==null?void 0:a.name)||null}})},enabled:s.length>0})}function $Qs(){const s=ma();return ct({queryKey:["all-deal-tags-map",s],queryFn:async()=>{if(!s)return{tags:[],byDeal:{},unique:[]};const{data:t,error:n}=await q.from("deal_tags").select("id, deal_id, tag").eq("owner_user_id",s);if(n)throw n;const r=t||[],a={},i=new Set;r.forEach(o=>{a[o.deal_id]||(a[o.deal_id]=[]),a[o.deal_id].push(o.tag),i.add(o.tag)});const l=Array.from(i).sort((o,c)=>o.localeCompare(c));return{tags:r,byDeal:a,unique:l}},enabled:!!s})}function w2t({stages:s,currentStageId:t,onStageSelect:n,disabled:r}){const[a,i]=N.useState(!1),l=s.find(c=>c.id===t),o=c=>{c.id!==t&&n(c.id,c.name),i(!1)};return e.jsxs(wc,{open:a,onOpenChange:i,children:[e.jsx(jc,{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(xa,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(cc,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&T0e[c.icon]||lm,u=c.id===t;return e.jsxs(Qr,{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(Ir,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const UQs={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"}},qQs={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 j2t({deal:s,onClick:t,isDragging:n,stages:r,onStageChange:a,showStagePicker:i=!1,isWonStage:l=!1,ownerInfo:o=null}){var b,S;const c=wR(),d=UQs[s.deal_type],u=qQs[s.priority],h=N.useMemo(()=>s.target_close_date?Wv(Cl(s.target_close_date),new Date):null,[s.target_close_date]),p=h!==null&&h<0,f=h!==null&&h<=7&&h>=0,g=N.useMemo(()=>{var L;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const A=((L=s.listing)==null?void 0:L.created_at)||s.listing_date;if(!A)return null;const T=s.contract_date?Cl(s.contract_date):new Date;return Wv(T,Cl(A))},[s]),_=l&&!s.scorecard_transaction_id,v=!!s.scorecard_transaction_id,j=A=>A?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(A):null;return e.jsx(fe,{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",p&&"border-red-200 bg-red-50/30",_&&"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(Ee,{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(ni,{src:o.avatar_url||""}),e.jsx(aa,{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(ze,{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(aa,{className:"text-[10px] bg-primary/10 text-primary",children:[(b=s.contact.first_name)==null?void 0:b[0],(S=s.contact.last_name)==null?void 0:S[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(El,{className:"h-3 w-3 text-primary shrink-0"}),e.jsx("span",{className:"text-primary truncate",children:"Linked to Listing Exchange"})]}),_&&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(vo,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate font-medium",children:"Add to Scorecard"})]}),v&&l&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400",children:[e.jsx(xr,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:"Synced to Scorecard"})]}),g!==null&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(om,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:Et("font-medium",g>90?"text-red-600":g>60?"text-amber-600":"text-muted-foreground"),children:[g," DOM"]}),s.contract_date&&e.jsx("span",{className:"text-muted-foreground",children:"(final)"})]}),!s.listing&&(s.property_address||s.city)&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Or,{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(Zl,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:j(s.expected_price)}),s.expected_commission&&e.jsxs("span",{className:"text-muted-foreground",children:["• ",j(s.expected_commission)," GCI"]}),(()=>{const A=Cv(s);return A!==null&&A!==s.expected_commission?e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:["• ",j(A)," Net"]}):null})()]}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className: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(w2t,{stages:r,currentStageId:s.stage_id||"",onStageSelect:(A,T)=>a(s.id,A,T)}):s.target_close_date?e.jsxs("div",{className:Et("flex items-center gap-1 text-[10px]",p&&"text-red-600",f&&!p&&"text-amber-600",!p&&!f&&"text-muted-foreground"),children:[p?e.jsx(Gi,{className:"h-3 w-3"}):e.jsx(yr,{className:"h-3 w-3"}),e.jsx("span",{children:p?`${Math.abs(h)}d overdue`:f?`${h}d left`:Ss(Cl(s.target_close_date),"MMM d")})]}):null]})]})})}function VQs({stage:s,deals:t,onDealClick:n,onAddDeal:r,onDragStart:a,onDragOver:i,onDrop:l,isDragOver:o,isWonStage:c=!1,getOwnerInfo:d}){const u=N.useRef(null),h=t.reduce((v,j)=>v+(j.expected_price||0),0),p=t.reduce((v,j)=>v+(j.expected_commission||0),0),f=t.reduce((v,j)=>v+(Cv(j)||0),0),g=v=>v>=1e6?`$${(v/1e6).toFixed(1)}M`:v>=1e3?`$${(v/1e3).toFixed(0)}K`:`$${v.toFixed(0)}`,_=s.icon&&T0e[s.icon]||lm;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:v=>i(v,s.id),onDrop:v=>l(v,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(_,{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(ze,{variant:"secondary",className:"text-xs font-medium px-2",children:t.length})]}),h>0&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:g(h)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[g(p)," GCI"]}),f>0&&f!==p&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:[g(f)," Net"]})]})]})]}),e.jsx(hi,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(v=>e.jsx("div",{draggable:!0,onDragStart:j=>{j.dataTransfer.effectAllowed="move",a(v.id,s.id)},children:e.jsx(j2t,{deal:v,onClick:()=>n(v),isWonStage:c,ownerInfo:(d==null?void 0:d(v))||null})},v.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(Is,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}function HQs({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:Oc,color:"text-blue-500",bgColor:"bg-blue-500/10"},{label:"Weighted GCI",value:n((s==null?void 0:s.weightedGCI)||0),icon:N9,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:jL,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:ZS,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:mo,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(fe,{className:"animate-pulse",children:e.jsx(Ee,{className:"p-4",children:e.jsx("div",{className:"h-10 bg-muted rounded"})})},a))}):e.jsx(Ww,{children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:r.map(a=>{const i=e.jsx(fe,{className:"border-border/50 hover:shadow-sm transition-shadow",children:e.jsx(Ee,{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(Ec,{children:[e.jsx(Ac,{asChild:!0,children:i}),e.jsx(vc,{children:e.jsx("p",{children:a.tooltip})})]},a.label):i})})})}function GQs({formData:s,onChange:t,isEditing:n}){const{isAdmin:r}=ys(),[a,i]=N.useState(s.portal_enabled);if(!r)return e.jsxs("div",{className:"border rounded-lg p-4 opacity-60",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(ze,{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(dy,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(uy,{className:"w-full p-4 flex items-center justify-between hover:bg-muted/50 transition-colors rounded-t-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),s.portal_enabled&&e.jsx(ze,{className:"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200",variant:"outline",children:"Enabled"})]}),e.jsx(io,{className:Et("h-4 w-4 text-muted-foreground transition-transform",a&&"rotate-180")})]}),e.jsx(hy,{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(bn,{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(cb,{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(Rd,{value:"private"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Kc,{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(Rd,{value:"public"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(lc,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm font-medium",children:"Public"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Shareable link"})]})]})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/30",children:[e.jsx(ui,{id:"require_onboarding",checked:s.require_onboarding,onCheckedChange:o=>l({require_onboarding:!!o}),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"require_onboarding",className:"text-sm font-medium cursor-pointer",children:"Require client onboarding before portal access"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Client confirms contact details + preferences before viewing portal. Info is saved to your contacts."})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ui,{id:"allow_spouse",checked:s.allow_spouse,onCheckedChange:o=>l({allow_spouse:!!o})}),e.jsx(se,{htmlFor:"allow_spouse",className:"text-sm cursor-pointer",children:"Allow client to add spouse/partner during onboarding"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"text-sm font-medium",children:"Client Invite Details"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Client Full Name"}),e.jsx(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(ds,{value:s.invite_method,onValueChange:o=>l({invite_method:o}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"email",children:"Email"}),e.jsxs(Qe,{value:"sms",disabled:!s.client_phone,children:["SMS ",!s.client_phone&&"(add phone first)"]})]})]})]})]})]})]})]})})]})})}const WQs=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],KQs=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function YQs({open:s,onOpenChange:t,deal:n,defaultStageId:r}){const{data:a}=KU(),{data:i}=ox(),{data:l}=rpt(),o=Uye(),c=g2t(),d=y2t(),u=vLe(),[h,p]=N.useState({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"}),[f,g]=N.useState(""),[_,v]=N.useState(!1),[j,b]=N.useState(!1),[S,A]=N.useState({first_name:"",last_name:"",email:"",phone:""}),T=(l==null?void 0:l.filter(Y=>((n==null?void 0:n.listing_id)===Y.id,!0)))||[],[L,D]=N.useState({deal_name:"",deal_type:"buyer",stage_id:"",contact_id:"",listing_id:"",property_address:"",city:"",state:"",zip_code:"",expected_price:"",commission_percentage:"3",brokerage_split_pct:"",team_split_pct:"",referral_fee_pct:"",franchise_fee_pct:"",transaction_fee:"",commission_calc_method:"standard",target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:"50",notes:""});N.useEffect(()=>{var Y,K,J,ne,ie,he,ce,pe;s&&(n?(D({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:((Y=n.expected_price)==null?void 0:Y.toString())||"",commission_percentage:((K=n.commission_percentage)==null?void 0:K.toString())||"3",brokerage_split_pct:((J=n.brokerage_split_pct)==null?void 0:J.toString())||"",team_split_pct:((ne=n.team_split_pct)==null?void 0:ne.toString())||"",referral_fee_pct:((ie=n.referral_fee_pct)==null?void 0:ie.toString())||"",franchise_fee_pct:((he=n.franchise_fee_pct)==null?void 0:he.toString())||"",transaction_fee:((ce=n.transaction_fee)==null?void 0:ce.toString())||"",commission_calc_method:n.commission_calc_method||"standard",target_close_date:n.target_close_date?Cl(n.target_close_date):void 0,contract_date:n.contract_date?Cl(n.contract_date):void 0,listing_date:n.listing_date?Cl(n.listing_date):void 0,priority:n.priority,probability:n.probability.toString(),notes:n.notes||""}),n.contact&&g(`${n.contact.first_name} ${n.contact.last_name}`)):(D({deal_name:"",deal_type:"buyer",stage_id:r||((pe=a==null?void 0:a[0])==null?void 0:pe.id)||"",contact_id:"",listing_id:"",property_address:"",city:"",state:"",zip_code:"",expected_price:"",commission_percentage:"3",brokerage_split_pct:"",team_split_pct:"",referral_fee_pct:"",franchise_fee_pct:"",transaction_fee:"",commission_calc_method:"standard",target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:"50",notes:""}),g(""),p({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"})))},[s,n,r,a]);const M=i==null?void 0:i.filter(Y=>{var ve,ge,Te,Me,Ce;const K=f.toLowerCase().trim();if(!K)return!0;const J=((ve=Y.first_name)==null?void 0:ve.toLowerCase())||"",ne=((ge=Y.last_name)==null?void 0:ge.toLowerCase())||"",ie=((Te=Y.email)==null?void 0:Te.toLowerCase())||"",he=((Ce=(Me=Y.phone)==null?void 0:Me.toLowerCase)==null?void 0:Ce.call(Me))||"",ce=`${J} ${ne}`.trim(),pe=`${ne} ${J}`.trim();if(ce.includes(K)||pe.includes(K)||J.includes(K)||ne.includes(K)||ie.includes(K)||he.includes(K))return!0;const le=K.split(/\s+/).filter(Boolean);return le.length>1?le.every(Ae=>J.includes(Ae)||ne.includes(Ae)||ie.includes(Ae)||he.includes(Ae)):!1}).slice(0,8),F=()=>{const Y=parseFloat(L.expected_price)||0,K=parseFloat(L.commission_percentage)||0;return Y*(K/100)},z=()=>{const Y=F();if(!Y)return null;const K=parseFloat(L.brokerage_split_pct)||0,J=parseFloat(L.team_split_pct)||0,ne=parseFloat(L.referral_fee_pct)||0,ie=parseFloat(L.franchise_fee_pct)||0,he=parseFloat(L.transaction_fee)||0;if(L.commission_calc_method==="referral_first"){let pe=Y;ne&&(pe-=Y*ne/100);let le=pe;return K&&(le-=pe*K/100),J&&(le-=Y*J/100),ie&&(le-=Y*ie/100),he&&(le-=he),Math.max(0,le)}let ce=Y;return K&&(ce=ce*((100-K)/100)),J&&(ce=ce*((100-J)/100)),ne&&(ce=ce-Y*ne/100),ie&&(ce=ce-Y*ie/100),he&&(ce=ce-he),Math.max(0,ce)},V=async Y=>{var K,J,ne;if(Y.preventDefault(),!L.deal_name.trim()){ae.error("Please enter a deal name");return}try{const ie={deal_name:L.deal_name,deal_type:L.deal_type,stage_id:L.stage_id||null,contact_id:L.contact_id||null,listing_id:L.listing_id||null,property_address:L.property_address||null,city:L.city||null,state:L.state||null,zip_code:L.zip_code||null,expected_price:L.expected_price?parseFloat(L.expected_price):null,expected_commission:F()||null,commission_percentage:L.commission_percentage?parseFloat(L.commission_percentage):3,brokerage_split_pct:L.brokerage_split_pct?parseFloat(L.brokerage_split_pct):null,team_split_pct:L.team_split_pct?parseFloat(L.team_split_pct):null,referral_fee_pct:L.referral_fee_pct?parseFloat(L.referral_fee_pct):null,franchise_fee_pct:L.franchise_fee_pct?parseFloat(L.franchise_fee_pct):null,transaction_fee:L.transaction_fee?parseFloat(L.transaction_fee):null,commission_calc_method:L.commission_calc_method,target_close_date:((K=L.target_close_date)==null?void 0:K.toISOString().split("T")[0])||null,contract_date:((J=L.contract_date)==null?void 0:J.toISOString().split("T")[0])||null,listing_date:((ne=L.listing_date)==null?void 0:ne.toISOString().split("T")[0])||null,priority:L.priority,probability:parseInt(L.probability)||50,notes:L.notes||null};if(n)await d.mutateAsync({id:n.id,...ie}),ae.success("Deal updated successfully");else{const he=await c.mutateAsync(ie);if(ae.success("Deal created successfully"),h.portal_enabled&&(he!=null&&he.id))try{await u.mutateAsync({deal_id:he.id,visibility:h.visibility,require_onboarding:h.require_onboarding,allow_spouse:h.allow_spouse,client_name:h.client_name||null,client_email:h.client_email||null,client_phone:h.client_phone||null,invite_method:h.invite_method}),ae.success("Client portal created!")}catch{ae.error("Deal created, but portal setup failed")}}t(!1)}catch{ae.error("Failed to save deal")}},W=c.isPending||d.isPending;return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:n?"Edit Deal":"Add New Deal"}),e.jsx(Qn,{children:n?"Update the deal details below.":"Enter the details for your new deal."})]}),e.jsxs("form",{onSubmit:V,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:L.deal_name,onChange:Y=>D(K=>({...K,deal_name:Y.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(ds,{value:L.deal_type,onValueChange:Y=>D(K=>({...K,deal_type:Y})),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:WQs.map(Y=>e.jsx(Qe,{value:Y.value,children:Y.label},Y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Stage"}),e.jsxs(ds,{value:L.stage_id||"none",onValueChange:Y=>D(K=>({...K,stage_id:Y==="none"?"":Y})),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select stage"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"No Stage"}),a==null?void 0:a.map(Y=>e.jsx(Qe,{value:Y.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:Y.color}}),Y.name]})},Y.id))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Link to Contact"}),e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:f,onChange:Y=>{g(Y.target.value),v(!0),b(!1),Y.target.value||D(K=>({...K,contact_id:""}))},onFocus:()=>v(!0),placeholder:"Search contacts...",className:"pl-9"}),_&&f&&e.jsxs("div",{className:"absolute z-10 w-full mt-1 bg-background border rounded-lg shadow-lg max-h-60 overflow-y-auto",children:[M&&M.length>0?M.map(Y=>e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2",onClick:()=>{D(K=>({...K,contact_id:Y.id})),g(`${Y.first_name} ${Y.last_name}`),v(!1)},children:[e.jsx(Xi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[Y.first_name," ",Y.last_name]}),Y.email&&e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:Y.email})]},Y.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 Y=f.trim().split(/\s+/);A({first_name:Y[0]||"",last_name:Y.slice(1).join(" ")||"",email:"",phone:""}),b(!0),v(!1)},children:[e.jsx(Fo,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',f.trim(),'"']})]})]})]}),j&&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(Fo,{className:"h-3.5 w-3.5"}),"Quick Add Contact"]}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>b(!1),children:"Cancel"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ye,{placeholder:"First name *",value:S.first_name,onChange:Y=>A(K=>({...K,first_name:Y.target.value})),className:"h-8 text-sm"}),e.jsx(ye,{placeholder:"Last name",value:S.last_name,onChange:Y=>A(K=>({...K,last_name:Y.target.value})),className:"h-8 text-sm"}),e.jsx(ye,{placeholder:"Email",type:"email",value:S.email,onChange:Y=>A(K=>({...K,email:Y.target.value})),className:"h-8 text-sm"}),e.jsx(ye,{placeholder:"Phone",type:"tel",value:S.phone,onChange:Y=>A(K=>({...K,phone:Y.target.value})),className:"h-8 text-sm"})]}),e.jsx(B,{type:"button",size:"sm",className:"w-full h-8",disabled:!S.first_name.trim()||o.isPending,onClick:async()=>{try{const Y=await o.mutateAsync({first_name:S.first_name.trim(),last_name:S.last_name.trim()||null,email:S.email.trim()||null,phone:S.phone.trim()||null});Y&&(D(K=>({...K,contact_id:Y.id})),g(`${Y.first_name} ${Y.last_name||""}`.trim()),b(!1))}catch{}},children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Fo,{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(El,{className:"h-4 w-4"}),"Link to Listing Exchange"]}),e.jsxs(ds,{value:L.listing_id||"none",onValueChange:Y=>{const K=Y==="none"?"":Y,J=T.find(ne=>ne.id===K);D(J?ne=>{var ie;return{...ne,listing_id:K,deal_type:"seller",property_address:J.property_address||ne.property_address,city:J.city||ne.city,state:J.state||ne.state,expected_price:((ie=J.price)==null?void 0:ie.toString())||ne.expected_price}}:ne=>({...ne,listing_id:K}))},children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select a listing to sync status..."})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"None"}),T.map(Y=>e.jsx(Qe,{value:Y.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:Y.property_address||`${Y.city}, ${Y.state}`}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["$",(Y.price/1e3).toFixed(0),"K"]})]})},Y.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:L.property_address,onChange:Y=>D(K=>({...K,property_address:Y.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:L.city,onChange:Y=>D(K=>({...K,city:Y.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:L.state,onChange:Y=>D(K=>({...K,state:Y.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:L.zip_code,onChange:Y=>D(K=>({...K,zip_code:Y.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:L.expected_price,onChange:Y=>D(K=>({...K,expected_price:Y.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:L.commission_percentage,onChange:Y=>D(K=>({...K,commission_percentage:Y.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:F()?`$${F().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(ds,{value:L.commission_calc_method,onValueChange:Y=>D(K=>({...K,commission_calc_method:Y})),children:[e.jsx(ls,{className:"h-7 text-xs",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"standard",children:"Standard (all splits on GCI)"}),e.jsx(Qe,{value:"referral_first",children:"Referral First (brokerage split after referral)"})]})]})]}),L.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:L.brokerage_split_pct,onChange:Y=>D(K=>({...K,brokerage_split_pct:Y.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:L.team_split_pct,onChange:Y=>D(K=>({...K,team_split_pct:Y.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:L.referral_fee_pct,onChange:Y=>D(K=>({...K,referral_fee_pct:Y.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:L.franchise_fee_pct,onChange:Y=>D(K=>({...K,franchise_fee_pct:Y.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:L.transaction_fee,onChange:Y=>D(K=>({...K,transaction_fee:Y.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:z()?`$${Math.round(z()).toLocaleString()}`:"-",disabled:!0,className:"bg-muted h-8 text-sm font-semibold"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Dates & Status"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Target Close Date"}),e.jsxs(el,{children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal",!L.target_close_date&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),L.target_close_date?Ss(L.target_close_date,"PPP"):"Pick a date"]})}),e.jsx(Ho,{className:"w-auto p-0",align:"start",children:e.jsx(Kg,{mode:"single",selected:L.target_close_date,onSelect:Y=>D(K=>({...K,target_close_date:Y})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Contract Date"}),e.jsxs(el,{children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal",!L.contract_date&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),L.contract_date?Ss(L.contract_date,"PPP"):"Pick a date"]})}),e.jsx(Ho,{className:"w-auto p-0",align:"start",children:e.jsx(Kg,{mode:"single",selected:L.contract_date,onSelect:Y=>D(K=>({...K,contract_date:Y})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),(L.deal_type==="seller"||L.deal_type==="dual")&&!L.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(el,{children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal",!L.listing_date&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),L.listing_date?Ss(L.listing_date,"PPP"):"Pick a date"]})}),e.jsx(Ho,{className:"w-auto p-0",align:"start",children:e.jsx(Kg,{mode:"single",selected:L.listing_date,onSelect:Y=>D(K=>({...K,listing_date:Y})),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(ds,{value:L.priority,onValueChange:Y=>D(K=>({...K,priority:Y})),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:KQs.map(Y=>e.jsx(Qe,{value:Y.value,children:Y.label},Y.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:L.probability,onChange:Y=>D(K=>({...K,probability:Y.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(Es,{id:"notes",value:L.notes,onChange:Y=>D(K=>({...K,notes:Y.target.value})),placeholder:"Add any additional notes about this deal...",rows:3})]}),!n&&e.jsx(GQs,{formData:h,onChange:p}),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:W,children:[W&&e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Update Deal":"Create Deal"]})]})]})]})})}function ZQs({dealId:s}){const t=ma(),n=Ht(),[r,a]=N.useState(""),[i,l]=N.useState(!1),{data:o=[]}=ct({queryKey:["deal-tags",s],queryFn:async()=>{const{data:g,error:_}=await q.from("deal_tags").select("*").eq("deal_id",s).order("created_at");if(_)throw _;return g},enabled:!!s}),{data:c=[]}=ct({queryKey:["all-deal-tags",t],queryFn:async()=>{if(!t)return[];const{data:g,error:_}=await q.from("deal_tags").select("tag").eq("owner_user_id",t);if(_)throw _;return[...new Set(g.map(j=>j.tag))].sort()},enabled:!!t}),d=gt({mutationFn:async g=>{if(!t)throw new Error("Not authenticated");const{error:_}=await q.from("deal_tags").insert({deal_id:s,owner_user_id:t,tag:g.trim()});if(_)throw _},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]}),n.invalidateQueries({queryKey:["all-deal-tags"]}),a("")}}),u=gt({mutationFn:async g=>{const{error:_}=await q.from("deal_tags").delete().eq("id",g);if(_)throw _},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]})}}),h=()=>{const g=r.trim();g&&(o.some(_=>_.tag.toLowerCase()===g.toLowerCase())||d.mutate(g))},p=o.map(g=>g.tag.toLowerCase()),f=c.filter(g=>g.toLowerCase().includes(r.toLowerCase())&&!p.includes(g.toLowerCase())).slice(0,5);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[o.map(g=>e.jsxs(ze,{variant:"secondary",className:"gap-1 text-xs",children:[g.tag,e.jsx("button",{type:"button",onClick:()=>u.mutate(g.id),className:"ml-0.5 hover:text-destructive",children:e.jsx(Bn,{className:"h-3 w-3"})})]},g.id)),!i&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground px-2 py-0.5 rounded border border-dashed border-border hover:border-primary transition-colors",children:[e.jsx(Is,{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:g=>a(g.target.value),onKeyDown:g=>{g.key==="Enter"&&(g.preventDefault(),h()),g.key==="Escape"&&(l(!1),a(""))},placeholder:"Type tag name...",className:"h-8 text-xs flex-1",autoFocus:!0}),e.jsx("button",{type:"button",onClick:h,disabled:!r.trim()||d.isPending,className:"h-8 px-3 rounded-md bg-primary text-primary-foreground text-xs font-medium disabled:opacity-50 shrink-0",children:"Add"}),e.jsx("button",{type:"button",onClick:()=>{l(!1),a("")},className:"h-8 px-2 rounded-md bg-muted text-muted-foreground text-xs shrink-0",children:"Cancel"})]}),r&&f.length>0&&e.jsx("div",{className:"absolute z-20 w-full mt-1 bg-background border rounded shadow-lg max-h-32 overflow-y-auto",children:f.map(g=>e.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-xs hover:bg-muted active:bg-muted",onClick:_=>{_.preventDefault(),d.mutate(g)},children:g},g))})]})]})}function QQs(s){return ct({queryKey:["deal-files",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_files").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function XQs(){const s=ma(),t=Ht();return gt({mutationFn:async({dealId:n,file:r})=>{if(!s)throw new Error("Not authenticated");const a=r.name.split(".").pop(),i=`${s}/${n}/${crypto.randomUUID()}.${a}`,{error:l}=await q.storage.from("deal-files").upload(i,r);if(l)throw l;const{data:o,error:c}=await q.from("deal_files").insert({deal_id:n,owner_user_id:s,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["deal-files",r.dealId]})}})}function JQs(){const s=Ht();return gt({mutationFn:async({fileId:t,storagePath:n,dealId:r})=>{await q.storage.from("deal-files").remove([n]);const{error:a}=await q.from("deal_files").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}function eXs(){const s=Ht();return gt({mutationFn:async({fileId:t,visible:n,dealId:r})=>{const{error:a}=await q.from("deal_files").update({visible_on_portal:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}async function tXs(s){const{data:t,error:n}=await q.storage.from("deal-files").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const iXe={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function N2t({open:s,onOpenChange:t}){const{data:n,isLoading:r}=CWs(),a=TWs(),i=EWs(),l=AWs(),[o,c]=N.useState(!1),[d,u]=N.useState({question_text:"",field_type:"text",options:[],is_required:!1}),[h,p]=N.useState(""),f=async()=>{if(d.question_text.trim())try{await a.mutateAsync({question_text:d.question_text.trim(),field_type:d.field_type,options:d.field_type==="dropdown"?d.options:[],is_required:d.is_required,sort_order:((n==null?void 0:n.length)||0)+1}),u({question_text:"",field_type:"text",options:[],is_required:!1}),p(""),c(!1),ae.success("Question added")}catch{ae.error("Failed to add question")}},g=async b=>{try{await l.mutateAsync(b),ae.success("Question removed")}catch{ae.error("Failed to remove question")}},_=async(b,S)=>{try{await i.mutateAsync({id:b,is_required:S})}catch{ae.error("Failed to update question")}},v=()=>{h.trim()&&(u(b=>({...b,options:[...b.options,h.trim()]})),p(""))},j=b=>{u(S=>({...S,options:S.options.filter((A,T)=>T!==b)}))};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md max-h-[85vh] flex flex-col",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Custom Intake Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"These questions appear on all your portal onboarding forms."})]}),e.jsx(hi,{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(ts,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),n==null?void 0:n.map(b=>{var S;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(Fu,{className:"h-4 w-4 text-muted-foreground/40 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:b.question_text}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ze,{variant:"secondary",className:"text-xs",children:iXe[b.field_type]||b.field_type}),b.is_required&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"Required"})]}),b.field_type==="dropdown"&&((S=b.options)==null?void 0:S.length)>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Options: ",b.options.join(", ")]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(bn,{checked:b.is_required,onCheckedChange:A=>_(b.id,A),className:"scale-75"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>g(b.id),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})},b.id)}),!r&&(n==null?void 0:n.length)===0&&!o&&e.jsxs("div",{className:"text-center py-8 border border-dashed rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"No custom questions yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add questions that clients will answer during onboarding."})]}),o&&e.jsxs("div",{className:"border-2 border-primary/20 rounded-lg p-4 space-y-3 bg-primary/5",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Question"}),e.jsx(ye,{value:d.question_text,onChange:b=>u(S=>({...S,question_text:b.target.value})),className:"mt-1",placeholder:"e.g., Do you have a home to sell first?",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(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(iXe).map(([b,S])=>e.jsx("button",{type:"button",onClick:()=>u(A=>({...A,field_type:b,options:[]})),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${d.field_type===b?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:S},b))})]}),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((b,S)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"flex-1 text-sm bg-muted/50 rounded px-2 py-1",children:b}),e.jsx("button",{onClick:()=>j(S),className:"text-muted-foreground hover:text-destructive",children:e.jsx(Bn,{className:"h-3.5 w-3.5"})})]},S)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:h,onChange:b=>p(b.target.value),onKeyDown:b=>b.key==="Enter"&&(b.preventDefault(),v()),placeholder:"Add option...",className:"h-8 text-sm"}),e.jsx(B,{variant:"outline",size:"sm",onClick:v,disabled:!h.trim(),className:"h-8",children:e.jsx(Is,{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(bn,{checked:d.is_required,onCheckedChange:b=>u(S=>({...S,is_required:b}))}),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:f,disabled:!d.question_text.trim()||a.isPending,className:"flex-1",children:[a.isPending?e.jsx(ts,{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(Is,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function sXs({override:s,onChange:t}){const n=ma(),{data:r}=Fht(),[a,i]=N.useState(null),l=d=>t({...s,...d}),o=async(d,u)=>{if(n){if(d.size>5*1024*1024){ae.error("Image must be under 5MB");return}i(u);try{const h=await zht(n,d,`${u}`);l(u==="logo"?{logo_url:h}:{cover_photo_url:h})}catch(h){ae.error(`Upload failed: ${h.message||h}`)}finally{i(null)}}},c=Object.values(s||{}).some(d=>d!=null&&d!=="");return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-primary/5 border border-primary/10",children:[e.jsx(un,{className:"h-4 w-4 text-primary shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["These settings ",e.jsx("span",{className:"font-medium text-foreground",children:"override your global Portal Branding"})," for this deal only. Leave any field empty to use your global default."]})]}),e.jsx(oXe,{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(oXe,{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(lXe,{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(lXe,{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(_n,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function oXe({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(nl,{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(ts,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Na,{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(_n,{className:"h-3.5 w-3.5"})})]})]})]})}function lXe({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(_n,{className:"h-3 w-3"})})]})]})}function nXs({portalId:s,agentUserId:t}){const n=Ht(),{data:r,isLoading:a}=ct({queryKey:["portal-vendor-manage",s,t],queryFn:async()=>{const{data:h}=await q.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),p=h==null?void 0:h.brokerage_id,f=q.from("vendors").select("*").eq("is_active",!0),g=p?f.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${p})`):f.eq("owner_type","agent").eq("owner_user_id",t),[{data:_,error:v},{data:j},{data:b}]=await Promise.all([g.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),q.from("agent_vendor_selections").select("vendor_id, is_visible").eq("agent_user_id",t),q.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s)]);if(v)throw v;const S=new Map;(j||[]).forEach(T=>S.set(T.vendor_id,T.is_visible));const A=new Map;return(b||[]).forEach(T=>A.set(T.vendor_id,T.is_visible)),{vendors:_||[],selMap:S,overrideMap:A}}}),i=gt({mutationFn:async({vendorId:h,isVisible:p})=>{const{data:f}=await q.from("portal_vendor_overrides").select("id").eq("portal_id",s).eq("vendor_id",h).maybeSingle();if(f){const{error:g}=await q.from("portal_vendor_overrides").update({is_visible:p}).eq("id",f.id);if(g)throw g}else{const{error:g}=await q.from("portal_vendor_overrides").insert({portal_id:s,vendor_id:h,is_visible:p});if(g)throw g}},onSuccess:()=>{n.invalidateQueries({queryKey:["portal-vendor-manage",s,t]}),n.invalidateQueries({queryKey:["portal-vendors",s]})},onError:h=>ae.error(h.message)});if(a)return e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ts,{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(pb,{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 p=c.get(h.id);if(p!==void 0)return p;if(h.is_required)return!0;const f=o.get(h.id);return f===void 0?!0:f!==!1},u=h=>{var p;return((p=WD.find(f=>f.value===h))==null?void 0:p.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(hi,{className:"h-[400px] rounded-lg border",children:e.jsx("div",{className:"divide-y",children:l.map(h=>{const p=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(ze,{variant:"outline",className:"text-[10px] shrink-0",children:u(h.category)}),h.owner_type==="brokerage"&&e.jsx(ze,{variant:"secondary",className:"text-[10px] shrink-0",children:"Brokerage"}),h.is_required&&e.jsx(ze,{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(bn,{checked:p,disabled:h.is_required||i.isPending,onCheckedChange:f=>i.mutate({vendorId:h.id,isVisible:f})})]},h.id)})})})]})}function rXs({portalId:s,ownerId:t,clientEmail:n,linkedPortalId:r,onLink:a}){const[i,l]=N.useState(""),[o,c]=N.useState(!1),{data:d,isLoading:u}=ct({queryKey:["all-owner-portals",t],queryFn:async()=>{const{data:g,error:_}=await q.from("client_portals").select(` id, slug, client_name, client_email, deal_id, archived_at, deal_pipeline (id, deal_name, deal_type, property_address) `).eq("owner_user_id",t).neq("id",s).is("archived_at",null).eq("is_enabled",!0);if(_)throw _;return g},enabled:o||!!r}),h=N.useMemo(()=>!r||!d?null:d.find(g=>g.id===r),[r,d]),p=N.useMemo(()=>!d||!n?[]:d.filter(g=>{var _;return((_=g.client_email)==null?void 0:_.toLowerCase())===n.toLowerCase()&&g.id!==s}),[d,n,s]),f=N.useMemo(()=>{if(!d||!i.trim())return[];const g=i.toLowerCase();return d.filter(_=>{var j,b,S,A;const v=_.deal_pipeline;return((j=_.client_name)==null?void 0:j.toLowerCase().includes(g))||((b=_.client_email)==null?void 0:b.toLowerCase().includes(g))||((S=v==null?void 0:v.deal_name)==null?void 0:S.toLowerCase().includes(g))||((A=v==null?void 0:v.property_address)==null?void 0:A.toLowerCase().includes(g))})},[d,i]);if(r){const g=h==null?void 0:h.deal_pipeline;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(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(El,{className:"h-4 w-4 text-primary shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:(h==null?void 0:h.client_name)||(g==null?void 0:g.deal_name)||"Linked Portal"}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[(g==null?void 0:g.deal_type)==="listing"?"🏠 Listing":"🔑 Purchase"," · ",(g==null?void 0:g.property_address)||"No address"]})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive shrink-0",onClick:()=>a(null),children:[e.jsx(qA,{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(El,{className:"h-3 w-3 mr-1"}),o?"Cancel":"Link"]})]}),!o&&p.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)"}),p.map(g=>{const _=g.deal_pipeline;return e.jsxs("button",{onClick:()=>a(g.id),className:"w-full flex items-center gap-2 bg-amber-50 border border-amber-200 rounded-lg p-2.5 hover:bg-amber-100 transition-colors text-left",children:[e.jsx(ze,{variant:"outline",className:"text-[10px] shrink-0 bg-amber-100 border-amber-300 text-amber-700",children:(_==null?void 0:_.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:(_==null?void 0:_.deal_name)||g.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:_==null?void 0:_.property_address})]}),e.jsx(El,{className:"h-3.5 w-3.5 text-amber-600 shrink-0"})]},g.id)})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(vr,{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:g=>l(g.target.value),placeholder:"Search by name, email, or address...",className:"pl-8 h-8 text-xs",autoFocus:!0})]}),u&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ts,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),f.length>0&&e.jsx("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:f.map(g=>{const _=g.deal_pipeline;return e.jsxs("button",{onClick:()=>{a(g.id),c(!1),l("")},className:"w-full flex items-center gap-2 border rounded-lg p-2 hover:bg-muted/50 transition-colors text-left",children:[e.jsx(ze,{variant:"outline",className:"text-[10px] shrink-0",children:(_==null?void 0:_.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:(_==null?void 0:_.deal_name)||g.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:g.client_email})]})]},g.id)})}),i&&f.length===0&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No portals found"})]})]})}function b8e({contactId:s,onVideoReady:t}){const[n,r]=N.useState(!1),[a,i]=N.useState("record"),[l,o]=N.useState(0),[c,d]=N.useState(0),u=IN(),h=()=>{i("record"),o(0),d(0)},p=g=>{!g&&(a==="uploading"||a==="processing")||(r(g),g||h())},f=N.useCallback(async(g,_)=>{i("uploading");try{const v="Card Video",{videoId:j,libraryId:b}=await i6(v),{uploadUrl:S,apiKey:A}=await o6(j),T=new XMLHttpRequest;T.upload.onprogress=W=>{W.lengthComputable&&o(W.loaded/W.total*100)},await new Promise((W,Y)=>{T.onload=()=>T.status>=200&&T.status<300?W():Y(new Error("Upload failed")),T.onerror=()=>Y(new Error("Upload failed")),T.open("PUT",S),T.setRequestHeader("AccessKey",A),T.send(g)}),i("processing");let L=0;const D=Date.now(),M=9e4,F=`https://iframe.mediadelivery.net/embed/${b}/${j}`;for(;L<4;){if(await new Promise(Y=>setTimeout(Y,3e3)),Date.now()-D>M){const Y=g.size/1048576;await u.mutateAsync({bunny_video_id:j,playback_url:`https://iframe.mediadelivery.net/play/${b}/${j}`,file_size_mb:Y,title:v,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(F),ae.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{r(!1),h()},1500);return}const W=await $w(j);if(L=W.status,d(W.encodeProgress||0),L===5||L===6)throw new Error("Video processing failed")}const z=await $w(j),V=(z.storageSize||g.size)/(1024*1024);await u.mutateAsync({bunny_video_id:j,contact_id:s||void 0,playback_url:z.directPlayUrl||F,thumbnail_url:z.thumbnailUrl,preview_url:z.previewUrl||null,duration_seconds:z.length||_,file_size_mb:V,title:v,status:"ready",touch_type:"video"}),t(F),ae.success("Video recorded & added to your library!"),i("done"),setTimeout(()=>{r(!1),h()},1500)}catch(v){console.error("Recording upload error:",v),ae.error("Failed to process video. Please try again."),i("record")}},[s,t,u]);return e.jsxs(bs,{open:n,onOpenChange:p,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 w-full",children:[e.jsx(br,{className:"h-3.5 w-3.5"}),"Record Video"]})}),e.jsxs(vs,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx(u6,{maxDurationSeconds:600,onRecordingComplete:f,onError:g=>ae.error(g)}),a==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(ts,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(pi,{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(ts,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(pi,{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(Ri,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your card!"})]})]})]})}const aXs=s=>`portal-settings-draft:${s}`;function _8e({open:s,onOpenChange:t,portal:n,dealOwnerId:r}){const a=jR(),[i,l]=N.useState(!1),o=N.useMemo(()=>aXs(n.id),[n.id]),[c,d]=N.useState(!1),[u,h]=N.useState(n.next_step_text||""),[p,f]=N.useState(n.next_step_video_url||""),[g,_]=N.useState(n.inspection_date||""),[v,j]=N.useState(n.appraisal_date||""),[b,S]=N.useState(n.welcome_message||""),[A,T]=N.useState(n.review_url||""),[L,D]=N.useState(n.show_post_close_tips),[M,F]=N.useState(n.notify_client),[z,V]=N.useState(n.require_onboarding),[W,Y]=N.useState(n.allow_spouse),[K,J]=N.useState(n.visibility),[ne,ie]=N.useState(n.stage_mapping||[]),[he,ce]=N.useState(null),[pe,le]=N.useState(n.linked_portal_id||null),[ve,ge]=N.useState(n.referral_enabled??!0),[Te,Me]=N.useState(n.referral_reward_text||""),[Ce,Ae]=N.useState(n.referral_cta_headline||""),[De,Ie]=N.useState(n.homeowner_hub_video_url||""),[Fe,qe]=N.useState(n.branding_override||{}),be=()=>{h(n.next_step_text||""),f(n.next_step_video_url||""),_(n.inspection_date||""),j(n.appraisal_date||""),S(n.welcome_message||""),T(n.review_url||""),D(n.show_post_close_tips),F(n.notify_client),V(n.require_onboarding),Y(n.allow_spouse),J(n.visibility),ie(n.stage_mapping||[]),le(n.linked_portal_id||null),ge(n.referral_enabled??!0),Me(n.referral_reward_text||""),Ae(n.referral_cta_headline||""),Ie(n.homeowner_hub_video_url||""),qe(n.branding_override||{})};N.useEffect(()=>{d(!1);const Ye=localStorage.getItem(o);if(Ye)try{const We=JSON.parse(Ye);h(We.nextStepText||""),f(We.nextStepVideo||""),_(We.inspectionDate||""),j(We.appraisalDate||""),S(We.welcomeMessage||""),T(We.reviewUrl||""),D(!!We.showPostClose),F(!!We.notifyClient),V(!!We.requireOnboarding),Y(!!We.allowSpouse),J(We.visibility||n.visibility),ie(We.stageMapping||[]),le(We.linkedPortalId??null),ge(We.referralEnabled??!0),Me(We.referralRewardText||""),Ae(We.referralCtaHeadline||""),Ie(We.homeownerHubVideoUrl||""),qe(We.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}be(),d(!0)},[o,n]),N.useEffect(()=>{if(!c)return;const Ye={nextStepText:u,nextStepVideo:p,inspectionDate:g,appraisalDate:v,welcomeMessage:b,reviewUrl:A,showPostClose:L,notifyClient:M,requireOnboarding:z,allowSpouse:W,visibility:K,stageMapping:ne,linkedPortalId:pe,referralEnabled:ve,referralRewardText:Te,referralCtaHeadline:Ce,homeownerHubVideoUrl:De,brandingOverride:Fe};u!==(n.next_step_text||"")||p!==(n.next_step_video_url||"")||g!==(n.inspection_date||"")||v!==(n.appraisal_date||"")||b!==(n.welcome_message||"")||A!==(n.review_url||"")||L!==n.show_post_close_tips||M!==n.notify_client||z!==n.require_onboarding||W!==n.allow_spouse||K!==n.visibility||JSON.stringify(ne)!==JSON.stringify(n.stage_mapping||[])||pe!==(n.linked_portal_id||null)||ve!==(n.referral_enabled??!0)||Te!==(n.referral_reward_text||"")||Ce!==(n.referral_cta_headline||"")||De!==(n.homeowner_hub_video_url||"")||JSON.stringify(Fe)!==JSON.stringify(n.branding_override||{})?localStorage.setItem(o,JSON.stringify(Ye)):localStorage.removeItem(o)},[u,p,g,v,b,A,L,M,z,W,K,ne,pe,ve,Te,Ce,De,Fe,o,c,n]);const Ze=()=>{localStorage.removeItem(o),be()},Ne=async()=>{try{await a.mutateAsync({id:n.id,next_step_text:u||null,next_step_video_url:p||null,inspection_date:g||null,appraisal_date:v||null,welcome_message:b||null,review_url:A||null,show_post_close_tips:L,notify_client:M,require_onboarding:z,allow_spouse:W,visibility:K,stage_mapping:ne.length>0?ne:null,linked_portal_id:pe,referral_enabled:ve,referral_reward_text:Te||null,referral_cta_headline:Ce||null,homeowner_hub_video_url:De||null,branding_override:Object.values(Fe).some(We=>We!=null&&We!=="")?Fe:null});const Ye=n.linked_portal_id;pe&&pe!==Ye&&await q.from("client_portals").update({linked_portal_id:n.id}).eq("id",pe),!pe&&Ye&&await q.from("client_portals").update({linked_portal_id:null}).eq("id",Ye),localStorage.removeItem(o),ae.success("Portal settings saved"),t(!1)}catch{ae.error("Failed to save settings")}},it=()=>{ie([...ne,{label:""}])},je=Ye=>{ie(ne.filter((We,rt)=>rt!==Ye)),he===Ye&&ce(null)},Ge=(Ye,We,rt)=>{const tt=[...ne];tt[Ye]={...tt[Ye],[We]:rt},ie(tt)},Be=()=>{const We=Mye(null).map(rt=>({label:rt.label,description:rt.description,stageId:void 0}));ie(We)};return e.jsxs(e.Fragment,{children:[e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Portal Settings"})}),e.jsxs(Br,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Fr,{className:"grid grid-cols-5 shrink-0",children:[e.jsx(Kt,{value:"general",children:"General"}),e.jsx(Kt,{value:"timeline",children:"Timeline"}),e.jsx(Kt,{value:"content",children:"Content"}),e.jsx(Kt,{value:"vendors",children:"Vendors"}),e.jsx(Kt,{value:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(is,{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(Ye=>e.jsx("button",{onClick:()=>J(Ye),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${K===Ye?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:Ye.charAt(0).toUpperCase()+Ye.slice(1)},Ye))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(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(bn,{checked:z,onCheckedChange:V})]}),z&&e.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-primary/20",children:[e.jsxs("div",{children:[e.jsx(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(bn,{checked:W,onCheckedChange:Y})]}),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(bn,{checked:L,onCheckedChange:D})]}),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(bn,{checked:M,onCheckedChange:F})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(rXs,{portalId:n.id,ownerId:r,clientEmail:n.client_email,linkedPortalId:pe,onLink:le})}),e.jsx("div",{children:e.jsx(ye,{type:"date",value:g,onChange:Ye=>_(Ye.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:v,onChange:Ye=>j(Ye.target.value),className:"mt-1"})]})]}),e.jsx(is,{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:Be,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.'}),ne.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:Be,children:"Customize journey labels"})]}),e.jsx("div",{className:"space-y-2 mt-2",children:ne.map((Ye,We)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fu,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(ye,{value:Ye.label,onChange:rt=>Ge(We,"label",rt.target.value),placeholder:`Stage ${We+1} label`,className:"flex-1 h-9 text-sm"}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-9 px-2 text-xs text-muted-foreground hover:text-primary",onClick:()=>ce(he===We?null:We),children:he===We?"Less":"More"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>je(We),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]}),he===We&&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:Ye.description||"",onChange:rt=>Ge(We,"description",rt.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"}),Ye.video_url?e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 text-xs text-muted-foreground truncate bg-muted/50 rounded px-2 py-1.5 border border-input",children:Ye.video_url.length>40?Ye.video_url.slice(0,40)+"...":Ye.video_url}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>Ge(We,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(b8e,{onVideoReady:rt=>Ge(We,"video_url",rt)}),e.jsx(a6,{userId:r,onSelect:rt=>Ge(We,"video_url",rt),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 rt=prompt("Paste a YouTube or Loom URL:");rt&&Ge(We,"video_url",rt)},children:[e.jsx(Jo,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},We))}),ne.length>0&&e.jsxs(B,{variant:"outline",size:"sm",onClick:it,className:"mt-2 text-xs w-full",children:[e.jsx(Is,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(is,{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:b,onChange:Ye=>S(Ye.target.value),className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[60px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"Welcome! Here's everything you need for your transaction."})]}),e.jsxs("div",{children:[e.jsx(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:Ye=>h(Ye.target.value),className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[60px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"We're waiting on the inspection report..."})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Next Step Video (optional)"}),e.jsx(ye,{value:p,onChange:Ye=>f(Ye.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:A,onChange:Ye=>T(Ye.target.value),className:"mt-1",placeholder:"https://g.page/r/..."})]}),e.jsxs("div",{className:"border-t pt-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-base",children:"🎁"}),e.jsx(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(bn,{checked:ve,onCheckedChange:ge})]}),ve&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Headline"}),e.jsx(ye,{value:Ce,onChange:Ye=>Ae(Ye.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:Te,onChange:Ye=>Me(Ye.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:De,onChange:Ye=>Ie(Ye.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(is,{value:"vendors",className:"space-y-4 mt-0 px-1",children:e.jsx(nXs,{portalId:n.id,agentUserId:r})}),e.jsx(is,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx(sXs,{override:Fe,onChange:qe})})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 border-t shrink-0",children:[e.jsx(B,{variant:"ghost",onClick:Ze,children:"Reset Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(B,{onClick:Ne,disabled:a.isPending,children:[a.isPending?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(qo,{className:"h-4 w-4 mr-2"}),"Save Settings"]})]})]})]})}),e.jsx(N2t,{open:i,onOpenChange:l})]})}const iXs=s=>`portal-update-draft:${s}`;function w8e({open:s,onOpenChange:t,portalId:n,portalSlug:r,notifyClient:a}){const i=N.useMemo(()=>iXs(n),[n]),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState(!1),[g,_]=N.useState(a??!1),[v,j]=N.useState(!1),b=Y_t();N.useEffect(()=>{j(!1);const T=localStorage.getItem(i);if(T)try{const L=JSON.parse(T);o(L.title||""),d(L.content||""),h(L.videoUrl||""),f(!!L.isStageChange),_(typeof L.sendNotification=="boolean"?L.sendNotification:a??!1),j(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),h(""),f(!1),_(a??!1),j(!0)},[i,a]),N.useEffect(()=>{if(!v)return;const T={title:l,content:c,videoUrl:u,isStageChange:p,sendNotification:g};l.trim()||c.trim()||u.trim()||p||g!==(a??!1)?localStorage.setItem(i,JSON.stringify(T)):localStorage.removeItem(i)},[l,c,u,p,g,v,i,a]);const S=()=>{localStorage.removeItem(i),o(""),d(""),h(""),f(!1),_(a??!1)},A=async()=>{if(l.trim())try{if(await b.mutateAsync({portal_id:n,title:l.trim(),content:c.trim()||void 0,video_url:u.trim()||void 0,is_stage_change:p}),g&&r)try{const T=Tw(r);await q.functions.invoke("send-portal-notification",{body:{portal_id:n,update_title:l.trim(),update_content:c.trim()||null,portal_url:T}}),ae.success("Update posted & client notified")}catch(T){console.error("Notification failed:",T),ae.success("Update posted (notification failed to send)")}else ae.success("Update posted to portal");S(),t(!1)}catch{ae.error("Failed to post update")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{children:e.jsx(_s,{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(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("button",{type:"button",onClick:()=>f(!p),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${p?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-background text-muted-foreground border-input"}`,children:"📊 Stage Change"}),e.jsxs("button",{type:"button",onClick:()=>_(!g),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors flex items-center gap-1.5 ${g?"bg-blue-500/10 text-blue-700 border-blue-200":"bg-background text-muted-foreground border-input"}`,children:[g?e.jsx(im,{className:"h-3 w-3"}):e.jsx(pw,{className:"h-3 w-3"}),g?"Notify Client":"No Notification"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-2",children:[e.jsx(B,{variant:"ghost",onClick:S,children:"Clear Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(B,{onClick:A,disabled:!l.trim()||b.isPending,children:[b.isPending?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function j8e({open:s,onOpenChange:t,portal:n,dealName:r}){const a=jR(),{isGmailConnected:i,gmailEmail:l}=Oh(),[o,c]=N.useState(n.client_name||""),[d,u]=N.useState(n.client_email||""),[h,p]=N.useState(!1),[f,g]=N.useState(!1),_=Tw(n.slug),v=o.split(" ")[0]||"there",j=`Your Transaction Portal – ${r}`,b=`Hi ${v}, I've set up a dedicated portal where you can track the progress of your transaction in real-time. Here's your link: ${_} You can view your timeline, key dates, documents, and any updates I post along the way. Let me know if you have any questions!`,S=()=>{navigator.clipboard.writeText(_),g(!0),setTimeout(()=>g(!1),2e3),ae.success("Portal link copied!")},A=async()=>{if(!d.trim()){ae.error("Please enter the client email");return}p(!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:L}=await q.functions.invoke("gmail-send",{body:{to:d,subject:j,body:b.replace(/\n/g,"
")}});if(L){let D="";try{const M=L==null?void 0:L.context;if(M&&typeof M.json=="function"){const F=await M.json();D=(F==null?void 0:F.message)||(F==null?void 0:F.error)||""}}catch{}throw new Error(D||L.message||"Failed to send invite")}ae.success(`Invite sent to ${d}`),t(!1)}catch(L){ae.error(L.message||"Failed to send invite")}finally{p(!1)}},T=()=>{const L=encodeURIComponent(j),D=encodeURIComponent(b);window.open(`mailto:${d}?subject=${L}&body=${D}`,"_blank"),a.mutateAsync({id:n.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"}).catch(()=>{})};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(ws,{children:e.jsx(_s,{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:L=>c(L.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:L=>u(L.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:_})}),e.jsx(B,{variant:"outline",size:"icon",onClick:S,className:"shrink-0",children:f?e.jsx(Ir,{className:"h-4 w-4 text-emerald-600"}):e.jsx(Xr,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[i?e.jsxs(B,{onClick:A,disabled:h||!d.trim(),className:"w-full",children:[h?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Vs,{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:S,className:"w-full text-muted-foreground",children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function oXs({deal:s}){const{isAdmin:t,user:n}=ys(),{data:r,isLoading:a}=kWs(s.id),i=vLe(),l=jR(),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState(!1),[f,g]=N.useState(!1),_=`portal-management-ui:${s.id}`;if(N.useEffect(()=>{const L=sessionStorage.getItem(_);if(L)try{const D=JSON.parse(L);u(!!D.settingsOpen),p(!!D.composerOpen),g(!!D.inviteOpen)}catch{sessionStorage.removeItem(_)}},[_]),N.useEffect(()=>{d||h||f?sessionStorage.setItem(_,JSON.stringify({settingsOpen:d,composerOpen:h,inviteOpen:f})):sessionStorage.removeItem(_)},[d,h,f,_]),a)return e.jsx("div",{className:"border rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(ts,{className:"h-3 w-3 animate-spin ml-auto"})]})});const v=async()=>{var L,D;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:((L=s.contact)==null?void 0:L.email)||void 0,client_phone:((D=s.contact)==null?void 0:D.phone)||void 0}),ae.success("Client portal enabled!")}catch{ae.error("Failed to create portal")}finally{c(!1)}},j=async L=>{if(r)try{await l.mutateAsync({id:r.id,is_enabled:L}),ae.success(L?"Portal enabled":"Portal disabled")}catch{ae.error("Failed to update portal")}},b=()=>{if(!r)return;const L=Tw(r.slug);navigator.clipboard.writeText(L),ae.success("Portal link copied!")},S=()=>{if(!r)return;const L=Tw(r.slug);window.open(L,"_blank")};if(!r)return e.jsxs("div",{className:"border rounded-lg p-4 border-dashed",children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Create a beautiful portal so your client can track their deal progress in real-time."}),e.jsxs(B,{onClick:v,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const A=Tw(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(un,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(ze,{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(bn,{checked:r.is_enabled,onCheckedChange:j})]}),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(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:r.visibility==="private"?"Private":"Public"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Onboarding:"}),e.jsx("span",{className:"text-foreground",children:r.require_onboarding?"Required":"Disabled"})]}),r.client_name&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Client:"}),e.jsx("span",{className:"text-foreground",children:r.client_name})]})]}),e.jsx("div",{className:"bg-muted/50 rounded-md p-2 mb-3",children:e.jsx("p",{className:"text-xs font-mono text-muted-foreground truncate",children:A})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 mb-2 w-full",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:b,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Xr,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Copy"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:S,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(tr,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Preview"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>g(!0),className:"text-xs w-full min-w-0 px-2",children:[e.jsx(cr,{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:()=>p(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(nw,{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(Xo,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Settings"})]})]}),e.jsxs(Ln,{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(Oi,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx(_8e,{open:d,onOpenChange:u,portal:r,dealOwnerId:T}),e.jsx(w8e,{open:h,onOpenChange:p,portalId:r.id,portalSlug:r.slug,notifyClient:r.notify_client}),e.jsx(j8e,{open:f,onOpenChange:g,portal:r,dealName:s.deal_name})]})}const lXs=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function cXs(s){return ct({queryKey:["deal-contacts",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_contacts").select(` id, deal_id, contact_id, role, created_at, contact:innercircle_contacts(id, first_name, last_name, email, phone) `).eq("deal_id",s).order("created_at");if(n)throw n;return t||[]},enabled:!!s})}function dXs(){const s=Ht();return gt({mutationFn:async({dealId:t,contactId:n,role:r})=>{const{data:a,error:i}=await q.from("deal_contacts").insert({deal_id:t,contact_id:n,role:r}).select().single();if(i)throw i;return a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),ae.success("Contact linked to deal")},onError:t=>{var n;(n=t.message)!=null&&n.includes("duplicate")?ae.error("This contact is already linked to this deal"):ae.error("Failed to link contact")}})}function uXs(){const s=Ht();return gt({mutationFn:async({id:t,dealId:n})=>{const{error:r}=await q.from("deal_contacts").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),ae.success("Contact removed from deal")},onError:()=>{ae.error("Failed to remove contact")}})}function hXs({dealId:s,primaryContactId:t}){const n=Mn(),{data:r,isLoading:a}=cXs(s),{data:i}=ox(),l=dXs(),o=uXs(),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState("Client"),g=new Set((r==null?void 0:r.map(S=>S.contact_id))||[]);t&&g.add(t);const _=i==null?void 0:i.filter(S=>{var T,L,D;if(g.has(S.id))return!1;if(!u.trim())return!0;const A=u.toLowerCase();return((T=S.first_name)==null?void 0:T.toLowerCase().includes(A))||((L=S.last_name)==null?void 0:L.toLowerCase().includes(A))||((D=S.email)==null?void 0:D.toLowerCase().includes(A))}).slice(0,8),v=S=>{l.mutate({dealId:s,contactId:S,role:p}),d(!1),h("")},j=S=>{o.mutate({id:S,dealId:s})},b={Client:"bg-primary/10 text-primary","Co-Buyer":"bg-blue-500/10 text-blue-600","Co-Seller":"bg-emerald-500/10 text-emerald-600",Spouse:"bg-pink-500/10 text-pink-600",Lender:"bg-amber-500/10 text-amber-600","Title Company":"bg-purple-500/10 text-purple-600",Inspector:"bg-orange-500/10 text-orange-600",Appraiser:"bg-cyan-500/10 text-cyan-600",Attorney:"bg-slate-500/10 text-slate-600",Contractor:"bg-lime-500/10 text-lime-600",Other:"bg-muted text-muted-foreground"};return!(r!=null&&r.length)&&!c?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(el,{open:c,onOpenChange:d,children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(Ho,{className:"w-80 p-3",align:"start",children:e.jsx(cXe,{search:u,setSearch:h,selectedRole:p,setSelectedRole:f,filteredContacts:_,onAdd:v})})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Linked Contacts",r&&r.length>0&&e.jsx(ze,{variant:"secondary",className:"text-[10px] px-1.5",children:r.length})]}),e.jsxs(el,{open:c,onOpenChange:d,children:[e.jsx(tl,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx(Is,{className:"h-3.5 w-3.5"})})}),e.jsx(Ho,{className:"w-80 p-3",align:"end",children:e.jsx(cXe,{search:u,setSearch:h,selectedRole:p,setSelectedRole:f,filteredContacts:_,onAdd:v})})]})]}),e.jsx("div",{className:"space-y-1.5",children:r==null?void 0:r.map(S=>{var A,T,L,D,M,F,z,V;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(aa,{className:"text-[10px] bg-primary/10 text-primary",children:[(T=(A=S.contact)==null?void 0:A.first_name)==null?void 0:T[0],(D=(L=S.contact)==null?void 0:L.last_name)==null?void 0:D[0]]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("button",{onClick:()=>n(`/mission-control/contacts/${S.contact_id}`),className:"text-sm font-medium hover:underline text-primary truncate block",children:[(M=S.contact)==null?void 0:M.first_name," ",(F=S.contact)==null?void 0:F.last_name]})}),e.jsx(ze,{variant:"outline",className:`text-[10px] px-1.5 py-0 shrink-0 ${b[S.role]||b.Other}`,children:S.role}),e.jsxs("div",{className:"flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[((z=S.contact)==null?void 0:z.phone)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`tel:${S.contact.phone}`,children:e.jsx(Ar,{className:"h-3 w-3"})})}),((V=S.contact)==null?void 0:V.email)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`mailto:${S.contact.email}`,children:e.jsx(Vs,{className:"h-3 w-3"})})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>j(S.id),children:e.jsx(_n,{className:"h-3 w-3"})})]})]},S.id)})})]})}function cXe({search:s,setSearch:t,selectedRole:n,setSelectedRole:r,filteredContacts:a,onAdd:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ds,{value:n,onValueChange:r,children:[e.jsx(ls,{className:"h-8 text-sm",children:e.jsx(us,{placeholder:"Role"})}),e.jsx(cs,{children:lXs.map(l=>e.jsx(Qe,{value:l,children:l},l))})]}),e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{value:s,onChange:l=>t(l.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(hi,{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 A7=[{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"}],mXs=[{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 pXs(){const s=Ht();return gt({mutationFn:async({dealId:t,dates:n})=>{const r={};Object.entries(n).forEach(([i,l])=>{r[i]=l&&l.trim()!==""?l:null});const{error:a}=await q.from("deal_pipeline").update(r).eq("id",t);if(a)throw a},onSuccess:()=>{s.invalidateQueries({queryKey:["deals"]}),s.invalidateQueries({queryKey:["deal-pipeline"]}),s.invalidateQueries({queryKey:["tc-dashboard"]})}})}function fXs(){return ct({queryKey:["tc-playbooks"],queryFn:async()=>{const{data:s,error:t}=await q.from("tc_playbooks").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;const{data:n,error:r}=await q.from("tc_playbook_tasks").select("*").order("sort_order");if(r)throw r;return(s||[]).map(a=>({...a,tasks:(n||[]).filter(i=>i.playbook_id===a.id)}))},staleTime:10*6e4})}function xXs(){const s=ma(),t=Ht();return gt({mutationFn:async({playbookId:n,dealId:r})=>{if(!s)throw new Error("Not authenticated");const[{data:a,error:i},{data:l,error:o}]=await Promise.all([q.from("deal_pipeline").select("*").eq("id",r).single(),q.from("tc_playbook_tasks").select("*").eq("playbook_id",n).order("sort_order")]);if(i)throw i;if(o)throw o;if(!l||l.length===0)return 0;const{data:c}=await q.from("deal_tasks").select("title").eq("deal_id",r),d=new Set((c||[]).map(g=>String(g.title).toLowerCase())),u=a,h=(g,_)=>{const v=g==="stage_entry"?null:u[g],j=v?new Date(`${v}T12:00:00`):new Date;return j.setDate(j.getDate()+(_||0)),j.toISOString().split("T")[0]},p=l.filter(g=>!d.has(String(g.title).toLowerCase())).map((g,_)=>({owner_user_id:s,deal_id:r,contact_id:u.contact_id,stage_id:u.stage_id,title:g.title,description:g.description,priority:g.priority,status:"todo",due_date:h(g.due_anchor,g.due_offset_days),sort_order:_}));if(p.length===0)return 0;const{error:f}=await q.from("deal_tasks").insert(p);if(f)throw f;return p.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]}),t.invalidateQueries({queryKey:["tc-dashboard"]})}})}function gXs(){const s=ma(),t=Ht();return gt({mutationFn:async({playbookId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const[{data:a},{data:i,error:l}]=await Promise.all([q.from("tc_playbooks").select("deal_type").eq("id",n).single(),q.from("tc_playbook_tasks").select("*").eq("playbook_id",n).order("sort_order")]);if(l)throw l;if(!i||i.length===0)return 0;const{data:o}=await q.from("deal_task_templates").select("title").eq("owner_user_id",s).eq("stage_id",r),c=new Set((o||[]).map(h=>String(h.title).toLowerCase())),d=i.filter(h=>!c.has(String(h.title).toLowerCase())).map((h,p)=>({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:p}));if(d.length===0)return 0;const{error:u}=await q.from("deal_task_templates").insert(d);if(u)throw u;return d.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function yXs(){const s=ma();return ct({queryKey:["tc-dashboard",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_pipeline").select(` id, deal_name, deal_type, property_address, city, state, expected_price, expected_commission, stage_id, contact_id, contract_date, target_close_date, actual_close_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, earnest_money_due_date, title_docs_due_date, final_walkthrough_date, stage:deal_pipeline_stages(id, name, color, is_won_stage, is_lost_stage), contact:innercircle_contacts(id, first_name, last_name, email, phone) `).eq("owner_user_id",s);if(n)throw n;const r=(t||[]).filter(l=>{var o,c;return!((o=l.stage)!=null&&o.is_lost_stage)&&!((c=l.stage)!=null&&c.is_won_stage)}),a=r.map(l=>l.id);let i={};if(a.length>0){const{data:l}=await q.from("deal_tasks").select("id, deal_id, title, status, priority, due_date").in("deal_id",a).order("due_date",{ascending:!0,nullsFirst:!1});(l||[]).forEach(o=>{var c;o.deal_id&&(i[c=o.deal_id]||(i[c]=[])).push(o)})}return r.map(l=>({...l,tasks:i[l.id]||[]}))},enabled:!!s})}function N8e(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 q_(s){const t=N8e(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 vXs(s){return s===null?"none":s<0?"overdue":s===0?"today":s<=3?"soon":"upcoming"}const bXs={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 _Xs(s){const t=N8e(s);return t?t.toLocaleDateString("en-US",{month:"short",day:"numeric"}):null}function dXe(s){return s===null?"Not set":s===0?"Today":s<0?`${Math.abs(s)}d overdue`:`in ${s}d`}function wXs({deal:s,compact:t=!1}){const n=pXs(),[r,a]=N.useState(!1),[i,l]=N.useState({}),o=()=>{const g={};A7.forEach(_=>{g[_.key]=(s==null?void 0:s[_.key])??""}),l(g),a(!0)},c=async()=>{try{await n.mutateAsync({dealId:s.id,dates:i}),ae.success("Transaction dates updated"),a(!1)}catch(g){ae.error((g==null?void 0:g.message)||"Could not save dates")}},d=N.useMemo(()=>A7.map(g=>{const _=(s==null?void 0:s[g.key])??null,v=q_(_);return{...g,value:_,days:v,urgency:vXs(v)}}),[s]),u=d.filter(g=>g.value).length,h=q_(s==null?void 0:s.target_close_date),p=d.filter(g=>g.value&&g.days!==null&&g.days>=0).sort((g,_)=>(g.days??0)-(_.days??0))[0],f=d.filter(g=>g.urgency==="overdue");return 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(om,{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:h!==null?h>=0?`${h} day${h===1?"":"s"} to closing`:`Closing was ${Math.abs(h)} day${Math.abs(h)===1?"":"s"} ago`:`${u} of ${A7.length} key dates set`})]})]}),e.jsxs(el,{open:r,onOpenChange:g=>g?o():a(!1),children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"shrink-0 gap-1.5",children:[e.jsx(_a,{className:"h-3.5 w-3.5"}),t?"":"Edit dates"]})}),e.jsxs(Ho,{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:A7.map(g=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{htmlFor:`kd-${g.key}`,className:"text-xs text-muted-foreground",children:g.label}),e.jsx(ye,{id:`kd-${g.key}`,type:"date",value:i[g.key]??"",onChange:_=>l(v=>({...v,[g.key]:_.target.value})),className:"h-9"})]},g.key))}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(B,{size:"sm",onClick:c,disabled:n.isPending,children:[n.isPending?e.jsx(ts,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(Ir,{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:d.map(g=>e.jsxs("div",{className:Et("rounded-lg border px-2.5 py-2 transition-colors",bXs[g.urgency]),children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide opacity-70 truncate",children:g.short}),e.jsx("p",{className:"text-sm font-semibold leading-tight truncate",children:_Xs(g.value)??"—"}),g.value&&e.jsx("p",{className:"text-[10px] opacity-80 truncate",children:dXe(g.days)})]},g.key))}),(f.length>0||p)&&e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-xs",children:[f.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($l,{className:"h-3 w-3"}),f.length," date",f.length===1?"":"s"," past due"]}),p&&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: ",p.label," · ",dXe(p.days)]})]}),u===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 jXs={Home:Or,FileSignature:Yk,Handshake:pb,CalendarClock:om,Sparkles:un,ClipboardCheck:G2},NXs={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 kXs(s,t){var a;const n=((a=mXs.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 k2t({open:s,onOpenChange:t,dealId:n,dealName:r}){const{data:a,isLoading:i}=fXs(),{data:l}=KU(),o=xXs(),c=gXs(),[d,u]=N.useState(null),[h,p]=N.useState({}),f=v=>{if(h[v.id])return h[v.id];const j=l==null?void 0:l.find(b=>{var S,A;return((S=b.name)==null?void 0:S.toLowerCase())===((A=v.target_stage_name)==null?void 0:A.toLowerCase())});return(j==null?void 0:j.id)??""},g=async v=>{if(n){u(v.id);try{const j=await o.mutateAsync({playbookId:v.id,dealId:n});ae.success(j>0?`Added ${j} task${j===1?"":"s"} to this deal`:"All tasks already exist on this deal"),j>0&&t(!1)}catch(j){ae.error((j==null?void 0:j.message)||"Could not apply playbook")}finally{u(null)}}},_=async v=>{const j=f(v);if(!j){ae.error("Pick which stage this playbook should trigger on");return}u(`install-${v.id}`);try{const b=await c.mutateAsync({playbookId:v.id,stageId:j});ae.success(b>0?`Automated — ${b} task${b===1?"":"s"} will now be created every time a deal reaches this stage`:"This playbook is already automated for that stage")}catch(b){ae.error((b==null?void 0:b.message)||"Could not automate playbook")}finally{u(null)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0",children:[e.jsx(ws,{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(Ou,{className:"h-4.5 w-4.5 text-primary"})}),e.jsxs("div",{children:[e.jsx(_s,{children:"Transaction Playbooks"}),e.jsx(Qn,{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(hi,{className:"flex-1",children:e.jsx("div",{className:"p-6 pt-4",children:i?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsx(vIe,{type:"single",collapsible:!0,className:"space-y-3",children:(a||[]).map(v=>{const j=jXs[v.icon||"ClipboardCheck"]||G2,b=v.accent_color||"hsl(var(--primary))";return e.jsxs(dve,{value:v.id,className:"border rounded-xl px-0 overflow-hidden bg-card",children:[e.jsx(uve,{className:"px-4 py-3 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-3 text-left flex-1 min-w-0",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${b}1a`},children:e.jsx(j,{className:"h-5 w-5",style:{color:b}})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm",children:v.name}),e.jsxs(ze,{variant:"secondary",className:"text-[10px]",children:[v.tasks.length," steps"]}),v.deal_type&&e.jsx(ze,{variant:"outline",className:"text-[10px] capitalize",children:v.deal_type})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:v.description})]})]})}),e.jsxs(hve,{className:"px-4 pb-4",children:[e.jsx("div",{className:"space-y-1.5 mb-4",children:v.tasks.map((S,A)=>e.jsxs("div",{className:"flex items-start gap-2.5 rounded-lg border bg-background px-3 py-2",children:[e.jsx("span",{className:"text-[10px] font-mono text-muted-foreground mt-0.5 w-4 shrink-0",children:A+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:S.title}),S.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:S.description}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:kXs(S.due_anchor,S.due_offset_days)})]}),e.jsx("span",{className:Et("text-[10px] px-1.5 py-0.5 rounded-full shrink-0 capitalize",NXs[S.priority]),children:S.priority})]},S.id))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 pt-2 border-t",children:[n&&e.jsxs(B,{size:"sm",className:"gap-1.5",onClick:()=>g(v),disabled:d===v.id,children:[d===v.id?e.jsx(ts,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(hh,{className:"h-3.5 w-3.5"}),"Add to this deal"]}),e.jsxs("div",{className:"flex gap-2 flex-1",children:[e.jsxs(ds,{value:f(v),onValueChange:S=>p(A=>({...A,[v.id]:S})),children:[e.jsx(ls,{className:"h-9 text-xs flex-1",children:e.jsx(us,{placeholder:"Trigger stage"})}),e.jsx(cs,{children:(l||[]).map(S=>e.jsx(Qe,{value:S.id,children:S.name},S.id))})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>_(v),disabled:d===`install-${v.id}`,children:[d===`install-${v.id}`?e.jsx(ts,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(xL,{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(xr,{className:"h-3 w-3"}),"Automating adds these steps to every future deal that reaches that stage."]})]})]},v.id)})})})})]})})}const SXs={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"}},CXs={note:Ei,call:Ar,email:Vs,meeting:yr,stage_change:tr,task_completed:xr,document:Or,system:gr};function TXs({deal:s,open:t,onOpenChange:n,onEdit:r,onAddToScorecard:a,isWonStage:i}){var Fe,qe;const l=Mn(),{data:o,isLoading:c}=KZs((s==null?void 0:s.id)||""),{data:d,isLoading:u}=ZZs((s==null?void 0:s.id)||""),h=YZs(),p=XZs(),f=QZs(),g=WZs(),{data:_,isLoading:v}=QQs((s==null?void 0:s.id)||""),j=XQs(),b=JQs(),S=eXs(),A=N.useRef(null),[T,L]=N.useState(""),[D,M]=N.useState(""),[F,z]=N.useState(!1),[V,W]=N.useState(!1),[Y,K]=N.useState(!1);if(!s)return null;const J=SXs[s.deal_type],ne=(()=>{var Ne;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const be=((Ne=s.listing)==null?void 0:Ne.created_at)||s.listing_date;if(!be)return null;const Ze=s.contract_date?Cl(s.contract_date):new Date;return Wv(Ze,Cl(be))})(),ie=be=>be?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(be):"-",he=async()=>{if(T.trim())try{await h.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:T}),L(""),ae.success("Note added")}catch{ae.error("Failed to add note")}},ce=async()=>{if(D.trim())try{await p.mutateAsync({deal_id:s.id,title:D,sort_order:((d==null?void 0:d.length)||0)+1}),M(""),ae.success("Task added")}catch{ae.error("Failed to add task")}},pe=async(be,Ze)=>{try{await f.mutateAsync({id:be,is_completed:Ze,deal_id:s.id})}catch{ae.error("Failed to update task")}},le=async()=>{try{await g.mutateAsync(s.id),ae.success("Deal deleted"),n(!1)}catch{ae.error("Failed to delete deal")}},ve=(d==null?void 0:d.filter(be=>be.is_completed).length)||0,ge=(d==null?void 0:d.length)||0,Te=(_==null?void 0:_.length)||0,Me=be=>be<1024?`${be} B`:be<1024*1024?`${(be/1024).toFixed(1)} KB`:`${(be/(1024*1024)).toFixed(1)} MB`,Ce=be=>be?be.startsWith("image/")?nl:be.includes("pdf")?Nr:sL:sL,Ae=async be=>{const Ze=be.target.files;if(!(!Ze||!s)){K(!0);try{for(const Ne of Array.from(Ze)){if(Ne.size>20*1024*1024){ae.error(`${Ne.name} exceeds 20MB limit`);continue}await j.mutateAsync({dealId:s.id,file:Ne})}ae.success("File(s) uploaded")}catch{ae.error("Failed to upload file")}finally{K(!1),A.current&&(A.current.value="")}}},De=async(be,Ze)=>{if(s)try{await b.mutateAsync({fileId:be,storagePath:Ze,dealId:s.id}),ae.success("File deleted")}catch{ae.error("Failed to delete file")}},Ie=async(be,Ze)=>{try{const Ne=await tXs(be),it=document.createElement("a");it.href=Ne,it.download=Ze,it.target="_blank",document.body.appendChild(it),it.click(),document.body.removeChild(it)}catch{ae.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx(cg,{open:t,onOpenChange:n,children:e.jsxs(ix,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(n0,{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(ze,{variant:"outline",className:Et("text-xs",J.color),children:J.label}),e.jsxs(ze,{variant:"secondary",className:"text-xs capitalize",children:[s.priority," priority"]})]}),e.jsx(r0,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(ZQs,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>r(s),children:e.jsx(ku,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"icon",className:"text-destructive hover:bg-destructive/10",onClick:()=>W(!0),children:e.jsx(_n,{className:"h-4 w-4"})})]})]})}),e.jsx(hi,{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(aa,{className:"bg-primary/10 text-primary",children:[(Fe=s.contact.first_name)==null?void 0:Fe[0],(qe=s.contact.last_name)==null?void 0:qe[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(Ar,{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(Vs,{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(hXs,{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(Or,{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:ie(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:ie(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?` (${ie(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:ie(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:ie(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(vo,{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(xr,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{children:"Synced to Scorecard"})]}),ne!==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",ne>90?"text-red-600":ne>60?"text-amber-600":"text-foreground"),children:[ne," ",s.contract_date?"(final)":"days"]})]}),s.target_close_date&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(yr,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",Ss(Cl(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Zl,{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(wXs,{deal:s}),e.jsx(oXs,{deal:s}),e.jsxs(Br,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(Fr,{className:"w-full grid grid-cols-3",children:[e.jsxs(Kt,{value:"tasks",className:"gap-1",children:[e.jsx(xr,{className:"h-4 w-4"}),"Tasks ",ge>0&&`(${ve}/${ge})`]}),e.jsxs(Kt,{value:"files",className:"gap-1",children:[e.jsx(n4,{className:"h-4 w-4"}),"Files ",Te>0&&`(${Te})`]}),e.jsxs(Kt,{value:"activity",className:"gap-1",children:[e.jsx(gr,{className:"h-4 w-4"}),"Activity"]})]}),e.jsxs(is,{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:D,onChange:be=>M(be.target.value),onKeyDown:be=>be.key==="Enter"&&ce()}),e.jsx(B,{onClick:ce,disabled:!D.trim(),children:e.jsx(Is,{className:"h-4 w-4"})}),e.jsxs(B,{variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>z(!0),children:[e.jsx(Ou,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"space-y-2",children:[d==null?void 0:d.map(be=>e.jsxs("div",{className:Et("flex items-center gap-3 p-3 rounded-lg border transition-colors",be.is_completed?"bg-muted/50 border-border":"bg-background"),children:[e.jsx(ui,{checked:be.is_completed,onCheckedChange:Ze=>pe(be.id,!!Ze)}),e.jsx("span",{className:Et("flex-1 text-sm",be.is_completed&&"line-through text-muted-foreground"),children:be.title}),be.due_date&&e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date(be.due_date),"MMM d")})]},be.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(is,{value:"files",className:"mt-4 space-y-3",children:[e.jsx("input",{type:"file",ref:A,className:"hidden",multiple:!0,onChange:Ae,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 be;return(be=A.current)==null?void 0:be.click()},disabled:Y,children:[Y?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Na,{className:"h-4 w-4 mr-2"}),Y?"Uploading...":"Upload Files"]}),e.jsxs("div",{className:"space-y-2",children:[_==null?void 0:_.map(be=>{const Ze=Ce(be.file_type);return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-background",children:[e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center shrink-0",children:e.jsx(Ze,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:be.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Me(be.file_size)," · ",Ss(new Date(be.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ww,{children:e.jsxs(Ec,{children:[e.jsx(Ac,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:`h-8 w-8 transition-colors ${be.visible_on_portal?"text-primary bg-primary/10 hover:bg-primary/20":"text-muted-foreground/40 hover:text-muted-foreground"}`,onClick:()=>S.mutate({fileId:be.id,visible:!be.visible_on_portal,dealId:s.id}),children:be.visible_on_portal?e.jsx(Er,{className:"h-4 w-4"}):e.jsx(xf,{className:"h-4 w-4"})})}),e.jsx(vc,{side:"top",children:be.visible_on_portal?"Visible on client portal":"Hidden from client portal"})]})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Ie(be.storage_path,be.file_name),children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>De(be.id,be.storage_path),children:e.jsx(Bn,{className:"h-4 w-4"})})]})]},be.id)}),(_==null?void 0:_.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(is,{value:"activity",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Es,{placeholder:"Add a note...",value:T,onChange:be=>L(be.target.value),rows:2}),e.jsxs(B,{onClick:he,disabled:!T.trim(),size:"sm",className:"w-full",children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Add Note"]})]}),e.jsxs("div",{className:"space-y-3",children:[o==null?void 0:o.map(be=>{const Ze=CXs[be.activity_type]||gr;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(Ze,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:be.title}),be.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:be.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Vo(new Date(be.created_at),{addSuffix:!0})})]})]},be.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(k2t,{open:F,onOpenChange:z,dealId:s==null?void 0:s.id,dealName:s==null?void 0:s.deal_name}),e.jsx(Oo,{open:V,onOpenChange:W,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Deal?"}),e.jsxs(Mo,{children:['This will permanently delete "',s.deal_name,'" and all associated data. This action cannot be undone.']})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:le,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function EXs({open:s,onOpenChange:t,deal:n,onComplete:r}){const a=qye(),i=y2t(),{data:l}=ZD(),{data:o}=Sy(),[c,d]=N.useState({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:Ss(new Date,"yyyy-MM-dd"),sale_price:0,commission_amount:0,lead_source_id:"",client_type_id:"",notes:""});N.useEffect(()=>{if(n&&s){const p=n.deal_type==="seller"?"seller":"buyer",f=n.expected_price||0,g=n.commission_percentage||3,_=n.expected_commission||f*g/100;d({property_address:n.property_address||n.deal_name||"",city:n.city||"",state:n.state||"",zip:n.zip_code||"",transaction_type:p,close_date:n.actual_close_date||n.target_close_date||Ss(new Date,"yyyy-MM-dd"),sale_price:f,commission_amount:_,lead_source_id:"",client_type_id:"",notes:n.notes||""})}},[n,s]);const u=async p=>{if(p.preventDefault(),!!n)try{const f=await a.mutateAsync({property_address:c.property_address,city:c.city||null,state:c.state||null,zip:c.zip||null,transaction_type:c.transaction_type,close_date:c.close_date,sale_price:c.sale_price,commission_amount:c.commission_amount||null,brokerage_split_pct:n.brokerage_split_pct||null,team_split_pct:n.team_split_pct||null,franchise_fee_pct:n.franchise_fee_pct||null,referral_fee_pct:n.referral_fee_pct||null,transaction_fee:n.transaction_fee||null,lead_source_id:c.lead_source_id||null,client_type_id:c.client_type_id||null,contact_id:n.contact_id||null,notes:c.notes||null,is_win:!0});await i.mutateAsync({id:n.id,scorecard_transaction_id:f.id,actual_close_date:c.close_date}),ae.success("Deal added to Scorecard! 🎉"),t(!1),r==null||r()}catch(f){console.error("Error syncing to scorecard:",f),ae.error("Failed to add to scorecard")}},h=p=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(p);return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[550px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{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(vo,{className:"h-6 w-6 text-green-600 dark:text-green-400"})}),e.jsx(_s,{className:"text-center text-xl",children:"Congratulations on Closing! 🎉"}),e.jsx(Qn,{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(Or,{className:"h-4 w-4 text-muted-foreground"}),"Property Address *"]}),e.jsx(ye,{id:"property_address",value:c.property_address,onChange:p=>d(f=>({...f,property_address:p.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:p=>d(f=>({...f,city:p.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:p=>d(f=>({...f,state:p.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:p=>d(f=>({...f,zip:p.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(ds,{value:c.transaction_type,onValueChange:p=>d(f=>({...f,transaction_type:p})),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"buyer",children:"Buyer"}),e.jsx(Qe,{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(yr,{className:"h-4 w-4 text-muted-foreground"}),"Close Date *"]}),e.jsx(ye,{id:"close_date",type:"date",value:c.close_date,onChange:p=>d(f=>({...f,close_date:p.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(Zl,{className:"h-4 w-4 text-muted-foreground"}),"Sale Price *"]}),e.jsx(ye,{id:"sale_price",type:"number",value:c.sale_price||"",onChange:p=>d(f=>({...f,sale_price:Number(p.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(a4,{className:"h-4 w-4 text-muted-foreground"}),"GCI (Commission)"]}),e.jsx(ye,{id:"commission_amount",type:"number",value:c.commission_amount||"",onChange:p=>d(f=>({...f,commission_amount:Number(p.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(ds,{value:c.lead_source_id,onValueChange:p=>d(f=>({...f,lead_source_id:p})),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select source"})}),e.jsx(cs,{children:l==null?void 0:l.map(p=>e.jsx(Qe,{value:p.id,children:p.name},p.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Client Type"}),e.jsxs(ds,{value:c.client_type_id,onValueChange:p=>d(f=>({...f,client_type_id:p})),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select type"})}),e.jsx(cs,{children:o==null?void 0:o.map(p=>e.jsx(Qe,{value:p.id,children:p.name},p.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"notes",children:"Notes"}),e.jsx(Es,{id:"notes",value:c.notes,onChange:p=>d(f=>({...f,notes:p.target.value})),placeholder:"Any additional notes about this transaction...",rows:2})]}),e.jsxs(Xn,{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(Oa,{className:"ml-2 h-4 w-4"})]})})]})]})]})})}const AXs={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"}},uXe={urgent:0,high:1,medium:2,low:3};function MXs({deals:s,stages:t,onDealClick:n,onStageChange:r}){const[a,i]=N.useState("target_close_date"),[l,o]=N.useState("asc"),c=f=>{a===f?o(g=>g==="asc"?"desc":"asc"):(i(f),o("asc"))},d=N.useMemo(()=>[...s].sort((f,g)=>{var v,j;let _=0;switch(a){case"deal_name":_=f.deal_name.localeCompare(g.deal_name);break;case"stage":{const b=((v=t.find(A=>A.id===f.stage_id))==null?void 0:v.sort_order)||0,S=((j=t.find(A=>A.id===g.stage_id))==null?void 0:j.sort_order)||0;_=b-S;break}case"expected_price":_=(f.expected_price||0)-(g.expected_price||0);break;case"expected_commission":_=(f.expected_commission||0)-(g.expected_commission||0);break;case"target_close_date":{const b=f.target_close_date?Cl(f.target_close_date).getTime():1/0,S=g.target_close_date?Cl(g.target_close_date).getTime():1/0;_=b-S;break}case"priority":_=uXe[f.priority]-uXe[g.priority];break}return l==="asc"?_:-_}),[s,t,a,l]),u=f=>f?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(f):"—",h=f=>f?t.find(g=>g.id===f):null,p=({field:f,children:g})=>e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>c(f),children:[g,a===f?l==="asc"?e.jsx(Ru,{className:"ml-2 h-4 w-4"}):e.jsx(am,{className:"ml-2 h-4 w-4"}):e.jsx(em,{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(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{className:"bg-muted/50",children:[e.jsx(Ct,{className:"w-[250px]",children:e.jsx(p,{field:"deal_name",children:"Deal Name"})}),e.jsx(Ct,{className:"w-[150px]",children:e.jsx(p,{field:"stage",children:"Stage"})}),e.jsx(Ct,{className:"w-[100px]",children:"Type"}),e.jsx(Ct,{className:"w-[120px]",children:e.jsx(p,{field:"expected_price",children:"Price"})}),e.jsx(Ct,{className:"w-[120px]",children:e.jsx(p,{field:"expected_commission",children:"GCI"})}),e.jsx(Ct,{className:"w-[130px]",children:e.jsx(p,{field:"target_close_date",children:"Close Date"})}),e.jsx(Ct,{className:"w-[100px]",children:e.jsx(p,{field:"priority",children:"Priority"})})]})}),e.jsx(ha,{children:d.map(f=>{h(f.stage_id);const g=AXs[f.deal_type],_=f.target_close_date?Wv(Cl(f.target_close_date),new Date):null,v=_!==null&&_<0,j=_!==null&&_<=7&&_>=0;return e.jsxs(Hs,{className:Et("cursor-pointer hover:bg-muted/50 transition-colors",v&&"bg-red-50/50"),onClick:()=>n(f),children:[e.jsx(ut,{className:"font-medium",children:e.jsxs("div",{children:[e.jsx("p",{className:"truncate max-w-[230px]",children:f.deal_name}),f.contact&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[f.contact.first_name," ",f.contact.last_name]})]})}),e.jsx(ut,{onClick:b=>b.stopPropagation(),children:e.jsx(w2t,{stages:t,currentStageId:f.stage_id||"",onStageSelect:(b,S)=>r(f.id,b,S)})}),e.jsx(ut,{children:e.jsx(ze,{variant:"outline",className:Et("text-xs",g.color),children:g.label})}),e.jsx(ut,{children:e.jsx("span",{className:"font-medium",children:u(f.expected_price)})}),e.jsx(ut,{children:e.jsx("span",{className:"text-emerald-600",children:u(f.expected_commission)})}),e.jsx(ut,{children:f.target_close_date?e.jsxs("div",{className:Et("flex items-center gap-1 text-sm",v&&"text-red-600",j&&!v&&"text-amber-600"),children:[v&&e.jsx(Gi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:Ss(Cl(f.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ut,{children:e.jsx(ze,{variant:"outline",className:Et("text-xs capitalize",f.priority==="urgent"&&"border-red-200 bg-red-50 text-red-700",f.priority==="high"&&"border-orange-200 bg-orange-50 text-orange-700",f.priority==="medium"&&"border-amber-200 bg-amber-50 text-amber-700",f.priority==="low"&&"border-slate-200 bg-slate-50 text-slate-600"),children:f.priority})})]},f.id)})})]})})}function IXs(){const s=ma();return ct({queryKey:["deal-tasks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_tasks").select(` *, deal:deal_pipeline(id, deal_name, stage_id), contact:innercircle_contacts(id, first_name, last_name), stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function PXs(s){const t=ma();return ct({queryKey:["deal-tasks","deal",s,t],queryFn:async()=>{if(!t||!s)return[];const{data:n,error:r}=await q.from("deal_tasks").select(` *, stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("deal_id",s).order("sort_order",{ascending:!0});if(r)throw r;return n},enabled:!!t&&!!s})}function LXs(){const s=ma(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("deal_tasks").insert({owner_user_id:s,title:n.title,description:n.description||null,deal_id:n.deal_id||null,contact_id:n.contact_id||null,stage_id:n.stage_id||null,priority:n.priority||"medium",status:n.status||"todo",due_date:n.due_date||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}function DXs(){const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("deal_tasks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function RXs(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("deal_tasks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function ibe(){const s=Ht();return gt({mutationFn:async({id:t,status:n})=>{const{data:r,error:a}=await q.from("deal_tasks").update({status:n,completed_at:n==="done"?new Date().toISOString():null}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function OXs(){const s=Ht();return gt({mutationFn:async t=>{if(t.length===0)return;const{error:n}=await q.from("deal_tasks").update({status:"done",completed_at:new Date().toISOString()}).in("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function FXs(s){const t=ma();return ct({queryKey:["deal-task-templates",t,s],queryFn:async()=>{if(!t)return[];let n=q.from("deal_task_templates").select("*").eq("owner_user_id",t).order("sort_order",{ascending:!0});s&&(n=n.eq("stage_id",s));const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})}function zXs(){const s=ma(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("deal_task_templates").insert({owner_user_id:s,stage_id:n.stage_id,title:n.title,description:n.description||null,priority:n.priority||"medium",default_due_offset_days:n.default_due_offset_days||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function BXs(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("deal_task_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-task-templates"]})}})}function $Xs(){const s=ma(),t=Ht();return gt({mutationFn:async({dealId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("deal_task_templates").select("*").eq("owner_user_id",s).eq("stage_id",r).order("sort_order");if(i)throw i;if(!a||a.length===0)return[];const{data:l}=await q.from("deal_tasks").select("title, stage_id").eq("deal_id",n).eq("stage_id",r),o=new Set((l||[]).map(h=>h.title)),c=a.filter(h=>!o.has(h.title)).map((h,p)=>({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:p,status:"todo"}));if(c.length===0)return[];const{data:d,error:u}=await q.from("deal_tasks").insert(c).select();if(u)throw u;return d},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}const UXs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function qXs({open:s,onOpenChange:t,dealId:n,dealName:r,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=PXs(s?n:void 0),u=OXs(),h=$Xs(),[p,f]=N.useState(new Set),[g,_]=N.useState(!1),v=(c||[]).filter(A=>A.status!=="done");N.useEffect(()=>{v.length>0&&f(new Set(v.map(A=>A.id)))},[c]);const j=A=>{f(T=>{const L=new Set(T);return L.has(A)?L.delete(A):L.add(A),L})},b=async()=>{_(!0);try{const A=Array.from(p);A.length>0&&await u.mutateAsync(A),await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(A){console.error("Stage move failed:",A),ae.error((A==null?void 0:A.message)||"Failed to move deal. Please try again.")}finally{_(!1)}},S=async()=>{_(!0);try{await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(A){console.error("Stage move (skip) failed:",A),ae.error((A==null?void 0:A.message)||"Failed to move deal. Please try again.")}finally{_(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[480px]",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Move Deal"}),e.jsxs(Qn,{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(ze,{variant:"outline",className:"text-sm",children:a}),e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ze,{className:"text-sm bg-primary",children:i})]}),d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["You have ",e.jsx("span",{className:"font-medium text-foreground",children:v.length})," incomplete task",v.length!==1?"s":"",". Select which to mark as done:"]}),e.jsx(hi,{className:"max-h-[250px]",children:e.jsx("div",{className:"space-y-1",children:v.map(A=>e.jsxs("label",{className:"flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-muted/50 cursor-pointer transition-colors",children:[e.jsx(ui,{checked:p.has(A.id),onCheckedChange:()=>j(A.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[UXs[A.priority]," ",A.title]}),A.stage&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full",style:{backgroundColor:A.stage.color+"20",color:A.stage.color},children:A.stage.name})]},A.id))})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>{p.size===v.length?f(new Set):f(new Set(v.map(A=>A.id)))},children:p.size===v.length?"Deselect All":"Select All"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:S,disabled:g,children:"Skip"}),e.jsxs(B,{size:"sm",onClick:b,disabled:g,children:[g&&e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}),p.size>0?`Complete ${p.size} & Move`:"Move Deal"]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-center py-4",children:[e.jsx(xr,{className:"h-8 w-8 text-emerald-500 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"All tasks completed! Ready to move."})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:b,disabled:g,children:[g&&e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}),"Move to ",i]})]})]})]})})}const VXs=[{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"}];function S2t({open:s,onOpenChange:t}){const n=ma(),{data:r,isLoading:a}=Fht(),i=FJt(),[l,o]=N.useState({logo_url:null,cover_photo_url:null,brand_color:null,accent_color:null,tagline:null,welcome_message:null}),[c,d]=N.useState(null);N.useEffect(()=>{s&&o({logo_url:(r==null?void 0:r.logo_url)??null,cover_photo_url:(r==null?void 0:r.cover_photo_url)??null,brand_color:(r==null?void 0:r.brand_color)??null,accent_color:(r==null?void 0:r.accent_color)??null,tagline:(r==null?void 0:r.tagline)??null,welcome_message:(r==null?void 0:r.welcome_message)??null})},[s,r]);const u=f=>o(g=>({...g,...f})),h=async(f,g)=>{if(n){if(f.size>5*1024*1024){ae.error("Image must be under 5MB");return}d(g);try{const _=await zht(n,f,g);u(g==="logo"?{logo_url:_}:{cover_photo_url:_})}catch(_){ae.error(`Upload failed: ${_.message||_}`)}finally{d(null)}}},p=async()=>{try{await i.mutateAsync(l),ae.success("Portal branding saved"),t(!1)}catch{ae.error("Failed to save branding")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(fl,{className:"h-5 w-5 text-primary"}),"Portal Branding"]}),e.jsx(Qn,{children:"Customize how your client portals look. These defaults apply to every portal — you can override them per deal."})]}),e.jsx(hi,{className:"flex-1 pr-3 -mr-3",children:a?e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx(ts,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6 py-2",children:[e.jsx(HXs,{draft:l}),e.jsx(hXe,{label:"Logo",hint:"Shown above your name on the portal. PNG with transparent background works best.",value:l.logo_url,uploading:c==="logo",onUpload:f=>h(f,"logo"),onClear:()=>u({logo_url:null}),aspect:"square"}),e.jsx(hXe,{label:"Cover Photo",hint:"Hero background at the top of the portal. Wide landscape works best.",value:l.cover_photo_url,uploading:c==="cover",onUpload:f=>h(f,"cover"),onClear:()=>u({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(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:VXs.map(f=>{const g=l.brand_color===f.brand&&l.accent_color===f.accent;return e.jsxs("button",{type:"button",onClick:()=>u({brand_color:f.brand,accent_color:f.accent}),className:Et("group relative rounded-lg border-2 p-2 text-left transition-all",g?"border-primary ring-2 ring-primary/20":"border-input hover:border-primary/40"),children:[e.jsxs("div",{className:"flex h-6 rounded-md overflow-hidden",children:[e.jsx("div",{className:"flex-1",style:{background:f.brand}}),e.jsx("div",{className:"flex-1",style:{background:f.accent}})]}),e.jsx("div",{className:"text-[11px] mt-1.5 font-medium text-foreground",children:f.name})]},f.name)})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(mXe,{label:"Brand",value:l.brand_color,onChange:f=>u({brand_color:f})}),e.jsx(mXe,{label:"Accent",value:l.accent_color,onChange:f=>u({accent_color:f})})]})]}),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:f=>u({tagline:f.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:f=>u({welcome_message:f.target.value}),placeholder:"Welcome! Here's everything you need for your transaction.",className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[70px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",maxLength:300})]})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:p,disabled:i.isPending,children:[i.isPending?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(qo,{className:"h-4 w-4 mr-2"}),"Save Branding"]})]})]})})}function HXs({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 hXe({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(nl,{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(ts,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Na,{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(_n,{className:"h-3.5 w-3.5"})})]})]})]})}function mXe({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 GXs(){const s=ma();return ct({queryKey:["all-client-portals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("client_portals").select("*").eq("owner_user_id",s);if(n)throw n;return t||[]},enabled:!!s})}function WXs({dealId:s,dealName:t,contactName:n,portal:r,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=vLe(),d=jR(),u=G_t(),h=W_t(),[p,f]=N.useState(!1),g=!!(r!=null&&r.archived_at),_=async()=>{f(!0);try{await c.mutateAsync({deal_id:s,visibility:"private",require_onboarding:!0}),ae.success("Portal enabled!")}catch{ae.error("Failed to create portal")}finally{f(!1)}},v=async T=>{if(r)try{await d.mutateAsync({id:r.id,is_enabled:T}),ae.success(T?"Portal enabled":"Portal disabled")}catch{ae.error("Failed to update portal")}},j=()=>{r&&(navigator.clipboard.writeText(Tw(r.slug)),ae.success("Link copied!"))},b=()=>{r&&window.open(Tw(r.slug),"_blank")},S=async()=>{if(r)try{await u.mutateAsync(r.id),ae.success("Portal archived")}catch{ae.error("Failed to archive portal")}},A=async()=>{if(r)try{await h.mutateAsync(r.id),ae.success("Portal restored")}catch{ae.error("Failed to restore portal")}};return r?g?e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg opacity-60 bg-muted/30",children:[e.jsxs(Ln,{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(ze,{variant:"outline",className:"text-[10px] bg-muted text-muted-foreground",children:"Archived"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.client_name||n||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:A,className:"text-xs gap-1",children:[e.jsx(ZP,{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(_n,{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(Ln,{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(ze,{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(xa,{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:j,title:"Copy link",children:e.jsx(Xr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:b,title:"Preview",children:e.jsx(tr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(r,t),title:"Invite client",children:e.jsx(cr,{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(nw,{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(Xo,{className:"h-3.5 w-3.5"})}),e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Qf,{className:"h-3.5 w-3.5"})})}),e.jsx(cc,{align:"end",children:e.jsxs(Qr,{onClick:S,children:[e.jsx(rm,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(bn,{checked:r.is_enabled,onCheckedChange:v,className:"ml-1"})]})]}):e.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg border-dashed bg-muted/20",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n||"No contact"})]}),e.jsxs(B,{size:"sm",onClick:_,disabled:p,className:"shrink-0 ml-4",children:[p?e.jsx(ts,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(un,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function C2t(){const{data:s,isLoading:t}=abe(),{data:n,isLoading:r}=GXs(),[a,i]=N.useState(""),[l,o]=N.useState("all"),c=K_t(),[d,u]=N.useState(null),[h,p]=N.useState(null),[f,g]=N.useState(null),[_,v]=N.useState(null),[j,b]=N.useState(!1),S=ma(),A=t||r,T=new Map;n==null||n.forEach(W=>T.set(W.deal_id,W));const D=[...(s||[]).filter(W=>{var ie,he,ce,pe,le;const Y=T.get(W.id),K=a.toLowerCase(),J=!K||W.deal_name.toLowerCase().includes(K)||((he=(ie=W.contact)==null?void 0:ie.first_name)==null?void 0:he.toLowerCase().includes(K))||((pe=(ce=W.contact)==null?void 0:ce.last_name)==null?void 0:pe.toLowerCase().includes(K))||((le=Y==null?void 0:Y.client_name)==null?void 0:le.toLowerCase().includes(K));let ne=!0;return l==="active"?ne=!!(Y!=null&&Y.is_enabled)&&!(Y!=null&&Y.archived_at):l==="disabled"?ne=!!Y&&!Y.is_enabled&&!Y.archived_at:l==="archived"?ne=!!(Y!=null&&Y.archived_at):l==="none"?ne=!Y:l==="all"&&(ne=!(Y!=null&&Y.archived_at)||!Y),J&&ne})].sort((W,Y)=>{const K=T.get(W.id),J=T.get(Y.id);if(K!=null&&K.archived_at&&!(J!=null&&J.archived_at))return 1;if(!(K!=null&&K.archived_at)&&(J!=null&&J.archived_at)||K&&!J)return-1;if(!K&&J)return 1;if(K&&J){if(K.is_enabled&&!J.is_enabled)return-1;if(!K.is_enabled&&J.is_enabled)return 1}return 0}),M=(n==null?void 0:n.filter(W=>!W.archived_at).length)||0,F=(n==null?void 0:n.filter(W=>W.is_enabled&&!W.archived_at).length)||0,z=(n==null?void 0:n.filter(W=>W.archived_at).length)||0,V=async()=>{if(_)try{await c.mutateAsync({id:_.id,dealId:_.deal_id}),ae.success("Portal permanently deleted"),v(null)}catch{ae.error("Failed to delete portal")}};return A?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium",children:[M," Portals"]})]}),e.jsxs("span",{className:"text-muted-foreground",children:[F," active · ",M-F," disabled",z>0&&` · ${z} archived`]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>b(!0),className:"gap-1.5",children:[e.jsx(fl,{className:"h-3.5 w-3.5"}),"Portal Branding"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search deals or clients...",value:a,onChange:W=>i(W.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(Bn,{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(W=>e.jsx(B,{variant:l===W?"secondary":"ghost",size:"sm",onClick:()=>o(W),className:"text-xs px-3 capitalize",children:W==="none"?"No Portal":W},W))})]}),e.jsx(hi,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[D.map(W=>{const Y=T.get(W.id)||null,K=W.contact?`${W.contact.first_name||""} ${W.contact.last_name||""}`.trim():"";return e.jsx(WXs,{dealId:W.id,dealName:W.deal_name,contactName:K,portal:Y,onSettingsOpen:u,onComposerOpen:J=>p(J),onInviteOpen:(J,ne)=>g({portal:J,dealName:ne}),onDeleteConfirm:v},W.id)}),D.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-3 bg-muted rounded-full flex items-center justify-center",children:e.jsx(un,{className:"h-5 w-5 text-muted-foreground"})}),e.jsx("p",{className:"text-sm font-medium",children:"No matching deals"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Try adjusting your search or filters"})]})]})})]}),d&&e.jsx(_8e,{open:!!d,onOpenChange:W=>!W&&u(null),portal:d,dealOwnerId:S||""}),h&&e.jsx(w8e,{open:!!h,onOpenChange:W=>!W&&p(null),portalId:h.id,portalSlug:h.slug,notifyClient:h.notify_client}),f&&e.jsx(j8e,{open:!!f,onOpenChange:W=>!W&&g(null),portal:f.portal,dealName:f.dealName}),e.jsx(S2t,{open:j,onOpenChange:b}),e.jsx(Oo,{open:!!_,onOpenChange:W=>!W&&v(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Permanently delete this portal?"}),e.jsx(Mo,{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(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:V,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}class KXs extends N.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("DealPipeline error:",t,n)}render(){return this.state.hasError?e.jsx(Ts,{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 FF="deal-pipeline-detail-sheet";function YXs(){var Cs;const s=wR(),{data:t,isLoading:n}=KU(),{data:r,isLoading:a,refetch:i}=abe(),{data:l,isLoading:o}=JZs(),c=x2t(),d=GZs(),[u,h]=N.useState("board"),[p,f]=N.useState(!1),[g,_]=N.useState(!1),[v,j]=N.useState(null),[b,S]=N.useState(null),[A,T]=N.useState(null),[L,D]=N.useState(null),[M,F]=N.useState(!1),[z,V]=N.useState(null),[W,Y]=N.useState(""),[K,J]=N.useState("all"),[ne,ie]=N.useState("all"),[he,ce]=N.useState("all"),{data:pe}=$Qs(),[le,ve]=N.useState(!1),[ge,Te]=N.useState(!1),[Me,Ce]=N.useState(new Set),Ae=N.useRef(!1),[De,Ie]=N.useState(null),{data:Fe}=Zv(),{isTeamLeader:qe,teamMembers:be}=zQs(),Ze=N.useMemo(()=>Array.from(Me),[Me]),{data:Ne}=BQs(Ze),it=N.useMemo(()=>{const As=new Map;return be.forEach(rn=>As.set(rn.id,{name:rn.name,avatar_url:rn.avatar_url,color:rn.color})),As},[be]),je=N.useCallback(As=>As.owner_user_id&&it.get(As.owner_user_id)||null,[it]),Ge=N.useCallback(As=>{Ce(rn=>{const tn=new Set(rn);return tn.has(As)?tn.delete(As):tn.add(As),tn})},[]);N.useEffect(()=>{!n&&t&&t.length===0&&c.mutate()},[n,t]);const[Be,Ye]=gl(),We=N.useRef(!1);N.useEffect(()=>{const As=Be.get("deal");if(As&&r&&r.length>0&&!We.current){const rn=r.find(tn=>tn.id===As);rn&&(We.current=!0,j(rn),_(!0),Be.delete("deal"),Ye(Be,{replace:!0}))}},[r,Be]);const rt=N.useMemo(()=>{if(!Ne||!t)return[];const As=new Map(t.map(rn=>[rn.name,rn.id]));return Ne.map(rn=>{const tn=rn._stage_name&&As.get(rn._stage_name)||null;return{...rn,stage_id:tn||rn.stage_id}})},[Ne,t]),tt=N.useMemo(()=>[...r||[],...rt],[r,rt]);N.useEffect(()=>{if(Ae.current||tt.length===0)return;Ae.current=!0;const As=sessionStorage.getItem(FF);if(As)try{const rn=JSON.parse(As);if(!rn.open||!rn.dealId)return;const tn=tt.find(er=>er.id===rn.dealId);tn&&(j(tn),_(!0))}catch{sessionStorage.removeItem(FF)}},[tt]),N.useEffect(()=>{g&&(v!=null&&v.id)?sessionStorage.setItem(FF,JSON.stringify({dealId:v.id,open:!0})):sessionStorage.removeItem(FF)},[g,v==null?void 0:v.id]);const at=(pe==null?void 0:pe.byDeal)||{},He=(pe==null?void 0:pe.unique)||[],dt=tt.filter(As=>{var Ls,fi,Lr,Jn,js,Dn;const rn=W.toLowerCase(),tn=at[As.id]||[],er=!rn||As.deal_name.toLowerCase().includes(rn)||((fi=(Ls=As.contact)==null?void 0:Ls.first_name)==null?void 0:fi.toLowerCase().includes(rn))||((Jn=(Lr=As.contact)==null?void 0:Lr.last_name)==null?void 0:Jn.toLowerCase().includes(rn))||((js=As.property_address)==null?void 0:js.toLowerCase().includes(rn))||((Dn=As.city)==null?void 0:Dn.toLowerCase().includes(rn))||tn.some(wr=>wr.toLowerCase().includes(rn)),gn=K==="all"||As.deal_type===K,In=ne==="all"||tn.includes(ne),Zn=As.actual_close_date||As.target_close_date||As.contract_date||As.created_at,ea=Zn?String(Zn).slice(0,4):null;return er&&gn&&In&&(he==="all"||ea===he)}),bt=N.useMemo(()=>{const As=new Set;return As.add(String(new Date().getFullYear())),tt.forEach(rn=>{const tn=rn.actual_close_date||rn.target_close_date||rn.contract_date||rn.created_at;tn&&As.add(String(tn).slice(0,4))}),Array.from(As).sort((rn,tn)=>Number(tn)-Number(rn))},[tt]),vt=N.useMemo(()=>{if(!t)return l||null;const As=new Set(t.filter(Zn=>Zn.is_won_stage).map(Zn=>Zn.id)),rn=new Set(t.filter(Zn=>Zn.is_lost_stage).map(Zn=>Zn.id)),tn=tt.filter(Zn=>Zn.stage_id&&!As.has(Zn.stage_id)&&!rn.has(Zn.stage_id)),er=tt.filter(Zn=>Zn.stage_id&&As.has(Zn.stage_id)),gn=new Date().getFullYear(),In=er.filter(Zn=>Zn.actual_close_date?new Date(Zn.actual_close_date).getFullYear()===gn:!0);return{totalDeals:tt.length,activeDeals:tn.length,wonDeals:er.length,pipelineValue:tn.reduce((Zn,ea)=>Zn+(ea.expected_price||0),0),expectedCommission:tn.reduce((Zn,ea)=>Zn+(ea.expected_commission||0),0),expectedNetToAgent:tn.reduce((Zn,ea)=>Zn+(Cv(ea)||0),0),wonValue:er.reduce((Zn,ea)=>Zn+(ea.expected_price||0),0),weightedGCI:tn.reduce((Zn,ea)=>Zn+(ea.expected_commission||0)*((ea.probability??50)/100),0),weightedNet:tn.reduce((Zn,ea)=>Zn+(Cv(ea)||0)*((ea.probability??50)/100),0),ytdWonDeals:In.length,ytdWonGCI:In.reduce((Zn,ea)=>Zn+(ea.expected_commission||0),0),ytdWonNet:In.reduce((Zn,ea)=>Zn+(Cv(ea)||0),0),projectedAnnualNet:In.reduce((Zn,ea)=>Zn+(Cv(ea)||0),0)+tn.reduce((Zn,ea)=>Zn+(Cv(ea)||0)*((ea.probability??50)/100),0)}},[tt,t,l]),Bt=As=>{j(As),_(!0)},Zt=As=>{S(As||null),j(null),f(!0)},Fs=As=>{j(As),_(!1),f(!0)},Rs=As=>{_(As),As||sessionStorage.removeItem(FF)},ms=(As,rn)=>{T(As)},Pt=(As,rn)=>{As.preventDefault(),As.dataTransfer.dropEffect="move",D(rn)},Jt=async(As,rn)=>{if(As.preventDefault(),D(null),!A)return;const tn=r==null?void 0:r.find(In=>In.id===A),er=t==null?void 0:t.find(In=>In.id===rn),gn=t==null?void 0:t.find(In=>In.id===(tn==null?void 0:tn.stage_id));if(!tn||!er||tn.stage_id===rn){T(null);return}Ie({dealId:A,dealName:tn.deal_name,fromStageName:(gn==null?void 0:gn.name)||"Unknown",toStageName:er.name,toStageId:rn,isWonStage:er.is_won_stage,deal:tn}),T(null)},ft=async()=>{if(!De)return;const{dealId:As,toStageId:rn,toStageName:tn,isWonStage:er,deal:gn}=De;if(await d.mutateAsync({dealId:As,stageId:rn,stageName:tn}),ae.success(`Moved to ${tn}`),er&&!gn.scorecard_transaction_id){const In={...gn,stage_id:rn};V(In),F(!0)}},Vt=N.useCallback(async(As,rn,tn)=>{const er=r==null?void 0:r.find(Zn=>Zn.id===As),gn=t==null?void 0:t.find(Zn=>Zn.id===rn),In=t==null?void 0:t.find(Zn=>Zn.id===(er==null?void 0:er.stage_id));!er||!gn||er.stage_id===rn||Ie({dealId:As,dealName:er.deal_name,fromStageName:(In==null?void 0:In.name)||"Unknown",toStageName:tn,toStageId:rn,isWonStage:gn.is_won_stage,deal:er})},[r,t]),Ms=As=>dt.filter(rn=>rn.stage_id===As),Xt=n||a,Js=s?"list":u;return e.jsxs(Ts,{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(Ti,{className:"h-4 w-4"})}),!s&&e.jsx(Ww,{children:e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsxs(Ec,{children:[e.jsx(Ac,{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(yf,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Board"})]})}),e.jsx(vc,{children:"Kanban board view"})]}),e.jsxs(Ec,{children:[e.jsx(Ac,{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(Tp,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"List"})]})}),e.jsx(vc,{children:"Grouped list view"})]}),e.jsxs(Ec,{children:[e.jsx(Ac,{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(yL,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Table"})]})}),e.jsx(vc,{children:"Sortable table view"})]}),e.jsxs(Ec,{children:[e.jsx(Ac,{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(un,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Portals"})]})}),e.jsx(vc,{children:"Client portal management"})]})]})}),Fe&&!qe&&e.jsxs(B,{variant:"outline",onClick:()=>ve(!0),children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Team"]}),e.jsxs(B,{onClick:()=>Zt(),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Deal"]})]})]}),Js!=="portals"&&e.jsx(HQs,{stats:vt,isLoading:o}),Js!=="portals"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search deals, contacts, addresses, tags...",value:W,onChange:As=>Y(As.target.value),className:"pl-9 pr-8"}),W&&e.jsx("button",{onClick:()=>Y(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(Bn,{className:"h-4 w-4"})})]}),e.jsxs(ds,{value:K,onValueChange:J,children:[e.jsx(ls,{className:"w-[140px]",children:e.jsx(us,{placeholder:"All Types"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Types"}),e.jsx(Qe,{value:"buyer",children:"Buyer"}),e.jsx(Qe,{value:"seller",children:"Seller"}),e.jsx(Qe,{value:"dual",children:"Dual"}),e.jsx(Qe,{value:"referral",children:"Referral"}),e.jsx(Qe,{value:"lease",children:"Lease"})]})]}),e.jsxs(ds,{value:he,onValueChange:ce,children:[e.jsx(ls,{className:"w-[120px]",children:e.jsx(us,{placeholder:"Year"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Years"}),bt.map(As=>e.jsx(Qe,{value:As,children:As},As))]})]}),e.jsxs(ds,{value:ne,onValueChange:ie,children:[e.jsxs(ls,{className:"w-[160px]",children:[e.jsx(uh,{className:"h-3.5 w-3.5 mr-1.5 text-muted-foreground"}),e.jsx(us,{placeholder:"All Tags"})]}),e.jsxs(cs,{className:"max-h-[300px]",children:[e.jsx(Qe,{value:"all",children:"All Tags"}),He.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),He.map(As=>e.jsx(Qe,{value:As,children:As},As))]})]}),ne!=="all"&&e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(uh,{className:"h-3 w-3"}),ne,e.jsx("button",{onClick:()=>ie("all"),className:"ml-1 hover:text-foreground","aria-label":"Clear tag filter",children:e.jsx(Bn,{className:"h-3 w-3"})})]}),(W||K!=="all"||ne!=="all"||he!=="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:[qe&&!s&&be.length>0&&e.jsx(FQs,{members:be,enabledMembers:Me,onToggleMember:Ge,isOpen:ge,onToggleOpen:()=>Te(As=>!As)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:Xt?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(As=>e.jsx("div",{className:"min-w-[280px] max-w-[320px] flex-shrink-0",children:e.jsx(Ws,{className:"h-full rounded-xl"})},As))}):Js==="board"?e.jsxs(hi,{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(As=>e.jsx(VQs,{stage:As,deals:Ms(As.id),onDealClick:Bt,onAddDeal:Zt,onDragStart:ms,onDragOver:Pt,onDrop:Jt,isDragOver:L===As.id,isWonStage:As.is_won_stage,getOwnerInfo:je},As.id))}),e.jsx(iU,{orientation:"horizontal"})]}):Js==="table"?e.jsx(hi,{className:"h-full",children:e.jsx(MXs,{deals:dt,stages:t||[],onDealClick:Bt,onStageChange:Vt})}):Js==="portals"?e.jsx(C2t,{}):e.jsx(hi,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map(As=>{const rn=Ms(As.id);return rn.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:As.color}}),e.jsx("h3",{className:"font-semibold",children:As.name}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",rn.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:rn.map(tn=>e.jsx(j2t,{deal:tn,onClick:()=>Bt(tn),stages:t,onStageChange:Vt,showStagePicker:!0,isWonStage:As.is_won_stage,ownerInfo:je(tn)},tn.id))})]},As.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(yf,{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:()=>Zt(),children:[e.jsx(Is,{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(vr,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"font-semibold text-lg mb-2",children:"No matching deals"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Try adjusting your search or filters"}),e.jsx(B,{variant:"outline",onClick:()=>{Y(""),J("all"),ie("all"),ce("all")},children:"Clear Filters"})]})]})})})]})]}),e.jsx(YQs,{open:p,onOpenChange:f,deal:v,defaultStageId:b}),e.jsx(TXs,{deal:v,open:g,onOpenChange:Rs,onEdit:Fs,isWonStage:v?(Cs=t==null?void 0:t.find(As=>As.id===v.stage_id))==null?void 0:Cs.is_won_stage:!1,onAddToScorecard:As=>{V(As),F(!0),_(!1)}}),e.jsx(EXs,{open:M,onOpenChange:F,deal:z,onComplete:()=>{i(),V(null)}}),De&&e.jsx(qXs,{open:!!De,onOpenChange:As=>{As||Ie(null)},dealId:De.dealId,dealName:De.dealName,fromStageName:De.fromStageName,toStageName:De.toStageName,toStageId:De.toStageId,onConfirm:ft}),e.jsx(RQs,{open:le,onOpenChange:ve})]})}function ZXs(){return e.jsx(KXs,{children:e.jsx(YXs,{})})}function T2t({open:s,onOpenChange:t,editTask:n,defaultDealId:r,defaultStageId:a}){var Y;const i=LXs(),l=DXs(),{data:o}=abe(),c=ma(),{data:d}=ct({queryKey:["contacts-for-tasks",c],queryFn:async()=>{if(!c)return[];const{data:K,error:J}=await q.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",c).order("first_name").limit(500);if(J)throw J;return K},enabled:!!c&&s}),[u,h]=N.useState(""),[p,f]=N.useState(""),[g,_]=N.useState("none"),[v,j]=N.useState("none"),[b,S]=N.useState("medium"),[A,T]=N.useState("todo"),[L,D]=N.useState(),[M,F]=N.useState(!1),[z,V]=N.useState(!1);N.useEffect(()=>{n?(h(n.title),f(n.description||""),_(n.deal_id||"none"),j(n.contact_id||"none"),S(n.priority),T(n.status),D(n.due_date?Xh(n.due_date):void 0)):(h(""),f(""),_(r||"none"),j("none"),S("medium"),T("todo"),D(void 0))},[n,s,r]);const W=async()=>{if(!u.trim()){ae.error("Task title is required");return}try{const K={title:u.trim(),description:p.trim()||null,deal_id:g==="none"?null:g,contact_id:v==="none"?null:v,stage_id:a||null,priority:b,status:A,due_date:L?Ss(L,"yyyy-MM-dd"):null};n?(await l.mutateAsync({id:n.id,...K}),ae.success("Task updated")):(await i.mutateAsync(K),ae.success("Task created")),t(!1)}catch{ae.error("Failed to save task")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[480px]",children:[e.jsx(ws,{children:e.jsx(_s,{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:K=>h(K.target.value),placeholder:"e.g., Send inspection report"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Es,{value:p,onChange:K=>f(K.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(ds,{value:b,onValueChange:K=>S(K),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"low",children:"🟢 Low"}),e.jsx(Qe,{value:"medium",children:"🟡 Medium"}),e.jsx(Qe,{value:"high",children:"🟠 High"}),e.jsx(Qe,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Status"}),e.jsxs(ds,{value:A,onValueChange:K=>T(K),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"todo",children:"To Do"}),e.jsx(Qe,{value:"in_progress",children:"In Progress"}),e.jsx(Qe,{value:"done",children:"Done"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Due Date"}),e.jsxs(el,{children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal",!L&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),L?Ss(L,"PPP"):"Pick a date"]})}),e.jsx(Ho,{className:"w-auto p-0",align:"start",children:e.jsx(Kg,{mode:"single",selected:L,onSelect:D,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Link to Deal"}),e.jsxs(el,{open:M,onOpenChange:F,children:[e.jsx(tl,{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(Va,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),g!=="none"?((Y=o==null?void 0:o.find(K=>K.id===g))==null?void 0:Y.deal_name)||"Select deal":"No Deal"]}),e.jsx(qg,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ho,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Qg,{children:[e.jsx(Xg,{placeholder:"Search deals..."}),e.jsxs(Jg,{children:[e.jsx(e0,{children:"No deals found."}),e.jsxs(t0,{children:[e.jsxs(Jf,{value:"no-deal",onSelect:()=>{_("none"),F(!1)},children:[e.jsx(Ir,{className:Et("mr-2 h-4 w-4",g==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),o==null?void 0:o.map(K=>e.jsxs(Jf,{value:K.deal_name,onSelect:()=>{_(K.id),F(!1)},children:[e.jsx(Ir,{className:Et("mr-2 h-4 w-4",g===K.id?"opacity-100":"opacity-0")}),K.deal_name]},K.id))]})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Link to Contact"}),e.jsxs(el,{open:z,onOpenChange:V,children:[e.jsx(tl,{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(Xi,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),v!=="none"?(()=>{const K=d==null?void 0:d.find(J=>J.id===v);return K?`${K.first_name} ${K.last_name}`:"Select contact"})():"No Contact"]}),e.jsx(qg,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ho,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Qg,{children:[e.jsx(Xg,{placeholder:"Search contacts..."}),e.jsxs(Jg,{children:[e.jsx(e0,{children:"No contacts found."}),e.jsxs(t0,{children:[e.jsxs(Jf,{value:"no-contact",onSelect:()=>{j("none"),V(!1)},children:[e.jsx(Ir,{className:Et("mr-2 h-4 w-4",v==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map(K=>e.jsxs(Jf,{value:`${K.first_name} ${K.last_name}`,onSelect:()=>{j(K.id),V(!1)},children:[e.jsx(Ir,{className:Et("mr-2 h-4 w-4",v===K.id?"opacity-100":"opacity-0")}),K.first_name," ",K.last_name]},K.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:W,disabled:i.isPending||l.isPending,children:n?"Save Changes":"Create Task"})]})]})]})})}const QXs={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 XXs({tasks:s}){const t=ibe(),n=RXs(),r=Mn(),[a,i]=N.useState(null),l=async u=>{const h=u.status==="done"?"todo":"done";try{await t.mutateAsync({id:u.id,status:h})}catch{ae.error("Failed to update task")}},o=async u=>{try{await n.mutateAsync(u),ae.success("Task deleted")}catch{ae.error("Failed to delete task")}};if(s.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[e.jsx(xr,{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(pXe,{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(Va,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("h3",{className:"font-medium text-sm",children:h.dealName}),e.jsxs(ze,{variant:"secondary",className:"ml-auto text-xs",children:[h.tasks.filter(p=>p.status==="done").length,"/",h.tasks.length]}),e.jsx(xa,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),h.tasks.map(p=>e.jsx(pXe,{task:p,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:f=>r(`/mission-control/pipeline?deal=${f}`)},p.id))]},u)),a&&e.jsx(T2t,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function pXe({task:s,onToggle:t,onDelete:n,onEdit:r,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&ww(Xh(s.due_date))&&!cf(Xh(s.due_date)),o=!i&&s.due_date&&cf(Xh(s.due_date)),c=QXs[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(xr,{className:"h-5 w-5 text-emerald-500"}):e.jsx(lm,{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(Xi,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]})]}),e.jsxs(ze,{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(gr,{className:"h-3 w-3"}),Ss(Xh(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(ku,{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(_n,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const JXs=[{status:"todo",label:"To Do",icon:lm,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:Au,color:"border-t-blue-500"},{status:"done",label:"Done",icon:xr,color:"border-t-emerald-500"}],eJs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function tJs({tasks:s}){const t=ibe(),n=N.useMemo(()=>{const i={todo:[],in_progress:[],done:[]};return s.forEach(l=>i[l.status].push(l)),i},[s]),r=(i,l)=>{i.dataTransfer.setData("taskId",l)},a=async(i,l)=>{i.preventDefault();const o=i.dataTransfer.getData("taskId");if(!o)return;const c=s.find(d=>d.id===o);if(!(!c||c.status===l))try{await t.mutateAsync({id:o,status:l})}catch{ae.error("Failed to move task")}};return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:JXs.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(ze,{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(sJs,{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 sJs({task:s,onDragStart:t}){const n=s.status==="done",r=!n&&s.due_date&&ww(Xh(s.due_date))&&!cf(Xh(s.due_date)),a=!n&&s.due_date&&cf(Xh(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:eJs[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(Va,{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(Xi,{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(gr,{className:"h-2.5 w-2.5"}),r?"Overdue — ":a?"Due today — ":"",Ss(Xh(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 fXe={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function nJs({tasks:s}){const[t,n]=N.useState(new Date),r=ibe(),a=Fd(t),i=V0(t),l=Wm(a),o=w8(i),c=D4e({start:l,end:o}),d=N.useMemo(()=>{const p=new Map;return s.forEach(f=>{if(!f.due_date)return;const g=f.due_date,_=p.get(g)||[];_.push(f),p.set(g,_)}),p},[s]),u=N.useMemo(()=>s.filter(p=>!p.due_date),[s]),h=async p=>{const f=p.status==="done"?"todo":"done";try{await r.mutateAsync({id:p.id,status:f})}catch{ae.error("Failed to update task")}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>n(GE(t,1)),children:e.jsx(pl,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:Ss(t,"MMMM yyyy")}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>n(Nf(t,1)),children:e.jsx(xa,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-7 text-center",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(p=>e.jsx("div",{className:"text-xs font-medium text-muted-foreground py-2",children:p},p))}),e.jsx("div",{className:"grid grid-cols-7 border-l border-t",children:c.map(p=>{const f=Ss(p,"yyyy-MM-dd"),g=d.get(f)||[],_=sU(p,t),v=cf(p);return e.jsxs("div",{className:Et("border-r border-b min-h-[100px] p-1",!_&&"bg-muted/30",v&&"bg-primary/5"),children:[e.jsx("div",{className:Et("text-xs font-medium mb-1 text-right px-1",!_&&"text-muted-foreground/40",v&&"text-primary font-bold"),children:Ss(p,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[g.slice(0,3).map(j=>e.jsxs("button",{onClick:()=>h(j),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",j.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[j.status==="done"?e.jsx(xr,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(lm,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[fXe[j.priority]," ",j.title]})]},j.id)),g.length>3&&e.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",g.length-3," more"]})]})]},f)})}),u.length>0&&e.jsxs("div",{className:"border rounded-lg p-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-muted-foreground mb-2",children:["No Due Date (",u.length,")"]}),e.jsx("div",{className:"space-y-1",children:u.map(p=>e.jsxs("button",{onClick:()=>h(p),className:Et("w-full text-left text-xs px-2 py-1.5 rounded flex items-center gap-2 hover:bg-muted transition-colors",p.status==="done"&&"opacity-50 line-through"),children:[p.status==="done"?e.jsx(xr,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(lm,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[fXe[p.priority]," ",p.title]}),p.deal&&e.jsxs("span",{className:"text-muted-foreground ml-auto shrink-0",children:["• ",p.deal.deal_name]})]},p.id))})]})]})}const rJs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function aJs({open:s,onOpenChange:t,stages:n}){var j;const[r,a]=N.useState(((j=n[0])==null?void 0:j.id)||""),{data:i,isLoading:l}=FXs(r||void 0),o=zXs(),c=BXs(),[d,u]=N.useState(""),[h,p]=N.useState("medium"),[f,g]=N.useState(""),_=async()=>{if(!(!d.trim()||!r))try{await o.mutateAsync({stage_id:r,title:d.trim(),priority:h,default_due_offset_days:f?parseInt(f):null,sort_order:((i==null?void 0:i.length)||0)+1}),u(""),g(""),ae.success("Template added")}catch{ae.error("Failed to add template")}},v=async b=>{try{await c.mutateAsync(b),ae.success("Template deleted")}catch{ae.error("Failed to delete template")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[560px]",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(t9,{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(b=>!b.is_won_stage&&!b.is_lost_stage).map(b=>e.jsx("button",{onClick:()=>a(b.id),className:Et("px-3 py-1.5 rounded-full text-xs font-medium border transition-colors",r===b.id?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted"),children:b.name},b.id))})]}),e.jsx(hi,{className:"max-h-[250px]",children:e.jsxs("div",{className:"space-y-1.5",children:[i==null?void 0:i.map((b,S)=>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:rJs[b.priority]}),e.jsx("span",{className:"text-sm flex-1 truncate",children:b.title}),b.default_due_offset_days&&e.jsxs(ze,{variant:"outline",className:"text-[10px]",children:["+",b.default_due_offset_days,"d"]}),e.jsx("button",{onClick:()=>v(b.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(_n,{className:"h-3.5 w-3.5 text-destructive"})})]},b.id)),(i==null?void 0:i.length)===0&&r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No templates for this stage yet"})]})}),r&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(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:b=>u(b.target.value),className:"flex-1",onKeyDown:b=>b.key==="Enter"&&_()}),e.jsxs(ds,{value:h,onValueChange:b=>p(b),children:[e.jsx(ls,{className:"w-[100px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"low",children:"🟢 Low"}),e.jsx(Qe,{value:"medium",children:"🟡 Med"}),e.jsx(Qe,{value:"high",children:"🟠 High"}),e.jsx(Qe,{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:f,onChange:b=>g(b.target.value)})]}),e.jsxs(B,{onClick:_,disabled:!d.trim()||o.isPending,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function iJs(){const{data:s,isLoading:t}=IXs(),{data:n}=KU(),[r,a]=N.useState("list"),[i,l]=N.useState(""),[o,c]=N.useState("active"),[d,u]=N.useState("all"),[h,p]=N.useState("all"),[f,g]=N.useState(!1),[_,v]=N.useState(!1),j=N.useMemo(()=>{if(!s)return[];const A=new Map;return s.forEach(T=>{T.deal&&A.set(T.deal.id,T.deal.deal_name)}),Array.from(A,([T,L])=>({id:T,name:L}))},[s]),b=N.useMemo(()=>s?s.filter(A=>{var z,V,W,Y;const T=i.toLowerCase(),L=!T||A.title.toLowerCase().includes(T)||((V=(z=A.deal)==null?void 0:z.deal_name)==null?void 0:V.toLowerCase().includes(T))||`${((W=A.contact)==null?void 0:W.first_name)||""} ${((Y=A.contact)==null?void 0:Y.last_name)||""}`.toLowerCase().includes(T),D=o==="all"||o==="active"&&A.status!=="done"||o==="todo"&&A.status==="todo"||o==="in_progress"&&A.status==="in_progress"||o==="done"&&A.status==="done"||o==="overdue"&&A.status!=="done"&&A.due_date&&ww(Xh(A.due_date))&&!cf(Xh(A.due_date)),M=d==="all"||A.priority===d,F=h==="all"||h==="no_deal"&&!A.deal_id||A.deal_id===h;return L&&D&&M&&F}):[],[s,i,o,d,h]),S=N.useMemo(()=>{if(!s)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const A=s.filter(T=>T.status!=="done");return{total:A.length,overdue:A.filter(T=>T.due_date&&ww(Xh(T.due_date))&&!cf(Xh(T.due_date))).length,dueToday:A.filter(T=>T.due_date&&cf(Xh(T.due_date))).length,dueThisWeek:A.filter(T=>T.due_date&&zUt(Xh(T.due_date))).length,completed:s.filter(T=>T.status==="done").length}},[s]);return e.jsx(Ts,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-6 max-w-[1600px] mx-auto",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Tasks"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Manage tasks across deals and contacts"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>v(!0),children:[e.jsx(Rv,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs(B,{size:"sm",onClick:()=>g(!0),children:[e.jsx(Is,{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(Tp,{className:"h-3.5 w-3.5"}),"Active"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:S.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($l,{className:"h-3.5 w-3.5"}),"Overdue"]}),e.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:S.overdue})]}),e.jsxs("button",{onClick:()=>{c("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-xs font-medium",children:[e.jsx(gr,{className:"h-3.5 w-3.5"}),"Due Today"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:S.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(Tl,{className:"h-3.5 w-3.5"}),"This Week"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:S.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(xr,{className:"h-3.5 w-3.5"}),"Completed"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:S.completed})]})]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3 items-start md:items-center",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search tasks...",value:i,onChange:A=>l(A.target.value),className:"pl-9"})]}),e.jsxs(ds,{value:d,onValueChange:u,children:[e.jsx(ls,{className:"w-[130px]",children:e.jsx(us,{placeholder:"Priority"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Priorities"}),e.jsx(Qe,{value:"urgent",children:"🔴 Urgent"}),e.jsx(Qe,{value:"high",children:"🟠 High"}),e.jsx(Qe,{value:"medium",children:"🟡 Medium"}),e.jsx(Qe,{value:"low",children:"🟢 Low"})]})]}),e.jsxs(ds,{value:h,onValueChange:p,children:[e.jsx(ls,{className:"w-[160px]",children:e.jsx(us,{placeholder:"Deal"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Deals"}),e.jsx(Qe,{value:"no_deal",children:"No Deal"}),j.map(A=>e.jsx(Qe,{value:A.id,children:A.name},A.id))]})]}),e.jsxs("div",{className:"flex items-center border rounded-lg p-0.5 ml-auto",children:[e.jsx("button",{onClick:()=>a("list"),className:`p-1.5 rounded-md transition-colors ${r==="list"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(Tp,{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(Z2,{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(Tl,{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(XXs,{tasks:b}),r==="kanban"&&e.jsx(tJs,{tasks:b}),r==="calendar"&&e.jsx(nJs,{tasks:b})]}),e.jsx(T2t,{open:f,onOpenChange:g}),e.jsx(aJs,{open:_,onOpenChange:v,stages:n||[]})]})})}function oJs(s){const t=N8e(s);return t?t.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):""}function lJs({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 EG({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 cJs(){const s=Mn(),{data:t,isLoading:n}=yXs(),r=ibe(),[a,i]=N.useState(""),[l,o]=N.useState(!1),[c,d]=N.useState("all"),u=N.useMemo(()=>{let b=t||[];c==="contract"&&(b=b.filter(A=>!!A.contract_date));const S=a.trim().toLowerCase();return S&&(b=b.filter(A=>{var T,L,D,M;return((T=A.deal_name)==null?void 0:T.toLowerCase().includes(S))||((L=A.property_address)==null?void 0:L.toLowerCase().includes(S))||`${((D=A.contact)==null?void 0:D.first_name)??""} ${((M=A.contact)==null?void 0:M.last_name)??""}`.toLowerCase().includes(S)})),b},[t,a,c]),h=N.useMemo(()=>{const b=[];return(u||[]).forEach(S=>{A7.forEach(A=>{const T=S[A.key],L=q_(T);T&&L!==null&&L<=30&&b.push({id:`${S.id}-${A.key}`,kind:"date",label:A.label,dealId:S.id,dealName:S.deal_name,date:T,days:L})}),S.tasks.filter(A=>A.status!=="done"&&A.due_date).forEach(A=>{const T=q_(A.due_date);T!==null&&T<=30&&b.push({id:A.id,kind:"task",label:A.title,dealId:S.id,dealName:S.deal_name,date:A.due_date,days:T,priority:A.priority})})}),b.sort((S,A)=>S.days-A.days)},[u]),p=N.useMemo(()=>({overdue:h.filter(b=>b.days<0),today:h.filter(b=>b.days===0),week:h.filter(b=>b.days>0&&b.days<=7),later:h.filter(b=>b.days>7)}),[h]),f=N.useMemo(()=>{const b=t||[],S=b.filter(L=>{const D=q_(L.target_close_date);return D!==null&&D>=0&&D<=7}).length,A=b.reduce((L,D)=>L+D.tasks.filter(M=>{const F=q_(M.due_date);return M.status!=="done"&&F!==null&&F<0}).length,0),T=b.reduce((L,D)=>L+(Number(D.expected_price)||0),0);return{active:b.length,closingSoon:S,overdueTasks:A,volume:T}},[t]),g=b=>b.tasks.length===0?0:b.tasks.filter(S=>S.status==="done").length/b.tasks.length*100,_=b=>s(`/mission-control/pipeline?deal=${b}`),v=async b=>{try{await r.mutateAsync({id:b,status:"done"}),ae.success("Task completed")}catch{ae.error("Could not update task")}},j=({title:b,items:S,tone:A})=>{if(S.length===0)return null;const T=A==="danger"?"bg-destructive":A==="warn"?"bg-amber-500":"bg-primary";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 px-1",children:[e.jsx("span",{className: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:b}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",S.length,")"]})]}),S.slice(0,12).map(L=>e.jsxs("div",{className:Et("group flex items-center gap-3 rounded-lg border px-3 py-2 transition-colors hover:bg-muted/50",A==="danger"&&"border-destructive/30 bg-destructive/5"),children:[L.kind==="task"?e.jsx(ui,{className:"shrink-0",onCheckedChange:()=>v(L.id),"aria-label":`Complete ${L.label}`}):e.jsx(om,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>_(L.dealId),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"text-sm font-medium leading-tight truncate",children:L.label}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[L.dealName," · ",oJs(L.date)]})]}),e.jsx("span",{className:Et("text-[11px] font-semibold shrink-0 tabular-nums",L.days<0?"text-destructive":L.days<=3?"text-amber-600":"text-muted-foreground"),children:L.days<0?`${Math.abs(L.days)}d late`:L.days===0?"Today":`${L.days}d`})]},L.id))]})};return e.jsxs(Ts,{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(Ou,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(EG,{icon:Dv,label:"Active transactions",value:f.active}),e.jsx(EG,{icon:Dc,label:"Closing within 7 days",value:f.closingSoon,tone:"warn"}),e.jsx(EG,{icon:$l,label:"Overdue tasks",value:f.overdueTasks,tone:f.overdueTasks>0?"danger":"good"}),e.jsx(EG,{icon:mo,label:"Pipeline volume",value:f.volume>=1e6?`$${(f.volume/1e6).toFixed(1)}M`:`$${Math.round(f.volume/1e3)}K`,tone:"good"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{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:b=>i(b.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-1 rounded-lg border p-1 bg-card",children:[e.jsx(B,{size:"sm",variant:c==="all"?"default":"ghost",onClick:()=>d("all"),className:"h-8",children:"All active"}),e.jsx(B,{size:"sm",variant:c==="contract"?"default":"ghost",onClick:()=>d("contract"),className:"h-8",children:"Under contract"})]})]}),n?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(ts,{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(om,{className:"h-4 w-4 text-primary"}),e.jsx("h2",{className:"text-sm font-semibold",children:"Deadline Radar"}),e.jsx(ze,{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(xr,{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(j,{title:"Overdue",items:p.overdue,tone:"danger"}),e.jsx(j,{title:"Today",items:p.today,tone:"warn"}),e.jsx(j,{title:"This week",items:p.week,tone:"warn"}),e.jsx(j,{title:"Coming up",items:p.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(Or,{className:"h-8 w-8 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium",children:"No active transactions"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Deals in progress will appear here with their full deadline chain."}),e.jsx(B,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/pipeline"),children:"Go to Deal Pipeline"})]}):u.map(b=>{const S=g(b),A=q_(b.target_close_date),T=b.tasks.filter(M=>M.status!=="done"),L=T.filter(M=>{const F=q_(M.due_date);return F!==null&&F<0}),D=T.filter(M=>M.due_date).sort((M,F)=>(q_(M.due_date)??0)-(q_(F.due_date)??0))[0];return e.jsx("button",{type:"button",onClick:()=>_(b.id),className:"w-full text-left rounded-xl border bg-card p-4 hover:border-primary/40 hover:shadow-sm transition-all group",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(lJs,{value:S}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-semibold truncate group-hover:text-primary transition-colors",children:b.deal_name}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[b.property_address||"Address TBD",b.contact&&` · ${b.contact.first_name} ${b.contact.last_name}`]})]}),e.jsx(xa,{className:"h-4 w-4 text-muted-foreground shrink-0 mt-0.5"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-2",children:[b.stage&&e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:`${b.stage.color}1f`,color:b.stage.color},children:b.stage.name}),e.jsx(ze,{variant:"outline",className:"text-[10px] capitalize",children:b.deal_type}),A!==null&&e.jsx(ze,{variant:"secondary",className:Et("text-[10px]",A<0&&"bg-destructive/10 text-destructive",A>=0&&A<=7&&"bg-amber-500/10 text-amber-700 dark:text-amber-400"),children:A<0?`Closing ${Math.abs(A)}d overdue`:`Closes in ${A}d`}),L.length>0&&e.jsxs(ze,{className:"text-[10px] bg-destructive/10 text-destructive hover:bg-destructive/10",children:[L.length," overdue"]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(pi,{value:S,className:"h-1.5"}),e.jsxs("div",{className:"flex items-center justify-between mt-1.5 gap-2",children:[e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[b.tasks.filter(M=>M.status==="done").length," of"," ",b.tasks.length," steps complete"]}),D&&e.jsxs("p",{className:"text-[11px] text-muted-foreground truncate max-w-[55%]",children:["Next: ",D.title]})]})]}),b.tasks.length===0&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-2 italic",children:"No checklist yet — open the deal and apply a playbook."})]})]})},b.id)})})]})]}),e.jsx(k2t,{open:l,onOpenChange:o})]})}function E2t(){const s=ma();return ct({queryKey:["portal-referrals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("portal_referrals").select("*, client_portals!inner(slug, client_name, deal_id)").eq("owner_user_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]},enabled:!!s})}function dJs(){const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("portal_referrals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}function uJs(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("portal_referrals").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}const hJs=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),BNe=[{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"}],mJs={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function A2t(){const{data:s=[],isLoading:t}=E2t(),n=dJs(),r=uJs(),[a,i]=N.useState("all"),[l,o]=N.useState({}),c=N.useMemo(()=>a==="all"?s:s.filter(f=>f.status===a),[s,a]),d=N.useMemo(()=>({total:s.length,new:s.filter(f=>f.status==="new").length,converted:s.filter(f=>f.status==="converted").length}),[s]),u=(f,g)=>{n.mutate({id:f.id,status:g}),ae.success("Status updated")},h=f=>{const g=l[f.id];n.mutate({id:f.id,agent_notes:g}),o(_=>{const{[f.id]:v,...j}=_;return j}),ae.success("Notes saved")},p=f=>{confirm(`Delete referral for ${f.friend_name}?`)&&r.mutate(f.id)};return e.jsxs("div",{className:"container max-w-5xl py-6 px-4",children:[e.jsx(Go,{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(Oi,{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"},...BNe.map(f=>({v:f.value,l:f.label}))].map(f=>e.jsx("button",{onClick:()=>i(f.v),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${a===f.v?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:f.l},f.v))}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(Oi,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No referrals yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Once your closed clients refer friends from their portal, they'll show up here."})]})}):e.jsx("div",{className:"space-y-3",children:c.map(f=>{var j,b;const g=BNe.find(S=>S.value===f.status),_=(j=f.client_portals)==null?void 0:j.slug,v=f.referrer_name||((b=f.client_portals)==null?void 0:b.client_name)||"Anonymous client";return e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:f.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1.5",children:[e.jsx(yr,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:v})," ·"," ",hJs(f.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ze,{variant:"outline",className:g==null?void 0:g.className,children:(g==null?void 0:g.label)||f.status}),e.jsxs(ds,{value:f.status,onValueChange:S=>u(f,S),children:[e.jsx(ls,{className:"h-8 w-[130px] text-xs",children:e.jsx(us,{})}),e.jsx(cs,{children:BNe.map(S=>e.jsx(Qe,{value:S.value,className:"text-xs",children:S.label},S.value))})]})]})]})}),e.jsxs(Ee,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[f.friend_interest&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:mJs[f.friend_interest]||f.friend_interest}),f.friend_email&&e.jsxs("a",{href:`mailto:${f.friend_email}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Vs,{className:"h-3 w-3"}),f.friend_email]}),f.friend_phone&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${f.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Ar,{className:"h-3 w-3"}),f.friend_phone]}),e.jsxs("a",{href:`sms:${f.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Ql,{className:"h-3 w-3"}),"Text"]})]})]}),f.friend_message&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-3 text-sm",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Note from referrer"}),e.jsxs("p",{className:"italic text-foreground",children:['"',f.friend_message,'"']})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Your notes"}),l[f.id]!==void 0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Es,{value:l[f.id],onChange:S=>o(A=>({...A,[f.id]:S.target.value})),rows:3,className:"text-sm"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",onClick:()=>h(f),children:"Save"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>o(S=>{const{[f.id]:A,...T}=S;return T}),children:"Cancel"})]})]}):e.jsx("button",{onClick:()=>o(S=>({...S,[f.id]:f.agent_notes||""})),className:"text-sm text-left w-full p-2 rounded border border-dashed border-input hover:border-primary/50 hover:bg-muted/30 transition-colors",children:f.agent_notes||e.jsx("span",{className:"text-muted-foreground italic",children:"Click to add notes..."})})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-3",children:[_&&e.jsxs("a",{href:`/portal/${_}`,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:()=>p(f),className:"text-destructive hover:text-destructive ml-auto h-8",children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})]},f.id)})})]})}function M2t({vendor:s,onEdit:t,onDelete:n,onToggleVisible:r,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=WD.find(d=>d.value===s.category))==null?void 0:c.label)||s.category;return e.jsxs(fe,{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(Kc,{className:"w-3.5 h-3.5 text-amber-600","aria-label":"Required"}),s.is_featured&&e.jsx(ca,{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(ze,{variant:"secondary",className:"text-[10px]",children:o}),i==="brokerage"&&e.jsx(ze,{variant:"outline",className:"text-[10px]",children:"Brokerage"}),i==="agent"&&e.jsx(ze,{variant:"outline",className:"text-[10px]",children:"Personal"}),!s.is_active&&e.jsx(ze,{variant:"destructive",className:"text-[10px]",children:"Inactive"}),typeof l=="number"&&l>0&&e.jsxs(ze,{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(Ar,{className:"w-3 h-3"}),s.phone]}),s.email&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Vs,{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(lc,{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(yr,{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(ka,{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(Er,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx(xf,{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(ku,{className:"w-3.5 h-3.5"})}),n&&e.jsx(B,{size:"sm",variant:"ghost",onClick:n,className:"text-destructive",children:e.jsx(_n,{className:"w-3.5 h-3.5"})})]})]})}function I2t({open:s,onOpenChange:t,vendor:n,ownerType:r,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=SJt(),[c,d]=N.useState({}),[u,h]=N.useState(!1),p=N.useRef(null),f=async v=>{if(!v.type.startsWith("image/")){ae.error("Please select an image");return}if(v.size>5*1024*1024){ae.error("Image must be under 5MB");return}h(!0);try{const j=v.name.split(".").pop()||"png",b=`${r}/${a||i||"misc"}/${Date.now()}.${j}`,{error:S}=await q.storage.from("vendor-logos").upload(b,v,{upsert:!0,contentType:v.type});if(S)throw S;const{data:A}=q.storage.from("vendor-logos").getPublicUrl(b);d(T=>({...T,logo_url:A.publicUrl})),ae.success("Logo uploaded")}catch(j){ae.error(j.message||"Upload failed")}finally{h(!1)}};N.useEffect(()=>{s&&d(n||{owner_type:r,owner_brokerage_id:r==="brokerage"&&a||null,owner_user_id:r==="agent"&&i||null,category:"other",action_type:"call",is_active:!0,is_featured:!1,is_required:!1})},[s,n,r,a,i]);const g=(v,j)=>d(b=>({...b,[v]:j})),_=async()=>{var v;if(!((v=c.name)!=null&&v.trim())){ae.error("Name is required");return}try{await o.mutateAsync(c),ae.success(n?"Vendor updated":"Vendor added"),t(!1)}catch(j){ae.error(j.message||"Failed to save vendor")}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:n?"Edit Vendor":"Add Vendor"})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Contact Name *"}),e.jsx(ye,{value:c.name||"",onChange:v=>g("name",v.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Company"}),e.jsx(ye,{value:c.company||"",onChange:v=>g("company",v.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Category"}),e.jsxs(ds,{value:c.category,onValueChange:v=>g("category",v),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:WD.map(v=>e.jsx(Qe,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:c.phone||"",onChange:v=>g("phone",v.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ye,{type:"email",value:c.email||"",onChange:v=>g("email",v.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Website"}),e.jsx(ye,{value:c.website||"",onChange:v=>g("website",v.target.value),placeholder:"https://..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Logo"}),e.jsx("input",{ref:p,type:"file",accept:"image/*",className:"hidden",onChange:v=>{var b;const j=(b=v.target.files)==null?void 0:b[0];j&&f(j),v.target.value=""}}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[c.logo_url?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:c.logo_url,alt:"Vendor logo",className:"h-14 w-14 rounded-md object-cover border"}),e.jsx("button",{type:"button",onClick:()=>g("logo_url",""),className:"absolute -top-2 -right-2 bg-background border rounded-full p-0.5 shadow","aria-label":"Remove logo",children:e.jsx(Bn,{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(Na,{className:"h-5 w-5"})}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var v;return(v=p.current)==null?void 0:v.click()},disabled:u,children:[u?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Na,{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:v=>g("address",v.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Es,{rows:3,value:c.description||"",onChange:v=>g("description",v.target.value),placeholder:"Why your clients should use this vendor..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Primary Action"}),e.jsxs(ds,{value:c.action_type,onValueChange:v=>g("action_type",v),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:jJt.map(v=>e.jsx(Qe,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Booking URL (Calendly etc.)"}),e.jsx(ye,{value:c.booking_url||"",onChange:v=>g("booking_url",v.target.value),placeholder:"https://calendly.com/..."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Compliance Disclosure (optional)"}),e.jsx(Es,{rows:2,value:c.disclosure_text||"",onChange:v=>g("disclosure_text",v.target.value),placeholder:"e.g. Agent receives no compensation for this referral."})]}),e.jsxs("div",{className:"flex items-center justify-between md:col-span-2 border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this vendor in client portals"})]}),e.jsx(bn,{checked:!!c.is_active,onCheckedChange:v=>g("is_active",v)})]}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight in agent library"})]}),e.jsx(bn,{checked:!!c.is_featured,onCheckedChange:v=>g("is_featured",v)})]}),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(bn,{checked:!!c.is_required,onCheckedChange:v=>g("is_required",v)})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:_,disabled:o.isPending,children:o.isPending?"Saving...":"Save Vendor"})]})]})})}function P2t({embedded:s=!1}={}){const t=ma(),{brokerageId:n}=ys(),{data:r,isLoading:a}=kJt(),{data:i={}}=Lht("agent",t),l=Iht(),o=CJt(),[c,d]=N.useState(null),[u,h]=N.useState(!1),[p,f]=N.useState(""),[g,_]=N.useState("all"),v=(r==null?void 0:r.vendors)||[],j=(r==null?void 0:r.selections)||[],b=N.useMemo(()=>{const z=new Map;return j.forEach(V=>z.set(V.vendor_id,V.is_visible)),z},[j]),S=N.useMemo(()=>v.filter(z=>!(g!=="all"&&z.category!==g||p&&!`${z.name} ${z.company||""}`.toLowerCase().includes(p.toLowerCase()))),[v,p,g]),A=S.filter(z=>z.owner_type==="agent"),T=S.filter(z=>z.owner_type==="brokerage"),L=async z=>{if(confirm("Delete this vendor?"))try{await l.mutateAsync(z),ae.success("Vendor deleted")}catch(V){ae.error(V.message)}},D=async(z,V)=>{try{await o.mutateAsync({vendorId:z,isVisible:V})}catch(W){ae.error(W.message)}},M=z=>z.is_required?!0:b.get(z.id)??z.owner_type==="agent",F=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(qm,{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(Is,{className:"w-4 h-4 mr-2"})," Add Personal Vendor"]})]}),e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(vr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(ye,{className:"pl-9",placeholder:"Search vendors...",value:p,onChange:z=>f(z.target.value)})]}),e.jsxs("select",{value:g,onChange:z=>_(z.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),WD.map(z=>e.jsx("option",{value:z.value,children:z.label},z.value))]})]}),a?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):e.jsxs(Br,{defaultValue:n?"all":"personal",children:[e.jsxs(Fr,{children:[e.jsxs(Kt,{value:"all",children:["All (",S.length,")"]}),n&&e.jsxs(Kt,{value:"brokerage",children:["From Brokerage (",T.length,")"]}),e.jsxs(Kt,{value:"personal",children:["My Personal (",A.length,")"]})]}),e.jsx(is,{value:"all",className:"mt-4",children:e.jsx($Ne,{vendors:S,isVisibleInPortals:M,onToggle:D,onEdit:z=>{d(z),h(!0)},onDelete:L,userId:t,clicks:i})}),n&&e.jsx(is,{value:"brokerage",className:"mt-4",children:T.length===0?e.jsx(xXe,{icon:e.jsx(un,{className:"w-12 h-12"}),title:"No brokerage vendors yet",desc:"Your brokerage hasn't added any vendors. Ask your manager to set them up."}):e.jsx($Ne,{vendors:T,isVisibleInPortals:M,onToggle:D,userId:t,clicks:i})}),e.jsx(is,{value:"personal",className:"mt-4",children:A.length===0?e.jsx(xXe,{icon:e.jsx(qm,{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(Is,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx($Ne,{vendors:A,isVisibleInPortals:M,onToggle:D,onEdit:z=>{d(z),h(!0)},onDelete:L,userId:t,clicks:i})})]}),e.jsx(I2t,{open:u,onOpenChange:h,vendor:c,ownerType:"agent",agentUserId:t})]});return s?F:e.jsx(Ts,{children:F})}function $Ne({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(M2t,{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 xXe({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 pJs(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=ys(),{data:a=[],isLoading:i}=NJt(s),{data:l={}}=Lht("brokerage",s),o=Iht(),[c,d]=N.useState(null),[u,h]=N.useState(!1),[p,f]=N.useState(""),[g,_]=N.useState("all");if(r)return e.jsx(Ts,{children:e.jsx("div",{className:"p-8",children:"Loading..."})});if(!t&&!n)return e.jsx(Ts,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const v=a.filter(b=>!(g!=="all"&&b.category!==g||p&&!`${b.name} ${b.company||""}`.toLowerCase().includes(p.toLowerCase()))),j=async b=>{if(confirm("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(b),ae.success("Vendor deleted")}catch(S){ae.error(S.message)}};return e.jsx(Ts,{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(Va,{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(Is,{className:"w-4 h-4 mr-2"})," Add Vendor"]})]}),e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(vr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(ye,{className:"pl-9",placeholder:"Search vendors...",value:p,onChange:b=>f(b.target.value)})]}),e.jsxs("select",{value:g,onChange:b=>_(b.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),WD.map(b=>e.jsx("option",{value:b.value,children:b.label},b.value))]})]}),i?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):v.length===0?e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx(Va,{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(Is,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:v.map(b=>e.jsx(M2t,{vendor:b,onEdit:()=>{d(b),h(!0)},onDelete:()=>j(b.id),clickCount:l[b.id]},b.id))}),e.jsx(I2t,{open:u,onOpenChange:h,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}const fJs=[{value:"overview",label:"Portals",icon:yf},{value:"vendors",label:"Vendors",icon:pb},{value:"referrals",label:"Referrals",icon:Oi},{value:"branding",label:"Branding",icon:fl},{value:"questions",label:"Onboarding",icon:uu}];function xJs(){const[s,t]=gl(),n=s.get("tab")||"overview",[r,a]=N.useState(n),[i,l]=N.useState(!1),[o,c]=N.useState(!1);return N.useEffect(()=>{t(d=>{const u=new URLSearchParams(d);return u.set("tab",r),u},{replace:!0})},[r,t]),e.jsxs(Ts,{children:[e.jsx(Go,{children:e.jsx("title",{children:"Client Portals"})}),e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsx("div",{className:"flex items-start justify-between flex-wrap gap-4",children:e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(un,{className:"w-6 h-6 text-primary"}),"Client Portals"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-2xl",children:"Your central hub for everything client-facing — manage active portals, curate trusted vendors, tune branding, and inbox referrals from happy clients."})]})}),e.jsx("div",{className:"border rounded-xl p-5 bg-card",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(U9,{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(Ln,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs(Br,{value:r,onValueChange:a,className:"w-full",children:[e.jsx(Fr,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:fJs.map(d=>e.jsxs(Kt,{value:d.value,className:"gap-2",children:[e.jsx(d.icon,{className:"w-4 h-4"}),d.label]},d.value))}),e.jsx(is,{value:"overview",className:"mt-6",children:e.jsx(C2t,{})}),e.jsx(is,{value:"vendors",className:"mt-6",children:e.jsx(gJs,{})}),e.jsx(is,{value:"referrals",className:"mt-6",children:e.jsx(yJs,{})}),e.jsx(is,{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(fl,{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(Xo,{className:"w-4 h-4 mr-2"}),"Edit Branding Defaults"]})]})]})})}),e.jsx(is,{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(uu,{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(Xo,{className:"w-4 h-4 mr-2"}),"Manage Questions"]})]})]})})})]})]}),e.jsx(S2t,{open:i,onOpenChange:l}),e.jsx(N2t,{open:o,onOpenChange:c})]})}function gJs(){return e.jsx(P2t,{embedded:!0})}function yJs(){return e.jsx(A2t,{})}const $I=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function vJs(s){return ct({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("client_portals").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return{portal:null,deal:null};const{data:r,error:a}=await q.from("deal_pipeline").select("deal_name, contact_id").eq("id",t.deal_id).maybeSingle();if(a)throw a;let i=null;if(r!=null&&r.contact_id){const{data:l,error:o}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",r.contact_id).maybeSingle();if(o)throw o;i=l}return{portal:t,deal:r?{deal_name:r.deal_name,contact_id:r.contact_id,contact:i}:null}},enabled:!!s})}function bJs(){const{portalId:s}=bi(),t=Mn(),n=ma(),{data:r,isLoading:a}=vJs(s),{data:i=[]}=SWs(s),{data:l=[]}=E2t(),o=jR(),c=G_t(),d=W_t(),u=K_t(),[h,p]=N.useState(!1),[f,g]=N.useState(!1),[_,v]=N.useState(!1),[j,b]=N.useState(!1),S=(r==null?void 0:r.portal)??null,A=(r==null?void 0:r.deal)??null,T=N.useMemo(()=>S?l.filter(ne=>ne.portal_id===S.id):[],[l,S==null?void 0:S.id]);if(a)return e.jsx(Ts,{children:e.jsx("div",{className:"flex items-center justify-center py-24",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!S)return e.jsx(Ts,{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(Ln,{to:"/mission-control/client-portals",children:[e.jsx(Hr,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const L=Tw(S.slug),D=(A==null?void 0:A.deal_name)||"Untitled deal",M=A==null?void 0:A.contact,F=M?`${M.first_name||""} ${M.last_name||""}`.trim():"",z=!!S.archived_at,V=()=>{navigator.clipboard.writeText(L),ae.success("Portal link copied!")},W=async ne=>{try{await o.mutateAsync({id:S.id,is_enabled:ne}),ae.success(ne?"Portal enabled":"Portal disabled")}catch{ae.error("Failed to update")}},Y=async()=>{try{await c.mutateAsync(S.id),ae.success("Portal archived")}catch{ae.error("Failed to archive")}},K=async()=>{try{await d.mutateAsync(S.id),ae.success("Portal restored")}catch{ae.error("Failed to restore")}},J=async()=>{try{await u.mutateAsync({id:S.id,dealId:S.deal_id}),ae.success("Portal deleted"),t("/mission-control/client-portals")}catch{ae.error("Failed to delete")}};return e.jsxs(Ts,{children:[e.jsx(Go,{children:e.jsxs("title",{children:[D," — 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(Ln,{to:"/mission-control/client-portals?tab=overview",children:[e.jsx(Hr,{className:"w-4 h-4 mr-1"})," All Client Portals"]})})}),e.jsxs("div",{className:"border rounded-xl p-6 bg-gradient-to-br from-card to-muted/30",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx(un,{className:"w-5 h-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold truncate",children:D}),e.jsx(ze,{variant:"outline",className:z?"bg-muted text-muted-foreground":S.is_enabled?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-muted text-muted-foreground",children:z?"Archived":S.is_enabled?"Active":"Disabled"}),e.jsx(ze,{variant:"outline",className:"capitalize text-xs",children:S.visibility})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2 flex-wrap",children:[e.jsx(Xi,{className:"w-3.5 h-3.5"}),S.client_name||F||"No client name set",(M==null?void 0:M.email)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(Vs,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"truncate",children:M.email})]}),(M==null?void 0:M.phone)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(Ar,{className:"w-3.5 h-3.5"}),M.phone]})]}),e.jsx("div",{className:"mt-3 flex items-center gap-2 bg-background/60 border rounded-md px-3 py-1.5 max-w-full",children:e.jsx("code",{className:"text-xs font-mono text-muted-foreground truncate flex-1",children:L})})]}),!z&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Live"}),e.jsx(bn,{checked:S.is_enabled,onCheckedChange:W})]})]}),e.jsxs("div",{className:"mt-5 flex items-center gap-2 flex-wrap",children:[e.jsxs(B,{onClick:V,variant:"outline",size:"sm",children:[e.jsx(Xr,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs(B,{onClick:()=>window.open(L,"_blank"),variant:"outline",size:"sm",children:[e.jsx(tr,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs(B,{onClick:()=>v(!0),size:"sm",children:[e.jsx(cr,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs(B,{onClick:()=>g(!0),variant:"outline",size:"sm",children:[e.jsx(nw,{className:"w-4 h-4 mr-1.5"})," Post Update"]}),e.jsxs(B,{onClick:()=>p(!0),variant:"outline",size:"sm",children:[e.jsx(Xo,{className:"w-4 h-4 mr-1.5"})," Settings"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[z?e.jsxs(B,{onClick:K,variant:"outline",size:"sm",children:[e.jsx(ZP,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs(B,{onClick:Y,variant:"ghost",size:"sm",children:[e.jsx(rm,{className:"w-4 h-4 mr-1.5"})," Archive"]}),e.jsx(B,{onClick:()=>b(!0),variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(AG,{icon:nw,label:"Updates Posted",value:i.length}),e.jsx(AG,{icon:Oi,label:"Referrals",value:T.length}),e.jsx(AG,{icon:yr,label:"Inspection",value:S.inspection_date?$I(S.inspection_date):"—"}),e.jsx(AG,{icon:yr,label:"Appraisal",value:S.appraisal_date?$I(S.appraisal_date):"—"})]}),e.jsxs(Br,{defaultValue:"updates",className:"w-full",children:[e.jsxs(Fr,{children:[e.jsxs(Kt,{value:"updates",children:["Updates (",i.length,")"]}),e.jsxs(Kt,{value:"referrals",children:["Referrals (",T.length,")"]}),e.jsx(Kt,{value:"branding",children:"Branding"}),e.jsx(Kt,{value:"details",children:"Details"})]}),e.jsx(is,{value:"updates",className:"mt-4",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold",children:"Portal Update Feed"}),e.jsxs(B,{size:"sm",onClick:()=>g(!0),children:[e.jsx(nw,{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(nw,{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(ne=>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:ne.title}),ne.is_stage_change&&e.jsx(ze,{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:$I(ne.created_at)}),ne.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:ne.content}),ne.video_url&&e.jsxs("a",{href:ne.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(br,{className:"w-3 h-3"})," View video"]})]})})},ne.id))})]})})}),e.jsx(is,{value:"referrals",className:"mt-4",children:e.jsx(fe,{children:e.jsxs(Ee,{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(Oi,{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(ne=>e.jsx(Ln,{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:ne.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ne.friend_email||ne.friend_phone||"No contact info"," · ",$I(ne.created_at)]})]}),e.jsx(ze,{variant:"outline",className:"text-xs capitalize",children:ne.status})]})},ne.id))})]})})}),e.jsx(is,{value:"branding",className:"mt-4",children:e.jsx(fe,{children:e.jsx(Ee,{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(fl,{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:()=>p(!0),children:[e.jsx(Xo,{className:"w-4 h-4 mr-2"}),"Edit Branding (in Settings)"]})]})]})})})}),e.jsx(is,{value:"details",className:"mt-4",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 space-y-4",children:[e.jsx(Mk,{label:"Visibility",value:S.visibility}),e.jsx(Mk,{label:"Onboarding Required",value:S.require_onboarding?"Yes":"No"}),e.jsx(Mk,{label:"Allow Spouse",value:S.allow_spouse?"Yes":"No"}),e.jsx(Mk,{label:"Notify Client on Updates",value:S.notify_client?"Yes":"No"}),e.jsx(Mk,{label:"Show Post-Close Tips",value:S.show_post_close_tips?"Yes":"No"}),e.jsx(Mk,{label:"Slug",value:S.slug,mono:!0}),e.jsx(Mk,{label:"Created",value:$I(S.created_at)}),e.jsx(Mk,{label:"Last Updated",value:$I(S.updated_at)}),e.jsx("div",{className:"pt-2",children:e.jsxs(B,{variant:"outline",onClick:()=>p(!0),children:[e.jsx(Xo,{className:"w-4 h-4 mr-2"})," Edit All Settings"]})})]})})})]})]}),e.jsx(_8e,{open:h,onOpenChange:p,portal:S,dealOwnerId:n||""}),e.jsx(w8e,{open:f,onOpenChange:g,portalId:S.id,portalSlug:S.slug,notifyClient:S.notify_client}),e.jsx(j8e,{open:_,onOpenChange:v,portal:S,dealName:D}),e.jsx(Oo,{open:j,onOpenChange:b,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Permanently delete this portal?"}),e.jsx(Mo,{children:"This removes the portal and all its updates. The client will lose access. This action cannot be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:J,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function AG({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 Mk({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 NTe=[{value:"video_intro",label:"Video Intro",icon:br,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:bw,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:uh,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:El,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:Hl,description:"Links to your social profiles"}],_Js=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],wJs={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function L2t({cardId:s}){const{data:t,isLoading:n}=Czt(s),r=Tzt(),a=Ezt(),i=Azt(),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState(null);if(n)return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ws,{className:"h-16 w-full"}),e.jsx(Ws,{className:"h-16 w-full"})]});const p=()=>{c&&r.mutate({card_id:s,block_type:c,sort_order:(t==null?void 0:t.length)||0,config:wJs[c]||{}},{onSuccess:()=>{o(!1),d("")}})},f=b=>{a.mutate({id:b.id,is_visible:!b.is_visible})},g=(b,S)=>{if(!t)return;const A=t.findIndex(D=>D.id===b.id),T=S==="up"?A-1:A+1;if(T<0||T>=t.length)return;const L=t[T];a.mutate({id:b.id,sort_order:L.sort_order}),a.mutate({id:L.id,sort_order:b.sort_order})},_=b=>{confirm("Remove this block from this card?")&&i.mutate(b.id)},v=(b,S)=>{a.mutate({id:b.id,config:S},{onSuccess:()=>h(null)})},j=b=>NTe.find(S=>S.value===b);return e.jsxs("div",{className:"space-y-3",children:[!t||t.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("p",{className:"text-muted-foreground mb-4 text-sm",children:"No blocks yet. Add a block to customize this card."}),e.jsxs(B,{size:"sm",onClick:()=>o(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((b,S)=>{const A=j(b.block_type),T=(A==null?void 0:A.icon)||uh;return e.jsx(fe,{className:b.is_visible?"":"opacity-50",children:e.jsx(Ee,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fu,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx(T,{className:"h-4 w-4 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-xs",children:(A==null?void 0:A.label)||b.block_type}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:jJs(b)})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(b,"up"),disabled:S===0,children:e.jsx(Ru,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(b,"down"),disabled:S===t.length-1,children:e.jsx(am,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>f(b),children:b.is_visible?e.jsx(Er,{className:"h-3 w-3"}):e.jsx(xf,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>h(b),children:"Edit"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>_(b),children:e.jsx(_n,{className:"h-3 w-3"})})]})]})})},b.id)}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:NTe.map(b=>{const S=b.icon;return e.jsxs("button",{onClick:()=>d(b.value),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors ${c===b.value?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[e.jsx(S,{className:"h-5 w-5 text-primary flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:b.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b.description})]})]},b.value)})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{onClick:p,disabled:!c||r.isPending,children:"Add Block"})]})]})}),u&&e.jsx(NJs,{block:u,onSave:b=>v(u,b),onClose:()=>h(null)})]})}function jJs(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 NJs({block:s,onSave:t,onClose:n}){const[r,a]=N.useState(s.config),i=NTe.find(l=>l.value===s.block_type);return e.jsx(bs,{open:!0,onOpenChange:n,children:e.jsxs(vs,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(kJs,{config:r,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx(SJs,{config:r,onChange:a}),s.block_type==="specialties"&&e.jsx(CJs,{config:r,onChange:a}),s.block_type==="custom_links"&&e.jsx(TJs,{config:r,onChange:a}),s.block_type==="social_media"&&e.jsx(EJs,{config:r,onChange:a}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(B,{onClick:()=>t(r),children:"Save"})]})]})})}function kJs({config:s,onChange:t,cardId:n}){var f,g;const[r,a]=N.useState(""),[i,l]=N.useState((f=s.video_url)!=null&&f.includes("youtube")||(g=s.video_url)!=null&&g.includes("youtu.be")?"youtube":"library"),{data:o}=ct({queryKey:["card-owner",n],queryFn:async()=>{const{data:_}=await q.from("agent_cards").select("user_id").eq("id",n).single();return _==null?void 0:_.user_id},enabled:!!n}),{data:c,isLoading:d}=ct({queryKey:["agent-videos-library",o],queryFn:async()=>{const{data:_,error:v}=await q.from("agent_videos").select("id, title, bunny_video_id, thumbnail_url, playback_url, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(v)throw v;return _||[]},enabled:!!o}),u=(c==null?void 0:c.filter(_=>!r||(_.title||"").toLowerCase().includes(r.toLowerCase())))||[],h=s.bunny_video_id,p=_=>{var S;const v=(S=_.playback_url)==null?void 0:S.match(/\/(?:play|embed)\/(\d+)\//),b=`https://iframe.mediadelivery.net/embed/${v?v[1]:"570924"}/${_.bunny_video_id}?autoplay=false&responsive=true`;t({...s,video_url:b,bunny_video_id:_.bunny_video_id,video_source:"library"})};return e.jsx("div",{className:"space-y-4",children:e.jsxs(Br,{value:i,onValueChange:l,children:[e.jsxs(Fr,{className:"w-full",children:[e.jsx(Kt,{value:"library",className:"flex-1",children:"Video Library"}),e.jsx(Kt,{value:"youtube",className:"flex-1",children:"YouTube URL"})]}),e.jsxs(is,{value:"library",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search videos...",value:r,onChange:_=>a(_.target.value),className:"pl-9"})]}),e.jsx(hi,{className:"h-[240px]",children:d?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ws,{className:"h-14 w-full"}),e.jsx(Ws,{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(_=>e.jsxs("button",{onClick:()=>p(_),className:`w-full flex items-center gap-3 p-2 rounded-lg border text-left transition-colors ${h===_.bunny_video_id?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[_.thumbnail_url?e.jsx("img",{src:_.thumbnail_url,alt:"",className:"h-10 w-16 rounded object-cover flex-shrink-0 bg-muted",onError:v=>{var j;v.currentTarget.style.display="none",(j=v.currentTarget.nextElementSibling)==null||j.classList.remove("hidden")}}):null,e.jsx("div",{className:`h-10 w-16 rounded bg-muted flex items-center justify-center flex-shrink-0 ${_.thumbnail_url?"hidden":""}`,children:e.jsx(br,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:_.title||"Untitled Video"}),h===_.bunny_video_id&&e.jsx(Ir,{className:"h-4 w-4 text-primary flex-shrink-0"})]},_.id))})})]}),e.jsx(is,{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:_=>t({...s,video_url:_.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 SJs({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(fe,{children:e.jsxs(Ee,{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(_n,{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(Is,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function CJs({config:s,onChange:t}){const n=s.tags||[],[r,a]=N.useState(""),i=o=>{t({...s,tags:n.includes(o)?n.filter(c=>c!==o):[...n,o]})},l=()=>{r.trim()&&!n.includes(r.trim())&&(t({...s,tags:[...n,r.trim()]}),a(""))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm mb-2 block",children:"Preset Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:_Js.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 TJs({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(_n,{className:"h-3 w-3"})})]},o)),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const gXe=[{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 EJs({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=gXe.filter(c=>!n.find(d=>d.platform===c.value)),o=c=>{const d=P4e[c],u=gXe.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(_n,{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=P4e[c.value];return e.jsxs("button",{onClick:()=>r(c.value),className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-full border border-border bg-muted hover:bg-muted/80 transition-colors",children:[(d==null?void 0:d.icon)&&e.jsx("svg",{viewBox:"0 0 24 24",width:12,height:12,fill:d.color,children:e.jsx("path",{d:d.icon})}),c.label]},c.value)})})]}),n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Tap a platform above to add your social media profile."})]})}var AJs=Object.defineProperty,Kge=Object.getOwnPropertySymbols,D2t=Object.prototype.hasOwnProperty,R2t=Object.prototype.propertyIsEnumerable,yXe=(s,t,n)=>t in s?AJs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,kTe=(s,t)=>{for(var n in t||(t={}))D2t.call(t,n)&&yXe(s,n,t[n]);if(Kge)for(var n of Kge(t))R2t.call(t,n)&&yXe(s,n,t[n]);return s},STe=(s,t)=>{var n={};for(var r in s)D2t.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&Kge)for(var r of Kge(s))t.indexOf(r)<0&&R2t.call(s,r)&&(n[r]=s[r]);return n};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var FM;(s=>{const t=class ul{constructor(c,d,u,h){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],cul.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 p=[];for(let g=0;g7)throw new RangeError("Invalid value");let g,_;for(g=u;;g++){const S=ul.getNumDataCodewords(g,d)*8,A=l.getTotalBits(c,g);if(A<=S){_=A;break}if(g>=h)throw new RangeError("Data too long")}for(const S of[ul.Ecc.MEDIUM,ul.Ecc.QUARTILE,ul.Ecc.HIGH])f&&_<=ul.getNumDataCodewords(g,S)*8&&(d=S);let v=[];for(const S of c){n(S.mode.modeBits,4,v),n(S.numChars,S.mode.numCharCountBits(g),v);for(const A of S.getData())v.push(A)}a(v.length==_);const j=ul.getNumDataCodewords(g,d)*8;a(v.length<=j),n(0,Math.min(4,j-v.length),v),n(0,(8-v.length%8)%8,v),a(v.length%8==0);for(let S=236;v.lengthb[A>>>3]|=S<<7-(A&7)),new ul(g,d,b,p)}getModule(c,d){return 0<=c&&c>>9)*1335;const h=(d<<10|u)^21522;a(h>>>15==0);for(let p=0;p<=5;p++)this.setFunctionModule(8,p,r(h,p));this.setFunctionModule(8,7,r(h,6)),this.setFunctionModule(8,8,r(h,7)),this.setFunctionModule(7,8,r(h,8));for(let p=9;p<15;p++)this.setFunctionModule(14-p,8,r(h,p));for(let p=0;p<8;p++)this.setFunctionModule(this.size-1-p,8,r(h,p));for(let p=8;p<15;p++)this.setFunctionModule(8,this.size-15+p,r(h,p));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),p=this.size-11+u%3,f=Math.floor(u/3);this.setFunctionModule(p,f,h),this.setFunctionModule(f,p,h)}}drawFinderPattern(c,d){for(let u=-4;u<=4;u++)for(let h=-4;h<=4;h++){const p=Math.max(Math.abs(h),Math.abs(u)),f=c+h,g=d+u;0<=f&&f{(S!=_-p||T>=g)&&b.push(A[S])});return a(b.length==f),b}drawCodewords(c){if(c.length!=Math.floor(ul.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let d=0;for(let u=this.size-1;u>=1;u-=2){u==6&&(u=5);for(let h=0;h>>3],7-(d&7)),d++)}}a(d==c.length*8)}applyMask(c){if(c<0||c>7)throw new RangeError("Mask value out of range");for(let d=0;d5&&c++):(this.finderPenaltyAddHistory(g,_),f||(c+=this.finderPenaltyCountPatterns(_)*ul.PENALTY_N3),f=this.modules[p][v],g=1);c+=this.finderPenaltyTerminateAndCount(f,g,_)*ul.PENALTY_N3}for(let p=0;p5&&c++):(this.finderPenaltyAddHistory(g,_),f||(c+=this.finderPenaltyCountPatterns(_)*ul.PENALTY_N3),f=this.modules[v][p],g=1);c+=this.finderPenaltyTerminateAndCount(f,g,_)*ul.PENALTY_N3}for(let p=0;pf+(g?1:0),d);const u=this.size*this.size,h=Math.ceil(Math.abs(d*20-u*10)/u)-1;return a(0<=h&&h<=9),c+=h*ul.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.lengthul.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(ul.getNumRawDataModules(c)/8)-ul.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*ul.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 p=h^u.shift();u.push(0),d.forEach((f,g)=>u[g]^=ul.reedSolomonMultiply(f,p))}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 eh{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 eh(eh.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!eh.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={}))})(FM||(FM={}));(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={}))})(FM||(FM={}));var BP=FM;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var MJs={L:BP.QrCode.Ecc.LOW,M:BP.QrCode.Ecc.MEDIUM,Q:BP.QrCode.Ecc.QUARTILE,H:BP.QrCode.Ecc.HIGH},O2t=128,F2t="L",z2t="#FFFFFF",B2t="#000000",$2t=!1,U2t=1,IJs=4,PJs=0,LJs=.1;function q2t(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 V2t(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 DJs(s,t,n,r){if(r==null)return null;const a=s.length+n*2,i=Math.floor(t*LJs),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 p=null;if(r.excavate){let g=Math.floor(d),_=Math.floor(u),v=Math.ceil(o+d-g),j=Math.ceil(c+u-_);p={x:g,y:_,w:v,h:j}}const f=r.crossOrigin;return{x:d,y:u,h:c,w:o,excavation:p,opacity:h,crossOrigin:f}}function RJs(s,t){return t!=null?Math.max(Math.floor(t),0):s?IJs:PJs}function H2t({value:s,level:t,minVersion:n,includeMargin:r,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=St.useMemo(()=>{const g=(Array.isArray(s)?s:[s]).reduce((_,v)=>(_.push(...BP.QrSegment.makeSegments(v)),_),[]);return BP.QrCode.encodeSegments(g,MJs[t],n,void 0,void 0,o)},[s,t,n,o]);const{cells:d,margin:u,numCells:h,calculatedImageSettings:p}=St.useMemo(()=>{let f=c.getModules();const g=RJs(r,a),_=f.length+g*2,v=DJs(f,l,g,i);return{cells:f,margin:g,numCells:_,calculatedImageSettings:v}},[c,l,i,r,a]);return{qrcode:c,margin:u,cells:d,numCells:h,calculatedImageSettings:p}}var OJs=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),FJs=St.forwardRef(function(t,n){const r=t,{value:a,size:i=O2t,level:l=F2t,bgColor:o=z2t,fgColor:c=B2t,includeMargin:d=$2t,minVersion:u=U2t,boostLevel:h,marginSize:p,imageSettings:f}=r,_=STe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:v}=_,j=STe(_,["style"]),b=f==null?void 0:f.src,S=St.useRef(null),A=St.useRef(null),T=St.useCallback(K=>{S.current=K,typeof n=="function"?n(K):n&&(n.current=K)},[n]),[L,D]=St.useState(!1),{margin:M,cells:F,numCells:z,calculatedImageSettings:V}=H2t({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:p,imageSettings:f,size:i});St.useEffect(()=>{if(S.current!=null){const K=S.current,J=K.getContext("2d");if(!J)return;let ne=F;const ie=A.current,he=V!=null&&ie!==null&&ie.complete&&ie.naturalHeight!==0&&ie.naturalWidth!==0;he&&V.excavation!=null&&(ne=V2t(F,V.excavation));const ce=window.devicePixelRatio||1;K.height=K.width=i*ce;const pe=i/z*ce;J.scale(pe,pe),J.fillStyle=o,J.fillRect(0,0,z,z),J.fillStyle=c,OJs?J.fill(new Path2D(q2t(ne,M))):F.forEach(function(le,ve){le.forEach(function(ge,Te){ge&&J.fillRect(Te+M,ve+M,1,1)})}),V&&(J.globalAlpha=V.opacity),he&&J.drawImage(ie,V.x+M,V.y+M,V.w,V.h)}}),St.useEffect(()=>{D(!1)},[b]);const W=kTe({height:i,width:i},v);let Y=null;return b!=null&&(Y=St.createElement("img",{src:b,key:b,style:{display:"none"},onLoad:()=>{D(!0)},ref:A,crossOrigin:V==null?void 0:V.crossOrigin})),St.createElement(St.Fragment,null,St.createElement("canvas",kTe({style:W,height:i,width:i,ref:T,role:"img"},j)),Y)});FJs.displayName="QRCodeCanvas";var YU=St.forwardRef(function(t,n){const r=t,{value:a,size:i=O2t,level:l=F2t,bgColor:o=z2t,fgColor:c=B2t,includeMargin:d=$2t,minVersion:u=U2t,boostLevel:h,title:p,marginSize:f,imageSettings:g}=r,_=STe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:v,cells:j,numCells:b,calculatedImageSettings:S}=H2t({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:f,imageSettings:g,size:i});let A=j,T=null;g!=null&&S!=null&&(S.excavation!=null&&(A=V2t(j,S.excavation)),T=St.createElement("image",{href:g.src,height:S.h,width:S.w,x:S.x+v,y:S.y+v,preserveAspectRatio:"none",opacity:S.opacity,crossOrigin:S.crossOrigin}));const L=q2t(A,v);return St.createElement("svg",kTe({height:i,width:i,viewBox:`0 0 ${b} ${b}`,ref:n,role:"img"},_),!!p&&St.createElement("title",null,p),St.createElement("path",{fill:o,d:`M0,0 h${b}v${b}H0z`,shapeRendering:"crispEdges"}),St.createElement("path",{fill:c,d:L,shapeRendering:"crispEdges"}),T)});YU.displayName="QRCodeSVG";function zJs({slug:s,agentName:t}){const n=N.useRef(null),r=`https://cards.relevelup.com/${s}`,a=N.useCallback(()=>{var h;const i=(h=n.current)==null?void 0:h.querySelector("svg");if(!i)return;const l=document.createElement("canvas"),o=1024;l.width=o,l.height=o;const c=l.getContext("2d");if(!c)return;const d=new XMLSerializer().serializeToString(i),u=new Image;u.onload=()=>{c.fillStyle="#ffffff",c.fillRect(0,0,o,o),c.drawImage(u,0,0,o,o);const p=document.createElement("a");p.download=`${s}-qr-code.png`,p.href=l.toDataURL("image/png"),p.click(),ae.success("QR code downloaded!")},u.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(d)))},[s]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"text-sm font-medium",children:"QR Code"}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{ref:n,className:"bg-white p-3 rounded-lg border shadow-sm shrink-0",children:e.jsx(YU,{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(Pa,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function UNe(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 BJs(){const{user:s}=ys(),{data:t,isLoading:n}=Nzt(s==null?void 0:s.id),r=wR(),[a,i]=N.useState(null),l=N.useMemo(()=>a||(t?UNe(t):null),[a,t]);if(n)return e.jsx(Ts,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 space-y-4",children:[e.jsx(Ws,{className:"h-8 w-48"}),e.jsx(Ws,{className:"h-32 w-full"}),e.jsx(Ws,{className:"h-32 w-full"})]})});if(!t)return e.jsx(Ts,{children:e.jsx(UJs,{userId:s==null?void 0:s.id})});const o=l||UNe(t),c=d=>{i(u=>{const h=u||UNe(t);return typeof d=="function"?d(h):d})};return e.jsx(Ts,{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(qJs,{card:t}),e.jsx(WJs,{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(xb,{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($Js,{card:t,form:o})})]})})]})})}function $Js({card:s,form:t}){const{data:n}=ct({queryKey:["card-preview-profile",s.user_id],queryFn:async()=>{const{data:a}=await q.from("profiles").select("name, email, phone, avatar_url, brokerage_id").eq("id",s.user_id).single();let i=(a==null?void 0:a.avatar_url)||null;if(!i){const{data:l}=await q.storage.from("avatars").list(`${s.user_id}`);if(l&&l.length>0){const{data:o}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${l[0].name}`);i=`${o.publicUrl}?t=${Date.now()}`}}return{...a,avatar_url:i}}}),r=N.useMemo(()=>({...s,is_published:t.is_published,theme:t.theme,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,custom_cta_url:s.custom_cta_url,show_photo:t.show_photo,show_bio:t.show_bio,show_video:s.show_video,show_credentials:t.show_credentials,show_social_links:t.show_social_links,show_save_contact:t.show_save_contact,show_leave_review:t.show_leave_review,show_refer_friend:t.show_refer_friend,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,display_email:t.display_email||null,social_links:s.social_links||[],profile:{name:(n==null?void 0:n.name)||null,email:t.display_email||(n==null?void 0:n.email)||null,phone:(n==null?void 0:n.phone)||null,brokerage_id:(n==null?void 0:n.brokerage_id)||null},brokerage_name:t.brokerage_display_name||null,avatar_url:(n==null?void 0:n.avatar_url)||null}),[s,t,n]);return e.jsx("div",{className:"transform scale-[0.85] origin-top",children:e.jsx(tMe,{card:r})})}function UJs({userId:s}){var c;const[t,n]=N.useState(""),r=gct(),{data:a}=ct({queryKey:["my-profile-for-card",s],queryFn:async()=>{if(!s)return null;const{data:d}=await q.from("profiles").select("name").eq("id",s).single();return d},enabled:!!s}),i=((c=a==null?void 0:a.name)==null?void 0:c.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||"",l=()=>{if(!s)return;const d=(t.trim()||i).toLowerCase().replace(/[^a-z0-9-]/g,"-");if(!d){ae.error("Please enter a URL slug for your card");return}r.mutate({user_id:s,slug:d,is_published:!0},{onSuccess:()=>ae.success("Your digital card has been created!")})},o=[{icon:lc,title:"Shareable Link",desc:"One link that works everywhere"},{icon:hh,title:"Lead Capture",desc:"Collect leads automatically"},{icon:dh,title:"Always Up-to-Date",desc:"Edit anytime, changes are instant"},{icon:fl,title:"Fully Customizable",desc:"Themes, colors, and content blocks"}];return e.jsxs("div",{className:"max-w-2xl mx-auto p-4 animate-fade-in",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary/90 via-primary to-primary/80 p-8 md:p-12 mb-8 text-primary-foreground",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_30%_20%,rgba(255,255,255,0.15),transparent_50%)]"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_80%_80%,rgba(0,0,0,0.1),transparent_50%)]"}),e.jsxs("div",{className:"relative z-10",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/20 backdrop-blur-sm text-sm font-medium mb-4",children:[e.jsx(un,{className:"h-3.5 w-3.5"}),"New Feature"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3 tracking-tight",children:"Your Digital Business Card"}),e.jsx("p",{className:"text-primary-foreground/80 text-lg max-w-md leading-relaxed",children:"Ditch the paper. Share a beautiful, interactive card that captures leads and makes a lasting impression."})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 mb-8",children:o.map(d=>e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-xl border bg-card hover:shadow-md transition-shadow",children:[e.jsx("div",{className:"mt-0.5 p-2 rounded-lg bg-primary/10 shrink-0",children:e.jsx(d.icon,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:d.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.desc})]})]},d.title))}),e.jsxs(fe,{className:"shadow-lg border-2",children:[e.jsxs(Mt,{className:"text-center pb-2",children:[e.jsx(It,{className:"text-xl",children:"Set Up Your Card"}),e.jsx(Vn,{children:"Choose a URL slug — this is the link you'll share with clients"})]}),e.jsxs(Ee,{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(un,{className:"h-4 w-4 mr-2"}),r.isPending?"Creating...":"Create My Card"]})]})]})]})}function qJs({card:s}){const n=`https://cards.relevelup.com/${s.slug}`,r=()=>{navigator.clipboard.writeText(n),ae.success("Card link copied!")};return e.jsx("div",{className:"rounded-xl border bg-card p-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-bold",children:"My Digital Card"}),e.jsx(ze,{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(lc,{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(Xr,{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 VJs({userId:s}){const t=Ht(),n=N.useRef(null),[r,a]=N.useState(!1),[i,l]=N.useState(""),{data:o,isLoading:c}=ct({queryKey:["card-editor-profile",s],queryFn:async()=>{const{data:V}=await q.from("profiles").select("name, email, phone, avatar_url").eq("id",s).single();let W=(V==null?void 0:V.avatar_url)||null;if(!W){const{data:Y}=await q.storage.from("avatars").list(`${s}`);if(Y&&Y.length>0){const{data:K}=q.storage.from("avatars").getPublicUrl(`${s}/${Y[0].name}`);W=`${K.publicUrl}?t=${Date.now()}`,await q.from("profiles").update({avatar_url:W}).eq("id",s)}}return{...V,avatar_url:W}}}),[d,u]=N.useState(null),[h,p]=N.useState(null),[f,g]=N.useState(null),[_,v]=N.useState(!1),j=d??(o==null?void 0:o.name)??"",b=h??(o==null?void 0:o.phone)??"",S=f??(o==null?void 0:o.email)??"",A=o==null?void 0:o.avatar_url,T=((o==null?void 0:o.name)||"A").split(" ").map(V=>V[0]).join("").toUpperCase().slice(0,2),L=!(o!=null&&o.avatar_url)||!(o!=null&&o.phone),D=gt({mutationFn:async V=>{const{error:W}=await q.from("profiles").update(V).eq("id",s);if(W)throw W},onSuccess:()=>{t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ae.success("Profile updated!")},onError:()=>ae.error("Failed to update profile")}),M=()=>{const V={};if(d!==null&&d!==(o==null?void 0:o.name)&&(V.name=d),h!==null&&h!==(o==null?void 0:o.phone)&&(V.phone=h||null),f!==null&&f!==(o==null?void 0:o.email)&&(V.email=f),Object.keys(V).length===0){ae.info("No changes to save");return}D.mutate(V)},F=V=>{var K;const W=(K=V.target.files)==null?void 0:K[0];if(!W)return;if(!W.type.startsWith("image/")){ae.error("Please select an image file");return}const Y=new FileReader;Y.onloadend=()=>{l(Y.result),a(!0)},Y.readAsDataURL(W),V.target.value=""},z=async V=>{v(!0);try{const{data:W}=await q.storage.from("avatars").list(`${s}`);W&&W.length>0&&await q.storage.from("avatars").remove(W.map(ie=>`${s}/${ie.name}`));const Y=`${s}/avatar.jpg`,{error:K}=await q.storage.from("avatars").upload(Y,V,{upsert:!0,contentType:"image/jpeg"});if(K)throw K;const{data:J}=q.storage.from("avatars").getPublicUrl(Y),ne=J.publicUrl+"?t="+Date.now();await q.from("profiles").update({avatar_url:ne}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ae.success("Photo updated!")}catch{ae.error("Failed to upload photo")}finally{v(!1)}};return c?e.jsx(Ws,{className:"h-32 w-full rounded-xl"}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:L?"border-amber-300 dark:border-amber-700":"",children:e.jsxs(Ee,{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"}),L&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 font-medium",children:[e.jsx(Gi,{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 V;return(V=n.current)==null?void 0:V.click()},children:[e.jsxs(ra,{className:"h-16 w-16 ring-2 ring-muted",children:[e.jsx(ni,{src:A||void 0,alt:j}),e.jsx(aa,{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(mf,{className:"h-5 w-5 text-white"})}),e.jsx("input",{ref:n,type:"file",accept:"image/*",className:"hidden",onChange:F})]}),e.jsxs("div",{className:"flex-1 space-y-0.5",children:[e.jsx("p",{className:"text-sm font-medium",children:_?"Uploading...":A?"Tap to change photo":"Add a profile photo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This photo appears on your card, profile, and community posts"})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Full Name"}),e.jsx(ye,{value:j,onChange:V=>u(V.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:b,onChange:V=>p(V.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:S,onChange:V=>g(V.target.value),placeholder:"you@example.com",className:"h-10",type:"email"})]})]})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:M,disabled:D.isPending,className:"w-full",children:D.isPending?"Saving...":"Update Profile Info"})]})}),e.jsx(hIe,{open:r,onClose:()=>a(!1),imageSrc:i,onCropComplete:z,aspectRatio:1})]})}function HJs({form:s,setForm:t,userId:n}){const[r,a]=N.useState(null),[i,l]=N.useState(s.brokerage_logo_url?"logo":"name"),[o,c]=N.useState(s.team_logo_url?"logo":"name"),d=f=>{l(f),t(f==="name"?g=>({...g,brokerage_logo_url:""}):g=>({...g,brokerage_display_name:""}))},u=f=>{c(f),t(f==="name"?g=>({...g,team_logo_url:""}):g=>({...g,team_name:""}))},h=async(f,g)=>{var v;const _=(v=f.target.files)==null?void 0:v[0];if(_){if(!_.type.startsWith("image/")){ae.error("Please select an image file");return}a(g);try{const j=_.name.split(".").pop()||"png",S=`${n}/${g==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${j}`,{error:A}=await q.storage.from("card-logos").upload(S,_,{upsert:!0});if(A)throw A;const{data:T}=q.storage.from("card-logos").getPublicUrl(S),L=T.publicUrl+"?t="+Date.now();t(g==="brokerage_logo_url"?D=>({...D,[g]:L,brokerage_display_name:""}):D=>({...D,[g]:L,team_name:""})),ae.success("Logo uploaded!")}catch{ae.error("Failed to upload logo")}finally{a(null),f.target.value=""}}},p=f=>{t(g=>({...g,[f]:""}))};return e.jsx(fe,{children:e.jsxs(Ee,{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:f=>t(g=>({...g,brokerage_display_name:f.target.value})),placeholder:"e.g. Keller Williams Realty",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(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:()=>p("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(mf,{className:"h-3.5 w-3.5"}),r==="brokerage_logo_url"?"Uploading...":s.brokerage_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:f=>h(f,"brokerage_logo_url"),disabled:r!==null})]})]}),s.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(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(Bm,{value:[s.brokerage_logo_size||56],onValueChange:([f])=>t(g=>({...g,brokerage_logo_size:f})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(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:f=>t(g=>({...g,team_name:f.target.value})),placeholder:"e.g. The Smith Group",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(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:()=>p("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(mf,{className:"h-3.5 w-3.5"}),r==="team_logo_url"?"Uploading...":s.team_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:f=>h(f,"team_logo_url"),disabled:r!==null})]})]}),s.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(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(Bm,{value:[s.team_logo_size||56],onValueChange:([f])=>t(g=>({...g,team_logo_size:f})),min:24,max:120,step:4})]})]})]})]})})}function GJs({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(fl,{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 WJs({card:s,form:t,setForm:n}){var _;const r=yct(),a=Ht(),{data:i}=vct(s.id),[l,o]=N.useState(s.slug),[c,d]=N.useState(!1),[u,h]=N.useState("idle"),p=N.useRef(JSON.stringify(t)),f=N.useRef(null);N.useEffect(()=>{const v=JSON.stringify(t);if(v!==p.current)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{h("saving"),r.mutate({id:s.id,...t,is_published:!0,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,bold_theme_colors:t.bold_theme_colors||null,display_email:t.display_email||null},{onSuccess:()=>{p.current=v,h("saved"),setTimeout(()=>h("idle"),2e3)},onError:()=>h("idle")})},1500),()=>{f.current&&clearTimeout(f.current)}},[t]);const g=async()=>{const v=l.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!v){ae.error("Please enter a valid URL");return}if(v===s.slug){ae.info("No changes to save");return}d(!0);try{const{data:j}=await q.from("agent_cards").select("id").eq("slug",v).neq("id",s.id).maybeSingle();if(j){ae.error("This URL is already taken. Try another one.");return}const{error:b}=await q.from("agent_cards").update({slug:v}).eq("id",s.id);if(b)throw b;o(v),a.invalidateQueries({queryKey:["agent-card"]}),ae.success("Card address updated!")}catch{ae.error("Failed to update card address")}finally{d(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Br,{defaultValue:"content",children:[e.jsxs(Fr,{className:"w-full h-11 p-1",children:[e.jsxs(Kt,{value:"content",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(pf,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Content"]}),e.jsxs(Kt,{value:"sections",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Er,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Sections"]}),e.jsxs(Kt,{value:"blocks",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(hh,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Blocks"]}),e.jsxs(Kt,{value:"qrcode",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(oy,{className:"h-3.5 w-3.5 hidden sm:inline"}),"QR Code"]}),e.jsxs(Kt,{value:"analytics",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(oc,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(is,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(VJs,{userId:s.user_id}),e.jsx(HJs,{form:t,setForm:n,userId:s.user_id}),e.jsx(fe,{children:e.jsxs(Ee,{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(bn,{checked:t.is_published,onCheckedChange:v=>n(j=>({...j,is_published:v}))})]}),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:v=>o(v.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"your-name",className:"rounded-l-none h-10"})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:g,disabled:c||l===s.slug,className:"shrink-0",children:c?"Saving...":"Update"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is your unique card URL. Only letters, numbers, and dashes allowed."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Card Email (Override)"}),e.jsx(ye,{value:t.display_email,onChange:v=>n(j=>({...j,display_email:v.target.value})),placeholder:"you@yourbusiness.com",className:"h-11",type:"email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional — use a different email on your card instead of your sign-in email."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Theme"}),e.jsxs(ds,{value:t.theme,onValueChange:v=>n(j=>({...j,theme:v})),children:[e.jsx(ls,{className:"h-11",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"standard",children:"✨ Standard — Modern & Clean"}),e.jsx(Qe,{value:"luxury",children:"🌙 Luxury — Dark & Gold"}),e.jsx(Qe,{value:"bold",children:"🔥 Bold — Vibrant & Punchy"}),e.jsx(Qe,{value:"classic",children:"📋 Classic — Professional"})]})]})]}),t.theme==="bold"&&e.jsx(GJs,{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:v=>n(j=>({...j,title:v.target.value})),placeholder:"e.g. Luxury Real Estate Specialist",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown below your name on the card"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Positioning Statement"}),e.jsx(ye,{value:t.positioning_statement,onChange:v=>n(j=>({...j,positioning_statement:v.target.value})),placeholder:"Your home journey, handled with care.",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Bio"}),e.jsx(Es,{value:t.bio,onChange:v=>n(j=>({...j,bio:v.target.value})),placeholder:"A short intro about you and what makes you different...",rows:3})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Review Snippet"}),e.jsx(ye,{value:t.review_snippet,onChange:v=>n(j=>({...j,review_snippet:v.target.value})),placeholder:"Best agent we've ever worked with...",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Review Source URL"}),e.jsx(ye,{value:t.review_source_url,onChange:v=>n(j=>({...j,review_source_url:v.target.value})),placeholder:"https://g.page/your-business/review",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Booking URL"}),e.jsx(ye,{value:t.booking_url,onChange:v=>n(j=>({...j,booking_url:v.target.value})),placeholder:"https://calendly.com/your-link",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to show a built-in lead form instead"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Custom CTA Label"}),e.jsx(ye,{value:t.custom_cta_label,onChange:v=>n(j=>({...j,custom_cta_label:v.target.value})),placeholder:"Book a Call",className:"h-11"})]})]})})]}),e.jsx(is,{value:"sections",className:"mt-4",children:e.jsx(fe,{children:e.jsx(Ee,{className:"p-5 divide-y",children:[{key:"show_photo",label:"Photo",desc:"Uses the photo from your Profile Info above"},{key:"show_bio",label:"Bio Section",desc:"Display your bio on the card"},{key:"show_credentials",label:"Credentials",desc:"Show star rating and reviews"},{key:"show_social_links",label:"Social Links",desc:"Display your social media links"},{key:"show_save_contact",label:"Save Contact",desc:"Let visitors save you as a contact"},{key:"show_leave_review",label:"Leave Review",desc:"Link to your review page"},{key:"show_refer_friend",label:"Refer a Friend",desc:"Enable referral submissions"}].map(({key:v,label:j,desc:b})=>e.jsxs("div",{className:"flex items-center justify-between py-4 first:pt-0 last:pb-0",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(se,{className:"text-sm font-medium",children:j}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]}),e.jsx(bn,{checked:t[v],onCheckedChange:S=>n(A=>({...A,[v]:S}))})]},v))})})}),e.jsx(is,{value:"blocks",className:"mt-4",children:e.jsx(L2t,{cardId:s.id})}),e.jsx(is,{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:Er,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:oc,color:"text-amber-600 bg-amber-100 dark:text-amber-400 dark:bg-amber-900/30"},{label:"Leads",value:((_=i==null?void 0:i.leads)==null?void 0:_.length)??0,icon:Fo,color:"text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-900/30"}].map(v=>e.jsx(fe,{className:"overflow-hidden",children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:`p-1.5 rounded-md ${v.color}`,children:e.jsx(v.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:v.label})]}),e.jsx("div",{className:"text-2xl font-bold",children:v.value})]})},v.label))}),i&&i.leads.length>0&&e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsx(It,{className:"text-base",children:"Recent Leads"})}),e.jsx(Ee,{className:"pt-0 space-y-2",children:i.leads.slice(0,5).map(v=>e.jsxs("div",{className:"flex items-center justify-between text-sm p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:v.name}),v.phone&&e.jsx("span",{className:"text-muted-foreground ml-2",children:v.phone})]}),v.intent&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:v.intent})]},v.id))})]}),(!i||i.leads.length===0)&&e.jsx(fe,{children:e.jsxs(Ee,{className:"p-8 text-center",children:[e.jsx(oc,{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(is,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(fe,{children:e.jsx(Ee,{className:"p-6",children:e.jsx(zJs,{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 KJs(){const s=Ht(),[t,n]=N.useState(""),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,p]=N.useState(!1),[f,g]=N.useState(null),[_,v]=N.useState(null),[j,b]=N.useState(0),[S,A]=N.useState(""),[T,L]=N.useState(!1),{data:D,isLoading:M}=ct({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:ce,error:pe}=await q.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(pe)throw pe;return ce}}),F=gt({mutationFn:async ce=>{const{data:pe,error:le}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:ce}});if(le)throw le;if(pe!=null&&pe.error)throw new Error(pe.error);return pe},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),n(""),ae.success("BoldTrail connected successfully!")},onError:ce=>{ae.error(ce.message||"Failed to connect BoldTrail")}}),z=gt({mutationFn:async()=>{const{data:ce,error:pe}=await q.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(pe)throw pe;return ce},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ae.success("BoldTrail disconnected")},onError:()=>ae.error("Failed to disconnect")}),V=gt({mutationFn:async ce=>{const{data:pe,error:le}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:ce}});if(le)throw le;if(pe!=null&&pe.error)throw new Error(pe.error);return pe},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ae.success("Sync direction saved")},onError:ce=>{ae.error(ce.message||"Failed to save sync direction")}}),W=gt({mutationFn:async()=>{const{data:ce,error:pe}=await q.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(pe)throw pe;if(ce!=null&&ce.error)throw new Error(ce.error);return ce},onSuccess:ce=>{if(s.invalidateQueries({queryKey:["boldtrail-status"]}),ce.kvcore_user_id){const pe=ce.detected_name||ce.detected_email||`ID ${ce.kvcore_user_id}`;ae.success(`Detected your BoldTrail account: ${pe}`)}else if(ce.candidates&&ce.candidates.length>0){const pe=ce.candidates.slice(0,5).map(le=>`${le.id} (${le.count} contacts)`).join(", ");ae.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${pe}. Pick yours and enter it below.`,{duration:12e3}),L(!0)}else ae.warning("Couldn't auto-detect your BoldTrail user ID. Please find it in BoldTrail (My Profile URL) and enter it manually."),L(!0)},onError:ce=>ae.error(ce.message||"Detection failed")}),Y=gt({mutationFn:async ce=>{const{data:pe,error:le}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...ce}});if(le)throw le;if(pe!=null&&pe.error)throw new Error(pe.error);return pe},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ae.success("Settings saved"),L(!1)},onError:ce=>ae.error(ce.message||"Failed to save settings")}),K=gt({mutationFn:async()=>{const{data:ce,error:pe}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(pe)throw pe;if(ce!=null&&ce.error)throw new Error(ce.error);return ce},onSuccess:ce=>{g(null),c(ce),a(!0)},onError:ce=>{ae.error(ce.message||"Failed to generate sync preview")}}),J=gt({mutationFn:async()=>{v("Initializing sync..."),b(5);const{data:ce,error:pe}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:he}});if(pe)throw pe;if(ce!=null&&ce.error)throw new Error(ce.error);const le=ce;let ve=le.sync_log_id,ge=le.next_phase,Te=le.next_offset,Me=le.push_total||0,Ce=le.pull_total||0,Ae=0,De=0;for(;ge!=="finalize";){const qe=Me+Ce;ge==="fetch_bt"?v("Fetching BoldTrail contacts..."):ge==="analyze"?(v("Analyzing contacts..."),b(15)):ge==="push"?(v(`Pushing contacts to BoldTrail... (${Ae}/${Me})`),b(qe>0?Ae/qe*100:0)):ge==="pull"&&(v(`Pulling contacts from BoldTrail... (${De}/${Ce})`),b(qe>0?(Me+De)/qe*100:0));const{data:be,error:Ze}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:ge,offset:Te,sync_log_id:ve,sync_direction:he}});if(Ze)throw Ze;if(be!=null&&be.error)throw new Error(be.error);const Ne=be;Ae+=Ne.chunk_pushed||0,De+=Ne.chunk_pulled||0,Ne.push_total!==void 0&&(Me=Ne.push_total||0),Ne.pull_total!==void 0&&(Ce=Ne.pull_total||0),Ne.progress&&v(Ne.progress),ge==="pull"&&Ce>0?b(Math.min(95,De/Ce*100)):ge==="push"&&Me>0&&b(Math.min(95,Ae/Me*100)),ge=Ne.next_phase,Te=Ne.next_offset}v("Finalizing sync..."),b(95);const{data:Ie,error:Fe}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:ve,sync_direction:he}});if(Fe)throw Fe;return b(100),Ie},onSuccess:ce=>{v(null),b(0),a(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["contacts"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),ae.success(`Sync complete! Pushed ${ce.contacts_pushed||0}, pulled ${ce.contacts_pulled||0}, skipped ${ce.contacts_skipped||0} duplicates.`)},onError:ce=>{v(null),b(0),ae.error(ce.message||"Sync failed")}}),ne=D==null?void 0:D.connected,ie=(D==null?void 0:D.sync_direction)||"bidirectional",he=f??ie;return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(Mt,{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(em,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:["BoldTrail",ne&&e.jsx(ze,{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(Au,{className:"h-3.5 w-3.5"}),"Learn More"]})]}),e.jsx(Vn,{children:"Sync contacts bidirectionally between Agent OS and your BoldTrail (kvCORE) CRM."})]})]})}),e.jsx(Ee,{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(Ri,{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(Ri,{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(Ri,{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"})]}),ne?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"}),(D==null?void 0:D.last_sync_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sync: ",new Date(D.last_sync_at).toLocaleString(),D.last_sync_status&&e.jsx(ze,{variant:D.last_sync_status==="success"?"default":"secondary",className:"ml-2 text-[10px]",children:D.last_sync_status})]}),(D==null?void 0:D.boldtrail_contact_count)!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[D.boldtrail_contact_count," contacts in BoldTrail"]}),(D==null?void 0:D.last_sync_message)&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:D.last_sync_message})]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect BoldTrail?"}),e.jsx(Mo,{children:"This will remove your API token. Previously synced contacts will remain in both systems."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>z.mutate(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]})}),e.jsxs("div",{className:"rounded-lg border p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(bb,{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(bn,{checked:!!(D!=null&&D.sync_only_owned),onCheckedChange:ce=>Y.mutate({sync_only_owned:ce}),disabled:Y.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:S,onChange:ce=>A(ce.target.value),className:"h-8 text-sm"}),e.jsx(B,{size:"sm",onClick:()=>{const ce=S.trim()===""?null:Number(S);Y.mutate({kvcore_user_id:ce})},disabled:Y.isPending,children:"Save"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>L(!1),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-mono",children:(D==null?void 0:D.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:()=>W.mutate(),disabled:W.isPending,children:[W.isPending?e.jsx(Ti,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Auto-detect"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{var ce;A(((ce=D==null?void 0:D.kvcore_user_id)==null?void 0:ce.toString())??""),L(!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(X5e,{value:ie,onChange:ce=>V.mutate(ce)})}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(B,{onClick:()=>K.mutate(),disabled:K.isPending||J.isPending,variant:"outline",className:"gap-2",children:[K.isPending?e.jsx(Ti,{className:"h-4 w-4 animate-spin"}):e.jsx(Er,{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:ce=>n(ce.target.value),className:"flex-1"}),e.jsxs(B,{onClick:()=>F.mutate(t),disabled:!t||t.length<10||F.isPending,children:[F.isPending?e.jsx(Ti,{className:"h-4 w-4 animate-spin mr-2"}):null,"Connect"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Find your API token in BoldTrail → Lead Engine → Lead Dropbox → My API Tokens. Generate a ",e.jsx("strong",{children:"Contacts"})," scope token."]})]})]})})]}),e.jsx(bs,{open:r,onOpenChange:ce=>{J.isPending||a(ce)},children:e.jsxs(vs,{className:"sm:max-w-lg",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(em,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Qn,{children:"Review what will happen when you sync your contacts."})]}),o&&(()=>{const ce=he==="pull_only"?0:o.to_push,pe=he==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(X5e,{value:he,onChange:g,size:"sm"}),o.owner_filter_active&&e.jsxs("div",{className:"rounded-md border border-emerald-200 bg-emerald-50 p-2 text-xs text-emerald-900 flex items-start gap-2",children:[e.jsx(bb,{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 ${he==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:ce}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Ru,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${he==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:pe}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(am,{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(Nn,{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"]}),J.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(pi,{value:j||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:_||"Sync in progress..."})]}),ce>0&&e.jsxs(dy,{open:d,onOpenChange:u,children:[e.jsx(uy,{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(Ru,{className:"h-3 w-3 text-emerald-600"}),ce," contacts to push to BoldTrail"]}),e.jsx(io,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),e.jsx(hy,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.push_preview.map((le,ve)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:le.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:le.email})]},ve)),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"]})]})})]}),pe>0&&e.jsxs(dy,{open:h,onOpenChange:p,children:[e.jsx(uy,{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(am,{className:"h-3 w-3 text-blue-600"}),pe," contacts to pull from BoldTrail"]}),e.jsx(io,{className:`h-3 w-3 transition-transform ${h?"rotate-180":""}`})]})}),e.jsx(hy,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.pull_preview.map((le,ve)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:le.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:le.email})]},ve)),o.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",o.to_pull-20," more"]})]})})]}),ce===0&&pe===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:J.isPending,children:"Cancel"}),e.jsxs(B,{onClick:()=>J.mutate(),disabled:J.isPending||ce===0&&pe===0,className:"gap-2",children:[J.isPending?e.jsx(Ti,{className:"h-4 w-4 animate-spin"}):e.jsx(em,{className:"h-4 w-4"}),J.isPending?"Syncing...":"Sync Now"]})]})]})})()]})}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{className:"sm:max-w-2xl p-0 overflow-hidden",children:[e.jsx(ws,{className:"p-6 pb-0",children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(em,{className:"h-5 w-5 text-emerald-600"}),"How BoldTrail Sync Works"]})}),e.jsx("div",{className:"px-6 pb-6",children:e.jsx("video",{src:"/videos/BoldTrailIntegration.mp4",controls:!0,autoPlay:!0,className:"w-full rounded-lg",controlsList:"nodownload"})})]})})]})}function YJs(){const s=Ht(),[t,n]=N.useState(""),[r,a]=N.useState(!1),[i,l]=N.useState(0),[o,c]=N.useState(null),{data:d,isLoading:u}=ct({queryKey:["fub-status"],queryFn:async()=>{const{data:_,error:v}=await q.functions.invoke("followupboss-sync",{body:{action:"status"}});if(v)throw v;return _}}),h=gt({mutationFn:async _=>{const{data:v,error:j}=await q.functions.invoke("followupboss-sync",{body:{action:"save_token",api_key:_}});if(j)throw j;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{ae.success("Connected to Follow Up Boss"),n(""),s.invalidateQueries({queryKey:["fub-status"]})},onError:_=>ae.error(_.message)}),p=gt({mutationFn:async()=>{const{error:_}=await q.functions.invoke("followupboss-sync",{body:{action:"disconnect"}});if(_)throw _},onSuccess:()=>{ae.success("Disconnected"),s.invalidateQueries({queryKey:["fub-status"]})}}),f=gt({mutationFn:async _=>{const{error:v}=await q.functions.invoke("followupboss-sync",{body:{action:"set_direction",sync_direction:_}});if(v)throw v},onSuccess:()=>s.invalidateQueries({queryKey:["fub-status"]})}),g=async()=>{a(!0),l(0),c("Pulling from FUB…");let _=0,v=0,j=0,b=0;try{for(;;){const{data:L,error:D}=await q.functions.invoke("followupboss-sync",{body:{action:"sync",offset:_}});if(D)throw D;if(L!=null&&L.error)throw new Error(L.error);v+=L.chunk_created||0,j+=L.chunk_updated||0,b+=L.chunk_skipped||0,_=L.next_offset;const M=L.total?Math.min(100,Math.round(_/L.total*100)):100;if(l(M),c(`Pulling · ${_} / ${L.total||"?"}`),L.done)break;await new Promise(F=>setTimeout(F,400))}let S=0,A=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let L=0;for(l(0),c("Pushing to FUB…");;){const{data:D,error:M}=await q.functions.invoke("followupboss-sync",{body:{action:"push",offset:L}});if(M)throw M;if(D!=null&&D.error)throw new Error(D.error);S+=D.chunk_pushed||0,A+=D.chunk_failed||0,L=D.next_offset;const F=D.total?Math.min(100,Math.round(L/D.total*100)):100;if(l(F),c(`Pushing · ${L} / ${D.total||"?"}`),D.done)break;await new Promise(z=>setTimeout(z,400))}}const T=S||A?` · pushed ${S}${A?`, ${A} failed`:""}`:"";ae.success(`Sync complete · ${v} new, ${j} updated${b?`, ${b} skipped`:""}${T}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(S){ae.error(S.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(X2,{className:"h-5 w-5 text-primary"}),"Follow Up Boss",(d==null?void 0:d.connected)&&e.jsxs(ze,{variant:"default",className:"ml-1",children:[e.jsx(Ri,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Vn,{children:"Sync your Follow Up Boss contacts into Agent OS."})]})})}),e.jsx(Ee,{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(bn,{checked:d.sync_direction==="bidirectional",onCheckedChange:_=>f.mutate(_?"bidirectional":"pull_only"),disabled:r||f.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(pi,{value:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{onClick:g,disabled:r,children:[e.jsx(Ti,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:r,children:[e.jsx(_n,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Follow Up Boss?"}),e.jsx(Mo,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>p.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:_=>n(_.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 ZJs(){var K;const s=Ht(),[t,n]=N.useState(""),[r,a]=N.useState(""),[i,l]=N.useState(!1),[o,c]=N.useState(0),[d,u]=N.useState(null),[h,p]=N.useState(!1),[f,g]=N.useState(null),[_,v]=N.useState(!1),[j,b]=N.useState(new Set),{data:S,isLoading:A}=ct({queryKey:["cloze-status"],queryFn:async()=>{const{data:J,error:ne}=await q.functions.invoke("cloze-sync",{body:{action:"status"}});if(ne)throw ne;return J}}),T=gt({mutationFn:async()=>{const{data:J,error:ne}=await q.functions.invoke("cloze-sync",{body:{action:"save_token",api_key:t.trim(),account_email:r.trim()}});if(ne)throw ne;if(J!=null&&J.error)throw new Error(J.error);return J},onSuccess:()=>{ae.success("Connected to Cloze"),n(""),a(""),s.invalidateQueries({queryKey:["cloze-status"]})},onError:J=>ae.error(J.message)}),L=gt({mutationFn:async()=>{const{error:J}=await q.functions.invoke("cloze-sync",{body:{action:"disconnect"}});if(J)throw J},onSuccess:()=>{ae.success("Cloze disconnected"),s.invalidateQueries({queryKey:["cloze-status"]})}}),D=gt({mutationFn:async J=>{const{error:ne}=await q.functions.invoke("cloze-sync",{body:{action:"set_direction",sync_direction:J}});if(ne)throw ne},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),M=gt({mutationFn:async J=>{const{error:ne}=await q.functions.invoke("cloze-sync",{body:{action:"set_scope",...J}});if(ne)throw ne},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),F=async()=>{v(!0);try{const{data:J,error:ne}=await q.functions.invoke("cloze-sync",{body:{action:"list_segments"}});if(ne)throw ne;if(J!=null&&J.error)throw new Error(J.error);g(J.segments||[]),b(new Set((S==null?void 0:S.selected_segments)||[])),p(!0)}catch(J){ae.error(J.message||"Failed to load segments")}finally{v(!1)}},z=async()=>{const J=Array.from(j);await M.mutateAsync({sync_scope:"segments",selected_segments:J}),ae.success(`Saved · ${J.length} segment(s) selected`),p(!1)},V=async()=>{const J=(S==null?void 0:S.sync_direction)||"pull_only";l(!0),c(0);try{if(J==="pull_only"||J==="bidirectional"){u("Pulling from Cloze…");let ne=0,ie=0,he=0;for(;;){const{data:ce,error:pe}=await q.functions.invoke("cloze-sync",{body:{action:"sync",offset:ne}});if(pe)throw pe;if(ce!=null&&ce.error)throw new Error(ce.error);if(ie+=ce.chunk_created||0,he+=ce.chunk_updated||0,ne=ce.next_offset,u(`Pulling · ${ie+he} contacts processed`),c(ce.done?100:Math.min(95,(ie+he)%200/2)),ce.done)break;await new Promise(le=>setTimeout(le,300))}ae.success(`Pulled · ${ie} new, ${he} updated`)}if(J==="push_only"||J==="bidirectional"){c(0),u("Pushing to Cloze…");let ne=0,ie=0,he=0;for(;;){const{data:ce,error:pe}=await q.functions.invoke("cloze-sync",{body:{action:"push",offset:ne}});if(pe)throw pe;if(ce!=null&&ce.error)throw new Error(ce.error);ie+=ce.chunk_pushed||0,he+=ce.chunk_failed||0,ne=ce.next_offset;const le=ce.total?Math.min(100,Math.round(ne/ce.total*100)):100;if(c(le),u(`Pushing · ${ne} / ${ce.total||"?"}`),ce.done)break;await new Promise(ve=>setTimeout(ve,300))}ae.success(`Pushed · ${ie}${he?`, ${he} failed`:""}`)}s.invalidateQueries({queryKey:["cloze-status"]})}catch(ne){ae.error(ne.message||"Sync failed")}finally{l(!1),setTimeout(()=>{c(0),u(null)},2e3)}},W=(S==null?void 0:S.sync_scope)||"all",Y=((K=S==null?void 0:S.selected_segments)==null?void 0:K.length)||0;return e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(X2,{className:"h-5 w-5 text-primary"}),"Cloze",(S==null?void 0:S.connected)&&e.jsxs(ze,{variant:"default",className:"ml-1",children:[e.jsx(Ri,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Vn,{children:"Sync contacts between Cloze and Agent OS using your personal Cloze API key."})]})})}),e.jsx(Ee,{className:"space-y-4",children:A?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):S!=null&&S.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:S.account_email})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:S.last_sync_at?new Date(S.last_sync_at).toLocaleString():"Never"})]})]}),S.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:S.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(ds,{value:S.sync_direction||"pull_only",onValueChange:J=>D.mutate(J),disabled:i||D.isPending,children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"pull_only",children:"Pull from Cloze"}),e.jsx(Qe,{value:"push_only",children:"Push to Cloze"}),e.jsx(Qe,{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:W==="all"?"All Cloze contacts.":`${Y} segment${Y===1?"":"s"} selected.`})]}),e.jsxs(ds,{value:W,onValueChange:J=>{J==="all"?M.mutate({sync_scope:"all",selected_segments:[]}):(M.mutate({sync_scope:"segments",selected_segments:S.selected_segments||[]}),F())},disabled:i||M.isPending,children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All contacts"}),e.jsx(Qe,{value:"segments",children:"Selected segments"})]})]})]}),W==="segments"&&e.jsxs("div",{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:F,disabled:_,children:[e.jsx(I9,{className:"h-4 w-4 mr-2"}),_?"Loading segments…":"Choose segments"]}),h&&f&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"max-h-96 overflow-y-auto rounded-md border divide-y",children:[f.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-3",children:"No segments found in your Cloze account."}),f.map(J=>{const ne=j.has(J.id);return e.jsxs("label",{className:"flex items-center gap-3 p-2 cursor-pointer hover:bg-muted/50",children:[e.jsx(ui,{checked:ne,onCheckedChange:ie=>{const he=new Set(j);ie?he.add(J.id):he.delete(J.id),b(he)}}),e.jsx("span",{className:"flex-1 text-sm",children:J.name}),J.count!=null&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:J.count})]},J.id)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:z,disabled:M.isPending,children:["Save selection (",j.size,")"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>p(!1),children:"Cancel"})]})]})]})]}),d&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(pi,{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(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsxs(B,{disabled:i,children:[e.jsx(Ti,{className:`h-4 w-4 mr-2 ${i?"animate-spin":""}`}),i?"Syncing…":"Sync Now"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Preview sync"}),e.jsx(Mo,{asChild:!0,children:e.jsx(QJs,{segments:f})})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:V,children:"Start Sync"})]})]})]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:i,children:[e.jsx(_n,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Cloze?"}),e.jsx(Mo,{children:"Your API key will be removed. Contacts already synced will remain."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>L.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:J=>a(J.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:J=>n(J.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 QJs({segments:s}){var h;const[t,n]=N.useState(!0),[r,a]=N.useState(null),[i,l]=N.useState(null);if(N.useEffect(()=>{(async()=>{try{const{data:p,error:f}=await q.functions.invoke("cloze-sync",{body:{action:"preview"}});if(f)throw f;if(p!=null&&p.error)throw new Error(p.error);a(p)}catch(p){l(p.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(p=>[p.id,p.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(p=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{children:o.get(p.id)||p.id}),e.jsx("span",{className:"text-muted-foreground",children:p.total})]},p.id))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.note})]})}function XJs(){const s=Ht(),[t,n]=N.useState(""),[r,a]=N.useState(!1),[i,l]=N.useState(0),[o,c]=N.useState(null),{data:d,isLoading:u}=ct({queryKey:["boomtown-status"],queryFn:async()=>{const{data:_,error:v}=await q.functions.invoke("boomtown-sync",{body:{action:"status"}});if(v)throw v;return _}}),h=gt({mutationFn:async _=>{const{data:v,error:j}=await q.functions.invoke("boomtown-sync",{body:{action:"save_token",api_key:_}});if(j)throw j;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{ae.success("Connected to Boomtown"),n(""),s.invalidateQueries({queryKey:["boomtown-status"]})},onError:_=>ae.error(_.message)}),p=gt({mutationFn:async()=>{const{error:_}=await q.functions.invoke("boomtown-sync",{body:{action:"disconnect"}});if(_)throw _},onSuccess:()=>{ae.success("Disconnected"),s.invalidateQueries({queryKey:["boomtown-status"]})}}),f=gt({mutationFn:async _=>{const{error:v}=await q.functions.invoke("boomtown-sync",{body:{action:"set_direction",sync_direction:_}});if(v)throw v},onSuccess:()=>s.invalidateQueries({queryKey:["boomtown-status"]})}),g=async()=>{a(!0),l(0),c("Pulling from Boomtown…");let _=0,v=0,j=0,b=0;try{for(;;){const{data:L,error:D}=await q.functions.invoke("boomtown-sync",{body:{action:"sync",offset:_}});if(D)throw D;if(L!=null&&L.error)throw new Error(L.error);v+=L.chunk_created||0,j+=L.chunk_updated||0,b+=L.chunk_skipped||0,_=L.next_offset;const M=L.total?Math.min(100,Math.round(_/L.total*100)):100;if(l(M),c(`Pulling · ${_} / ${L.total||"?"}`),L.done)break;await new Promise(F=>setTimeout(F,400))}let S=0,A=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let L=0;for(l(0),c("Pushing to Boomtown…");;){const{data:D,error:M}=await q.functions.invoke("boomtown-sync",{body:{action:"push",offset:L}});if(M)throw M;if(D!=null&&D.error)throw new Error(D.error);S+=D.chunk_pushed||0,A+=D.chunk_failed||0,L=D.next_offset;const F=D.total?Math.min(100,Math.round(L/D.total*100)):100;if(l(F),c(`Pushing · ${L} / ${D.total||"?"}`),D.done)break;await new Promise(z=>setTimeout(z,400))}}const T=S||A?` · pushed ${S}${A?`, ${A} failed`:""}`:"";ae.success(`Sync complete · ${v} new, ${j} updated${b?`, ${b} skipped`:""}${T}`),s.invalidateQueries({queryKey:["boomtown-status"]})}catch(S){ae.error(S.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(X2,{className:"h-5 w-5 text-primary"}),"Boomtown",(d==null?void 0:d.connected)&&e.jsxs(ze,{variant:"default",className:"ml-1",children:[e.jsx(Ri,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Vn,{children:"Sync your Boomtown contacts into Agent OS."})]})})}),e.jsx(Ee,{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(bn,{checked:d.sync_direction==="bidirectional",onCheckedChange:_=>f.mutate(_?"bidirectional":"pull_only"),disabled:r||f.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(pi,{value:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{onClick:g,disabled:r,children:[e.jsx(Ti,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:r,children:[e.jsx(_n,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Boomtown?"}),e.jsx(Mo,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>p.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:_=>n(_.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 G2t(){const s=Mn(),[t,n]=N.useState(""),[r,a]=N.useState(""),[i,l]=N.useState("Test from ReLevelUp"),[o,c]=N.useState(!1),{data:d,isLoading:u}=ct({queryKey:["ses-config"],queryFn:async()=>{const{data:{session:f}}=await q.auth.getSession();if(!f)throw new Error("Not authenticated");return(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f.access_token}`},body:JSON.stringify({action:"check_config"})})).json()}}),h=async()=>{if(!t||!r){ae.error("Please fill in From and To email addresses");return}c(!0);try{const{data:{session:f}}=await q.auth.getSession();if(!f)throw new Error("Not authenticated");const _=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f.access_token}`},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();_.success?ae.success(`Test email sent! Message ID: ${_.messageId}`):ae.error(_.error||"Failed to send test email")}catch(f){ae.error(f.message||"Failed to send test email")}finally{c(!1)}},p=(d==null?void 0:d.configured)===!0;return e.jsxs(fe,{children:[e.jsx(Mt,{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(Vs,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:"Amazon SES — Mass Email"}),e.jsx(Vn,{children:"Send bulk email campaigns via Amazon SES"})]})]}),e.jsx(ze,{variant:p?"default":"secondary",children:u?"Checking...":p?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ri,{className:"h-3 w-3"})," Connected"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Gi,{className:"h-3 w-3"})," Not Configured"]})})]})}),p&&e.jsxs(Ee,{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:f=>a(f.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:f=>n(f.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:f=>l(f.target.value),className:"text-sm"})]})]}),e.jsxs(B,{onClick:h,disabled:o,size:"sm",children:[o?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Send Test"]})]}),e.jsxs(B,{onClick:()=>s("/admin/email-campaigns"),className:"w-full",children:[e.jsx($d,{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)"]})]})]}),!p&&!u&&e.jsx(Ee,{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 qNe(s){const{data:{session:t}}=await q.auth.getSession();if(!t)throw new Error("Not authenticated");const n=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-verify-sender",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.access_token}`},body:JSON.stringify(s)}),r=await n.json();if(!n.ok)throw new Error(r.error||"Request failed");return r}function JJs({status:s}){return s==="verified"?e.jsxs(ze,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(xr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(ze,{variant:"secondary",children:[e.jsx(gr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(ze,{variant:"destructive",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(ze,{variant:"outline",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"})," Not started"]})}function W2t({brokerageId:s,onVerifiedSelect:t}){const n=Ht(),[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(null),{data:f,isLoading:g}=ct({queryKey:["brokerage-verified-senders",s],queryFn:async()=>{const{data:b,error:S}=await q.from("brokerage_verified_senders").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(S)throw S;return b||[]}}),_=gt({mutationFn:async()=>qNe({action:"request_verification",brokerage_id:s,email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ae.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:b=>ae.error(b.message)}),v=async b=>{var S,A;u(b.id);try{const T=await qNe({action:"check_status",sender_id:b.id});n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((S=T.sender)==null?void 0:S.status)==="verified"?ae.success(`${b.email} is verified! 🎉`):ae.info(`Status: ${((A=T.sender)==null?void 0:A.status)||"unknown"}`)}catch(T){ae.error(T.message)}finally{u(null)}},j=gt({mutationFn:async b=>qNe({action:"delete",sender_id:b}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ae.success("Sender removed"),p(null)},onError:b=>ae.error(b.message)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Verified Sender Addresses"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Verify any email address (yours or your brokerage's) so recruiting emails can be sent from that address. Anyone managing this brokerage can use these senders."})]}),g?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):f&&f.length>0?e.jsx("div",{className:"space-y-2",children:f.map(b=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(Vs,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:b.email}),e.jsx(JJs,{status:b.status})]}),b.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',b.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b.status==="verified"&&t&&e.jsx(B,{size:"sm",variant:"outline",onClick:()=>t(b.email),children:"Use"}),b.status!=="verified"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>v(b),disabled:d===b.id,title:"Refresh status from AWS",children:d===b.id?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(Ti,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>p(b),className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})]})]},b.id))}):e.jsx("div",{className:"text-xs text-muted-foreground py-2 italic",children:"No verified senders yet. Add one below."}),o?e.jsxs("div",{className:"rounded-lg border p-4 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Email Address *"}),e.jsx(ye,{type:"email",value:r,onChange:b=>a(b.target.value),placeholder:"broker@yourbrokerage.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(ye,{value:i,onChange:b=>l(b.target.value),placeholder:"John at Acme Realty",className:"text-sm"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"We'll ask AWS to send a verification email to this address. The owner must click the link before this sender can be used."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>_.mutate(),disabled:!r.trim()||_.isPending,children:[_.isPending?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Vs,{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(Is,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Oo,{open:!!h,onOpenChange:b=>!b&&p(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Remove this sender?"}),e.jsxs(Mo,{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(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>h&&j.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function VNe(s){const{data:{session:t}}=await q.auth.getSession();if(!t)throw new Error("Not authenticated");const n=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-verify-sender",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.access_token}`},body:JSON.stringify(s)}),r=await n.json();if(!n.ok)throw new Error(r.error||"Request failed");return r}function een({status:s}){return s==="verified"?e.jsxs(ze,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(xr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(ze,{variant:"secondary",children:[e.jsx(gr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(ze,{variant:"destructive",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(ze,{variant:"outline",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"})," Not started"]})}function ten({userId:s,onVerifiedSelect:t}){const n=Ht(),[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(null),{data:f,isLoading:g}=ct({queryKey:["user-verified-senders",s],queryFn:async()=>{const{data:b,error:S}=await q.from("user_verified_senders").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(S)throw S;return b||[]}}),_=gt({mutationFn:async()=>VNe({action:"request_verification",scope:"user",email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),ae.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:b=>ae.error(b.message)}),v=async b=>{var S,A;u(b.id);try{const T=await VNe({action:"check_status",sender_id:b.id});n.invalidateQueries({queryKey:["user-verified-senders",s]}),((S=T.sender)==null?void 0:S.status)==="verified"?ae.success(`${b.email} is verified! 🎉`):ae.info(`Status: ${((A=T.sender)==null?void 0:A.status)||"unknown"}`)}catch(T){ae.error(T.message)}finally{u(null)}},j=gt({mutationFn:async b=>VNe({action:"delete",sender_id:b}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),ae.success("Sender removed"),p(null)},onError:b=>ae.error(b.message)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Your Verified Sender Addresses"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Verify your email address with Amazon so mass emails can be sent ",e.jsx("em",{children:"from"})," you. Add an address, then click the verification link Amazon sends to that inbox."]})]}),g?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):f&&f.length>0?e.jsx("div",{className:"space-y-2",children:f.map(b=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(Vs,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:b.email}),e.jsx(een,{status:b.status})]}),b.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',b.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b.status==="verified"&&t&&e.jsx(B,{size:"sm",variant:"outline",onClick:()=>t(b.email),children:"Use"}),b.status!=="verified"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>v(b),disabled:d===b.id,title:"Refresh status from AWS",children:d===b.id?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(Ti,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>p(b),className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})]})]},b.id))}):e.jsx("div",{className:"text-xs text-muted-foreground py-2 italic",children:"No verified senders yet. Add one below."}),o?e.jsxs("div",{className:"rounded-lg border p-4 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Email Address *"}),e.jsx(ye,{type:"email",value:r,onChange:b=>a(b.target.value),placeholder:"you@yourdomain.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(ye,{value:i,onChange:b=>l(b.target.value),placeholder:"Jane at Acme Realty",className:"text-sm"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"We'll ask Amazon to send a verification email to this address. You must click the link before this sender can be used in a campaign."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>_.mutate(),disabled:!r.trim()||_.isPending,children:[_.isPending?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Vs,{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(Is,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Oo,{open:!!h,onOpenChange:b=>!b&&p(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Remove this sender?"}),e.jsxs(Mo,{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(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>h&&j.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function sen(){var A,T,L,D,M;const{user:s,isBrokerageManager:t,isAdmin:n,managedBrokerages:r,selectedBrokerageId:a}=ys(),i=a||((A=r==null?void 0:r[0])==null?void 0:A.id)||null,l=(t||n)&&!!i,o=Ht(),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState(""),{data:g}=ct({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:F,error:z}=await q.from("mass_email_settings").select("*").eq("user_id",s.id).maybeSingle();if(z)throw z;return F}}),{data:_}=ct({queryKey:["agent-profile-email",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:F,error:z}=await q.from("profiles").select("email, name").eq("id",s.id).single();if(z)throw z;return F}}),v=((T=g==null?void 0:g.reply_to_email)==null?void 0:T.trim())||((L=_==null?void 0:_.email)==null?void 0:L.trim())||"",j=((D=g==null?void 0:g.display_name)==null?void 0:D.trim())||((M=_==null?void 0:_.name)==null?void 0:M.trim())||"";N.useEffect(()=>{c||(h(v),f(j))},[c,v,j]);const b=gt({mutationFn:async()=>{if(!s||!u.trim())throw new Error("Please enter a reply-to email");const F={reply_to_email:u.trim(),display_name:p.trim()||null,updated_at:new Date().toISOString()};if(g){const{error:z}=await q.from("mass_email_settings").update(F).eq("user_id",s.id);if(z)throw z}else{const{error:z}=await q.from("mass_email_settings").insert({user_id:s.id,...F});if(z)throw z}},onSuccess:()=>{o.invalidateQueries({queryKey:["mass-email-settings",s==null?void 0:s.id]}),o.invalidateQueries({queryKey:["mass-email-ready",s==null?void 0:s.id]}),o.invalidateQueries({queryKey:["mass-email-settings-check",s==null?void 0:s.id]}),ae.success("Reply-to email saved!"),d(!1)},onError:F=>ae.error(F.message)}),S=!!v;return e.jsxs(fe,{children:[e.jsx(Mt,{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(cr,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:["Mass Email",S?e.jsxs(ze,{variant:"default",className:"text-xs bg-green-600",children:[e.jsx(Ri,{className:"h-3 w-3 mr-1"})," Set Up"]}):e.jsx(ze,{variant:"secondary",className:"text-xs",children:"Setup Required"})]}),e.jsx(Vn,{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(Ee,{className:"space-y-3",children:[S&&!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:j||"No display name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[e.jsx(_a,{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:p,onChange:F=>f(F.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:F=>h(F.target.value)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>b.mutate(),disabled:b.isPending||!u.trim(),children:[e.jsx(qo,{className:"h-4 w-4 mr-1"})," Save"]}),c&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{d(!1),h(v),f(j)},children:[e.jsx(Bn,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(ll,{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(sg,{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(ten,{userId:s.id,onVerifiedSelect:F=>{h(F),d(!0)}})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(ll,{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(sg,{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(W2t,{brokerageId:i})]})]})]})]})}function nen(){const s=Mn(),{isAdmin:t}=ys(),n=Ht(),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(!1),{data:d,isLoading:u}=ct({queryKey:["gmail-integration"],queryFn:async()=>{const{data:T,error:L}=await q.from("gmail_integrations").select("*").maybeSingle();if(L)throw L;return T}}),{data:h}=ct({queryKey:["social-accounts"],queryFn:async()=>{const{data:{user:T}}=await q.auth.getUser();if(!T)return[];const{data:L,error:D}=await q.from("social_accounts").select("*").eq("user_id",T.id).order("created_at",{ascending:!1});if(D)throw D;return L}}),p=async()=>{a(!0);try{const{data:T,error:L}=await q.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if(L)throw L;if(T!=null&&T.authUrl)window.location.href=T.authUrl;else throw new Error("Failed to get authorization URL")}catch(T){console.error("Gmail OAuth error:",T),ae.error("Failed to start Gmail connection"),a(!1)}},f=async T=>{l(!0);try{const{data:L,error:D}=await q.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:T}});if(D)throw D;if(L!=null&&L.authUrl)window.location.href=L.authUrl;else throw new Error("Failed to get authorization URL")}catch(L){console.error("Meta OAuth error:",L),ae.error("Failed to start connection. Make sure Meta App credentials are configured."),l(!1)}},g=async()=>{c(!0);try{const{data:T,error:L}=await q.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(L)throw L;if(T!=null&&T.authUrl)window.location.href=T.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(T){console.error("LinkedIn OAuth error:",T),ae.error("Failed to start LinkedIn connection. Please try again."),c(!1)}},_=gt({mutationFn:async T=>{const{error:L}=await q.from("gmail_integrations").delete().eq("id",T);if(L)throw L},onSuccess:()=>{n.invalidateQueries({queryKey:["gmail-integration"]}),ae.success("Gmail disconnected")},onError:()=>{ae.error("Failed to disconnect Gmail")}}),v=gt({mutationFn:async T=>{const{error:L}=await q.from("social_accounts").delete().eq("id",T);if(L)throw L},onSuccess:()=>{n.invalidateQueries({queryKey:["social-accounts"]}),ae.success("Account disconnected")},onError:()=>{ae.error("Failed to disconnect account")}}),j=!!(d!=null&&d.is_active),b=(h==null?void 0:h.filter(T=>T.platform==="facebook"))||[],S=(h==null?void 0:h.filter(T=>T.platform==="instagram"))||[],A=(h==null?void 0:h.filter(T=>T.platform==="linkedin"))||[];return e.jsx(Ts,{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."})]}),e.jsxs(fe,{children:[e.jsx(Mt,{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(YS,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:"ChatGPT"}),e.jsx(Vn,{children:"Connect ChatGPT to LevelUp so it can use LevelUp tools on your behalf."})]})]})}),e.jsx(Ee,{children:e.jsxs(B,{variant:"outline",onClick:()=>s("/connect-chatgpt"),children:["View connection instructions ",e.jsx(Oa,{className:"h-4 w-4 ml-1"})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{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(Vs,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:["Gmail",j&&e.jsx(ze,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Vn,{children:"Send emails directly from your contact pages and auto-log them as touchpoints."})]})]})}),e.jsx(Ee,{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(Ri,{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(Ri,{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(Ri,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Quick compose from any contact detail page"})]}),j?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:d.gmail_email}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Gmail account"})]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Gmail?"}),e.jsx(Mo,{children:"This will remove your Gmail connection. You'll need to reconnect to send emails."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>_.mutate(d.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}):e.jsxs(B,{className:"mt-4",onClick:p,disabled:r||u,children:[r?e.jsx(Ti,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Connect Gmail",e.jsx(Oa,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{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(Lh,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:["Facebook",b.length>0&&e.jsx(ze,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Vn,{children:"Connect Facebook Pages to post content and reach your audience."})]})]})}),e.jsxs(Ee,{className:"space-y-3",children:[b.length>0&&e.jsx("div",{className:"space-y-2",children:b.map(T=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ra,{className:"h-8 w-8",children:[e.jsx(ni,{src:T.profile_picture_url||""}),e.jsx(aa,{children:e.jsx(Lh,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:T.page_name||T.platform_username||"Facebook Page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Facebook Page"})]})]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Facebook?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>v.mutate(T.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},T.id))}),e.jsxs(B,{onClick:()=>f("facebook"),disabled:i,variant:"outline",className:"gap-2",children:[i?e.jsx(Ti,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{className:"h-4 w-4"}),"Connect Facebook Page"]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{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(du,{className:"h-5 w-5 text-pink-600"})}),e.jsxs("div",{children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:["Instagram",S.length>0&&e.jsx(ze,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Vn,{children:"Connect an Instagram Business or Creator account to schedule and publish posts. Personal accounts are not supported by Meta's API."})]})]})}),e.jsxs(Ee,{className:"space-y-3",children:[S.length>0&&e.jsx("div",{className:"space-y-2",children:S.map(T=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ra,{className:"h-8 w-8",children:[e.jsx(ni,{src:T.profile_picture_url||""}),e.jsx(aa,{children:e.jsx(du,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-sm",children:["@",T.platform_username||"Instagram Account"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Instagram account"})]})]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Instagram?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>v.mutate(T.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},T.id))}),e.jsxs(B,{onClick:()=>f("instagram"),disabled:i,variant:"outline",className:"gap-2",children:[i?e.jsx(Ti,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{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(fe,{children:[e.jsx(Mt,{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(vf,{className:"h-5 w-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:["LinkedIn",A.length>0&&e.jsx(ze,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Vn,{children:"Connect your LinkedIn profile to share content and grow your professional network."})]})]})}),e.jsxs(Ee,{className:"space-y-3",children:[A.length>0&&e.jsx("div",{className:"space-y-2",children:A.map(T=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ra,{className:"h-8 w-8",children:[e.jsx(ni,{src:T.profile_picture_url||""}),e.jsx(aa,{children:e.jsx(vf,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:T.platform_username||"LinkedIn Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected LinkedIn profile"})]})]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect LinkedIn?"}),e.jsx(Mo,{children:"This will remove your LinkedIn connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>v.mutate(T.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},T.id))}),e.jsxs(B,{onClick:g,disabled:o,variant:"outline",className:"gap-2",children:[o?e.jsx(Ti,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{className:"h-4 w-4"}),"Connect LinkedIn"]})]})]}),e.jsx(KJs,{}),e.jsx(YJs,{}),e.jsx(ZJs,{}),e.jsx(XJs,{}),e.jsx(sen,{}),t&&e.jsx(G2t,{})]})})}const ren="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function aen(){const[s,t]=N.useState(null),[n,r]=N.useState(!1),[a,i]=N.useState(0),[l,o]=N.useState(!1),c="/levelup-extension.zip",d="https://tile-portal.lovable.app/levelup-extension.zip",u=window.location.hostname.startsWith("id-preview--"),h=async v=>{const j=new Uint8Array(await v.slice(0,4).arrayBuffer());return j[0]===80&&j[1]===75&&j[2]===3&&j[3]===4||j[0]===80&&j[1]===75&&j[2]===5&&j[3]===6||j[0]===80&&j[1]===75&&j[2]===7&&j[3]===8},p=v=>{const j=document.createElement("a");j.href=v,j.download="levelup-extension.zip",j.rel="noopener noreferrer",j.target="_blank",document.body.appendChild(j),j.click(),j.remove()},f=async()=>{o(!0);try{if(u){p(`${d}?v=${Date.now()}`);return}const v=await fetch(`${c}?v=${Date.now()}`,{cache:"no-store"});if(!v.ok)throw new Error(`Download failed (${v.status})`);const j=await v.blob();if(!await h(j)){p(`${d}?v=${Date.now()}`);return}const b=new Blob([j],{type:"application/zip"}),S=URL.createObjectURL(b),A=document.createElement("a");A.href=S,A.download="levelup-extension.zip",document.body.appendChild(A),A.click(),A.remove(),setTimeout(()=>URL.revokeObjectURL(S),1e3)}catch(v){ae.error(v.message||"Download failed")}finally{o(!1)}},g=async()=>{r(!0);try{await q.auth.refreshSession();const{data:v}=await q.auth.getSession();if(!v.session){ae.error("Your session has expired. Please sign in again.");return}const{data:j,error:b}=await q.functions.invoke("extension-pair-start",{headers:{Authorization:`Bearer ${v.session.access_token}`}});if(b)throw b;t(j.code),i(j.expires_in||300);const S=setInterval(()=>{i(A=>A<=1?(clearInterval(S),t(null),0):A-1)},1e3)}catch(v){console.error("generateCode error",v),ae.error("We couldn't generate a pairing code",{description:"Please refresh the page and try again. If it still fails, sign out and sign back in, then click Generate pairing code.",duration:8e3})}finally{r(!1)}},_=()=>{s&&(navigator.clipboard.writeText(s),ae.success("Copied"))};return e.jsx(Ts,{title:"Browser Extension",children:e.jsxs("div",{className:"container max-w-3xl mx-auto py-8 px-4 space-y-6",children:[e.jsxs(Go,{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(NA,{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(fe,{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(ren,"_blank","noopener,noreferrer"),children:[e.jsx(NA,{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(fe,{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:_,variant:"outline",className:"flex-1",children:[e.jsx(Xr,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs(B,{onClick:g,variant:"outline",className:"flex-1",children:[e.jsx(Ti,{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(Ir,{className:"w-4 h-4 mt-0.5 text-primary"}),e.jsx("span",{children:"Click the LevelUp icon in your browser toolbar and paste this code. You only need to do this once per browser."})]})]}):e.jsx(B,{onClick:g,disabled:n,size:"lg",className:"w-full",children:n?e.jsxs(e.Fragment,{children:[e.jsx(Ti,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(fe,{className:"p-6 space-y-4 bg-muted/30 border-dashed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rc,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h2",{className:"text-base font-semibold text-muted-foreground",children:"Manual install (advanced)"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"If you prefer to load the extension unpacked, or the Web Store is unavailable, download the ZIP below."}),e.jsxs("ol",{className:"text-sm space-y-2 list-decimal list-inside text-muted-foreground",children:[e.jsx("li",{children:e.jsx(B,{variant:"link",className:"h-auto p-0 text-sm",onClick:f,disabled:l,children:"Download the extension ZIP"})}),e.jsx("li",{children:"Unzip the downloaded file"}),e.jsxs("li",{children:["Open"," ",e.jsx("code",{className:"px-1.5 py-0.5 rounded bg-muted text-foreground",children:"chrome://extensions"})," ","in Chrome, Edge, Brave, or Arc"]}),e.jsxs("li",{children:["Turn on ",e.jsx("b",{className:"text-foreground",children:"Developer mode"})," (top-right toggle)"]}),e.jsxs("li",{children:["Click ",e.jsx("b",{className:"text-foreground",children:"Load unpacked"})," and pick the unzipped folder"]}),e.jsx("li",{children:"Pin the LevelUp icon to your toolbar"})]})]})]})})}function ien(){const[s]=gl(),t=Mn(),[n,r]=N.useState("loading"),[a,i]=N.useState("Connecting your Gmail account...");return N.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:h,error:p}=await q.functions.invoke("gmail-oauth",{body:{action:"exchange_code",code:o,state:u}});if(p)throw p;if(h!=null&&h.success)r("success"),i(h.message||"Gmail connected successfully!"),ae.success("Gmail connected!");else throw new Error((h==null?void 0:h.error)||"Unknown error")}catch(h){console.error("Gmail OAuth callback error:",h),r("error"),i(h instanceof Error?h.message:"Failed to connect Gmail"),ae.error("Failed to connect: "+(h instanceof Error?h.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[n==="loading"&&e.jsx(ts,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Ri,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Hc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(It,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:a})]}),e.jsx(Ee,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"Back to Integrations":"Try Again"})})]})})}function oen(){const s=Mn();return N.useEffect(()=>{const t=setTimeout(()=>{s("/mission-control/integrations",{replace:!0})},1500);return()=>clearTimeout(t)},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"h-10 w-10 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Finishing Canva connection…"})]})})}function len(){const[s]=gl(),t=Mn(),[n,r]=N.useState("loading"),[a,i]=N.useState("Processing your connection...");return N.useEffect(()=>{(async()=>{var h;const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:p,error:f}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:u,callbackPath:"/mission-control/integrations/meta/callback"}});if(p&&p.success===!1)throw new Error(p.error||"Failed to connect accounts");if(f){let g=f.message||"Failed to connect accounts";try{const _=f.context;if(_&&typeof _.json=="function"){const v=await _.json();v!=null&&v.error&&(g=v.error)}}catch{}throw new Error(g)}if(p!=null&&p.success)r("success"),i(`Successfully connected ${((h=p.accounts)==null?void 0:h.length)||0} account(s)!`),ae.success("Social accounts connected successfully!");else throw new Error((p==null?void 0:p.error)||"Unknown error")}catch(p){console.error("OAuth callback error:",p),r("error"),i(p instanceof Error?p.message:"Failed to connect accounts"),ae.error("Failed to connect: "+(p instanceof Error?p.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[n==="loading"&&e.jsx(ts,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Ri,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Hc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(It,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:a})]}),e.jsx(Ee,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"View Integrations":"Try Again"})})]})})}const K2t=new Date().getFullYear(),cen=Array.from({length:5},(s,t)=>K2t-t);function den(){const[s,t]=N.useState(K2t),n=Mn(),{data:r,isLoading:a}=Zrs();return a?e.jsx(Ts,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(i=>e.jsx(Ws,{className:"h-24"},i))}),e.jsx(Ws,{className:"h-96"})]})}):e.jsx(Ts,{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(ds,{value:String(s),onValueChange:i=>t(Number(i)),children:[e.jsx(ls,{className:"w-[120px]",children:e.jsx(us,{})}),e.jsx(cs,{children:cen.map(i=>e.jsx(Qe,{value:String(i),children:i},i))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Nn,{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(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(yo,{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(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Agents with Scorecards"}),e.jsx(Vn,{children:"Click to view individual agent scorecards"})]}),e.jsx(Ee,{children:!r||r.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(yo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents have added transactions yet"})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:r.map(i=>e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:i.name}),e.jsx(ut,{className:"text-muted-foreground",children:i.email}),e.jsx(ut,{className:"text-right",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n(`/admin/scorecard/${i.id}`),children:[e.jsx(Er,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const Y2t=new Date().getFullYear(),uen=Array.from({length:10},(s,t)=>Y2t-t);function vXe(){var _;const{userId:s}=bi(),t=Mn(),r=Jl().pathname.startsWith("/mission-control"),[a,i]=N.useState(Y2t),{data:l,isLoading:o}=ct({queryKey:["agent-profile",s],queryFn:async()=>{const{data:v,error:j}=await q.from("profiles").select("id, name, email").eq("id",s).single();if(j)throw j;return v},enabled:!!s}),{data:c,isLoading:d}=w6e(a,s),{yearStats:u,lifetimeStats:h,isLoading:p,showCommission:f}=ppt(a,s),{data:g}=mpt(a,s);return o?e.jsx(Ts,{title:"Agent Scorecard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(v=>e.jsx(Ws,{className:"h-24"},v))})]})}):e.jsx(Ts,{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(Hr,{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(ds,{value:String(a),onValueChange:v=>i(Number(v)),children:[e.jsx(ls,{className:"w-[120px]",children:e.jsx(us,{})}),e.jsx(cs,{children:uen.map(v=>e.jsx(Qe,{value:String(v),children:v},v))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Or,{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(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Nn,{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(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:yc(u.totalVolume,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(mo,{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:yc(u.averagePrice,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(bc,{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:((_=u.topLeadSource)==null?void 0:_.name)||"-"})]})})]}),g&&e.jsx(s2t,{goals:g,stats:u,year:a,showCommission:f}),e.jsxs(Br,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Fr,{children:[e.jsx(Kt,{value:"transactions",children:"Transactions"}),e.jsx(Kt,{value:"charts",children:"Charts"}),e.jsxs(Kt,{value:"map",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(is,{value:"transactions",children:e.jsx(f8e,{transactions:c||[],showCommission:f,isLoading:d})}),e.jsx(is,{value:"charts",children:e.jsx(x8e,{stats:u,year:a})}),e.jsx(is,{value:"map",children:e.jsx(g8e,{transactions:c||[],isLoading:d})})]})]})})}function hen(){const s=Ht(),[t,n]=N.useState(""),[r,a]=N.useState("all"),[i,l]=N.useState(null);Wht();const{data:o,refetch:c}=ct({queryKey:["listing-exchange-flag"],queryFn:async()=>{const{data:F}=await q.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").single();return(F==null?void 0:F.enabled)??!1}}),{data:d,isLoading:u}=ct({queryKey:["admin-listings"],queryFn:async()=>{const{data:F,error:z}=await q.from("listings").select(` *, agent:profiles!listings_agent_id_fkey(id, name, email), photos:listing_photos(id, photo_url, is_primary) `).order("created_at",{ascending:!1});if(z)throw z;return F}}),{data:h}=ct({queryKey:["admin-listing-stats"],queryFn:async()=>{const{data:F}=await q.from("listings").select("id, is_approved, status"),{data:z}=await q.from("listing_shares").select("id"),{data:V}=await q.from("listing_views").select("id"),{count:W}=await q.from("listing_leads").select("id",{count:"exact",head:!0}),Y=new Date(Date.now()-7*24*60*60*1e3).toISOString(),{count:K}=await q.from("listing_leads").select("id",{count:"exact",head:!0}).gte("created_at",Y);return{total:(F==null?void 0:F.length)||0,pending:(F==null?void 0:F.filter(J=>!J.is_approved).length)||0,active:(F==null?void 0:F.filter(J=>J.status==="active").length)||0,totalShares:(z==null?void 0:z.length)||0,totalViews:(V==null?void 0:V.length)||0,totalLeads:W||0,leadsLast7:K||0}}}),{data:p}=ct({queryKey:["admin-listing-lead-counts"],queryFn:async()=>{const F={};let z=0;const V=1e3;for(;;){const{data:W,error:Y}=await q.from("listing_leads").select("listing_id").range(z,z+V-1);if(Y)throw Y;if(!W||W.length===0)break;for(const K of W)K.listing_id&&(F[K.listing_id]=(F[K.listing_id]||0)+1);if(W.length{const{data:F,error:z}=await q.from("listing_leads").select("*").eq("listing_id",i.listingId).order("created_at",{ascending:!1});if(z)throw z;return F}}),_=async(F,z,V="submit_url")=>{try{const{data:{session:W}}=await q.auth.getSession();if(!W)return;const{data:Y,error:K}=await q.functions.invoke("google-indexing",{body:{action:V,listing_id:F,listing_slug:z}});if(K)throw K;if((Y==null?void 0:Y.configured)===!1)return;Y!=null&&Y.success&&ae.success("Submitted to Google for indexing")}catch(W){console.error("Google indexing submission failed:",W)}},v=gt({mutationFn:async()=>{const{data:{session:F}}=await q.auth.getSession();if(!F)throw new Error("Not authenticated");const{data:z,error:V}=await q.functions.invoke("google-indexing",{body:{action:"submit_all"}});if(V)throw V;return z},onSuccess:F=>{if((F==null?void 0:F.configured)===!1){ae.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}ae.success(`Submitted ${(F==null?void 0:F.succeeded)||0} URLs to Google (${(F==null?void 0:F.failed)||0} failed)`)},onError:F=>{ae.error("Failed to submit to Google"),console.error(F)}}),j=gt({mutationFn:async({id:F,approved:z,slug:V})=>{const{error:W}=await q.from("listings").update({is_approved:z}).eq("id",F);if(W)throw W;return{id:F,approved:z,slug:V}},onSuccess:F=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ae.success(F.approved?"Listing approved":"Listing unapproved"),F.approved?_(F.id,F.slug||null,"submit_url"):_(F.id,F.slug||null,"remove_url")}}),b=gt({mutationFn:async({id:F,featured:z})=>{const{error:V}=await q.from("listings").update({is_featured:z}).eq("id",F);if(V)throw V},onSuccess:(F,{featured:z})=>{s.invalidateQueries({queryKey:["admin-listings"]}),ae.success(z?"Listing featured":"Listing unfeatured")}}),S=gt({mutationFn:async F=>{const{error:z}=await q.from("listings").delete().eq("id",F);if(z)throw z},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ae.success("Listing deleted")}}),A=gt({mutationFn:async F=>{const{error:z}=await q.from("feature_flags").update({enabled:F}).eq("key","listing_exchange_enabled");if(z)throw z},onSuccess:()=>{c(),ae.success("Feature flag updated")}}),T=o??!1,L=d==null?void 0:d.filter(F=>{var W,Y,K,J;const z=((W=F.city)==null?void 0:W.toLowerCase().includes(t.toLowerCase()))||((K=(Y=F.agent)==null?void 0:Y.name)==null?void 0:K.toLowerCase().includes(t.toLowerCase()))||((J=F.property_address)==null?void 0:J.toLowerCase().includes(t.toLowerCase())),V=r==="all"||r==="pending"&&!F.is_approved||r==="approved"&&F.is_approved;return z&&V}),D=F=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(F),M=F=>{const z={active:"bg-green-500/10 text-green-600 border-green-200",coming_soon:"bg-blue-500/10 text-blue-600 border-blue-200",price_improvement:"bg-amber-500/10 text-amber-600 border-amber-200",under_contract:"bg-purple-500/10 text-purple-600 border-purple-200",sold:"bg-gray-500/10 text-gray-600 border-gray-200"};return z[F]||z.active};return e.jsxs(Ts,{title:"Listing Exchange Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage community listings"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending,className:"gap-2",children:[v.isPending?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(lc,{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(bn,{checked:T,onCheckedChange:F=>A.mutate(F)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Va,{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(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mo,{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(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nn,{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(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Er,{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(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hl,{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(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fo,{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(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by city, address, or agent...",value:t,onChange:F=>n(F.target.value),className:"pl-9"})]}),e.jsx(Br,{value:r,onValueChange:F=>a(F),children:e.jsxs(Fr,{children:[e.jsx(Kt,{value:"all",children:"All"}),e.jsx(Kt,{value:"pending",children:"Pending"}),e.jsx(Kt,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{children:["Listings (",(L==null?void 0:L.length)||0,")"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Property"}),e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Price"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-center",children:"Approved"}),e.jsx(Ct,{className:"text-center",children:"Featured"}),e.jsx(Ct,{children:"Views"}),e.jsx(Ct,{children:"Shares"}),e.jsx(Ct,{children:"Leads"}),e.jsx(Ct,{children:"Date"}),e.jsx(Ct,{})]})}),e.jsx(ha,{children:u?e.jsx(Hs,{children:e.jsx(ut,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):(L==null?void 0:L.length)===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"No listings found"})}):L==null?void 0:L.map(F=>{var z,V,W,Y,K;return e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[(V=(z=F.photos)==null?void 0:z[0])!=null&&V.photo_url?e.jsx("img",{src:F.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(Va,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:F.property_address||`${F.city}, ${F.state}`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(W=F.property_type)==null?void 0:W.replace("_"," ")})]})]})}),e.jsx(ut,{children:e.jsx("p",{className:"text-sm",children:((Y=F.agent)==null?void 0:Y.name)||"Unknown"})}),e.jsx(ut,{className:"font-medium",children:D(F.price)}),e.jsx(ut,{children:e.jsx(ze,{variant:"outline",className:M(F.status),children:(K=F.status)==null?void 0:K.replace("_"," ")})}),e.jsx(ut,{className:"text-center",children:e.jsx(bn,{checked:F.is_approved??!1,onCheckedChange:J=>j.mutate({id:F.id,approved:J,slug:F.slug})})}),e.jsx(ut,{className:"text-center",children:e.jsx(bn,{checked:F.is_featured??!1,onCheckedChange:J=>b.mutate({id:F.id,featured:J})})}),e.jsx(ut,{children:F.view_count||0}),e.jsx(ut,{children:F.share_count||0}),e.jsx(ut,{children:((p==null?void 0:p[F.id])??0)>0?e.jsx(B,{variant:"link",size:"sm",className:"px-0 h-auto font-semibold text-teal-600",onClick:()=>l({listingId:F.id,label:F.property_address||`${F.city}, ${F.state}`}),children:p==null?void 0:p[F.id]}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:Ss(new Date(F.created_at),"MMM d, yyyy")}),e.jsx(ut,{children:e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",children:e.jsx(Qf,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",children:[e.jsxs(Qr,{onClick:()=>window.open(`/mission-control/listings/${F.id}`,"_blank"),children:[e.jsx(Er,{className:"h-4 w-4 mr-2"}),"View Listing"]}),e.jsxs(Qr,{onClick:()=>b.mutate({id:F.id,featured:!F.is_featured}),children:[e.jsx(ca,{className:"h-4 w-4 mr-2"}),F.is_featured?"Unfeature":"Feature"]}),e.jsxs(Qr,{className:"text-destructive",onClick:()=>{confirm("Are you sure you want to delete this listing?")&&S.mutate(F.id)},children:[e.jsx(Bn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},F.id)})})]})})})]})]}),e.jsx(bs,{open:!!i,onOpenChange:F=>!F&&l(null),children:e.jsxs(vs,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Leads from listing"}),e.jsx(Qn,{children:i==null?void 0:i.label})]}),g?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ts,{className:"h-5 w-5 animate-spin inline mr-2"}),"Loading leads..."]}):!f||f.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No leads yet."}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Phone"}),e.jsx(Ct,{children:"Type"}),e.jsx(Ct,{children:"Captured"})]})}),e.jsx(ha,{children:f.map(F=>{var z;return e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:[F.first_name,F.last_name].filter(Boolean).join(" ")||"—"}),e.jsx(ut,{children:F.email}),e.jsx(ut,{children:F.phone||"—"}),e.jsx(ut,{children:e.jsx(ze,{variant:"outline",children:(z=F.lead_type)==null?void 0:z.replace("_"," ")})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:Ss(new Date(F.created_at),"MMM d, yyyy h:mm a")})]},F.id)})})]})]})})]})}function men(s){return s?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"—"}function pen(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("all"),{data:l,isLoading:o}=ct({queryKey:["admin-all-listing-leads"],queryFn:async()=>{const h=[];let p=0;const f=1e3;for(;;){const{data:g,error:_}=await q.from("listing_leads").select(` id, listing_id, agent_id, referred_by_agent_id, first_name, last_name, email, phone, lead_type, showing_mode, preferred_date, preferred_time, message, created_at, listing:listings!listing_leads_listing_id_fkey(id, slug, property_address, city, state, price), agent:profiles!listing_leads_agent_id_fkey(id, name, email), referrer:profiles!listing_leads_referred_by_agent_id_fkey(id, name, email) `).order("created_at",{ascending:!1}).range(p,p+f-1);if(_)throw _;if(!g||g.length===0||(h.push(...g),g.length{if(!l)return[];const h=n==="all"?0:Date.now()-parseInt(n)*24*60*60*1e3,p=s.trim().toLowerCase();return l.filter(f=>{var _,v,j,b,S,A;return h&&new Date(f.created_at).getTime(){const h=c.length,p=c.filter(_=>_.lead_type==="showing_request").length,f=new Set(c.map(_=>_.agent_id)).size,g=new Set(c.map(_=>_.listing_id)).size;return{total:h,showings:p,uniqueAgents:f,uniqueListings:g}},[c]),u=()=>{const p=[["Date","Name","Email","Phone","Type","Showing Date","Property","City","Price","Assigned Agent","Agent Email","Referred By","Message"],...c.map(v=>{var j,b,S,A,T,L;return[Ss(new Date(v.created_at),"yyyy-MM-dd HH:mm"),`${v.first_name||""} ${v.last_name||""}`.trim(),v.email,v.phone||"",v.lead_type,v.preferred_date?`${v.preferred_date} ${v.preferred_time||""}`:"",((j=v.listing)==null?void 0:j.property_address)||"",((b=v.listing)==null?void 0:b.city)||"",(S=v.listing)!=null&&S.price?String(v.listing.price):"",((A=v.agent)==null?void 0:A.name)||"",((T=v.agent)==null?void 0:T.email)||"",((L=v.referrer)==null?void 0:L.name)||"",(v.message||"").replace(/[\r\n]+/g," ")]})].map(v=>v.map(j=>`"${String(j).replace(/"/g,'""')}"`).join(",")).join(` `),f=new Blob([p],{type:"text/csv"}),g=URL.createObjectURL(f),_=document.createElement("a");_.href=g,_.download=`listing-leads-${Ss(new Date,"yyyy-MM-dd")}.csv`,_.click(),URL.revokeObjectURL(g)};return e.jsx(Ts,{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(Pa,{className:"h-4 w-4"}),"Export CSV"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fo,{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(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yr,{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(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{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(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fo,{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(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search name, email, property, agent...",value:s,onChange:h=>t(h.target.value),className:"pl-9"})]}),e.jsxs(ds,{value:a,onValueChange:h=>i(h),children:[e.jsx(ls,{className:"w-full sm:w-48",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Types"}),e.jsx(Qe,{value:"info_request",children:"Info Request"}),e.jsx(Qe,{value:"showing_request",children:"Showing Request"})]})]}),e.jsxs(ds,{value:n,onValueChange:h=>r(h),children:[e.jsx(ls,{className:"w-full sm:w-40",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Time"}),e.jsx(Qe,{value:"7",children:"Last 7 days"}),e.jsx(Qe,{value:"30",children:"Last 30 days"}),e.jsx(Qe,{value:"90",children:"Last 90 days"})]})]})]})})}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{children:["Leads (",c.length,")"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Date"}),e.jsx(Ct,{children:"Lead"}),e.jsx(Ct,{children:"Contact"}),e.jsx(Ct,{children:"Property"}),e.jsx(Ct,{children:"Type"}),e.jsx(Ct,{children:"Assigned To"}),e.jsx(Ct,{children:"Referred By"}),e.jsx(Ct,{children:"Message"})]})}),e.jsx(ha,{children:o?e.jsx(Hs,{children:e.jsx(ut,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):c.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"No leads found"})}):c.map(h=>{var p,f;return e.jsxs(Hs,{children:[e.jsxs(ut,{className:"whitespace-nowrap text-sm",children:[Ss(new Date(h.created_at),"MMM d, yyyy"),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ss(new Date(h.created_at),"h:mm a")})]}),e.jsx(ut,{children:e.jsx("div",{className:"font-medium",children:`${h.first_name||""} ${h.last_name||""}`.trim()||"—"})}),e.jsx(ut,{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(Vs,{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(Ar,{className:"h-3 w-3"}),h.phone]})]})}),e.jsx(ut,{children:h.listing?e.jsxs(Ln,{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(", ")," · ",men(h.listing.price)]})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsxs(ut,{children:[e.jsx(ze,{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(ut,{children:[e.jsx("div",{className:"text-sm font-medium",children:((p=h.agent)==null?void 0:p.name)||"—"}),((f=h.agent)==null?void 0:f.email)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:h.agent.email})]}),e.jsx(ut,{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(ut,{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(Ei,{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 UI={new_listing_alerts:{label:"New Listing Alerts",icon:im,color:"bg-amber-100 text-amber-800"},exit_intent:{label:"Exit Intent",icon:LA,color:"bg-rose-100 text-rose-800"},saved_listing:{label:"Saved Home",icon:gi,color:"bg-pink-100 text-pink-800"},saved_search:{label:"Saved Search",icon:vr,color:"bg-blue-100 text-blue-800"},buyer_guide:{label:"Buyer's Guide",icon:Ou,color:"bg-emerald-100 text-emerald-800"}},bXe=[{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 _Xe(s){return new Date(s).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}function fen(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState("30d"),[l,o]=N.useState("all"),[c,d]=N.useState("");N.useEffect(()=>{let f=!1;return(async()=>{r(!0);let g=q.from("public_site_leads").select("*").order("created_at",{ascending:!1}).limit(2e3);const _=bXe.find(b=>b.key===a);if(_&&_.days>0){const b=new Date(Date.now()-_.days*864e5).toISOString();g=g.gte("created_at",b)}const{data:v,error:j}=await g;f||(j?(console.error(j),t([])):t(v||[]),r(!1))})(),()=>{f=!0}},[a]);const u=N.useMemo(()=>s.filter(f=>{if(l!=="all"&&f.lead_type!==l)return!1;if(c){const g=c.toLowerCase();if(![f.email,f.first_name,f.last_name,f.phone,f.source_page,f.referrer].filter(Boolean).join(" ").toLowerCase().includes(g))return!1}return!0}),[s,l,c]),h=N.useMemo(()=>{const f=u.length,g=new Set(u.map(v=>v.email.toLowerCase())).size,_={};return u.forEach(v=>{_[v.lead_type]=(_[v.lead_type]||0)+1}),{total:f,uniqueEmails:g,byType:_}},[u]),p=()=>{const g=[["Date (ET)","Type","Email","First","Last","Phone","Listing ID","Source Page","Referrer","Criteria"].join(",")];u.forEach(b=>{var A;const S=[_Xe(b.created_at),((A=UI[b.lead_type])==null?void 0:A.label)||b.lead_type,b.email,b.first_name||"",b.last_name||"",b.phone||"",b.listing_id||"",b.source_page||"",b.referrer||"",b.criteria?JSON.stringify(b.criteria):""].map(T=>`"${String(T).replace(/"/g,'""')}"`);g.push(S.join(","))});const _=new Blob([g.join(` `)],{type:"text/csv"}),v=URL.createObjectURL(_),j=document.createElement("a");j.href=v,j.download=`public-site-leads-${new Date().toISOString().slice(0,10)}.csv`,j.click(),URL.revokeObjectURL(v)};return e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(Go,{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(Ln,{to:"/admin",children:e.jsxs(B,{variant:"ghost",size:"sm",children:[e.jsx(Hr,{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:p,variant:"outline",size:"sm",children:[e.jsx(Pa,{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(fe,{children:e.jsxs(Ee,{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(UI).map(f=>{const g=UI[f],_=g.icon;return e.jsx(fe,{children:e.jsxs(Ee,{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(_,{className:"h-3.5 w-3.5"}),g.label]}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:h.byType[f]||0})]})},f)})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ds,{value:a,onValueChange:f=>i(f),children:[e.jsx(ls,{className:"w-[160px] bg-white",children:e.jsx(us,{})}),e.jsx(cs,{children:bXe.map(f=>e.jsx(Qe,{value:f.key,children:f.label},f.key))})]}),e.jsxs(ds,{value:l,onValueChange:o,children:[e.jsx(ls,{className:"w-[200px] bg-white",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All lead types"}),Object.keys(UI).map(f=>e.jsx(Qe,{value:f,children:UI[f].label},f))]})]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{placeholder:"Search name, email, phone…",value:c,onChange:f=>d(f.target.value),className:"pl-9 bg-white"})]}),e.jsxs("div",{className:"ml-auto text-sm text-slate-500",children:[u.length," ",u.length===1?"lead":"leads"]})]}),e.jsx(fe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-slate-50 text-left text-xs uppercase tracking-wide text-slate-500",children:[e.jsx("th",{className:"px-4 py-3",children:"Date"}),e.jsx("th",{className:"px-4 py-3",children:"Type"}),e.jsx("th",{className:"px-4 py-3",children:"Contact"}),e.jsx("th",{className:"px-4 py-3",children:"Phone"}),e.jsx("th",{className:"px-4 py-3",children:"Details"}),e.jsx("th",{className:"px-4 py-3",children:"Source"})]})}),e.jsx("tbody",{children:n?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"Loading…"})}):u.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"No leads yet in this range."})}):u.map(f=>{const g=UI[f.lead_type],_=g==null?void 0:g.icon,v=[f.first_name,f.last_name].filter(Boolean).join(" ")||"—";return e.jsxs("tr",{className:"border-b hover:bg-slate-50/60",children:[e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-slate-600 text-xs",children:_Xe(f.created_at)}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:e.jsxs(ze,{className:`${(g==null?void 0:g.color)||""} font-normal`,variant:"secondary",children:[_?e.jsx(_,{className:"h-3 w-3 mr-1"}):null,(g==null?void 0:g.label)||f.lead_type]})}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"font-medium text-slate-900",children:v}),e.jsxs("a",{href:`mailto:${f.email}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(Vs,{className:"h-3 w-3"}),f.email]})]}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:f.phone?e.jsxs("a",{href:`tel:${f.phone}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(Ar,{className:"h-3 w-3"}),f.phone]}):e.jsx("span",{className:"text-slate-400 text-xs",children:"—"})}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-600 max-w-xs",children:[f.listing_id&&e.jsxs("div",{className:"mb-0.5",children:["Listing: ",e.jsxs("span",{className:"font-mono text-[10px]",children:[f.listing_id.slice(0,8),"…"]})]}),f.criteria&&Object.keys(f.criteria).length>0&&e.jsx("div",{className:"text-slate-500 line-clamp-2",children:Object.entries(f.criteria).map(([j,b])=>`${j}: ${b}`).join(" · ")})]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-500 max-w-xs truncate",children:[f.source_page&&e.jsxs("div",{className:"inline-flex items-center gap-1",children:[e.jsx(tr,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f.source_page})]}),f.referrer&&e.jsxs("div",{className:"text-slate-400 truncate",children:["from ",f.referrer]})]})]},f.id)})})]})})})]})]})}const xen=()=>{var h,p;const[s,t]=N.useState(""),[n,r]=N.useState(null),{data:a,isLoading:i}=ct({queryKey:["membership-reviews"],queryFn:async()=>{const{data:f,error:g}=await q.from("membership_reviews").select("*").order("created_at",{ascending:!1});if(g)throw g;const _=(f==null?void 0:f.map(b=>b.user_id))||[],{data:v}=await q.from("profiles").select("id, name, email").in("id",_);return f==null?void 0:f.map(b=>({...b,profiles:(v==null?void 0:v.find(S=>S.id===b.user_id))||null}))}}),l=a==null?void 0:a.filter(f=>{var _,v,j,b,S;const g=s.toLowerCase();return((v=(_=f.profiles)==null?void 0:_.name)==null?void 0:v.toLowerCase().includes(g))||((b=(j=f.profiles)==null?void 0:j.email)==null?void 0:b.toLowerCase().includes(g))||((S=f.review_text)==null?void 0:S.toLowerCase().includes(g))}),o=a!=null&&a.length?(a.reduce((f,g)=>f+g.rating,0)/a.length).toFixed(1):"0.0",c=a==null?void 0:a.reduce((f,g)=>(f[g.rating]=(f[g.rating]||0)+1,f),{}),d=(a==null?void 0:a.filter(f=>f.posted_to_google).length)||0,u=f=>e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(g=>e.jsx(ca,{className:Et("h-4 w-4",f>=g?"fill-yellow-400 text-yellow-400":"text-muted-foreground")},g))});return e.jsx(Ts,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{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(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Vn,{children:"Total Reviews"}),e.jsx(It,{className:"text-3xl",children:(a==null?void 0:a.length)||0})]})}),e.jsx(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Vn,{children:"Average Rating"}),e.jsxs(It,{className:"flex items-center gap-2 text-3xl",children:[o,e.jsx(ca,{className:"h-6 w-6 fill-yellow-400 text-yellow-400"})]})]})}),e.jsx(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Vn,{children:"5-Star Reviews"}),e.jsx(It,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),e.jsx(fe,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Vn,{children:"Posted to Google"}),e.jsxs(It,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(tr,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, or review...",value:s,onChange:f=>t(f.target.value),className:"pl-9"})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Member"}),e.jsx(Ct,{children:"Rating"}),e.jsx(Ct,{className:"hidden md:table-cell",children:"Review"}),e.jsx(Ct,{children:"Google"}),e.jsx(Ct,{children:"Date"})]})}),e.jsx(ha,{children:i?e.jsx(Hs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No reviews found"})}):l==null?void 0:l.map(f=>{var g,_;return e.jsxs(Hs,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>r(f),children:[e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:((g=f.profiles)==null?void 0:g.name)||"Unknown"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(_=f.profiles)==null?void 0:_.email})]})}),e.jsx(ut,{children:u(f.rating)}),e.jsx(ut,{className:"hidden md:table-cell max-w-xs",children:e.jsx("p",{className:"truncate text-sm text-muted-foreground",children:f.review_text||"-"})}),e.jsx(ut,{children:f.posted_to_google?e.jsx(ze,{variant:"secondary",className:"bg-green-100 text-green-800",children:"Posted"}):e.jsx(ze,{variant:"outline",children:"No"})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:Ss(new Date(f.created_at),"MMM d, yyyy")})]},f.id)})})]})})}),e.jsx(bs,{open:!!n,onOpenChange:()=>r(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Review Details"})}),n&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:((h=n.profiles)==null?void 0:h.name)||"Unknown Member"}),((p=n.profiles)==null?void 0:p.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(Vs,{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(yr,{className:"h-4 w-4"}),Ss(new Date(n.created_at),"MMMM d, yyyy 'at' h:mm a")]}),n.posted_to_google?e.jsxs(ze,{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(ze,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},wXe={agent_card:"Agent Card",listing:"Listing",lead_site:"Lead Site",guest_book:"Guest Book",landing_page:"Landing Page",connect_page:"Connect Page",booking:"Booking"},gen={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 yen(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("all"),[l,o]=N.useState("7"),{data:c,isLoading:d}=ct({queryKey:["lead-notification-log",l],queryFn:async()=>{const p=new Date(Date.now()-Number(l)*864e5).toISOString(),{data:f,error:g}=await q.from("lead_notification_log").select("*").gte("created_at",p).order("created_at",{ascending:!1}).limit(2e3);if(g)throw g;return f||[]}}),u=N.useMemo(()=>{const p=s.trim().toLowerCase();return(c||[]).filter(f=>n!=="all"&&f.source!==n||a!=="all"&&f.status!==a?!1:p?[f.agent_name,f.agent_email,f.lead_name,f.lead_email,f.lead_phone,f.subject].some(g=>(g||"").toLowerCase().includes(p)):!0)},[c,s,n,a]),h=N.useMemo(()=>{const p=u.length,f=u.filter(v=>v.status==="sent"||v.status==="backfilled").length,g=u.filter(v=>v.status==="failed").length,_=new Set(u.map(v=>v.agent_user_id).filter(Boolean)).size;return{total:p,sent:f,failed:g,agents:_}},[u]);return e.jsx(Ts,{children:e.jsxs("div",{className:"container mx-auto py-6 space-y-6",children:[e.jsx(Ud,{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(fe,{children:e.jsxs(Ee,{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(fe,{children:e.jsxs(Ee,{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(fe,{children:e.jsxs(Ee,{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(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Unique Agents"}),e.jsx("div",{className:"text-2xl font-bold",children:h.agents})]})})]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agent or lead name, email, phone…",value:s,onChange:p=>t(p.target.value),className:"pl-9"})]}),e.jsxs(ds,{value:n,onValueChange:r,children:[e.jsx(ls,{className:"w-full md:w-48",children:e.jsx(us,{placeholder:"Source"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Sources"}),Object.entries(wXe).map(([p,f])=>e.jsx(Qe,{value:p,children:f},p))]})]}),e.jsxs(ds,{value:a,onValueChange:i,children:[e.jsx(ls,{className:"w-full md:w-40",children:e.jsx(us,{placeholder:"Status"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Statuses"}),e.jsx(Qe,{value:"sent",children:"Sent"}),e.jsx(Qe,{value:"backfilled",children:"Backfilled"}),e.jsx(Qe,{value:"failed",children:"Failed"})]})]}),e.jsxs(ds,{value:l,onValueChange:o,children:[e.jsx(ls,{className:"w-full md:w-36",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"1",children:"Last 24h"}),e.jsx(Qe,{value:"7",children:"Last 7 days"}),e.jsx(Qe,{value:"14",children:"Last 14 days"}),e.jsx(Qe,{value:"30",children:"Last 30 days"})]})]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"When"}),e.jsx(Ct,{children:"Source"}),e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Lead"}),e.jsx(Ct,{children:"Status"})]})}),e.jsx(ha,{children:d?e.jsx(Hs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"Loading…"})}):u.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No notifications match the current filters."})}):u.map(p=>e.jsxs(Hs,{children:[e.jsx(ut,{className:"whitespace-nowrap text-sm",children:Ss(new Date(p.created_at),"MMM d, yyyy h:mm a")}),e.jsx(ut,{children:e.jsx(ze,{variant:"secondary",children:wXe[p.source]||p.source})}),e.jsxs(ut,{children:[e.jsx("div",{className:"font-medium",children:p.agent_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:p.agent_email||"—"})]}),e.jsxs(ut,{children:[e.jsx("div",{className:"font-medium",children:p.lead_name||"—"}),e.jsxs("div",{className:"text-xs text-muted-foreground flex flex-wrap gap-x-3 gap-y-1",children:[p.lead_email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vs,{className:"h-3 w-3"}),p.lead_email]}),p.lead_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ar,{className:"h-3 w-3"}),p.lead_phone]})]})]}),e.jsxs(ut,{children:[e.jsx(ze,{className:gen[p.status]||"",children:p.status}),p.error_message&&e.jsx("div",{className:"text-xs text-red-600 mt-1 max-w-[220px] truncate",title:p.error_message,children:p.error_message})]})]},p.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 ven=[{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"}],ben=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 _en(){const s=Ht(),{user:t}=ys(),[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(!1),{data:c,isLoading:d}=ct({queryKey:["weekly-digest-settings"],queryFn:async()=>{const{data:M,error:F}=await q.from("weekly_digest_settings").select("*").single();if(F)throw F;return M}}),{data:u,isLoading:h}=ct({queryKey:["weekly-digest-logs"],queryFn:async()=>{const{data:M,error:F}=await q.from("weekly_digest_logs").select("*").order("sent_at",{ascending:!1}).limit(100);if(F)throw F;return M}}),{data:p}=ct({queryKey:["digest-subscriber-count"],queryFn:async()=>{const{count:M,error:F}=await q.from("profiles").select("id",{count:"exact",head:!0}).eq("digest_opt_out",!1).not("email","is",null);if(F)throw F;return M||0}}),{data:f,refetch:g}=ct({queryKey:["digest-queue-status"],queryFn:async()=>{const M=new Date;M.setUTCHours(0,0,0,0);const[F,z,V,W]=await Promise.all([q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","pending").gte("created_at",M.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","processing").gte("created_at",M.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","sent").gte("created_at",M.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","failed").gte("created_at",M.toISOString())]);return{pending:F.count||0,processing:z.count||0,sent:V.count||0,failed:W.count||0,total:(F.count||0)+(z.count||0)+(V.count||0)+(W.count||0)}},refetchInterval:5e3});N.useEffect(()=>{if(f&&(f.pending>0||f.processing>0)){const M=setInterval(()=>{g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})},5e3);return()=>clearInterval(M)}},[f,g,s]);const{data:_=0}=ct({queryKey:["digest-today-failed-count"],queryFn:async()=>{const M=new Date;M.setUTCHours(0,0,0,0);const{count:F,error:z}=await q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",M.toISOString());if(z)throw z;return F||0}}),v=gt({mutationFn:async M=>{const{error:F}=await q.from("weekly_digest_settings").update(M).eq("id",c==null?void 0:c.id);if(F)throw F},onSuccess:()=>{s.invalidateQueries({queryKey:["weekly-digest-settings"]}),ae.success("Settings updated")},onError:M=>{ae.error("Failed to update settings: "+M.message)}}),j=async()=>{r(!0);try{const{data:M,error:F}=await q.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(F)throw F;M.queued?ae.success(`${M.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):M.sent!==void 0&&ae.success(`Digest sent! ${M.sent} emails delivered, ${M.failed} failed`),g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(M){ae.error("Failed to send digest: "+M.message)}finally{r(!1)}},b=async()=>{var M,F,z,V,W,Y;if(!(t!=null&&t.email)){ae.error("No email found for your account");return}i(!0);try{const{data:K,error:J}=await q.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:t.email}});if(J)throw J;const ne=K==null?void 0:K.resendId,ie=K==null?void 0:K.resendDetails,he=ie==null?void 0:ie.status,ce=((M=ie==null?void 0:ie.body)==null?void 0:M.status)||((z=(F=ie==null?void 0:ie.body)==null?void 0:F.data)==null?void 0:z.status),pe=((W=(V=ie==null?void 0:ie.body)==null?void 0:V.error)==null?void 0:W.message)||((Y=ie==null?void 0:ie.body)==null?void 0:Y.message);ae.success(ne?`Preview accepted by email provider (id: ${ne})${he?`, status check: ${he}`:""}${ce?`, provider: ${ce}`:""}${pe?` (${pe})`:""}. Check spam/promotions—delivery can take a few minutes.`:"Preview accepted by email provider. Check spam/promotions—delivery can take a few minutes.")}catch(K){ae.error("Failed to send preview: "+K.message)}finally{i(!1)}},S=async()=>{o(!0);try{const{data:M,error:F}=await q.functions.invoke("send-weekly-digest",{body:{retryFailed:!0}});if(F)throw F;M.queued===0||M.sent===0&&M.failed===0&&!M.queued?ae.info("No failed emails to retry"):M.queued?ae.success(`${M.queued} emails queued for retry!`):ae.success(`Retry complete! ${M.sent} emails delivered, ${M.failed} failed`),g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})}catch(M){ae.error("Failed to retry: "+M.message)}finally{o(!1)}},A=f!=null&&f.total?Math.round((f.sent+f.failed)/f.total*100):0,T=((f==null?void 0:f.pending)||0)>0||((f==null?void 0:f.processing)||0)>0,{data:L}=ct({queryKey:["digest-delivery-stats"],queryFn:async()=>{var Y,K;const M=new Date;M.setUTCHours(0,0,0,0);const[F,z,V,W]=await Promise.all([q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","sent").gte("sent_at",M.toISOString()),q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",M.toISOString()),q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("has_agent_os_activity",!0).gte("sent_at",M.toISOString()),q.from("weekly_digest_logs").select("sent_at").order("sent_at",{ascending:!1}).limit(1)]);return{totalSent:F.count||0,totalFailed:z.count||0,agentOsEngaged:V.count||0,lastSent:((K=(Y=W.data)==null?void 0:Y[0])==null?void 0:K.sent_at)||null}},refetchInterval:T?5e3:!1}),D={totalSent:(L==null?void 0:L.totalSent)||0,totalFailed:(L==null?void 0:L.totalFailed)||0,lastSent:L==null?void 0:L.lastSent,agentOsEngaged:(L==null?void 0:L.agentOsEngaged)||0};return d?e.jsx(Ts,{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(Ts,{title:"Weekly Digest",description:"Configure and manage automated weekly email digests for members",children:e.jsxs(Br,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(Fr,{children:[e.jsxs(Kt,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(Xo,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(Kt,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(yo,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(is,{value:"settings",className:"space-y-6",children:[T&&f&&e.jsx(fe,{className:"border-primary/50 bg-primary/5",children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[e.jsx(ts,{className:"h-5 w-5 animate-spin text-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:"Sending emails..."}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[f.sent.toLocaleString()," sent, ",f.pending.toLocaleString()," pending",f.failed>0&&`, ${f.failed} failed`]})]}),e.jsxs("span",{className:"text-sm font-medium",children:[A,"%"]})]}),e.jsx(pi,{value:A,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Processing ~80 emails per minute. Estimated time remaining: ~",Math.ceil(f.pending/80)," min"]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsx(Ee,{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(Nn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:p}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribers"})]})]})})}),e.jsx(fe,{children:e.jsx(Ee,{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(xr,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:D.totalSent}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Delivered"})]})]})})}),e.jsx(fe,{children:e.jsx(Ee,{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(Hc,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:D.totalFailed}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed"})]})]})})}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-primary/10",children:e.jsx(gr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:D.lastSent?Ss(new Date(D.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(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(gr,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(Vn,{children:"Configure when the digest is sent"})]}),e.jsxs(Ee,{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(bn,{checked:c==null?void 0:c.is_enabled,onCheckedChange:M=>v.mutate({is_enabled:M})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Cron Frequency"}),e.jsxs(ds,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:M=>v.mutate({cron_frequency:M}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"daily",children:"Daily (runs once at selected time)"}),e.jsx(Qe,{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(ds,{value:String(c==null?void 0:c.send_day),onValueChange:M=>v.mutate({send_day:parseInt(M)}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:ven.map(M=>e.jsx(Qe,{value:M.value,children:M.label},M.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Time (UTC)"}),e.jsxs(ds,{value:String(c==null?void 0:c.send_hour),onValueChange:M=>v.mutate({send_hour:parseInt(M)}),disabled:(c==null?void 0:c.cron_frequency)==="daily",children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:ben.map(M=>e.jsx(Qe,{value:M.value,children:M.label},M.value))})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{onClick:b,disabled:a,variant:"outline",className:"flex-1",children:[e.jsx(Er,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs(B,{onClick:j,disabled:n,className:"flex-1",children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),n?"Sending...":"Send to All"]})]}),_>0&&e.jsxs(B,{onClick:S,disabled:l,variant:"outline",className:"w-full",children:[e.jsx(Ti,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${_} Failed`]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Nr,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(Vn,{children:"Choose what to include in the digest"})]}),e.jsxs(Ee,{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(Nr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"New Resources"})]}),e.jsx(bn,{checked:c==null?void 0:c.include_new_resources,onCheckedChange:M=>v.mutate({include_new_resources:M})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"Community Highlights"})]}),e.jsx(bn,{checked:c==null?void 0:c.include_community_posts,onCheckedChange:M=>v.mutate({include_community_posts:M})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"Agent OS Stats"})]}),e.jsx(bn,{checked:c==null?void 0:c.include_agent_os_stats,onCheckedChange:M=>v.mutate({include_agent_os_stats:M})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"Upcoming Events"})]}),e.jsx(bn,{checked:c==null?void 0:c.include_upcoming_events,onCheckedChange:M=>v.mutate({include_upcoming_events:M})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"Goals Progress"})]}),e.jsx(bn,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:M=>v.mutate({include_goals_progress:M})})]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Custom Introduction"}),e.jsx(Vn,{children:"Personalize the intro message (optional)"})]}),e.jsx(Ee,{children:e.jsx(Es,{placeholder:"Here's what's new this week to help you grow your business...",value:(c==null?void 0:c.custom_intro_text)||"",onChange:M=>v.mutate({custom_intro_text:M.target.value||null}),rows:3})})]})]}),e.jsx(is,{value:"stats",children:e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(Vn,{children:"Recent digest emails sent to members"})]}),e.jsx(Ee,{children:h?e.jsx("div",{className:"animate-pulse space-y-2",children:[1,2,3,4,5].map(M=>e.jsx("div",{className:"h-12 bg-muted rounded"},M))}):u&&u.length>0?e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Email"}),e.jsx(Ct,{children:"Sent At"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Resources"}),e.jsx(Ct,{children:"Agent OS"})]})}),e.jsx(ha,{children:u.map(M=>e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:M.email_sent_to}),e.jsx(ut,{children:Ss(new Date(M.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(ut,{children:e.jsx(ze,{variant:M.delivery_status==="sent"?"default":"destructive",children:M.delivery_status})}),e.jsx(ut,{children:M.resources_count}),e.jsx(ut,{children:M.has_agent_os_activity?e.jsx(ze,{variant:"secondary",children:"Active"}):e.jsx(ze,{variant:"outline",children:"Not Started"})})]},M.id))})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Vs,{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 wen={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 jen(){var ve,ge,Te;const s=Ht(),[t,n]=N.useState(""),[r,a]=N.useState(null),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(!0),[_,v]=N.useState(!1),[j,b]=N.useState(""),[S,A]=N.useState(null),{data:T,isLoading:L}=ct({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:Me,error:Ce}=await q.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(Ce)throw Ce;const Ae=(Me==null?void 0:Me.map(Fe=>Fe.user_id))||[],{data:De}=await q.from("profiles").select("id, name, email").in("id",Ae),Ie=new Map((De==null?void 0:De.map(Fe=>[Fe.id,{name:Fe.name,email:Fe.email}]))||[]);return Me==null?void 0:Me.map(Fe=>({...Fe,profile:Ie.get(Fe.user_id)||null}))}}),{data:D}=ct({queryKey:["all-profiles-for-points",T],queryFn:async()=>{const Ce=[];let Ae=0;for(;;){const{data:De,error:Ie}=await q.from("profiles").select("id, name, email").order("name").range(Ae,Ae+1e3-1);if(Ie)throw Ie;if(Ce.push(...De),!De||De.length<1e3)break;Ae+=1e3}return Ce}}),F=((D==null?void 0:D.filter(Me=>!(T!=null&&T.some(Ce=>Ce.user_id===Me.id))))||[]).filter(Me=>{var Ae,De;if(!j)return!0;const Ce=j.toLowerCase();return((Ae=Me.name)==null?void 0:Ae.toLowerCase().includes(Ce))||((De=Me.email)==null?void 0:De.toLowerCase().includes(Ce))}),{data:z,isLoading:V}=ct({queryKey:["agent-point-history",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:Me,error:Ce}=await q.from("agent_points").select("*").eq("user_id",r.user_id).order("created_at",{ascending:!1});if(Ce)throw Ce;return Me},enabled:!!(r!=null&&r.user_id)&&o}),{data:W}=ct({queryKey:["agent-badges",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:Me,error:Ce}=await q.from("agent_badges").select("*").eq("user_id",r.user_id).order("earned_at",{ascending:!1});if(Ce)throw Ce;return Me},enabled:!!(r!=null&&r.user_id)}),Y=gt({mutationFn:async({userId:Me,points:Ce,reason:Ae})=>{const{error:De}=await q.from("agent_points").insert({user_id:Me,points:Ce,reason:Ae});if(De)throw De;const{data:Ie}=await q.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",Me).maybeSingle(),Fe=((Ie==null?void 0:Ie.total_points)||0)+Ce,qe=((Ie==null?void 0:Ie.spendable_points)||0)+Ce,{error:be}=await q.from("agent_attendance_stats").upsert({user_id:Me,total_points:Math.max(0,Fe),spendable_points:Math.max(0,qe),updated_at:new Date().toISOString()},{onConflict:"user_id"});if(be)throw be},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-agent-points"]}),s.invalidateQueries({queryKey:["agent-point-history"]}),l(!1),u(""),p(""),ae.success(f?"Points awarded successfully!":"Points deducted successfully!")},onError:Me=>{console.error("Error modifying points:",Me),ae.error("Failed to modify points")}}),K=()=>{if(!r||!d||!h){ae.error("Please fill in all fields");return}const Me=parseInt(d);if(isNaN(Me)||Me<=0){ae.error("Please enter a valid positive number");return}Y.mutate({userId:r.user_id,points:f?Me:-Me,reason:h})},J=()=>{if(!S||!d||!h){ae.error("Please fill in all fields");return}const Me=parseInt(d);if(isNaN(Me)||Me<=0){ae.error("Please enter a valid positive number");return}Y.mutate({userId:S.id,points:Me,reason:h},{onSuccess:()=>{v(!1),A(null),b("")}})},ne=(Me,Ce)=>{a(Me),g(Ce),l(!0)},ie=Me=>{a(Me),c(!0)},he=T==null?void 0:T.filter(Me=>{var Ie,Fe,qe,be;const Ce=((Fe=(Ie=Me.profile)==null?void 0:Ie.name)==null?void 0:Fe.toLowerCase())||"",Ae=((be=(qe=Me.profile)==null?void 0:qe.email)==null?void 0:be.toLowerCase())||"",De=t.toLowerCase();return Ce.includes(De)||Ae.includes(De)}),ce=(T==null?void 0:T.reduce((Me,Ce)=>Me+Ce.total_points,0))||0,pe=(T==null?void 0:T.length)||0,le=pe>0?Math.round(ce/pe):0;return L?e.jsx(Ts,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(Me=>e.jsx(Ws,{className:"h-24"},Me))}),e.jsx(Ws,{className:"h-96"})]})}):e.jsx(Ts,{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(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Nn,{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:pe}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(vo,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Points"})]}),e.jsx("p",{className:"text-2xl font-bold",children:ce.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"awarded across all agents"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(mo,{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:le}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"per agent"})]})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between",children:[e.jsxs("div",{className:"relative max-w-sm w-full",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents...",value:t,onChange:Me=>n(Me.target.value),className:"pl-10"})]}),e.jsxs(B,{onClick:()=>v(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Agent Leaderboard"}),e.jsx(Vn,{children:"All agents with their points, events, and streaks"})]}),e.jsx(Ee,{children:!he||he.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(vo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents with points yet"})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{className:"w-12",children:"#"}),e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{className:"text-center",children:"Total Points"}),e.jsx(Ct,{className:"text-center",children:"Spendable"}),e.jsx(Ct,{className:"text-center",children:"Events"}),e.jsx(Ct,{className:"text-center",children:"Streak"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:he.map((Me,Ce)=>{var Ae,De,Ie,Fe;return e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:Ce<3?e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center ${Ce===0?"bg-yellow-100 text-yellow-700":Ce===1?"bg-gray-100 text-gray-600":"bg-amber-100 text-amber-700"}`,children:Ce+1}):e.jsx("span",{className:"text-muted-foreground",children:Ce+1})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ra,{className:"h-8 w-8",children:e.jsx(aa,{children:((De=(Ae=Me.profile)==null?void 0:Ae.name)==null?void 0:De.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Ie=Me.profile)==null?void 0:Ie.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(Fe=Me.profile)==null?void 0:Fe.email})]})]})}),e.jsx(ut,{className:"text-center",children:e.jsxs(ze,{variant:"secondary",className:"font-bold",children:[e.jsx(ca,{className:"h-3 w-3 mr-1"}),Me.total_points]})}),e.jsx(ut,{className:"text-center",children:e.jsxs(ze,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(Oi,{className:"h-3 w-3 mr-1"}),Me.spendable_points||0]})}),e.jsx(ut,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(yr,{className:"h-3 w-3 text-muted-foreground"}),Me.total_events_attended]})}),e.jsx(ut,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Dc,{className:"h-3 w-3 text-orange-500"}),Me.current_streak]})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ne(Me,!0),title:"Award points",children:e.jsx(Is,{className:"h-4 w-4 text-green-600"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ne(Me,!1),title:"Deduct points",children:e.jsx(fb,{className:"h-4 w-4 text-red-600"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ie(Me),title:"View history",children:e.jsx(MA,{className:"h-4 w-4"})})]})})]},Me.user_id)})})]})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:f?"Award Points":"Deduct Points"}),e.jsxs(Qn,{children:[f?"Award":"Deduct"," points ",f?"to":"from"," ",((ve=r==null?void 0:r.profile)==null?void 0:ve.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:Me=>u(Me.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"reason",children:"Reason"}),e.jsx(Es,{id:"reason",placeholder:"Enter reason for this adjustment...",value:h,onChange:Me=>p(Me.target.value)})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:K,disabled:Y.isPending,className:f?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700",children:Y.isPending?"Saving...":f?"Award Points":"Deduct Points"})]})]})}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:["Point History: ",(ge=r==null?void 0:r.profile)==null?void 0:ge.name]}),e.jsx(Qn,{children:"View all point transactions and badges for this agent"})]}),e.jsxs(Br,{defaultValue:"history",className:"w-full",children:[e.jsxs(Fr,{className:"grid w-full grid-cols-2",children:[e.jsx(Kt,{value:"history",children:"Point History"}),e.jsx(Kt,{value:"badges",children:"Badges"})]}),e.jsx(is,{value:"history",className:"mt-4",children:V?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(Me=>e.jsx(Ws,{className:"h-12"},Me))}):!z||z.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(MA,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No point history yet"})]}):e.jsx("div",{className:"max-h-80 overflow-y-auto space-y-2",children:z.map(Me=>e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:Me.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ss(new Date(Me.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(ze,{variant:Me.points>=0?"default":"destructive",className:Me.points>=0?"bg-green-100 text-green-800":"",children:[Me.points>=0?"+":"",Me.points]})]},Me.id))})}),e.jsx(is,{value:"badges",className:"mt-4",children:!W||W.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(bc,{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:W.map(Me=>e.jsxs("div",{className:`p-3 rounded-lg ${wen[Me.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bc,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:Me.badge_name})]}),Me.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:Me.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",Ss(new Date(Me.earned_at),"MMM d, yyyy")]})]},Me.id))})})]})]})}),e.jsx(bs,{open:_,onOpenChange:Me=>{v(Me),Me||(A(null),b(""),u(""),p(""))},children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Award Points to New Agent"}),e.jsx(Qn,{children:"Select an agent who doesn't have points yet and award them points"})]}),e.jsx("div",{className:"space-y-4 py-4",children:S?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(aa,{children:((Te=S.name)==null?void 0:Te.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:S.name||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:S.email})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>A(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:Me=>u(Me.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"new-reason",children:"Reason"}),e.jsx(Es,{id:"new-reason",placeholder:"Enter reason for awarding points...",value:h,onChange:Me=>p(Me.target.value)})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Search Agent"}),e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:j,onChange:Me=>b(Me.target.value),className:"pl-10"})]})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto border rounded-lg",children:F.length===0?e.jsxs("div",{className:"text-center py-4 text-muted-foreground",children:[e.jsx(Nn,{className:"h-6 w-6 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:j?"No matching agents found":"All agents already have points"})]}):F.slice(0,20).map(Me=>{var Ce;return e.jsxs("button",{onClick:()=>A(Me),className:"w-full flex items-center gap-3 p-3 hover:bg-muted/50 transition-colors border-b last:border-b-0 text-left",children:[e.jsx(ra,{className:"h-8 w-8",children:e.jsx(aa,{children:((Ce=Me.name)==null?void 0:Ce.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:Me.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Me.email})]})]},Me.id)})})]})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),S&&e.jsxs(B,{onClick:J,disabled:Y.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function Nen(){const{data:s,isLoading:t}=jzt(),[n,r]=N.useState(null),[a,i]=N.useState(!1),[l,o]=N.useState(""),[c,d]=N.useState("all"),[u,h]=N.useState("newest"),[p,f]=N.useState("table"),g=N.useMemo(()=>(s==null?void 0:s.map(S=>S.user_id))||[],[s]),_=N.useMemo(()=>(s==null?void 0:s.map(S=>S.id))||[],[s]),{data:v}=ct({queryKey:["card-profiles-lookup",g],queryFn:async()=>{if(g.length===0)return{};const{data:S}=await q.from("profiles").select("id, name, email").in("id",g),A={};return S==null||S.forEach(T=>{A[T.id]={name:T.name||"",email:T.email||""}}),A},enabled:g.length>0}),{data:j}=ct({queryKey:["card-stats-all",_],queryFn:async()=>{if(_.length===0)return{};const S={};_.forEach(L=>{S[L]={views:0,leads:0}});const{data:A}=await q.from("agent_card_interactions").select("card_id").in("card_id",_).eq("interaction_type","card_view");A==null||A.forEach(L=>{S[L.card_id]&&S[L.card_id].views++});const{data:T}=await q.from("agent_card_leads").select("card_id").in("card_id",_);return T==null||T.forEach(L=>{S[L.card_id]&&S[L.card_id].leads++}),S},enabled:_.length>0}),b=N.useMemo(()=>{if(!s)return[];let S=[...s];if(c==="live"?S=S.filter(A=>A.is_published):c==="draft"&&(S=S.filter(A=>!A.is_published)),l.trim()){const A=l.toLowerCase();S=S.filter(T=>{var D,M;const L=v==null?void 0:v[T.user_id];return T.slug.toLowerCase().includes(A)||((D=L==null?void 0:L.name)==null?void 0:D.toLowerCase().includes(A))||((M=L==null?void 0:L.email)==null?void 0:M.toLowerCase().includes(A))})}return u==="newest"?S.sort((A,T)=>new Date(T.created_at).getTime()-new Date(A.created_at).getTime()):u==="oldest"?S.sort((A,T)=>new Date(A.created_at).getTime()-new Date(T.created_at).getTime()):u==="name"?S.sort((A,T)=>{var L,D;return(((L=v==null?void 0:v[A.user_id])==null?void 0:L.name)||"").localeCompare(((D=v==null?void 0:v[T.user_id])==null?void 0:D.name)||"")}):u==="slug"?S.sort((A,T)=>A.slug.localeCompare(T.slug)):u==="views_desc"?S.sort((A,T)=>{var L,D;return(((L=j==null?void 0:j[T.id])==null?void 0:L.views)||0)-(((D=j==null?void 0:j[A.id])==null?void 0:D.views)||0)}):u==="views_asc"?S.sort((A,T)=>{var L,D;return(((L=j==null?void 0:j[A.id])==null?void 0:L.views)||0)-(((D=j==null?void 0:j[T.id])==null?void 0:D.views)||0)}):u==="leads_desc"?S.sort((A,T)=>{var L,D;return(((L=j==null?void 0:j[T.id])==null?void 0:L.leads)||0)-(((D=j==null?void 0:j[A.id])==null?void 0:D.leads)||0)}):u==="leads_asc"&&S.sort((A,T)=>{var L,D;return(((L=j==null?void 0:j[A.id])==null?void 0:L.leads)||0)-(((D=j==null?void 0:j[T.id])==null?void 0:D.leads)||0)}),S},[s,c,l,u,v]);return e.jsxs(Ts,{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(Is,{className:"h-4 w-4 mr-2"}),"Create Card"]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, or slug...",value:l,onChange:S=>o(S.target.value),className:"pl-9"})]}),e.jsxs(ds,{value:c,onValueChange:d,children:[e.jsx(ls,{className:"w-full sm:w-36",children:e.jsx(us,{placeholder:"Status"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All Status"}),e.jsx(Qe,{value:"live",children:"Live"}),e.jsx(Qe,{value:"draft",children:"Draft"})]})]}),e.jsxs(ds,{value:u,onValueChange:h,children:[e.jsx(ls,{className:"w-full sm:w-44",children:e.jsx(us,{placeholder:"Sort by"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"newest",children:"Newest First"}),e.jsx(Qe,{value:"oldest",children:"Oldest First"}),e.jsx(Qe,{value:"name",children:"Name A–Z"}),e.jsx(Qe,{value:"slug",children:"Slug A–Z"}),e.jsx(Qe,{value:"views_desc",children:"Most Views"}),e.jsx(Qe,{value:"views_asc",children:"Fewest Views"}),e.jsx(Qe,{value:"leads_desc",children:"Most Leads"}),e.jsx(Qe,{value:"leads_asc",children:"Fewest Leads"})]})]}),e.jsxs("div",{className:"flex border rounded-md",children:[e.jsx(B,{variant:p==="table"?"default":"ghost",size:"sm",onClick:()=>f("table"),className:"rounded-r-none",children:e.jsx(yL,{className:"h-4 w-4"})}),e.jsx(B,{variant:p==="grid"?"default":"ghost",size:"sm",onClick:()=>f("grid"),className:"rounded-l-none",children:e.jsx(yf,{className:"h-4 w-4"})})]})]}),!t&&s&&s.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",b.length," of ",s.length," cards"]}),t?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(S=>e.jsx(Ws,{className:"h-48"},S))}):b.length>0?p==="table"?e.jsx(ken,{cards:b,cardProfiles:v,cardStats:j,onEdit:r,sortBy:u,setSortBy:h}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:b.map(S=>e.jsx(Sen,{card:S,onEdit:()=>r(S),stats:j==null?void 0:j[S.id]},S.id))}):s&&s.length>0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(vr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No matching cards"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Try adjusting your search or filters"})]})}):e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Nn,{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(Is,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(Cen,{open:a,onOpenChange:i}),n&&e.jsx(Ten,{card:n,open:!!n,onOpenChange:S=>!S&&r(null)})]})}function ken({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(am,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(Ru,{className:"h-3 w-3"}):e.jsx(em,{className:"h-3 w-3 opacity-40"});return e.jsx(fe,{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(Ru,{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(ze,{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(_a,{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),ae.success("Link copied!")},children:e.jsx(Xr,{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 Sen({card:s,onEdit:t,stats:n}){const[r,a]=N.useState(null);N.useEffect(()=>{(async()=>{const{data:c}=await q.from("profiles").select("name").eq("id",s.user_id).single();let d=null;try{const{data:u}=await q.storage.from("avatars").list(`${s.user_id}`);if(u&&u.length>0){const{data:h}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${u[0].name}`);d=h.publicUrl}}catch{}a({name:(c==null?void 0:c.name)||"Unknown",avatar_url:d})})()},[s.user_id]);const i=`https://cards.relevelup.com/${s.slug}`,l=()=>{navigator.clipboard.writeText(i),ae.success("Link copied!")};return e.jsx(fe,{children:e.jsxs(Ee,{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(ni,{src:(r==null?void 0:r.avatar_url)||void 0}),e.jsx(aa,{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(ze,{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(Er,{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(Nn,{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(_a,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:l,children:e.jsx(Xr,{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 Cen({open:s,onOpenChange:t}){const[n,r]=N.useState(""),[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState(!1),u=gct(),h=l.trim(),{data:p}=ct({queryKey:["profiles-search-for-cards",h],queryFn:async()=>{let b=q.from("profiles").select("id, name, email").order("name").limit(50);h.length>=2&&(b=b.or(`name.ilike.%${h}%,email.ilike.%${h}%`));const{data:S}=await b;return S||[]},enabled:s}),[f,g]=N.useState(null),_=(p==null?void 0:p.find(b=>b.id===n))||f,v=()=>{if(!n||!a.trim()){ae.error("Select an agent and enter a slug");return}u.mutate({user_id:n,slug:a.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-"),is_published:!0},{onSuccess:()=>{t(!1),r(""),i(""),o("")}})},j=b=>{var A;r(b),d(!1);const S=p==null?void 0:p.find(T=>T.id===b);S&&(g(S),i(((A=S.name)==null?void 0:A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||""))};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create Agent Card"}),e.jsx(Qn,{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(el,{open:c,onOpenChange:d,children:[e.jsx(tl,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":c,className:"w-full justify-between font-normal",children:[_?`${_.name} (${_.email})`:"Search for an agent...",e.jsx(qg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ho,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Qg,{shouldFilter:!1,children:[e.jsx(Xg,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(Jg,{children:[e.jsx(e0,{children:"No agents found."}),e.jsx(t0,{children:(p||[]).map(b=>e.jsxs(Jf,{value:b.id,onSelect:j,children:[e.jsx(Ir,{className:Et("mr-2 h-4 w-4",n===b.id?"opacity-100":"opacity-0")}),b.name," (",b.email,")"]},b.id))})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(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:b=>i(b.target.value),placeholder:"john-doe"})]})]}),e.jsx(B,{onClick:v,disabled:u.isPending,className:"w-full",children:u.isPending?"Creating...":"Create Card"})]})]})})}function Ten({card:s,open:t,onOpenChange:n}){const r=yct(),{data:a}=vct(s.id),i=Ht(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[p,f]=N.useState(""),[g,_]=N.useState(s.slug),[v,j]=N.useState(!1),[b,S]=N.useState({is_published:s.is_published,theme:s.theme,title:s.title||"",positioning_statement:s.positioning_statement||"",bio:s.bio||"",review_snippet:s.review_snippet||"",review_source_url:s.review_source_url||"",booking_url:s.booking_url||"",custom_cta_label:s.custom_cta_label||"",custom_cta_url:s.custom_cta_url||"",show_photo:s.show_photo,show_bio:s.show_bio,show_credentials:s.show_credentials,show_social_links:s.show_social_links,show_save_contact:s.show_save_contact,show_leave_review:s.show_leave_review,show_refer_friend:s.show_refer_friend,brokerage_display_name:s.brokerage_display_name||"",brokerage_logo_url:s.brokerage_logo_url||"",brokerage_logo_size:s.brokerage_logo_size||56,team_name:s.team_name||"",team_logo_url:s.team_logo_url||"",team_logo_size:s.team_logo_size||56});N.useEffect(()=>{t&&(async()=>{try{const{data:z}=await q.storage.from("avatars").list(`${s.user_id}`);if(z&&z.length>0){const{data:V}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${z[0].name}`);o(`${V.publicUrl}?t=${Date.now()}`)}}catch{}})()},[s.user_id,t]);const A=F=>{var W;const z=(W=F.target.files)==null?void 0:W[0];if(!z)return;if(!z.type.startsWith("image/")){ae.error("Please select an image file");return}if(z.size>5*1024*1024){ae.error("Image must be under 5MB");return}const V=new FileReader;V.onloadend=()=>{f(V.result),h(!0)},V.readAsDataURL(z),F.target.value=""},T=async F=>{d(!0);try{const{data:z}=await q.storage.from("avatars").list(`${s.user_id}`);z&&z.length>0&&await q.storage.from("avatars").remove(z.map(J=>`${s.user_id}/${J.name}`));const V=`${s.user_id}/avatar.jpg`,{error:W}=await q.storage.from("avatars").upload(V,F,{upsert:!0,contentType:"image/jpeg"});if(W)throw W;const{data:Y}=q.storage.from("avatars").getPublicUrl(V),K=`${Y.publicUrl}?t=${Date.now()}`;o(K),await q.from("profiles").update({avatar_url:K}).eq("id",s.user_id),i.invalidateQueries({queryKey:["agent-card-public"]}),ae.success("Photo updated!")}catch(z){ae.error(z.message||"Upload failed")}finally{d(!1)}},L=async()=>{const F=g.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!F){ae.error("Please enter a valid URL");return}if(F===s.slug){ae.info("No changes to save");return}j(!0);try{const{data:z}=await q.from("agent_cards").select("id").eq("slug",F).neq("id",s.id).maybeSingle();if(z){ae.error("This URL is already taken. Try another one.");return}const{error:V}=await q.from("agent_cards").update({slug:F}).eq("id",s.id);if(V)throw V;_(F),i.invalidateQueries({queryKey:["agent-cards-admin"]}),ae.success("Card address updated!")}catch{ae.error("Failed to update card address")}finally{j(!1)}},D=async(F,z)=>{var W;const V=(W=F.target.files)==null?void 0:W[0];if(V){if(!V.type.startsWith("image/")){ae.error("Please select an image file");return}try{const Y=V.name.split(".").pop()||"png",K=z==="brokerage_logo_url"?"brokerage-logo":"team-logo",J=`${s.user_id}/${K}.${Y}`,{error:ne}=await q.storage.from("card-logos").upload(J,V,{upsert:!0});if(ne)throw ne;const{data:ie}=q.storage.from("card-logos").getPublicUrl(J),he=ie.publicUrl+"?t="+Date.now();S(z==="brokerage_logo_url"?ce=>({...ce,[z]:he,brokerage_display_name:""}):ce=>({...ce,[z]:he,team_name:""})),ae.success("Logo uploaded!")}catch{ae.error("Failed to upload logo")}finally{F.target.value=""}}},M=()=>{r.mutate({id:s.id,...b,title:b.title||null,positioning_statement:b.positioning_statement||null,bio:b.bio||null,review_snippet:b.review_snippet||null,review_source_url:b.review_source_url||null,booking_url:b.booking_url||null,custom_cta_label:b.custom_cta_label||null,custom_cta_url:b.custom_cta_url||null,brokerage_display_name:b.brokerage_display_name||null,brokerage_logo_url:b.brokerage_logo_url||null,brokerage_logo_size:b.brokerage_logo_size,team_name:b.team_name||null,team_logo_url:b.team_logo_url||null,team_logo_size:b.team_logo_size},{onSuccess:()=>n(!1)})};return e.jsxs(e.Fragment,{children:[e.jsx(bs,{open:t,onOpenChange:n,children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Edit Agent Card"}),e.jsxs(Qn,{children:["/card/",s.slug]})]}),e.jsxs(Br,{defaultValue:"content",children:[e.jsxs(Fr,{className:"w-full",children:[e.jsx(Kt,{value:"content",className:"flex-1",children:"Content"}),e.jsx(Kt,{value:"sections",className:"flex-1",children:"Sections"}),e.jsx(Kt,{value:"blocks",className:"flex-1",children:"Blocks"}),e.jsx(Kt,{value:"analytics",className:"flex-1",children:"Analytics"})]}),e.jsxs(is,{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(bn,{checked:b.is_published,onCheckedChange:F=>S(z=>({...z,is_published:F}))})]}),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(ni,{src:l||void 0}),e.jsx(aa,{children:"?"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:A,disabled:c}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:c,children:e.jsx("span",{children:c?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-3 w-3 mr-1 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Na,{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:g,onChange:F=>_(F.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"agent-name",className:"rounded-l-none"})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:L,disabled:v||g===s.slug,className:"shrink-0",children:v?"Saving...":"Update"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Theme"}),e.jsxs(ds,{value:b.theme,onValueChange:F=>S(z=>({...z,theme:F})),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"standard",children:"✨ Standard (Modern Clean)"}),e.jsx(Qe,{value:"luxury",children:"🌙 Luxury (Dark & Gold)"}),e.jsx(Qe,{value:"bold",children:"🔥 Bold (Vibrant & Punchy)"}),e.jsx(Qe,{value:"classic",children:"📋 Classic (Professional)"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Title / Tagline"}),e.jsx(ye,{value:b.title,onChange:F=>S(z=>({...z,title:F.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:b.positioning_statement,onChange:F=>S(z=>({...z,positioning_statement:F.target.value})),placeholder:"Your home journey, handled with care."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Bio"}),e.jsx(Es,{value:b.bio,onChange:F=>S(z=>({...z,bio:F.target.value})),placeholder:"Short about me...",rows:3})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Review Snippet"}),e.jsx(ye,{value:b.review_snippet,onChange:F=>S(z=>({...z,review_snippet:F.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:b.review_source_url,onChange:F=>S(z=>({...z,review_source_url:F.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:b.booking_url,onChange:F=>S(z=>({...z,booking_url:F.target.value})),placeholder:"https://calendly.com/your-link"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Custom CTA Label (optional)"}),e.jsx(ye,{value:b.custom_cta_label,onChange:F=>S(z=>({...z,custom_cta_label:F.target.value})),placeholder:"Book a Call"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Custom CTA URL (optional)"}),e.jsx(ye,{value:b.custom_cta_url,onChange:F=>S(z=>({...z,custom_cta_url:F.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:b.brokerage_display_name,onChange:F=>S(z=>({...z,brokerage_display_name:F.target.value,brokerage_logo_url:""})),placeholder:"Brokerage name (or upload logo below)",disabled:!!b.brokerage_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[b.brokerage_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:b.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${b.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>S(F=>({...F,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(Na,{className:"h-3.5 w-3.5"}),b.brokerage_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:F=>D(F,"brokerage_logo_url")})]})]}),b.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b.brokerage_logo_size||56,"px"]})]}),e.jsx(Bm,{value:[b.brokerage_logo_size||56],onValueChange:([F])=>S(z=>({...z,brokerage_logo_size:F})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(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:b.team_name,onChange:F=>S(z=>({...z,team_name:F.target.value,team_logo_url:""})),placeholder:"Team name (or upload logo below)",disabled:!!b.team_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[b.team_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:b.team_logo_url,alt:"Team logo",style:{height:`${b.team_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>S(F=>({...F,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(Na,{className:"h-3.5 w-3.5"}),b.team_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:F=>D(F,"team_logo_url")})]})]}),b.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b.team_logo_size||56,"px"]})]}),e.jsx(Bm,{value:[b.team_logo_size||56],onValueChange:([F])=>S(z=>({...z,team_logo_size:F})),min:24,max:120,step:4})]})]})]})]}),e.jsx(is,{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:F,label:z,hint:V})=>e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{children:[e.jsx(se,{children:z}),V&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[V," ",F==="show_photo"&&e.jsx("a",{href:"/profile",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:no-underline",children:"Update Profile"})]})]}),e.jsx(bn,{checked:b[F],onCheckedChange:W=>S(Y=>({...Y,[F]:W}))})]},F))}),e.jsx(is,{value:"blocks",className:"mt-4",children:e.jsx(L2t,{cardId:s.id})}),e.jsx(is,{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(fe,{children:e.jsxs(Ee,{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(fe,{children:e.jsxs(Ee,{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(fe,{children:e.jsxs(Ee,{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(F=>e.jsxs("div",{className:"text-sm p-2 bg-muted/50 rounded-lg",children:[e.jsx("span",{className:"font-medium",children:F.name}),F.phone&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",F.phone]}),F.intent&&e.jsx(ze,{variant:"secondary",className:"ml-2 text-xs",children:F.intent})]},F.id))})]})]}):e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No analytics data yet"})})]}),e.jsx(B,{onClick:M,disabled:r.isPending,className:"w-full mt-4",children:r.isPending?"Saving...":"Save Changes"})]})}),e.jsx(hIe,{open:u,onClose:()=>h(!1),imageSrc:p,onCropComplete:T,aspectRatio:1})]})}const HL={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"},k8e={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 S8e(s=!0){return ct({queryKey:["marketplace-categories",s],queryFn:async()=>{let t=q.from("marketplace_categories").select("*").order("sort_order",{ascending:!0});s&&(t=t.eq("is_active",!0));const{data:n,error:r}=await t;if(r)throw r;return n}})}function Een(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ae.success("Category created successfully")},onError:t=>{ae.error("Failed to create category: "+t.message)}})}function Aen(){const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("marketplace_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ae.success("Category updated successfully")},onError:t=>{ae.error("Failed to update category: "+t.message)}})}function Men(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("marketplace_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ae.success("Category deleted successfully")},onError:t=>{ae.error("Failed to delete category: "+t.message)}})}function Z2t(s,t=!0){return ct({queryKey:["marketplace-products",s,t],queryFn:async()=>{let n=q.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).order("sort_order",{ascending:!0});s&&(n=n.eq("category_id",s)),t&&(n=n.eq("is_active",!0));const{data:r,error:a}=await n;if(a)throw a;return r}})}function Ien(s){return ct({queryKey:["marketplace-product",s],queryFn:async()=>{const{data:t,error:n}=await q.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function Pen(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_products").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ae.success("Product created successfully")},onError:t=>{ae.error("Failed to create product: "+t.message)}})}function Len(){const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("marketplace_products").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.id]}),ae.success("Product updated successfully")},onError:t=>{ae.error("Failed to update product: "+t.message)}})}function Den(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("marketplace_products").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ae.success("Product deleted successfully")},onError:t=>{ae.error("Failed to delete product: "+t.message)}})}function Ren(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_product_images").insert([t]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.product_id]})}})}function Oen(){const s=Ht();return gt({mutationFn:async({id:t,productId:n})=>{const{error:r}=await q.from("marketplace_product_images").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ae.success("Image deleted successfully")},onError:t=>{ae.error("Failed to delete image: "+t.message)}})}function Fen(){const s=Ht();return gt({mutationFn:async({imageId:t,productId:n})=>{const{error:r}=await q.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",n);if(r)throw r;const{error:a}=await q.from("marketplace_product_images").update({is_primary:!0}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ae.success("Primary image updated")},onError:t=>{ae.error("Failed to set primary image: "+t.message)}})}function zen(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_product_variants").insert([t]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.product_id]}),ae.success("Variant added successfully")}})}function Ben(){const s=Ht();return gt({mutationFn:async({id:t,productId:n})=>{const{error:r}=await q.from("marketplace_product_variants").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ae.success("Variant deleted successfully")}})}function $en(){const s=Ht();return gt({mutationFn:async({productId:t,videoUrl:n})=>{await q.from("marketplace_product_videos").delete().eq("product_id",t);const{data:r,error:a}=await q.from("marketplace_product_videos").insert({product_id:t,video_url:n}).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.productId]}),ae.success("Video updated successfully")}})}function Uen(s){const{isAdmin:t}=ys();return ct({queryKey:["marketplace-orders",s,t],queryFn:async()=>{let n=q.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).order("created_at",{ascending:!1});const{data:r,error:a}=await n;if(a)throw a;if(t&&r){const i=[...new Set(r.map(c=>c.user_id))],{data:l}=await q.from("profiles").select("id, name, email").in("id",i),o=new Map((l==null?void 0:l.map(c=>[c.id,c]))||[]);return r.map(c=>({...c,user:o.get(c.user_id)}))}return r}})}function qen(){const{user:s}=ys();return ct({queryKey:["my-marketplace-orders",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("user_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function Ven(s){return ct({queryKey:["marketplace-order",s],queryFn:async()=>{const{data:t,error:n}=await q.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function Hen(){const s=Ht(),{user:t}=ys();return gt({mutationFn:async({orderId:n,status:r,notes:a,trackingNumber:i,trackingUrl:l,previousStatus:o})=>{const c={status:r};i!==void 0&&(c.tracking_number=i),l!==void 0&&(c.tracking_url=l);const{error:d}=await q.from("marketplace_orders").update(c).eq("id",n);if(d)throw d;const{error:u}=await q.from("marketplace_order_status_history").insert({order_id:n,status:r,notes:a,created_by:t==null?void 0:t.id});if(u)throw u;if(["shipped","in_production","processing","completed"].includes(r)&&r!==o)try{await q.functions.invoke("marketplace-order-notify",{body:{orderId:n,notificationType:r==="shipped"?"shipped":"status_update",newStatus:r,trackingNumber:i,trackingUrl:l}})}catch(p){console.error("Failed to send notification email:",p)}},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",r.orderId]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ae.success("Order status updated")},onError:n=>{ae.error("Failed to update order: "+n.message)}})}function Gen(){const s=Ht();return gt({mutationFn:async({itemId:t,proofUrl:n,proofNotes:r,orderId:a})=>{const{error:i}=await q.from("marketplace_order_items").update({proof_url:n,proof_notes:r,proof_status:"pending"}).eq("id",t);if(i)throw i;await q.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",a);try{await q.functions.invoke("marketplace-order-notify",{body:{orderId:a,notificationType:"proof_ready"}})}catch(l){console.error("Failed to send proof notification:",l)}return a},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ae.success("Proof uploaded & customer notified")}})}function Wen(){const s=Ht();return gt({mutationFn:async({itemId:t,orderId:n})=>{const{error:r}=await q.from("marketplace_order_items").update({proof_status:"approved"}).eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ae.success("Proof approved")}})}function Ken(){const s=Ht();return gt({mutationFn:async({itemId:t,orderId:n,reason:r})=>{const{error:a}=await q.from("marketplace_order_items").update({proof_status:"rejected",proof_notes:r}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ae.success("Proof rejected - please upload a new proof")}})}function Yen(){const{data:s,isLoading:t}=S8e(!1),n=Een(),r=Aen(),a=Men(),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),h=()=>{u({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),c(null)},p=_=>{c(_),u({name:_.name,description:_.description||"",image_url:_.image_url||"",sort_order:_.sort_order,is_active:_.is_active}),l(!0)},f=async _=>{_.preventDefault(),o?await r.mutateAsync({id:o.id,...d}):await n.mutateAsync(d),l(!1),h()},g=async _=>{confirm("Are you sure you want to delete this category?")&&await a.mutateAsync(_)};return t?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Ws,{className:"h-8 w-48"})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(_=>e.jsx(Ws,{className:"h-12 w-full"},_))})})]}):e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(It,{children:"Categories"}),e.jsxs(bs,{open:i,onOpenChange:_=>{l(_),_||h()},children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:o?"Edit Category":"Add Category"})}),e.jsxs("form",{onSubmit:f,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name"}),e.jsx(ye,{id:"name",value:d.name,onChange:_=>u({...d,name:_.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Es,{id:"description",value:d.description,onChange:_=>u({...d,description:_.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:_=>u({...d,image_url:_.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:_=>u({...d,sort_order:parseInt(_.target.value)||0})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bn,{id:"is_active",checked:d.is_active,onCheckedChange:_=>u({...d,is_active:_})}),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(Ee,{children:s&&s.length>0?e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{children:"Sort Order"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:s.map(_=>e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium",children:_.name}),e.jsx(ut,{className:"max-w-xs truncate",children:_.description}),e.jsx(ut,{children:_.sort_order}),e.jsx(ut,{children:e.jsx("span",{className:`px-2 py-1 rounded-full text-xs ${_.is_active?"bg-green-100 text-green-800":"bg-gray-100 text-gray-800"}`,children:_.is_active?"Active":"Inactive"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>p(_),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>g(_.id),disabled:a.isPending,children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},_.id))})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first category to get started."})})]})}function Zen(){var le,ve;const{data:s,isLoading:t}=Z2t(void 0,!1),{data:n}=S8e(!1),r=Pen(),a=Len(),i=Den(),l=Ren(),o=Oen(),c=Fen(),d=zen(),u=Ben(),h=$en(),[p,f]=N.useState(!1),[g,_]=N.useState(!1),[v,j]=N.useState(!1),[b,S]=N.useState(null),[A,T]=N.useState(null),[L,D]=N.useState(!1),[M,F]=N.useState({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),[z,V]=N.useState({name:"",price_adjustment:0}),[W,Y]=N.useState(""),K=()=>{F({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),S(null)},J=ge=>{S(ge),F({name:ge.name,description:ge.description||"",base_price:Number(ge.base_price),shipping_fee:Number(ge.shipping_fee),category_id:ge.category_id||"",allow_artwork_upload:ge.allow_artwork_upload,requires_proof_approval:ge.requires_proof_approval,is_active:ge.is_active,sort_order:ge.sort_order}),f(!0)},ne=async ge=>{ge.preventDefault();const Te={...M,category_id:M.category_id||null};b?await a.mutateAsync({id:b.id,...Te}):await r.mutateAsync(Te),f(!1),K()},ie=async ge=>{confirm("Are you sure you want to delete this product?")&&await i.mutateAsync(ge)},he=async ge=>{if(!A||!ge.target.files||ge.target.files.length===0)return;D(!0);const Te=ge.target.files[0],Me=Te.name.split(".").pop(),Ce=`products/${A.id}/${Date.now()}.${Me}`;try{const{error:Ae}=await q.storage.from("marketplace").upload(Ce,Te);if(Ae)throw Ae;const{data:{publicUrl:De}}=q.storage.from("marketplace").getPublicUrl(Ce);await l.mutateAsync({product_id:A.id,image_url:De,is_primary:!A.images||A.images.length===0}),ae.success("Image uploaded successfully")}catch(Ae){ae.error("Failed to upload image: "+Ae.message)}finally{D(!1)}},ce=async ge=>{ge.preventDefault(),A&&(await d.mutateAsync({product_id:A.id,name:z.name,price_adjustment:z.price_adjustment}),V({name:"",price_adjustment:0}))},pe=async()=>{!A||!W||(await h.mutateAsync({productId:A.id,videoUrl:W}),Y(""))};return t?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Ws,{className:"h-8 w-48"})}),e.jsx(Ee,{children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(ge=>e.jsx(Ws,{className:"h-64 w-full"},ge))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(It,{children:"Products"}),e.jsxs(bs,{open:p,onOpenChange:ge=>{f(ge),ge||K()},children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Product"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:b?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:ne,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:M.name,onChange:ge=>F({...M,name:ge.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"category",children:"Category"}),e.jsxs(ds,{value:M.category_id,onValueChange:ge=>F({...M,category_id:ge}),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select category"})}),e.jsx(cs,{children:n==null?void 0:n.map(ge=>e.jsx(Qe,{value:ge.id,children:ge.name},ge.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Es,{id:"description",value:M.description,onChange:ge=>F({...M,description:ge.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:M.base_price,onChange:ge=>F({...M,base_price:parseFloat(ge.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:M.shipping_fee,onChange:ge=>F({...M,shipping_fee:parseFloat(ge.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:M.sort_order,onChange:ge=>F({...M,sort_order:parseInt(ge.target.value)||0})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bn,{id:"allow_artwork_upload",checked:M.allow_artwork_upload,onCheckedChange:ge=>F({...M,allow_artwork_upload:ge})}),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(bn,{id:"requires_proof_approval",checked:M.requires_proof_approval,onCheckedChange:ge=>F({...M,requires_proof_approval:ge})}),e.jsx(se,{htmlFor:"requires_proof_approval",children:"Requires proof approval"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bn,{id:"is_active",checked:M.is_active,onCheckedChange:ge=>F({...M,is_active:ge})}),e.jsx(se,{htmlFor:"is_active",children:"Active"})]})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:r.isPending||a.isPending,children:b?"Update Product":"Create Product"})]})]})]})]}),e.jsx(Ee,{children:s&&s.length>0?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(ge=>{var Te,Me;return e.jsxs(fe,{className:"overflow-hidden",children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[ge.images&&ge.images.length>0?e.jsx("img",{src:((Te=ge.images.find(Ce=>Ce.is_primary))==null?void 0:Te.image_url)||ge.images[0].image_url,alt:ge.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"}),!ge.is_active&&e.jsx(ze,{variant:"secondary",className:"absolute top-2 right-2",children:"Inactive"})]}),e.jsxs(Ee,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1",children:ge.name}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:((Me=ge.category)==null?void 0:Me.name)||"No category"}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"font-bold",children:["$",Number(ge.base_price).toFixed(2)]}),Number(ge.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["+$",Number(ge.shipping_fee).toFixed(2)," shipping"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[ge.allow_artwork_upload&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"Artwork Upload"}),ge.requires_proof_approval&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"Proof Required"}),ge.variants&&ge.variants.length>0&&e.jsxs(ze,{variant:"outline",className:"text-xs",children:[ge.variants.length," Variants"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>J(ge),children:[e.jsx(_a,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{T(ge),_(!0)},children:[e.jsx(ry,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{T(ge),j(!0)},children:[e.jsx(uh,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ie(ge.id),children:e.jsx(_n,{className:"h-3 w-3 text-destructive"})})]})]})]},ge.id)})}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No products yet. Create your first product to get started."})})]}),e.jsx(bs,{open:g,onOpenChange:_,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Manage Images - ",A==null?void 0:A.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-3 gap-4",children:(le=A==null?void 0:A.images)==null?void 0:le.map(ge=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:ge.image_url,alt:"",className:"w-full aspect-square object-cover rounded-lg"}),ge.is_primary&&e.jsx(ze,{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:[!ge.is_primary&&e.jsx(B,{variant:"secondary",size:"icon",onClick:async()=>{var Te;await c.mutateAsync({imageId:ge.id,productId:A.id}),T({...A,images:(Te=A.images)==null?void 0:Te.map(Me=>({...Me,is_primary:Me.id===ge.id}))})},disabled:c.isPending,title:"Set as primary",children:e.jsx(ca,{className:"h-4 w-4"})}),e.jsx(B,{variant:"destructive",size:"icon",onClick:async()=>{var Me;await o.mutateAsync({id:ge.id,productId:A.id});const Te=s==null?void 0:s.find(Ce=>Ce.id===A.id);Te&&T({...Te,images:(Me=Te.images)==null?void 0:Me.filter(Ce=>Ce.id!==ge.id)})},disabled:o.isPending,children:e.jsx(_n,{className:"h-4 w-4"})})]})]},ge.id))}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:he,className:"hidden",id:"image-upload",disabled:L}),e.jsxs("label",{htmlFor:"image-upload",className:"cursor-pointer",children:[e.jsx(ry,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:L?"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:W,onChange:ge=>Y(ge.target.value)}),e.jsxs(B,{onClick:pe,disabled:!W,children:[e.jsx(br,{className:"h-4 w-4 mr-2"}),"Set Video"]})]}),(A==null?void 0:A.video)&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["Current video: ",A.video.video_url]})]})]})]})}),e.jsx(bs,{open:v,onOpenChange:j,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Manage Variants - ",A==null?void 0:A.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("form",{onSubmit:ce,className:"flex gap-2",children:[e.jsx(ye,{placeholder:"Variant name (e.g., 500 count)",value:z.name,onChange:ge=>V({...z,name:ge.target.value}),required:!0}),e.jsx(ye,{type:"number",step:"0.01",placeholder:"Price adj.",value:z.price_adjustment,onChange:ge=>V({...z,price_adjustment:parseFloat(ge.target.value)||0}),className:"w-32"}),e.jsx(B,{type:"submit",children:"Add"})]}),e.jsxs("div",{className:"space-y-2",children:[(ve=A==null?void 0:A.variants)==null?void 0:ve.map(ge=>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:ge.name}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:[Number(ge.price_adjustment)>=0?"+":"","$",Number(ge.price_adjustment).toFixed(2)]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u.mutateAsync({id:ge.id,productId:A.id}),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]},ge.id)),(!(A!=null&&A.variants)||A.variants.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:'No variants yet. Add variants like "250 count", "500 count", etc.'})]})]})]})})]})}const Qen=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function Xen(){var _,v,j;const{data:s,isLoading:t}=Uen(),n=Hen(),r=Gen(),[a,i]=N.useState(null),[l,o]=N.useState(!1),[c,d]=N.useState({status:"",notes:"",trackingNumber:"",trackingUrl:""}),[u,h]=N.useState(!1),p=b=>{i(b),d({status:b.status,notes:"",trackingNumber:b.tracking_number||"",trackingUrl:b.tracking_url||""}),o(!0)},f=async()=>{a&&(await n.mutateAsync({orderId:a.id,status:c.status,notes:c.notes,trackingNumber:c.trackingNumber,trackingUrl:c.trackingUrl,previousStatus:a.status}),o(!1))},g=async(b,S)=>{if(!a||!b.target.files||b.target.files.length===0)return;h(!0);const A=b.target.files[0],T=A.name.split(".").pop(),L=`proofs/${a.id}/${S}/${Date.now()}.${T}`;try{const{error:D}=await q.storage.from("marketplace").upload(L,A);if(D)throw D;const{data:{publicUrl:M}}=q.storage.from("marketplace").getPublicUrl(L);await r.mutateAsync({itemId:S,proofUrl:M,orderId:a.id}),ae.success("Proof uploaded successfully")}catch(D){ae.error("Failed to upload proof: "+D.message)}finally{h(!1)}};return t?e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(Ws,{className:"h-8 w-48"})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(b=>e.jsx(Ws,{className:"h-16 w-full"},b))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"Orders"})}),e.jsx(Ee,{children:s&&s.length>0?e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Order #"}),e.jsx(Ct,{children:"Customer"}),e.jsx(Ct,{children:"Date"}),e.jsx(Ct,{children:"Total"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:s.map(b=>{var S,A;return e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-mono",children:b.order_number}),e.jsx(ut,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((S=b.user)==null?void 0:S.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(A=b.user)==null?void 0:A.email})]})}),e.jsx(ut,{children:Ss(new Date(b.created_at),"MMM d, yyyy")}),e.jsxs(ut,{className:"font-bold",children:["$",Number(b.total).toFixed(2)]}),e.jsx(ut,{children:e.jsx(ze,{className:k8e[b.status],children:HL[b.status]})}),e.jsx(ut,{className:"text-right",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>p(b),children:[e.jsx(Er,{className:"h-4 w-4 mr-1"}),"View"]})})]},b.id)})})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No orders yet."})})]}),e.jsx(bs,{open:l,onOpenChange:o,children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Order ",a==null?void 0:a.order_number]})}),a&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Customer"}),e.jsx("p",{children:(_=a.user)==null?void 0:_.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(v=a.user)==null?void 0:v.email})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Shipping Address"}),e.jsx("p",{children:a.shipping_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[a.shipping_address,e.jsx("br",{}),a.shipping_city,", ",a.shipping_state," ",a.shipping_zip]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Order Items"}),e.jsx("div",{className:"space-y-3",children:(j=a.items)==null?void 0:j.map(b=>e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:b.product_name}),b.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:b.variant_name})]}),e.jsxs("p",{className:"font-bold",children:["$",Number(b.unit_price).toFixed(2)," x ",b.quantity]})]}),b.artwork_url&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:"Customer Artwork:"}),e.jsx("a",{href:b.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-sm",children:"View Artwork"})]}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Proof Status: "}),e.jsx(ze,{variant:b.proof_status==="approved"?"default":"secondary",children:b.proof_status||"No proof yet"})]}),b.proof_url?e.jsx("a",{href:b.proof_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-sm",children:"View Proof"}):e.jsxs("div",{children:[e.jsx("input",{type:"file",accept:"image/*,.pdf",onChange:S=>g(S,b.id),className:"hidden",id:`proof-${b.id}`,disabled:u}),e.jsx("label",{htmlFor:`proof-${b.id}`,children:e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("span",{children:[e.jsx(Na,{className:"h-4 w-4 mr-1"}),u?"Uploading...":"Upload Proof"]})})})]})]})})]},b.id))})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Subtotal"}),e.jsxs("span",{children:["$",Number(a.subtotal).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",Number(a.shipping_total).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between font-bold text-lg mt-2",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:["$",Number(a.total).toFixed(2)]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:"Update Order Status"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Status"}),e.jsxs(ds,{value:c.status,onValueChange:b=>d({...c,status:b}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:Qen.map(b=>e.jsx(Qe,{value:b,children:HL[b]},b))})]})]}),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:b=>d({...c,trackingNumber:b.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:b=>d({...c,trackingUrl:b.target.value}),placeholder:"https://..."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Notes (optional)"}),e.jsx(Es,{value:c.notes,onChange:b=>d({...c,notes:b.target.value}),placeholder:"Add a note about this status change..."})]}),e.jsxs(B,{onClick:f,disabled:n.isPending,className:"w-full",children:[e.jsx(Rc,{className:"h-4 w-4 mr-2"}),"Update Status"]})]})]}),a.status_history&&a.status_history.length>0&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:"Status History"}),e.jsx("div",{className:"space-y-2",children:a.status_history.map(b=>e.jsxs("div",{className:"flex justify-between text-sm p-2 bg-muted rounded",children:[e.jsxs("div",{children:[e.jsx(ze,{variant:"outline",children:HL[b.status]}),b.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:b.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:Ss(new Date(b.created_at),"MMM d, h:mm a")})]},b.id))})]})]})]})})]})}function Jen(){const[s,t]=N.useState("products"),n=Mn();return e.jsx(Ts,{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(Br,{value:s,onValueChange:t,children:[e.jsxs(Fr,{className:"grid w-full grid-cols-3",children:[e.jsxs(Kt,{value:"products",className:"flex items-center gap-2",children:[e.jsx(Rc,{className:"h-4 w-4"}),"Products"]}),e.jsxs(Kt,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(gf,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(Kt,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(Og,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(is,{value:"products",children:e.jsx(Zen,{})}),e.jsx(is,{value:"categories",children:e.jsx(Yen,{})}),e.jsx(is,{value:"orders",children:e.jsx(Xen,{})})]})]})})}function Q2t(){return ct({queryKey:["reward-categories"],queryFn:async()=>{const{data:s,error:t}=await q.from("reward_store_categories").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s}})}function etn(s){return ct({queryKey:["reward-items",s],queryFn:async()=>{let t=q.from("reward_store_items").select(` *, category:reward_store_categories(*) `).order("created_at",{ascending:!1});const{data:n,error:r}=await t;if(r)throw r;return n}})}function ttn(s){return ct({queryKey:["active-reward-items",s],queryFn:async()=>{let t=q.from("reward_store_items").select(` *, category:reward_store_categories(*) `).eq("is_active",!0).order("created_at",{ascending:!1});s&&(t=t.eq("category_id",s));const{data:n,error:r}=await t;if(r)throw r;return n}})}function stn(s){return ct({queryKey:["user-purchases",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).eq("user_id",s).order("purchased_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function ntn(){return ct({queryKey:["all-reward-purchases"],queryFn:async()=>{const{data:s,error:t}=await q.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).order("purchased_at",{ascending:!1});if(t)throw t;if(!s||s.length===0)return[];const n=[...new Set(s.map(l=>l.user_id))],{data:r,error:a}=await q.from("profiles").select("id, name, email").in("id",n);if(a)throw a;const i=new Map((r==null?void 0:r.map(l=>[l.id,l]))||[]);return s.map(l=>({...l,user:i.get(l.user_id)||null}))}})}function rtn(s){return ct({queryKey:["spendable-points",s],queryFn:async()=>{if(!s)return 0;const{data:t,error:n}=await q.from("agent_attendance_stats").select("spendable_points").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return(t==null?void 0:t.spendable_points)||0},enabled:!!s})}function atn(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("purchase_reward_item",{p_item_id:t});if(r)throw r;const a=n;if(!a.success)throw new Error(a.error||"Purchase failed");return a},onSuccess:()=>{s.invalidateQueries({queryKey:["user-purchases"]}),s.invalidateQueries({queryKey:["spendable-points"]}),s.invalidateQueries({queryKey:["active-reward-items"]}),s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["homereel-credits"]})}})}function itn(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("reward_store_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function otn(){const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("reward_store_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function ltn(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("reward_store_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function ctn(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("reward_store_items").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function dtn(){const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("reward_store_items").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function utn(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("reward_store_items").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function htn(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function HNe(s,t){const n=htn(s);if(n)try{const{data:r,error:a}=await q.storage.from(n.bucket).download(n.path);if(a){console.error("Error downloading file:",a),ae.error("Failed to download file");return}const i=URL.createObjectURL(r),l=document.createElement("a");l.href=i,l.download=t||n.path.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(r){console.error("Download error:",r),ae.error("Failed to download file")}else try{const a=await(await fetch(s)).blob(),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=t||s.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(r){console.error("External download error:",r),ae.error("Failed to download file")}}function X2t(){return ct({queryKey:["point-reward-settings"],queryFn:async()=>{const{data:s,error:t}=await q.from("point_reward_settings").select("*").order("action_name");if(t)throw t;return s}})}function mtn(){const s=Ht();return gt({mutationFn:async({id:t,points:n,is_active:r})=>{const a={points:n};r!==void 0&&(a.is_active=r);const{data:i,error:l}=await q.from("point_reward_settings").update(a).eq("id",t).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["point-reward-settings"]})}})}function ptn(){const{user:s}=ys(),[t,n]=N.useState("items"),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(null),[_,v]=N.useState(!1),[j,b]=N.useState(null),[S,A]=N.useState(""),[T,L]=N.useState(""),[D,M]=N.useState(null),[F,z]=N.useState(""),[V,W]=N.useState("file"),[Y,K]=N.useState(""),[J,ne]=N.useState(""),[ie,he]=N.useState(""),[ce,pe]=N.useState(!0),[le,ve]=N.useState(null),[ge,Te]=N.useState(!1),[Me,Ce]=N.useState(!1),Ae=N.useRef(null),De=N.useRef(null),{data:Ie,isLoading:Fe}=Q2t(),{data:qe,isLoading:be}=etn(),{data:Ze,isLoading:Ne}=ntn(),{data:it,isLoading:je}=X2t(),Ge=itn(),Be=otn(),Ye=ltn(),We=ctn(),rt=dtn(),tt=utn(),at=mtn(),[He,dt]=N.useState({}),bt=ft=>{ft?(l(ft),c(ft.name),u(ft.description||""),p(ft.icon||"")):(l(null),c(""),u(""),p("")),a(!0)},vt=async()=>{if(!o.trim()){ae.error("Please enter a category name");return}try{i?(await Be.mutateAsync({id:i.id,name:o,description:d||null,icon:h||null}),ae.success("Category updated successfully")):(await Ge.mutateAsync({name:o,description:d||null,icon:h||null,sort_order:((Ie==null?void 0:Ie.length)||0)+1}),ae.success("Category created successfully")),a(!1)}catch(ft){console.error("Error saving category:",ft),ae.error("Failed to save category")}},Bt=async()=>{if(f)try{await Ye.mutateAsync(f),ae.success("Category deleted successfully"),g(null)}catch(ft){console.error("Error deleting category:",ft),ae.error("Failed to delete category")}},Zt=ft=>{var Vt;ft?(b(ft),A(ft.name),L(ft.description||""),M(ft.category_id),z(ft.points_cost.toString()),W(ft.item_type),K(ft.file_url||""),ne(ft.preview_image_url||""),he(((Vt=ft.max_quantity)==null?void 0:Vt.toString())||""),pe(ft.is_active)):(b(null),A(""),L(""),M(null),z(""),W("file"),K(""),ne(""),he(""),pe(!0)),v(!0)},Fs=async(ft,Vt)=>{Vt==="file"?Te(!0):Ce(!0);try{const Ms=ft.name.split(".").pop(),Xt=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Ms}`,Js=`${Vt==="file"?"items":"previews"}/${Xt}`,{error:Cs}=await q.storage.from("reward-store").upload(Js,ft);if(Cs)throw Cs;const{data:{publicUrl:As}}=q.storage.from("reward-store").getPublicUrl(Js);Vt==="file"?K(As):ne(As),ae.success("File uploaded successfully")}catch(Ms){console.error("Error uploading file:",Ms),ae.error("Failed to upload file")}finally{Vt==="file"?Te(!1):Ce(!1)}},Rs=async()=>{if(!S.trim()){ae.error("Please enter an item name");return}if(!F||parseInt(F)<0){ae.error("Please enter a valid points cost");return}try{const ft={name:S,description:T||null,category_id:D,points_cost:parseInt(F),item_type:V,file_url:Y||null,preview_image_url:J||null,max_quantity:ie?parseInt(ie):null,current_quantity:ie?parseInt(ie):null,is_active:ce,created_by:s==null?void 0:s.id};j?(await rt.mutateAsync({id:j.id,...ft,current_quantity:j.max_quantity!==(ie?parseInt(ie):null)?ie?parseInt(ie):null:j.current_quantity}),ae.success("Item updated successfully")):(await We.mutateAsync(ft),ae.success("Item created successfully")),v(!1)}catch(ft){console.error("Error saving item:",ft),ae.error("Failed to save item")}},ms=async()=>{if(le)try{await tt.mutateAsync(le),ae.success("Item deleted successfully"),ve(null)}catch(ft){console.error("Error deleting item:",ft),ae.error("Failed to delete item")}},Pt=async(ft,Vt)=>{const Ms=He[ft];if(Ms===void 0||Ms===Vt.toString())return;const Xt=parseInt(Ms);if(isNaN(Xt)||Xt<0){ae.error("Please enter a valid positive number");return}try{await at.mutateAsync({id:ft,points:Xt}),ae.success("Points updated successfully"),dt(Js=>{const Cs={...Js};return delete Cs[ft],Cs})}catch(Js){console.error("Error updating points:",Js),ae.error("Failed to update points")}};return Fe||be||Ne||je?e.jsx(Ts,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-8 w-64"}),e.jsx(Ws,{className:"h-96"})]})}):e.jsxs(Ts,{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(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Rc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Items"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(qe==null?void 0:qe.length)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(qe==null?void 0:qe.filter(ft=>ft.is_active).length)||0," active"]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(gf,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Categories"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Ie==null?void 0:Ie.length)||0})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ca,{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:[qe&&qe.length>0?Math.round(qe.reduce((ft,Vt)=>ft+Vt.points_cost,0)/qe.length):0," pts"]})]})})]}),e.jsxs(Br,{value:t,onValueChange:n,children:[e.jsxs(Fr,{children:[e.jsx(Kt,{value:"items",children:"Items"}),e.jsx(Kt,{value:"categories",children:"Categories"}),e.jsx(Kt,{value:"purchases",children:"Purchases"}),e.jsx(Kt,{value:"point-settings",children:"Point Settings"})]}),e.jsx(is,{value:"items",className:"mt-4",children:e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Store Items"}),e.jsx(Vn,{children:"Manage rewards that agents can purchase"})]}),e.jsxs(B,{onClick:()=>Zt(),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(Ee,{children:!qe||qe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Oi,{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(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Item"}),e.jsx(Ct,{children:"Category"}),e.jsx(Ct,{className:"text-center",children:"Cost"}),e.jsx(Ct,{className:"text-center",children:"Type"}),e.jsx(Ct,{className:"text-center",children:"Quantity"}),e.jsx(Ct,{className:"text-center",children:"Status"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:qe.map(ft=>e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ft.preview_image_url?e.jsx("img",{src:ft.preview_image_url,alt:ft.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(Oi,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ft.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:ft.description||"No description"})]})]})}),e.jsx(ut,{children:ft.category?e.jsx(ze,{variant:"outline",children:ft.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ut,{className:"text-center",children:e.jsxs(ze,{variant:"secondary",className:"font-bold",children:[e.jsx(ca,{className:"h-3 w-3 mr-1"}),ft.points_cost]})}),e.jsx(ut,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[ft.item_type==="file"?e.jsx(Nr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Jo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs capitalize",children:ft.item_type})]})}),e.jsx(ut,{className:"text-center",children:ft.max_quantity!==null?e.jsxs("span",{className:ft.current_quantity===0?"text-red-500":"",children:[ft.current_quantity,"/",ft.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(ut,{className:"text-center",children:e.jsx(ze,{variant:ft.is_active?"default":"secondary",children:ft.is_active?"Active":"Inactive"})}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Zt(ft),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ve(ft.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},ft.id))})]})})]})}),e.jsx(is,{value:"categories",className:"mt-4",children:e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Categories"}),e.jsx(Vn,{children:"Organize your store items into categories"})]}),e.jsxs(B,{onClick:()=>bt(),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(Ee,{children:!Ie||Ie.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(gf,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No categories yet. Add your first category!"})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Name"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{className:"text-center",children:"Items"}),e.jsx(Ct,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:Ie.map(ft=>e.jsxs(Hs,{children:[e.jsxs(ut,{className:"font-medium",children:[ft.icon&&e.jsx("span",{className:"mr-2",children:ft.icon}),ft.name]}),e.jsx(ut,{className:"text-muted-foreground",children:ft.description||"—"}),e.jsx(ut,{className:"text-center",children:(qe==null?void 0:qe.filter(Vt=>Vt.category_id===ft.id).length)||0}),e.jsx(ut,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>bt(ft),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>g(ft.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},ft.id))})]})})]})}),e.jsx(is,{value:"purchases",className:"mt-4",children:e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Og,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(Vn,{children:"View all reward redemptions by agents"})]}),e.jsx(Ee,{children:!Ze||Ze.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Og,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No purchases yet."})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Date"}),e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{children:"Item"}),e.jsx(Ct,{className:"text-center",children:"Points Spent"})]})}),e.jsx(ha,{children:Ze.map(ft=>{var Vt,Ms,Xt,Js;return e.jsxs(Hs,{children:[e.jsx(ut,{className:"text-muted-foreground",children:Ss(new Date(ft.purchased_at),"MMM d, yyyy 'at' h:mm a")}),e.jsx(ut,{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(Xi,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Vt=ft.user)==null?void 0:Vt.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((Ms=ft.user)==null?void 0:Ms.email)||"—"})]})]})}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(Xt=ft.item)!=null&&Xt.preview_image_url?e.jsx("img",{src:ft.item.preview_image_url,alt:ft.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(Oi,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((Js=ft.item)==null?void 0:Js.name)||"Deleted item"})]})}),e.jsx(ut,{className:"text-center",children:e.jsxs(ze,{variant:"secondary",className:"font-bold",children:[e.jsx(ca,{className:"h-3 w-3 mr-1"}),ft.points_spent]})})]},ft.id)})})]})})]})})]})]}),e.jsx(bs,{open:r,onOpenChange:a,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:i?"Edit Category":"Add Category"}),e.jsx(Qn,{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:ft=>c(ft.target.value),placeholder:"e.g., Templates, Resources"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"categoryDescription",children:"Description"}),e.jsx(Es,{id:"categoryDescription",value:d,onChange:ft=>u(ft.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:ft=>p(ft.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{onClick:vt,disabled:Ge.isPending||Be.isPending,children:Ge.isPending||Be.isPending?"Saving...":"Save"})]})]})}),e.jsx(bs,{open:_,onOpenChange:v,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:j?"Edit Item":"Add Item"}),e.jsx(Qn,{children:j?"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:S,onChange:ft=>A(ft.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(Es,{id:"itemDescription",value:T,onChange:ft=>L(ft.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(ds,{value:D||"none",onValueChange:ft=>M(ft==="none"?null:ft),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select category"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"No category"}),Ie==null?void 0:Ie.map(ft=>e.jsxs(Qe,{value:ft.id,children:[ft.icon&&`${ft.icon} `,ft.name]},ft.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:F,onChange:ft=>z(ft.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(ds,{value:V,onValueChange:W,children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"file",children:"File Download"}),e.jsx(Qe,{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:ie,onChange:ft=>he(ft.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:Y,onChange:ft=>K(ft.target.value),placeholder:V==="file"?"Upload a file or paste URL":"Paste external link"}),V==="file"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>{var ft;return(ft=Ae.current)==null?void 0:ft.click()},disabled:ge,children:e.jsx(Na,{className:"h-4 w-4"})}),e.jsx("input",{ref:Ae,type:"file",className:"hidden",onChange:ft=>{var Ms;const Vt=(Ms=ft.target.files)==null?void 0:Ms[0];Vt&&Fs(Vt,"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:J,onChange:ft=>ne(ft.target.value),placeholder:"Upload an image or paste URL"}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>{var ft;return(ft=De.current)==null?void 0:ft.click()},disabled:Me,children:e.jsx(nl,{className:"h-4 w-4"})}),e.jsx("input",{ref:De,type:"file",accept:"image/*",className:"hidden",onChange:ft=>{var Ms;const Vt=(Ms=ft.target.files)==null?void 0:Ms[0];Vt&&Fs(Vt,"preview")}})]}),J&&e.jsx("img",{src:J,alt:"Preview",className:"mt-2 h-24 rounded object-cover"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bn,{id:"itemIsActive",checked:ce,onCheckedChange:pe}),e.jsx(se,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx(B,{onClick:Rs,disabled:We.isPending||rt.isPending,children:We.isPending||rt.isPending?"Saving...":"Save"})]})]})}),e.jsx(Oo,{open:!!f,onOpenChange:()=>g(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Category"}),e.jsx(Mo,{children:"Are you sure you want to delete this category? Items in this category will become uncategorized."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:Bt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(Oo,{open:!!le,onOpenChange:()=>ve(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Item"}),e.jsx(Mo,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:ms,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),t==="point-settings"&&e.jsxs(fe,{className:"mt-4",children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xo,{className:"h-5 w-5"}),e.jsxs("div",{children:[e.jsx(It,{children:"Point Reward Settings"}),e.jsx(Vn,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(Ee,{children:!it||it.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Xo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No point settings configured."})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Action"}),e.jsx(Ct,{children:"Description"}),e.jsx(Ct,{className:"text-center w-32",children:"Points"}),e.jsx(Ct,{className:"text-right w-24",children:"Save"})]})}),e.jsx(ha,{children:it.map(ft=>e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsx("p",{className:"font-medium",children:ft.action_name})}),e.jsx(ut,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:ft.description})}),e.jsx(ut,{className:"text-center",children:e.jsx(ye,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:He[ft.id]??ft.points.toString(),onChange:Vt=>dt(Ms=>({...Ms,[ft.id]:Vt.target.value}))})}),e.jsx(ut,{className:"text-right",children:e.jsx(B,{size:"sm",variant:"outline",disabled:He[ft.id]===void 0||He[ft.id]===ft.points.toString()||at.isPending,onClick:()=>Pt(ft.id,ft.points),children:e.jsx(qo,{className:"h-4 w-4"})})})]},ft.id))})]})})]})]})}const jXe=()=>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"})]}),NXe=[{value:"template",label:"Templates"},{value:"brand",label:"Brand Assets"},{value:"listing",label:"Listing Assets"},{value:"social",label:"Social Media"},{value:"general",label:"General"}];function ftn(){const s=Ht(),[t,n]=N.useState(!1),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""}),{data:d,isLoading:u}=ct({queryKey:["canva-integration"],queryFn:async()=>{const{data:b,error:S}=await q.from("canva_integration").select("*").eq("is_active",!0).maybeSingle();if(S)throw S;return b}}),{data:h}=ct({queryKey:["brokerages-list"],queryFn:async()=>{const{data:b,error:S}=await q.from("brokerages").select("id, name").order("name");if(S)throw S;return b}}),{data:p}=ct({queryKey:["canva-brokerage-folders"],queryFn:async()=>{const{data:b,error:S}=await q.from("canva_brokerage_folders").select("*, brokerages(name)").order("sort_order");if(S)throw S;return b}}),f=async()=>{var b;n(!0);try{const{data:S}=await q.auth.getSession(),A=(b=S==null?void 0:S.session)==null?void 0:b.access_token;if(!A)throw new Error("Not authenticated");const D=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"get_auth_url"})}),M=await D.json();if(!D.ok||M!=null&&M.error)throw new Error((M==null?void 0:M.error)||"Failed to get authorization URL");if(M!=null&&M.authUrl){localStorage.setItem("canva_code_verifier",M.codeVerifier),localStorage.setItem("canva_oauth_state",M.state);const F=window.open(M.authUrl,"canva-oauth","width=600,height=700,scrollbars=yes,resizable=yes");if(!F){ae.error("Popup was blocked. Please allow popups for this site and try again."),n(!1);return}const z=W=>{var Y,K;W.origin===window.location.origin&&(((Y=W.data)==null?void 0:Y.type)==="canva-oauth-success"?(window.removeEventListener("message",z),ae.success("Canva connected successfully!"),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1)):((K=W.data)==null?void 0:K.type)==="canva-oauth-error"&&(window.removeEventListener("message",z),ae.error("Canva connection failed: "+(W.data.error||"Unknown error")),n(!1)))};window.addEventListener("message",z);const V=setInterval(()=>{F.closed&&(clearInterval(V),window.removeEventListener("message",z),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1))},500)}else throw new Error("Failed to get authorization URL")}catch(S){console.error("Canva connect error:",S);const A=(S==null?void 0:S.message)||"";A.includes("CANVA_CLIENT_ID")?ae.error("Canva app credentials not configured yet."):ae.error(A||"Failed to start Canva connection"),n(!1)}},g=gt({mutationFn:async b=>{var F;const{data:S}=await q.auth.getSession(),A=(F=S==null?void 0:S.session)==null?void 0:F.access_token;if(!A)throw new Error("Not authenticated");const D=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"disconnect",integrationId:b})}),M=await D.json();if(!D.ok||M!=null&&M.error)throw new Error((M==null?void 0:M.error)||"Failed to disconnect")},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-integration"]}),ae.success("Canva disconnected")},onError:b=>{ae.error(b.message||"Failed to disconnect Canva")}}),_=gt({mutationFn:async b=>{const{error:S}=await q.from("canva_brokerage_folders").insert({brokerage_id:b.brokerage_id,folder_id:b.folder_id.trim(),folder_name:b.folder_name.trim(),folder_type:b.folder_type,description:b.description.trim()||null,sort_order:(p==null?void 0:p.length)||0});if(S)throw S},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ae.success("Folder added"),l(!1),c({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""})},onError:()=>ae.error("Failed to add folder")}),v=gt({mutationFn:async b=>{const{error:S}=await q.from("canva_brokerage_folders").delete().eq("id",b);if(S)throw S},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ae.success("Folder removed")},onError:()=>ae.error("Failed to remove folder")}),j=!!d;return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(Mt,{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(jXe,{})}),e.jsxs("div",{children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:["Canva Connect",j&&e.jsx(ze,{variant:"default",className:"text-xs",children:"Connected"}),e.jsx(ze,{variant:"outline",className:"text-xs",children:"Admin Only"})]}),e.jsx(Vn,{children:"Auto-share brokerage asset folders with agents when they connect their Canva accounts."})]})]})})}),e.jsx(Ee,{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(Ri,{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(Ri,{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(Ri,{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"})]}),j?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(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Canva?"}),e.jsx(Mo,{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(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>g.mutate(d.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}),e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>a(!r),className:"w-full flex items-center justify-between p-3 text-sm font-medium hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gf,{className:"h-4 w-4 text-primary"}),"Brokerage Folder Mappings",p&&p.length>0&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:p.length})]}),r?e.jsx(tx,{className:"h-4 w-4"}):e.jsx(io,{className:"h-4 w-4"})]}),r&&e.jsxs("div",{className:"border-t p-3 space-y-2",children:[p&&p.length>0?p.map(b=>{var S,A;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md bg-muted/50 text-sm",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium truncate",children:b.folder_name}),e.jsx(ze,{variant:"outline",className:"text-xs shrink-0",children:((S=NXe.find(T=>T.value===b.folder_type))==null?void 0:S.label)||b.folder_type})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(A=b.brokerages)==null?void 0:A.name," · ID: ",e.jsx("span",{className:"font-mono",children:b.folder_id})]})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive shrink-0 ml-2",onClick:()=>v.mutate(b.id),children:e.jsx(Bn,{className:"h-3.5 w-3.5"})})]},b.id)}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-2",children:"No folders mapped yet"}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-1.5 mt-1",onClick:()=>l(!0),children:[e.jsx(Is,{className:"h-3.5 w-3.5"}),"Add Folder Mapping"]})]})]})]}):e.jsxs(B,{className:"mt-4",onClick:f,disabled:t||u,children:[t?e.jsx(Ti,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx("div",{className:"mr-2",children:e.jsx(jXe,{})}),"Connect Canva",e.jsx(Oa,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Add Brokerage Folder Mapping"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Brokerage"}),e.jsxs(ds,{value:o.brokerage_id,onValueChange:b=>c(S=>({...S,brokerage_id:b})),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select a brokerage…"})}),e.jsx(cs,{children:h==null?void 0:h.map(b=>e.jsx(Qe,{value:b.id,children:b.name},b.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:b=>c(S=>({...S,folder_id:b.target.value}))}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Found in the Canva folder URL: canva.com/folder/",e.jsx("strong",{children:"FOLDER_ID"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Folder Display Name"}),e.jsx(ye,{placeholder:"e.g. Brand Templates 2024",value:o.folder_name,onChange:b=>c(S=>({...S,folder_name:b.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Folder Type"}),e.jsxs(ds,{value:o.folder_type,onValueChange:b=>c(S=>({...S,folder_type:b})),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:NXe.map(b=>e.jsx(Qe,{value:b.value,children:b.label},b.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:b=>c(S=>({...S,description:b.target.value}))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>_.mutate(o),disabled:!o.brokerage_id||!o.folder_id||!o.folder_name||_.isPending,children:[_.isPending?e.jsx(Ti,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Add Folder"]})]})]})})]})}function xtn(){const s=Mn();return e.jsx(Ts,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Ud,{title:"Integrations",description:"Manage platform-level service connections"}),e.jsxs(fe,{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(Hl,{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(Oa,{className:"h-4 w-4 ml-1"})]})]}),e.jsx(ftn,{}),e.jsx(G2t,{})]})})}const kXe=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(Lh,{className:t}):s==="instagram"?e.jsx(du,{className:t}):s==="linkedin"?e.jsx(vf,{className:t}):s==="google"?e.jsx(Vs,{className:t}):null},gtn=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function ytn(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(""),[l,o]=N.useState("all");N.useEffect(()=>{(async()=>{r(!0);const{data:p,error:f}=await q.rpc("admin_get_social_connections");if(f){ae.error(f.message),r(!1);return}t(p||[]),r(!1)})()},[]);const c=N.useMemo(()=>{const p=a.trim().toLowerCase();return s.filter(f=>l!=="all"&&f.platform!==l?!1:p?(f.user_name||"").toLowerCase().includes(p)||(f.user_email||"").toLowerCase().includes(p)||(f.page_name||"").toLowerCase().includes(p)||(f.platform_username||"").toLowerCase().includes(p):!0)},[s,a,l]),d=N.useMemo(()=>{const p=new Map;return s.forEach(f=>{const g=p.get(f.user_id)||{name:f.user_name,email:f.user_email,platforms:new Set,count:0};g.platforms.add(f.platform),g.count+=1,p.set(f.user_id,g)}),Array.from(p.entries()).map(([f,g])=>({user_id:f,...g}))},[s]),u=N.useMemo(()=>{const p=new Map;return s.forEach(f=>p.set(f.platform,(p.get(f.platform)||0)+1)),{uniqueUsers:d.length,totalConnections:s.length,byPlatform:Array.from(p.entries())}},[s,d]),h=p=>p&&new Date(p).getTime()e.jsxs(fe,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[kXe(p)," ",p]}),e.jsx("div",{className:"text-2xl font-bold",children:f})]},p))]}),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:p=>i(p.target.value),className:"md:max-w-md"}),e.jsxs(ds,{value:l,onValueChange:o,children:[e.jsx(ls,{className:"md:w-48",children:e.jsx(us,{placeholder:"All platforms"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All platforms"}),e.jsx(Qe,{value:"facebook",children:"Facebook"}),e.jsx(Qe,{value:"instagram",children:"Instagram"}),e.jsx(Qe,{value:"linkedin",children:"LinkedIn"}),e.jsx(Qe,{value:"google",children:"Google"})]})]})]}),e.jsx(fe,{children:n?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(ts,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"User"}),e.jsx(Ct,{children:"Platform"}),e.jsx(Ct,{children:"Page / Account"}),e.jsx(Ct,{children:"Status"}),e.jsx(Ct,{children:"Connected"})]})}),e.jsx(ha,{children:c.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No connections found."})}):c.map(p=>{const f=h(p.token_expires_at);return e.jsxs(Hs,{children:[e.jsxs(ut,{children:[e.jsx("div",{className:"font-medium",children:p.user_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:p.user_email})]}),e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-2 capitalize",children:[kXe(p.platform)," ",p.platform]})}),e.jsxs(ut,{children:[e.jsx("div",{className:"font-medium",children:p.page_name||p.platform_username||"—"}),p.instagram_business_id&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["IG Business: ",p.instagram_business_id]})]}),e.jsx(ut,{children:p.is_active?f?e.jsxs(ze,{variant:"destructive",className:"gap-1",children:[e.jsx(Gi,{className:"h-3 w-3"})," Expired"]}):e.jsx(ze,{children:"Active"}):e.jsx(ze,{variant:"secondary",children:"Inactive"})}),e.jsx(ut,{className:"text-sm text-muted-foreground",children:gtn(p.created_at)})]},p.id)})})]})})]})})}const vtn={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 zF(s,t=18,n=10){return s.length<=t+n+3?s:`${s.slice(0,t)}…${s.slice(-n)}`}function btn(){var V,W,Y,K,J;const s=Ht(),[t,n]=N.useState("Test Push"),[r,a]=N.useState("Testing web push notification"),[i,l]=N.useState("/community"),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState({isSupported:typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window}),[f,g]=N.useState(null),[_,v]=N.useState(null),{data:j,isLoading:b}=ct({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:ne,error:ie}=await q.from("push_notification_settings").select("*").order("setting_key");if(ie)throw ie;return ne}}),{data:S,isLoading:A}=ct({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:ne,error:ie}=await q.from("push_subscriptions").select("*",{count:"exact",head:!0});if(ie)throw ie;return{totalSubscriptions:ne||0}}}),T=gt({mutationFn:async({settingKey:ne,isEnabled:ie})=>{const{error:he}=await q.from("push_notification_settings").update({is_enabled:ie}).eq("setting_key",ne);if(he)throw he},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),ae.success("Notification setting updated")},onError:ne=>{ae.error("Failed to update setting: "+ne.message)}}),L=N.useMemo(()=>{var ne,ie;return h.isSupported?`perm=${h.permission??"unknown"} · controller=${h.controllerPresent?"yes":"no"} · sw=${((ne=h.serviceWorker)==null?void 0:ne.activeState)??"unknown"} · sub=${(ie=h.subscription)!=null&&ie.endpoint?"yes":"no"}`:"Push not supported in this browser."},[h]);N.useEffect(()=>{let ne=!0;const ie=async()=>{var le,ve,ge,Te,Me,Ce,Ae;const ce="serviceWorker"in navigator&&"PushManager"in window,pe={isSupported:ce,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((le=navigator.serviceWorker)!=null&&le.controller)};if(!ce){ne&&p(pe);return}try{const{data:De,error:Ie}=await q.functions.invoke("get-vapid-public-key",{body:{}});if(Ie)throw Ie;pe.vapidPublicKey=De==null?void 0:De.vapidPublicKey;const qe=(await navigator.serviceWorker.getRegistrations()).find(be=>{var Ne,it,je;return(((Ne=be.active)==null?void 0:Ne.scriptURL)||((it=be.waiting)==null?void 0:it.scriptURL)||((je=be.installing)==null?void 0:je.scriptURL)||"").includes("/sw.js")});if(qe){pe.pushWorkerScriptUrl=((ve=qe.active)==null?void 0:ve.scriptURL)||((ge=qe.waiting)==null?void 0:ge.scriptURL)||((Te=qe.installing)==null?void 0:Te.scriptURL),pe.serviceWorker={scope:qe.scope,activeState:(Me=qe.active)==null?void 0:Me.state};const be=await qe.pushManager.getSubscription();if(be){const Ze=be.toJSON();pe.subscription={endpoint:Ze.endpoint,p256dh:(Ce=Ze.keys)==null?void 0:Ce.p256dh,auth:(Ae=Ze.keys)==null?void 0:Ae.auth}}}}catch(De){pe.error=(De==null?void 0:De.message)||String(De)}ne&&p(pe)};ie();const he=window.setInterval(ie,4e3);return()=>{ne=!1,window.clearInterval(he)}},[]);const D=async()=>{if(typeof Notification>"u"){ae.error("Notifications API not available in this browser.");return}try{if(Notification.permission!=="granted"&&await Notification.requestPermission()!=="granted"){ae.error("Notification permission not granted.");return}new Notification("Local notification test",{body:"If you see this, OS/browser notifications can display."}),ae.success("Triggered a local notification (not push).")}catch(ne){ae.error(`Local notification failed: ${(ne==null?void 0:ne.message)||String(ne)}`)}},M=async()=>{c(!0),g(null);try{const{data:ne,error:ie}=await q.functions.invoke("send-push-notification",{body:{title:t,body:r,url:i}});if(ie)throw ie;g({sent:ne==null?void 0:ne.sent,failed:ne==null?void 0:ne.failed,expiredCleaned:ne==null?void 0:ne.expiredCleaned,vapidPublicKey:ne==null?void 0:ne.vapidPublicKey}),(ne==null?void 0:ne.sent)>0?ae.success(`Test notification sent to ${ne.sent} subscriber(s)`):(ne==null?void 0:ne.failed)>0?ae.warning(`Notification failed for ${ne.failed} subscriber(s). ${ne.expired||0} expired subscriptions cleaned up.`):ae.info("No active subscriptions to send to")}catch(ne){console.error("Error sending test notification:",ne),g({error:(ne==null?void 0:ne.message)||String(ne)}),ae.error("Failed to send test notification: "+(ne.message||"Unknown error"))}finally{c(!1)}},F=async()=>{u(!0),v(null);try{const{data:ne,error:ie}=await q.functions.invoke("generate-vapid-keys",{body:{}});if(ie)throw ie;const he=ne==null?void 0:ne.publicKey,ce=ne==null?void 0:ne.privateKey;if(!he||!ce)throw new Error("generate-vapid-keys did not return keys");v({publicKey:he,privateKey:ce}),ae.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(ne){console.error("Error generating VAPID keys:",ne),ae.error("Failed to generate VAPID keys: "+((ne==null?void 0:ne.message)||"Unknown error"))}finally{u(!1)}},z=gt({mutationFn:async()=>{const{error:ne}=await q.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(ne)throw ne},onSuccess:()=>{ae.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:ne=>{ae.error("Failed to clear subscriptions: "+ne.message)}});return e.jsx(Ts,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{title:"Notification Settings",description:"Manage push notifications and test the notification system"}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5"}),"Push Notification Subscribers"]}),e.jsx(Vn,{children:"Current active push notification subscriptions"})]}),e.jsx(Ee,{children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"text-4xl font-bold",children:A?"...":(S==null?void 0:S.totalSubscriptions)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"active subscriptions"})]})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Xo,{className:"h-5 w-5"}),"Notification Types"]}),e.jsx(Vn,{children:"Control which types of push notifications are sent to users"})]}),e.jsx(Ee,{children:b?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading settings..."}):e.jsx("div",{className:"space-y-4",children:j==null?void 0:j.map(ne=>{const ie=vtn[ne.setting_key]||{label:ne.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:ie.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ie.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:ne.description})]})]}),e.jsx(bn,{checked:ne.is_enabled,onCheckedChange:he=>T.mutate({settingKey:ne.setting_key,isEnabled:he}),disabled:T.isPending})]},ne.id)})})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(im,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(Vn,{children:"Send a test push notification to all subscribed users"})]}),e.jsxs(Ee,{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:L}),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?zF(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: ",(V=h.serviceWorker)!=null&&V.scope?zF(h.serviceWorker.scope,24,8):"none"]}),e.jsxs("div",{children:["active: ",((W=h.serviceWorker)==null?void 0:W.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: ",(Y=h.subscription)!=null&&Y.endpoint?zF(h.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",(K=h.subscription)!=null&&K.p256dh?zF(h.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(J=h.subscription)!=null&&J.auth?zF(h.subscription.auth,22,10):"none"]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(B,{variant:"outline",onClick:D,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:ne=>n(ne.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(Es,{id:"test-body",value:r,onChange:ne=>a(ne.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:ne=>l(ne.target.value),placeholder:"/community or full URL"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Where users will be taken when they click the notification"})]}),e.jsxs(B,{onClick:M,disabled:o||!t||!r,className:"w-full sm:w-auto",children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),o?"Sending...":"Send Test Notification"]}),f&&e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Last send debug"}),f.error?e.jsxs("div",{className:"mt-1 text-destructive",children:["Error: ",f.error]}):e.jsxs("div",{className:"mt-1 space-y-1 text-muted-foreground",children:[e.jsxs("div",{children:["Result: ",f.sent??0," sent, ",f.failed??0," failed, ",f.expiredCleaned??0," expired cleaned"]}),f.vapidPublicKey?e.jsxs("div",{className:"break-all",children:["Backend VAPID public key: ",e.jsx("span",{className:"font-mono",children:f.vapidPublicKey})]}):e.jsx("div",{children:"Backend VAPID public key: (not returned)"})]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(_n,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(Vn,{children:"Clear all push subscriptions if VAPID keys were changed or subscriptions are invalid"})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"If you've recently updated the VAPID keys, existing subscriptions will no longer work. Use this to clear all subscriptions so users can re-subscribe with the new keys."}),e.jsxs(B,{variant:"destructive",onClick:()=>z.mutate(),disabled:z.isPending,children:[e.jsx(_n,{className:"h-4 w-4 mr-2"}),z.isPending?"Clearing...":"Clear All Subscriptions"]}),e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"VAPID key rotation helper"}),e.jsx("div",{className:"mt-1 text-muted-foreground",children:"If you suspect the backend public/private keys don’t match, generate a fresh pair, update backend secrets, then clear subscriptions and have users re-enable push."}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:e.jsx(B,{variant:"outline",onClick:F,disabled:d,children:d?"Generating…":"Generate VAPID keys"})}),_&&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:_.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:_.privateKey})]})]})]})]})]})]})})}function _tn(){const{toast:s}=Ba(),[t,n]=N.useState([]),[r,a]=N.useState({totalPresentations:0,totalViews:0,totalLeads:0,totalCtaClicks:0,agentsUsing:0}),[i,l]=N.useState(!0),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=kU("presentation_count","desc"),h=u(t,{name:g=>{var _;return((_=g.name)==null?void 0:_.toLowerCase())||""},presentations:g=>g.presentation_count,views:g=>g.total_views,leads:g=>g.total_leads,cta_clicks:g=>g.total_cta_clicks,conversion:g=>g.total_views>0?g.total_leads/g.total_views*100:0});N.useEffect(()=>{p()},[]);const p=async()=>{try{l(!0);const{data:g,error:_}=await q.rpc("get_admin_presentation_stats");if(_)throw _;if(!g||g.length===0){l(!1);return}const v=g.map(T=>T.owner_user_id),{data:j,error:b}=await q.from("profiles").select("id, name, email, avatar_url").in("id",v);if(b)throw b;const S=new Map((j==null?void 0:j.map(T=>[T.id,T]))||[]),A=g.map(T=>{const L=S.get(T.owner_user_id);return{owner_user_id:T.owner_user_id,name:(L==null?void 0:L.name)||"Unknown",email:(L==null?void 0:L.email)||"",avatar_url:(L==null?void 0:L.avatar_url)||null,presentation_count:Number(T.presentation_count),total_views:Number(T.total_views),total_leads:Number(T.total_leads),total_cta_clicks:Number(T.total_cta_clicks)}});n(A),n(A),a({totalPresentations:A.reduce((T,L)=>T+L.presentation_count,0),totalViews:A.reduce((T,L)=>T+L.total_views,0),totalLeads:A.reduce((T,L)=>T+L.total_leads,0),totalCtaClicks:A.reduce((T,L)=>T+L.total_cta_clicks,0),agentsUsing:A.length})}catch(g){console.error("Error loading presentation stats:",g),s({title:"Error",description:"Failed to load presentation analytics",variant:"destructive"})}finally{l(!1)}},f=[{label:"Agents Using",value:r.agentsUsing,icon:Nn,color:"text-blue-600"},{label:"Total Presentations",value:r.totalPresentations,icon:iy,color:"text-violet-600"},{label:"Total Views",value:r.totalViews,icon:Er,color:"text-emerald-600"},{label:"Total Leads",value:r.totalLeads,icon:Fo,color:"text-amber-600"},{label:"CTA Clicks",value:r.totalCtaClicks,icon:oc,color:"text-rose-600"}];return e.jsx(Ts,{title:"Presentation Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Presentation Analytics"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Track Smart Presentations usage and engagement across all agents"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4",children:f.map(g=>e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:g.label}),e.jsx(g.icon,{className:`h-4 w-4 ${g.color}`})]}),e.jsx(Ee,{children:i?e.jsx(Ws,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:g.value.toLocaleString()})})]},g.label))}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(mo,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Ee,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((g,_)=>e.jsx(Ws,{className:"h-12 w-full"},_))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No presentations created yet."}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ic,{sortKey:"name",currentSortKey:o,currentDirection:c,onSort:d,children:"Agent"}),e.jsx(Ic,{sortKey:"presentations",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Presentations"}),e.jsx(Ic,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Views"}),e.jsx(Ic,{sortKey:"leads",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Leads"}),e.jsx(Ic,{sortKey:"cta_clicks",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"CTA Clicks"}),e.jsx(Ic,{sortKey:"conversion",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Conversion"})]})}),e.jsx(ha,{children:h.map(g=>{var v,j;const _=g.total_views>0?(g.total_leads/g.total_views*100).toFixed(1):"0.0";return e.jsxs(Hs,{children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden",children:g.avatar_url?e.jsx("img",{src:g.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((j=(v=g.name)==null?void 0:v.charAt(0))==null?void 0:j.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:g.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:g.email})]})]})}),e.jsx(ut,{className:"text-center font-medium",children:g.presentation_count}),e.jsx(ut,{className:"text-center",children:g.total_views.toLocaleString()}),e.jsx(ut,{className:"text-center",children:g.total_leads>0?e.jsx(ze,{variant:"secondary",children:g.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ut,{className:"text-center",children:g.total_cta_clicks}),e.jsx(ut,{className:"text-center",children:e.jsxs("span",{className:Number(_)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[_,"%"]})})]},g.owner_user_id)})})]})})]})]})})}function wtn(){const{toast:s}=Ba(),[t,n]=N.useState([]),[r,a]=N.useState({totalOpenHouses:0,totalVisitors:0,totalLeads:0,activeOpenHouses:0,agentsUsing:0}),[i,l]=N.useState(!0);N.useEffect(()=>{o()},[]);const o=async()=>{try{l(!0);const{data:d,error:u}=await q.rpc("get_admin_guest_book_stats");if(u)throw u;if(!d||d.length===0){l(!1);return}const h=d.map(v=>v.agent_id),{data:p,error:f}=await q.from("profiles").select("id, name, email, avatar_url").in("id",h);if(f)throw f;const g=new Map((p==null?void 0:p.map(v=>[v.id,v]))||[]),_=d.map(v=>{const j=g.get(v.agent_id);return{agent_id:v.agent_id,name:(j==null?void 0:j.name)||"Unknown",email:(j==null?void 0:j.email)||"",avatar_url:(j==null?void 0:j.avatar_url)||null,open_house_count:Number(v.open_house_count),total_visitors:Number(v.total_visitors),total_leads:Number(v.total_leads),active_count:Number(v.active_count)}});_.sort((v,j)=>j.total_visitors-v.total_visitors),n(_),a({totalOpenHouses:_.reduce((v,j)=>v+j.open_house_count,0),totalVisitors:_.reduce((v,j)=>v+j.total_visitors,0),totalLeads:_.reduce((v,j)=>v+j.total_leads,0),activeOpenHouses:_.reduce((v,j)=>v+j.active_count,0),agentsUsing:_.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:Nn,color:"text-blue-600"},{label:"Total Open Houses",value:r.totalOpenHouses,icon:Or,color:"text-violet-600"},{label:"Active Now",value:r.activeOpenHouses,icon:Ri,color:"text-emerald-600"},{label:"Total Visitors",value:r.totalVisitors,icon:Er,color:"text-amber-600"},{label:"Leads Created",value:r.totalLeads,icon:Fo,color:"text-rose-600"}];return e.jsx(Ts,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:d.label}),e.jsx(d.icon,{className:`h-4 w-4 ${d.color}`})]}),e.jsx(Ee,{children:i?e.jsx(Ws,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:d.value.toLocaleString()})})]},d.label))}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(mo,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Ee,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((d,u)=>e.jsx(Ws,{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(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Agent"}),e.jsx(Ct,{className:"text-center",children:"Open Houses"}),e.jsx(Ct,{className:"text-center",children:"Active"}),e.jsx(Ct,{className:"text-center",children:"Visitors"}),e.jsx(Ct,{className:"text-center",children:"Leads"}),e.jsx(Ct,{className:"text-center",children:"Conversion"})]})}),e.jsx(ha,{children:t.map(d=>{var h,p;const u=d.total_visitors>0?(d.total_leads/d.total_visitors*100).toFixed(1):"0.0";return e.jsxs(Hs,{children:[e.jsx(ut,{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:((p=(h=d.name)==null?void 0:h.charAt(0))==null?void 0:p.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(ut,{className:"text-center font-medium",children:d.open_house_count}),e.jsx(ut,{className:"text-center",children:d.active_count>0?e.jsx(ze,{variant:"secondary",className:"bg-emerald-100 text-emerald-700",children:d.active_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ut,{className:"text-center",children:d.total_visitors.toLocaleString()}),e.jsx(ut,{className:"text-center",children:d.total_leads>0?e.jsx(ze,{variant:"secondary",children:d.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ut,{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 jtn(){const[s]=gl(),t=Mn(),[n,r]=N.useState("loading"),[a,i]=N.useState("Processing connection...");return N.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Failed to connect: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("Failed to connect: No authorization code");return}try{const{data:h,error:p}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:u}});if(h&&h.success===!1)throw new Error(h.error||"Failed to connect accounts");if(p){let f=p.message||"Failed to connect accounts";try{const g=p.context;if(g&&typeof g.json=="function"){const _=await g.json();_!=null&&_.error&&(f=_.error)}}catch{}throw new Error(f)}if(h!=null&&h.success)r("success"),i(h.message||"Accounts connected successfully!"),ae.success(h.message||"Social accounts connected!");else throw new Error((h==null?void 0:h.error)||"Failed to connect accounts")}catch(h){console.error("Callback error:",h),r("error"),i(h.message||"Failed to complete connection"),ae.error(h.message||"Failed to connect accounts")}})()},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4",children:[n==="loading"&&e.jsx(ts,{className:"h-12 w-12 animate-spin text-primary"}),n==="success"&&e.jsx(Ri,{className:"h-12 w-12 text-green-500"}),n==="error"&&e.jsx(Hc,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(It,{children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:a})]}),e.jsx(Ee,{className:"flex justify-center",children:e.jsx(B,{onClick:()=>t("/admin/integrations"),children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function Ntn(){const s=Ht(),[t,n]=N.useState(""),[r,a]=N.useState(""),[i,l]=N.useState([]),o=N.useRef(null),{data:c,isLoading:d}=ct({queryKey:["prospect-emails"],queryFn:async()=>{const{data:b,error:S}=await q.from("prospect_emails").select("*").order("sent_at",{ascending:!1});if(S)throw S;return b}}),u=(c==null?void 0:c.filter(b=>b.status==="live_lead"))||[],h={total:(c==null?void 0:c.length)||0,sent:(c==null?void 0:c.filter(b=>b.status==="sent").length)||0,converted:(c==null?void 0:c.filter(b=>b.status==="converted").length)||0,liveLeads:u.length,conversionRate:c!=null&&c.length?Math.round(c.filter(b=>b.status==="converted").length/c.length*100):0},p=gt({mutationFn:async b=>{const{data:S,error:A}=await q.functions.invoke("send-prospect-email",{body:{emails:b}});if(A)throw A;return S},onSuccess:b=>{s.invalidateQueries({queryKey:["prospect-emails"]}),ae.success(`${b.sent} email${b.sent>1?"s":""} sent successfully!`),n(""),a(""),l([])},onError:b=>{ae.error("Failed to send: "+b.message)}}),f=gt({mutationFn:async()=>{var T,L;const{data:{user:b}}=await q.auth.getUser();if(!(b!=null&&b.email))throw new Error("Could not get your email");const{data:S,error:A}=await q.functions.invoke("send-prospect-email",{body:{emails:[{email:b.email,first_name:(L=(T=b.user_metadata)==null?void 0:T.name)==null?void 0:L.split(" ")[0]}],test_mode:!0}});if(A)throw A;return S},onSuccess:()=>{ae.success("Test email sent to your inbox!")},onError:b=>{ae.error("Failed to send test: "+b.message)}}),g=gt({mutationFn:async()=>{const{data:b,error:S}=await q.functions.invoke("send-prospect-email",{body:{mode:"live_leads"}});if(S)throw S;return b},onSuccess:b=>{s.invalidateQueries({queryKey:["prospect-emails"]}),ae.success(`${b.sent} live lead invite${b.sent===1?"":"s"} sent!`)},onError:b=>{ae.error("Failed to send live lead invites: "+b.message)}}),_=()=>{if(!t.trim()){ae.error("Please enter an email address");return}if(c==null?void 0:c.find(S=>S.email.toLowerCase()===t.trim().toLowerCase())){ae.error("This email has already been prospected");return}p.mutate([{email:t.trim(),first_name:r.trim()||void 0}])},v=b=>{var T;const S=(T=b.target.files)==null?void 0:T[0];if(!S)return;const A=new FileReader;A.onload=L=>{var V,W;const M=((V=L.target)==null?void 0:V.result).split(` `).filter(Y=>Y.trim()),F=[],z=(W=M[0])!=null&&W.toLowerCase().includes("email")?1:0;for(let Y=z;Yie.trim().replace(/"/g,"")),J=K[0],ne=K[1];J&&J.includes("@")&&F.push({email:J,first_name:ne||void 0})}l(F),ae.success(`${F.length} entries loaded from CSV`)},A.readAsText(S),o.current&&(o.current.value="")},j=()=>{if(i.length===0){ae.error("No entries to send");return}const b=new Set((c==null?void 0:c.map(A=>A.email.toLowerCase()))||[]),S=i.filter(A=>!b.has(A.email.toLowerCase()));if(S.length===0){ae.error("All emails have already been prospected");return}S.length0&&e.jsxs(fe,{className:"border-red-200/50 bg-red-500/[0.02]",children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(_f,{className:"h-5 w-5 text-red-600"}),"Live Event Leads",e.jsx(ze,{variant:"secondary",className:"ml-2",children:h.liveLeads})]}),e.jsx(Vn,{children:"These agents registered on a LevelUp Live page but haven't received a free trial invite yet."})]}),e.jsx(Ee,{children:e.jsxs(B,{onClick:()=>g.mutate(),disabled:g.isPending,className:"gap-2",children:[g.isPending?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"}),"Send free trial invite to all live leads"]})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Oc,{className:"h-5 w-5"}),"Send Prospect Email"]}),e.jsxs(Vn,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Send a beautiful free trial invitation email to potential members"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>f.mutate(),disabled:f.isPending,className:"gap-2 ml-4 shrink-0",children:[f.isPending?e.jsx(ts,{className:"h-3 w-3 animate-spin"}):e.jsx(Vs,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(Ee,{children:e.jsxs(Br,{defaultValue:"single",children:[e.jsxs(Fr,{className:"mb-4",children:[e.jsxs(Kt,{value:"single",children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(Kt,{value:"bulk",children:[e.jsx(Na,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(is,{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:b=>n(b.target.value),onKeyDown:b=>b.key==="Enter"&&_()})]}),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:b=>a(b.target.value),onKeyDown:b=>b.key==="Enter"&&_()})]}),e.jsxs(B,{onClick:_,disabled:p.isPending,className:"gap-2",children:[p.isPending?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(is,{value:"bulk",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{ref:o,type:"file",accept:".csv",onChange:v,className:"hidden"}),e.jsxs(B,{variant:"outline",onClick:()=>{var b;return(b=o.current)==null?void 0:b.click()},className:"gap-2",children:[e.jsx(Nr,{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(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"}),i.length," entries ready"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>l([]),children:[e.jsx(Bn,{className:"h-4 w-4"}),"Clear"]})]}),e.jsxs("div",{className:"max-h-40 overflow-y-auto border rounded-lg p-3 bg-muted/30 text-sm font-mono space-y-1",children:[i.slice(0,20).map((b,S)=>e.jsxs("div",{className:"text-muted-foreground",children:[b.email,b.first_name?` — ${b.first_name}`:""]},S)),i.length>20&&e.jsxs("div",{className:"text-muted-foreground/60",children:["...and ",i.length-20," more"]})]}),e.jsxs(B,{onClick:j,disabled:p.isPending,className:"gap-2",children:[p.isPending?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"}),"Send ",i.length," Invites"]})]})]})})]})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(Vn,{children:"Track all sent invitations and their conversion status"})]}),e.jsx(Ee,{children:d?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((b,S)=>e.jsx(Ws,{className:"h-12 w-full"},S))}):c&&c.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Email"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Name"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Sent"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Converted"})]})}),e.jsx("tbody",{children:c.map(b=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-3 px-4 text-sm font-medium text-foreground",children:b.email}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.first_name||"—"}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:Ss(new Date(b.sent_at),"MMM d, yyyy")}),e.jsx("td",{className:"py-3 px-4",children:b.status==="converted"?e.jsxs(ze,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-0",children:[e.jsx(xr,{className:"h-3 w-3 mr-1"}),"Converted"]}):b.status==="live_lead"?e.jsxs(ze,{className:"bg-red-500/10 text-red-700 hover:bg-red-500/20 border-0 gap-1",children:[e.jsx(_f,{className:"h-3 w-3"}),"Live lead"]}):e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),"Sent"]})}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.converted_at?Ss(new Date(b.converted_at),"MMM d, yyyy"):"—"})]},b.id))})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Oc,{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 ZU(s){const t=Ht(),{toast:n}=Ba(),r=ct({queryKey:["recruit-stages",s],queryFn:async()=>{if(!s)return[];const{data:c,error:d}=await q.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(d)throw d;return c},enabled:!!s}),a=ct({queryKey:["recruit-prospects",s],queryFn:async()=>{if(!s)return[];const c=1e3;let d=[],u=0,h=!0;for(;h;){const{data:p,error:f}=await q.from("recruit_prospects").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(u,u+c-1);if(f)throw f;d=d.concat(p),h=p.length===c,u+=c}return d},enabled:!!s}),i=gt({mutationFn:async c=>{const{data:{user:d}}=await q.auth.getUser();if(!d)throw new Error("Not authenticated");const u={first_name:c.first_name||"",last_name:c.last_name||null,email:c.email||null,phone:c.phone||null,current_brokerage:c.current_brokerage||null,license_number:c.license_number||null,experience_years:c.experience_years??null,annual_production:c.annual_production||null,source:c.source||"manual",notes:c.notes||null,stage_id:c.stage_id||null,brokerage_id:s,created_by:d.id,address:c.address||null,city:c.city||null,state:c.state||null,zip_code:c.zip_code||null,last_year_volume:c.last_year_volume||null,last_year_transactions:c.last_year_transactions??null,avg_sale_price:c.avg_sale_price||null,specialties:c.specialties||null,linkedin_url:c.linkedin_url||null,website_url:c.website_url||null,instagram_handle:c.instagram_handle||null,facebook_url:c.facebook_url||null,birthday:c.birthday||null,spouse_name:c.spouse_name||null,interests:c.interests||null,referred_by:c.referred_by||null},{data:h,error:p}=await q.from("recruit_prospects").insert(u).select().single();if(p)throw p;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),n({title:"Prospect added"})},onError:c=>n({title:"Error",description:c.message,variant:"destructive"})}),l=gt({mutationFn:async({id:c,...d})=>{const{data:u,error:h}=await q.from("recruit_prospects").update({...d,updated_at:new Date().toISOString()}).eq("id",c).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]})},onError:c=>n({title:"Error",description:c.message,variant:"destructive"})}),o=gt({mutationFn:async c=>{const{error:d}=await q.from("recruit_prospects").delete().eq("id",c);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),n({title:"Prospect removed"})}});return{stages:r.data||[],prospects:a.data||[],isLoading:r.isLoading||a.isLoading,addProspect:i,updateProspect:l,deleteProspect:o}}function ktn(s){const t=Ht(),{toast:n}=Ba(),r=ct({queryKey:["recruit-activities",s],queryFn:async()=>{if(!s)return[];const{data:i,error:l}=await q.from("recruit_activities").select("*").eq("prospect_id",s).order("created_at",{ascending:!1});if(l)throw l;return i},enabled:!!s}),a=gt({mutationFn:async i=>{const{data:{user:l}}=await q.auth.getUser();if(!l)throw new Error("Not authenticated");const{data:o,error:c}=await q.from("recruit_activities").insert({...i,created_by:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-activities",s]}),n({title:"Activity logged"})},onError:i=>n({title:"Error",description:i.message,variant:"destructive"})});return{activities:r.data||[],isLoading:r.isLoading,addActivity:a}}const SXe=(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 J2t({open:s,onOpenChange:t,stages:n,defaultStageId:r,onSubmit:a,isSubmitting:i}){const[l,o]=N.useState(SXe(r,n)),c=u=>h=>o(p=>({...p,[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(SXe(r,n)),t(!1)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs(Br,{defaultValue:"basic",className:"w-full",children:[e.jsxs(Fr,{className:"grid w-full grid-cols-4",children:[e.jsx(Kt,{value:"basic",children:"Basic Info"}),e.jsx(Kt,{value:"production",children:"Production"}),e.jsx(Kt,{value:"social",children:"Social & Web"}),e.jsx(Kt,{value:"personal",children:"Personal"})]}),e.jsxs(is,{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(ds,{value:l.stage_id,onValueChange:u=>o(h=>({...h,stage_id:u})),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:n.map(u=>e.jsx(Qe,{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(is,{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(is,{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(is,{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(Es,{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 obe(){const{user:s}=ys();return ct({queryKey:["recruit-email-senders",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{const[t,n]=await Promise.all([q.from("user_verified_senders").select("email, display_name, status").eq("user_id",s.id).eq("status","verified").limit(1).maybeSingle(),q.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]);return{massEmail:t.data?{email:t.data.email,displayName:t.data.display_name}:null,gmail:n.data?{email:n.data.gmail_email}:null}}})}function C8e({value:s,onChange:t}){const{data:n,isLoading:r}=obe();return e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Send from"}),e.jsxs(ds,{value:s,onValueChange:a=>t(a),disabled:r,children:[e.jsx(ls,{className:"mt-1",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"default",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Va,{className:"h-3.5 w-3.5"})," Brokerage default sender"]})}),e.jsx(Qe,{value:"mass_email",disabled:!(n!=null&&n.massEmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Y2,{className:"h-3.5 w-3.5"}),"Mass Email",n!=null&&n.massEmail?` (${n.massEmail.email})`:" — not configured"]})}),e.jsx(Qe,{value:"gmail",disabled:!(n!=null&&n.gmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Vs,{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 eNt({open:s,onOpenChange:t,recruitVideoId:n,brokerageId:r,prospectName:a,prospectEmail:i,videoTitle:l,defaultMessage:o}){const c=(a||"").split(" ")[0]||"there",[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState("default"),[_,v]=N.useState(!1),j=Ht(),{data:b}=obe();N.useEffect(()=>{s&&(u(`${c}, I made you a quick video 🎥`),p(o||""),g(b!=null&&b.massEmail?"mass_email":b!=null&&b.gmail?"gmail":"default"))},[s,c,o,b==null?void 0:b.massEmail,b==null?void 0:b.gmail]);const S=async()=>{var A,T;if(!i){ae.error("This prospect has no email address on file.");return}v(!0);try{const{data:L,error:D}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[n],brokerage_id:r,subject_override:d.trim()||void 0,message_override:h.trim()||void 0,send_via:f}});if(D)throw D;if(((L==null?void 0:L.sent)??0)>0)ae.success(`Email sent to ${i}`),j.invalidateQueries({queryKey:["recruit-videos"]}),j.invalidateQueries({queryKey:["recruit-videos-prospect"]}),t(!1);else{const F=((T=(A=L==null?void 0:L.results)==null?void 0:A[0])==null?void 0:T.error)||"Failed to send";ae.error(F)}}catch(L){ae.error((L==null?void 0:L.message)||"Failed to send email")}finally{v(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Vs,{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(C8e,{value:f,onChange:g}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subject"}),e.jsx(ye,{value:d,onChange:A=>u(A.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Personal message (optional)"}),e.jsx(Es,{value:h,onChange:A=>p(A.target.value),rows:5,placeholder:`Hi ${c}, wanted to share a quick video...`,className:"mt-1"})]}),l&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Video: ",e.jsx("span",{className:"font-medium",children:l})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:_,children:"Cancel"}),e.jsxs(B,{onClick:S,disabled:_||!i,children:[_?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function lw(s){return s?s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url||s.preview_url||null:null}const CTe=[{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 Stn(s){return ct({queryKey:["recruit-videos",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_videos").select(` *, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("brokerage_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function Ctn(s){return ct({queryKey:["recruit-videos-prospect",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_videos").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("prospect_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function tNt(){const s=Ht(),{toast:t}=Ba();return gt({mutationFn:async n=>{const{data:{user:r}}=await q.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("recruit_videos").insert({prospect_id:n.prospect_id,video_id:n.video_id,brokerage_id:n.brokerage_id,message:n.message||null,created_by:r.id}).select("*, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token)").single();if(i)throw i;return a},onSuccess:n=>{s.invalidateQueries({queryKey:["recruit-videos"]}),s.invalidateQueries({queryKey:["recruit-videos-prospect",n.prospect_id]}),t({title:"Video linked to prospect"})},onError:n=>t({title:"Error",description:n.message,variant:"destructive"})})}function sNt(){const s=Ht();return gt({mutationFn:async({id:t,sent_via:n})=>{const{error:r}=await q.from("recruit_videos").update({sent_at:new Date().toISOString(),sent_via:n,updated_at:new Date().toISOString()}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-videos"]})}})}function nNt(s){return ct({queryKey:["recruit-video-scripts",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_video_scripts").select("*").or(`brokerage_id.eq.${s},is_global.eq.true`).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function Ttn(){const s=Ht(),{toast:t}=Ba();return gt({mutationFn:async n=>{const{data:{user:r}}=await q.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("recruit_video_scripts").insert({...n,created_by:r.id}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]}),t({title:"Script saved"})},onError:n=>t({title:"Error",description:n.message,variant:"destructive"})})}function Etn(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("recruit_video_scripts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]})}})}function Atn({prospectId:s,prospectName:t,prospectEmail:n,brokerageId:r}){var J;const{data:a=[],isLoading:i}=Ctn(s),{data:l=[]}=nNt(r),o=tNt(),c=IN();sNt();const[d,u]=N.useState("idle"),[h,p]=N.useState(0),[f,g]=N.useState(0),[_,v]=N.useState(""),[j,b]=N.useState(""),[S,A]=N.useState(!1),[T,L]=N.useState(null),[D,M]=N.useState(null),[F,z]=N.useState(null),V=((J=l.find(ne=>ne.id===_))==null?void 0:J.script_text)||"",W=()=>{u("idle"),p(0),g(0),v(""),b("")},Y=N.useCallback(async(ne,ie)=>{u("uploading");try{const he=`Recruiting: ${t}`,{videoId:ce,libraryId:pe}=await i6(he),{uploadUrl:le,apiKey:ve}=await o6(ce),ge=new XMLHttpRequest;ge.upload.onprogress=qe=>{qe.lengthComputable&&p(qe.loaded/qe.total*100)},await new Promise((qe,be)=>{ge.onload=()=>ge.status>=200&&ge.status<300?qe():be(new Error("Upload failed")),ge.onerror=()=>be(new Error("Upload failed")),ge.open("PUT",le),ge.setRequestHeader("AccessKey",ve),ge.send(ne)}),u("processing");let Te=0;const Me=Date.now(),Ce=9e4,Ae=`https://iframe.mediadelivery.net/embed/${pe}/${ce}`;for(;Te<4&&(await new Promise(be=>setTimeout(be,3e3)),!(Date.now()-Me>Ce));){const qe=await $w(ce);if(Te=qe.status,g(qe.encodeProgress||0),Te===5||Te===6)throw new Error("Video processing failed")}const De=await $w(ce),Ie=(De.storageSize||ne.size)/(1024*1024),Fe=await c.mutateAsync({bunny_video_id:ce,playback_url:De.directPlayUrl||Ae,thumbnail_url:De.thumbnailUrl,preview_url:De.previewUrl||null,duration_seconds:De.length||ie,file_size_mb:Ie,title:he,status:Te>=4?"ready":"processing",touch_type:"recruiting"});await o.mutateAsync({prospect_id:s,video_id:Fe.id,brokerage_id:r,message:j||void 0}),u("done"),ae.success("Video recorded and linked to prospect!"),setTimeout(()=>{A(!1),W()},1500)}catch(he){ae.error(he.message||"Failed to upload video"),u("record")}},[s,t,r,j,c,o]),K=ne=>{ne&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${ne}`),ae.success("Share link copied"))};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-1.5",children:[e.jsx(br,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(bs,{open:S,onOpenChange:ne=>{!ne&&(d==="uploading"||d==="processing")||(A(ne),ne||W())},children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>u("script"),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Record Video for ",t]})}),d==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Choose a Script (optional)"}),e.jsxs(ds,{value:_,onValueChange:v,children:[e.jsx(ls,{className:"mt-1",children:e.jsx(us,{placeholder:"No script — speak freely"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"No script"}),l.map(ne=>{var ie;return e.jsx(Qe,{value:ne.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[ne.title,e.jsx(ze,{variant:"outline",className:"text-[9px] ml-1",children:(ie=CTe.find(he=>he.value===ne.category))==null?void 0:ie.label})]})},ne.id)})]})]}),V&&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:V})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Personal Message (shown on landing page)"}),e.jsx(Es,{value:j,onChange:ne=>b(ne.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(br,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx(u6,{maxDurationSeconds:600,onRecordingComplete:Y,teleprompterContent:V||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(pi,{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(pi,{value:f,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(f),"%"]})]}),d==="done"&&e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(Al,{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(ne=>{var ie;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:lw(ne.video)?e.jsx("img",{src:lw(ne.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(br,{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:((ie=ne.video)==null?void 0:ie.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[ne.view_count>0?e.jsxs(ze,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(Er,{className:"h-2.5 w-2.5 mr-0.5"}),ne.view_count]}):ne.sent_at?e.jsxs(ze,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(cr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs(ze,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(gr,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Ss(new Date(ne.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:()=>K(ne.share_token),title:"Copy link",children:e.jsx(Xr,{className:"h-3 w-3"})}),e.jsxs(B,{variant:ne.sent_at?"ghost":"default",size:"sm",className:"h-7 gap-1",disabled:!n,onClick:()=>{var he;L(ne.id),M(((he=ne.video)==null?void 0:he.title)||null),z(ne.message||null)},title:n?"Email video to prospect":"No email on file",children:[e.jsx(Vs,{className:"h-3 w-3"}),e.jsx("span",{className:"text-[10px]",children:ne.sent_at?"Resend":"Email"})]})]})]},ne.id)})}),T&&e.jsx(eNt,{open:!!T,onOpenChange:ne=>{ne||L(null)},recruitVideoId:T,brokerageId:r,prospectName:t,prospectEmail:n,videoTitle:D,defaultMessage:F})]})}function Mtn({brokerageId:s,onSelect:t}){const{data:n=[],isLoading:r}=ct({queryKey:["recruit-email-templates",s??"global-only"],queryFn:async()=>{let i=q.from("recruit_email_templates").select("id,brokerage_id,category,title,subject,body,sort_order").eq("is_active",!0).order("sort_order");s?i=i.or(`brokerage_id.is.null,brokerage_id.eq.${s}`):i=i.is("brokerage_id",null);const{data:l,error:o}=await i;if(o)throw o;return l}}),a=n.reduce((i,l)=>{var o;return(i[o=l.category]||(i[o]=[])).push(l),i},{});return e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",type:"button",children:[e.jsx(Nr,{className:"h-4 w-4"}),"Use Template",e.jsx(io,{className:"h-3.5 w-3.5 opacity-60"})]})}),e.jsx(cc,{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(ts,{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(Zg,{}),e.jsx(M4,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:i}),l.map(c=>e.jsxs(Qr,{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(ze,{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 Itn({open:s,onOpenChange:t,prospectId:n,brokerageId:r,prospectName:a,prospectEmail:i}){const{user:l}=ys(),o=(a||"").split(" ")[0]||"there",[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState("default"),[g,_]=N.useState(!1),[v,j]=N.useState(null),[b,S]=N.useState(!1),A=Ht(),{data:T}=obe();N.useEffect(()=>{if(s){d(`Hi ${o}`),h("");const V=T!=null&&T.massEmail?"mass_email":T!=null&&T.gmail?"gmail":"default";f(V),j(null),S(!1)}},[s,o,T==null?void 0:T.massEmail,T==null?void 0:T.gmail]);const{data:L=[],isLoading:D}=ct({queryKey:["prospect-email-video-library",l==null?void 0:l.id],queryFn:async()=>{const{data:V,error:W}=await q.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, touch_type, created_at, share_token").eq("owner_user_id",l.id).eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(W)throw W;return V??[]},enabled:s&&!!(l!=null&&l.id)}),M=L.find(V=>V.id===v)||null,F=async()=>{var V,W;if(!i){ae.error("This prospect has no email address on file.");return}if(!c.trim()||!u.trim()){ae.error("Subject and message are required.");return}_(!0);try{if(v){const{data:Y}=await q.from("recruit_videos").select("id").eq("prospect_id",n).eq("video_id",v).maybeSingle();let K=Y==null?void 0:Y.id;if(!K){const{data:he,error:ce}=await q.from("recruit_videos").insert({prospect_id:n,video_id:v,brokerage_id:r,message:u.trim(),created_by:l.id}).select("id").single();if(ce)throw ce;K=he.id}const{data:J,error:ne}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[K],brokerage_id:r,subject_override:c.trim(),message_override:u.trim(),send_via:p}});if(ne)throw ne;if(((J==null?void 0:J.sent)??0)>0)ae.success(`Email sent to ${i}`),A.invalidateQueries({queryKey:["recruit-videos"]}),A.invalidateQueries({queryKey:["recruit-videos-prospect",n]}),A.invalidateQueries({queryKey:["recruit-activities",n]}),A.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1);else{const he=((W=(V=J==null?void 0:J.results)==null?void 0:V[0])==null?void 0:W.error)||"Failed to send";ae.error(he)}}else{const{data:Y,error:K}=await q.functions.invoke("send-recruit-prospect-email",{body:{prospect_id:n,brokerage_id:r,subject:c.trim(),message:u.trim(),send_via:p}});if(K)throw K;Y!=null&&Y.success?(ae.success(`Email sent to ${i}`),A.invalidateQueries({queryKey:["recruit-activities",n]}),A.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1)):ae.error((Y==null?void 0:Y.error)||"Failed to send")}}catch(Y){ae.error((Y==null?void 0:Y.message)||"Failed to send email")}finally{_(!1)}},z=V=>{const W=Y=>Y.replace(/\[First Name\]/gi,o);d(W(V.subject)),h(W(V.body)),ae.success(`Loaded "${V.title}"`)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Vs,{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(C8e,{value:p,onChange:f}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(se,{className:"text-xs",children:"Subject"}),e.jsx(Mtn,{brokerageId:r,onSelect:z})]}),e.jsx(ye,{value:c,onChange:V=>d(V.target.value)}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Message"}),e.jsx(Es,{value:u,onChange:V=>h(V.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(br,{className:"h-3.5 w-3.5"})," Include a video"]}),M?e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{j(null),S(!1)},children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"})," Remove"]}):e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>S(V=>!V),children:b?"Hide library":"Pick from library"})]}),M&&e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded bg-muted/40",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:lw(M)?e.jsx("img",{src:lw(M),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(br,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx("p",{className:"text-xs font-medium truncate flex-1",children:M.title||"Untitled video"})]}),!M&&b&&e.jsx("div",{className:"max-h-56 overflow-y-auto space-y-1 -mx-1 px-1",children:D?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ts,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):L.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."}):L.map(V=>e.jsxs("button",{type:"button",onClick:()=>{j(V.id),S(!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:lw(V)?e.jsx("img",{src:lw(V),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(br,{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:V.title||"Untitled video"}),V.duration_seconds&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[Math.floor(V.duration_seconds/60),":",String(Math.floor(V.duration_seconds%60)).padStart(2,"0")]})]})]},V.id))}),M&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"A tracked share link with thumbnail will be added to the email automatically."})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:g,children:"Cancel"}),e.jsxs(B,{onClick:F,disabled:g||!i,children:[g?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function Ptn(s){return ct({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_campaign_sends").select("id, prospect_id, subject, email_number, status, sent_at, opened_at, clicked_at, error_message, created_at").eq("prospect_id",s).neq("status","failed").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}const CXe=[{value:"call",label:"Phone Call",icon:Ar},{value:"email",label:"Email",icon:Vs},{value:"text",label:"Text Message",icon:Ei},{value:"meeting",label:"Meeting",icon:yr},{value:"note",label:"Note",icon:Nr},{value:"campaign_email",label:"Campaign Email",icon:cr}];function D0({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 MG({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 Id({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 rNt({prospect:s,stages:t,brokerageId:n,open:r,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=ktn((s==null?void 0:s.id)||null),{data:d=[]}=Ptn((s==null?void 0:s.id)||null),[u,h]=N.useState({type:"note",title:"",description:""}),[p,f]=N.useState(!1),[g,_]=N.useState(!1),[v,j]=N.useState({}),[b,S]=N.useState(!1);if(!s)return null;const A=()=>{var K,J;j({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:((K=s.experience_years)==null?void 0:K.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:((J=s.last_year_transactions)==null?void 0:J.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||""}),_(!0)},T=()=>{const K={id:s.id};for(const[J,ne]of Object.entries(v))J==="experience_years"||J==="last_year_transactions"?K[J]=ne?parseInt(ne):null:K[J]=ne||null;i(K),_(!1)},L=()=>_(!1),D=K=>J=>j(ne=>({...ne,[K]:J})),M=()=>{u.title.trim()&&(c.mutate({prospect_id:s.id,activity_type:u.type,title:u.title,description:u.description||null}),h({type:"note",title:"",description:""}),f(!1))},F=t.find(K=>K.id===s.stage_id),z=s.address||s.city||s.state,V=s.last_year_volume||s.last_year_transactions||s.avg_sale_price||s.specialties||s.annual_production,W=s.linkedin_url||s.website_url||s.instagram_handle||s.facebook_url,Y=s.birthday||s.spouse_name||s.interests||s.referred_by;return e.jsxs(cg,{open:r,onOpenChange:K=>{K||_(!1),a(K)},children:[e.jsx(ix,{className:"w-full sm:max-w-lg p-0",children:e.jsx(hi,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(n0,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(r0,{className:"text-xl",children:[s.first_name," ",s.last_name]}),F&&e.jsx(ze,{variant:"outline",style:{borderColor:F.color,color:F.color},className:"mt-1",children:F.name})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[g?e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:L,children:e.jsx(Bn,{className:"h-4 w-4"})}),e.jsx(B,{variant:"default",size:"icon",onClick:T,children:e.jsx(qo,{className:"h-4 w-4"})})]}):e.jsx(B,{variant:"ghost",size:"icon",onClick:A,title:"Edit prospect",children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete prospect?"}),e.jsx(Mo,{children:"This will permanently remove this prospect and all their activity history."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>{l(s.id),a(!1)},children:"Delete"})]})]})]})]})]})}),!g&&e.jsxs("div",{className:"space-y-2 text-sm",children:[s.email&&e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground min-w-0",children:[e.jsx(Vs,{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:()=>S(!0),children:[e.jsx(Vs,{className:"h-3 w-3"})," Email"]})]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ar,{className:"h-3.5 w-3.5"})," ",s.phone]}),z&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ka,{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(ds,{value:s.stage_id||"",onValueChange:K=>i({id:s.id,stage_id:K}),children:[e.jsx(ls,{className:"mt-1",children:e.jsx(us,{})}),e.jsx(cs,{children:t.map(K=>e.jsx(Qe,{value:K.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:K.color}}),K.name]})},K.id))})]})]}),e.jsxs(Br,{defaultValue:"details",className:"w-full",children:[e.jsxs(Fr,{className:"grid w-full grid-cols-4 h-8 text-xs",children:[e.jsx(Kt,{value:"details",className:"text-xs",children:"Details"}),e.jsx(Kt,{value:"production",className:"text-xs",children:"Production"}),e.jsx(Kt,{value:"social",className:"text-xs",children:"Social"}),e.jsx(Kt,{value:"personal",className:"text-xs",children:"Personal"})]}),g?e.jsxs(e.Fragment,{children:[e.jsxs(is,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Id,{label:"First Name",value:v.first_name,onChange:D("first_name")}),e.jsx(Id,{label:"Last Name",value:v.last_name,onChange:D("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Id,{label:"Email",value:v.email,onChange:D("email"),type:"email"}),e.jsx(Id,{label:"Phone",value:v.phone,onChange:D("phone")})]}),e.jsx(Id,{label:"Current Brokerage",value:v.current_brokerage,onChange:D("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Id,{label:"License #",value:v.license_number,onChange:D("license_number")}),e.jsx(Id,{label:"Experience (years)",value:v.experience_years,onChange:D("experience_years"),type:"number"})]}),e.jsx(Id,{label:"Address",value:v.address,onChange:D("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(Id,{label:"City",value:v.city,onChange:D("city")}),e.jsx(Id,{label:"State",value:v.state,onChange:D("state")}),e.jsx(Id,{label:"Zip",value:v.zip_code,onChange:D("zip_code")})]}),e.jsx(Id,{label:"Source",value:v.source,onChange:D("source")}),e.jsx(Id,{label:"Referred By",value:v.referred_by,onChange:D("referred_by")}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Notes"}),e.jsx(Es,{value:v.notes,onChange:K=>j(J=>({...J,notes:K.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(is,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(Id,{label:"Annual Production",value:v.annual_production,onChange:D("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Id,{label:"Last Year Volume",value:v.last_year_volume,onChange:D("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(Id,{label:"Last Year Transactions",value:v.last_year_transactions,onChange:D("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(Id,{label:"Avg Sale Price",value:v.avg_sale_price,onChange:D("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(Id,{label:"Specialties / Niche",value:v.specialties,onChange:D("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(is,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(Id,{label:"LinkedIn URL",value:v.linkedin_url,onChange:D("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(Id,{label:"Website URL",value:v.website_url,onChange:D("website_url"),type:"url",placeholder:"https://..."}),e.jsx(Id,{label:"Instagram Handle",value:v.instagram_handle,onChange:D("instagram_handle"),placeholder:"@handle"}),e.jsx(Id,{label:"Facebook URL",value:v.facebook_url,onChange:D("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(is,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(Id,{label:"Birthday",value:v.birthday,onChange:D("birthday"),type:"date"}),e.jsx(Id,{label:"Spouse / Partner",value:v.spouse_name,onChange:D("spouse_name")}),e.jsx(Id,{label:"Interests / Hobbies",value:v.interests,onChange:D("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(is,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(D0,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(D0,{label:"License #",value:s.license_number}),e.jsx(D0,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(D0,{label:"Referred By",value:s.referred_by}),e.jsx(D0,{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(is,{value:"production",className:"mt-3",children:V?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(D0,{label:"Annual Production",value:s.annual_production}),e.jsx(D0,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(D0,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(D0,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(D0,{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(is,{value:"social",className:"mt-3",children:W?e.jsxs("div",{className:"space-y-2",children:[e.jsx(MG,{label:"LinkedIn",url:s.linkedin_url,icon:vf}),e.jsx(MG,{label:"Website",url:s.website_url,icon:lc}),s.instagram_handle&&e.jsx(MG,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:du}),e.jsx(MG,{label:"Facebook",url:s.facebook_url,icon:Lh})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No social profiles added yet"})}),e.jsx(is,{value:"personal",className:"mt-3",children:Y?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(D0,{label:"Birthday",value:s.birthday?Ss(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:Oi}),e.jsx(D0,{label:"Spouse / Partner",value:s.spouse_name,icon:gi}),e.jsx("div",{className:"col-span-2",children:e.jsx(D0,{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(Atn,{prospectId:s.id,prospectName:`${s.first_name} ${s.last_name||""}`,prospectEmail:s.email,brokerageId:n}),e.jsx(ll,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Activity Log"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>f(!p),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Log Activity"]})]}),p&&e.jsxs("div",{className:"border rounded-lg p-3 mb-4 space-y-3 bg-muted/30",children:[e.jsxs(ds,{value:u.type,onValueChange:K=>h(J=>({...J,type:K})),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:CXe.map(K=>e.jsx(Qe,{value:K.value,children:K.label},K.value))})]}),e.jsx(ye,{placeholder:"Subject / Title",value:u.title,onChange:K=>h(J=>({...J,title:K.target.value}))}),e.jsx(Es,{placeholder:"Details (optional)",value:u.description,onChange:K=>h(J=>({...J,description:K.target.value})),rows:2}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>f(!1),children:"Cancel"}),e.jsx(B,{size:"sm",onClick:M,disabled:!u.title.trim(),children:"Save"})]})]}),e.jsx("div",{className:"space-y-3",children:(()=>{const K=[...o.map(J=>({type:"manual",data:J,date:J.created_at})),...d.map(J=>({type:"campaign_email",data:J,date:J.sent_at||J.created_at}))].sort((J,ne)=>new Date(ne.date).getTime()-new Date(J.date).getTime());return K.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"}):K.map(J=>{if(J.type==="manual"){const ie=J.data,he=CXe.find(pe=>pe.value===ie.activity_type),ce=(he==null?void 0:he.icon)||Nr;return e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center",children:e.jsx(ce,{className:"h-3.5 w-3.5 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:ie.title}),ie.description&&e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:ie.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Ss(new Date(ie.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${ie.id}`)}const ne=J.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(cr,{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 #",ne.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:ne.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[ne.status==="failed"?e.jsx(ze,{variant:"destructive",className:"text-[10px] px-1.5 py-0 h-4",children:"Failed"}):e.jsxs(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-green-500 text-green-600",children:[e.jsx(cr,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),ne.opened_at?e.jsxs(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-blue-500 text-blue-600",children:[e.jsx(Er,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",Ss(new Date(ne.opened_at),"MMM d, h:mm a")]}):ne.status!=="failed"?e.jsx(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,ne.clicked_at&&e.jsxs(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-purple-500 text-purple-600",children:[e.jsx(Om,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",Ss(new Date(ne.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Ss(new Date(ne.sent_at||ne.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${ne.id}`)})})()})]})]})})}),e.jsx(Itn,{open:b,onOpenChange:S,prospectId:s.id,brokerageId:s.brokerage_id,prospectName:`${s.first_name} ${s.last_name??""}`.trim(),prospectEmail:s.email})]})}const Ltn=["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 aNt({open:s,onOpenChange:t,brokerageId:n,stages:r}){var z;const{toast:a}=Ba(),i=Ht(),l=N.useRef(null),[o,c]=N.useState([]),[d,u]=N.useState([]),[h,p]=N.useState({}),[f,g]=N.useState(((z=r[0])==null?void 0:z.id)||""),[_,v]=N.useState(!1),[j,b]=N.useState("upload"),[S,A]=N.useState(0),T=()=>{c([]),u([]),p({}),b("upload"),A(0)},L=V=>{var K;const W=(K=V.target.files)==null?void 0:K[0];if(!W)return;const Y=new FileReader;Y.onload=J=>{var ve;const ie=((ve=J.target)==null?void 0:ve.result).split(/\r?\n/).filter(ge=>ge.trim());if(ie.length<2){a({title:"Invalid CSV",description:"File must have a header row and at least one data row",variant:"destructive"});return}const he=D(ie[0]);u(he);const ce={},pe=new Set;he.forEach((ge,Te)=>{const Me=ge.toLowerCase().replace(/[^a-z0-9]/g,"");let Ce=null;/^firstname$/.test(Me)||Me==="first"?Ce="first_name":/^lastname$/.test(Me)||Me==="last"?Ce="last_name":/^email$/.test(Me)||Me==="emailaddress"?Ce="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(Me)?Ce="phone":/officename|currentbrokerage|brokerage|company/.test(Me)?Ce="current_brokerage":/membernumber|licensenumber|license/.test(Me)?Ce="license_number":/experienceyears|yearsexperience/.test(Me)?Ce="experience_years":/^totalvolume$|annualproduction/.test(Me)?Ce="annual_production":/^address$/.test(Me)?Ce="address":/^city$/.test(Me)?Ce="city":/^state$/.test(Me)?Ce="state":/^postalcode$|^zip$|^zipcode$/.test(Me)?Ce="zip_code":/listsidevolume|lastyearvolume/.test(Me)?Ce="last_year_volume":/^totalcount$|lastyeartransactions/.test(Me)?Ce="last_year_transactions":/avgsaleprice|averageprice/.test(Me)?Ce="avg_sale_price":/linkedin/.test(Me)?Ce="linkedin_url":/website/.test(Me)?Ce="website_url":/specialt/.test(Me)?Ce="specialties":/referr/.test(Me)?Ce="referred_by":/^notes$|^note$/.test(Me)&&(Ce="notes"),Ce&&!pe.has(Ce)&&(ce[String(Te)]=Ce,pe.add(Ce))}),p(ce);const le=ie.slice(1).map(ge=>{const Te=D(ge),Me={};return he.forEach((Ce,Ae)=>{Me[String(Ae)]=Te[Ae]||""}),Me});c(le),b("map")},Y.readAsText(W)},D=V=>{const W=[];let Y="",K=!1;for(const J of V)J==='"'?K=!K:J===","&&!K?(W.push(Y.trim()),Y=""):Y+=J;return W.push(Y.trim()),W},M=async()=>{v(!0);try{const{data:{user:V}}=await q.auth.getUser();if(!V)throw new Error("Not authenticated");const W=o.map(K=>{const J={brokerage_id:n,created_by:V.id,stage_id:f,source:"csv_import",first_name:"Unknown"},ne=J;return Object.entries(h).forEach(([ie,he])=>{var pe;const ce=(pe=K[ie])==null?void 0:pe.trim();ce&&(he==="experience_years"||he==="last_year_transactions"?ne[he]=parseInt(ce.replace(/[^0-9.-]/g,""))||null:he==="annual_production"||he==="last_year_volume"||he==="avg_sale_price"?ne[he]=ce.replace(/[^0-9.$,.-]/g,""):ne[he]=ce)}),J});let Y=0;for(let K=0;K{const V=`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`,W=new Blob([V],{type:"text/csv"}),Y=URL.createObjectURL(W),K=document.createElement("a");K.href=Y,K.download="recruit-prospects-template.csv",K.click(),URL.revokeObjectURL(Y)};return e.jsx(bs,{open:s,onOpenChange:V=>{V||T(),t(V)},children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Import Prospects from CSV"})}),j==="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(gw,{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:L}),e.jsxs(B,{onClick:()=>{var V;return(V=l.current)==null?void 0:V.click()},children:[e.jsx(Na,{className:"h-4 w-4 mr-2"})," Choose File"]})]}),e.jsx(B,{variant:"link",className:"text-xs",onClick:F,children:"Download CSV template"})]}),j==="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(ds,{value:f,onValueChange:g,children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(us,{})}),e.jsx(cs,{children:r.map(V=>e.jsx(Qe,{value:V.id,children:V.name},V.id))})]})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{className:"w-[140px]",children:"CSV Column"}),e.jsx(Ct,{className:"w-[160px]",children:"Map To"}),e.jsx(Ct,{children:"Preview"})]})}),e.jsx(ha,{children:d.map((V,W)=>{var Y;return e.jsxs(Hs,{children:[e.jsx(ut,{className:"font-medium text-xs",children:V}),e.jsx(ut,{children:e.jsxs(ds,{value:h[String(W)]||"skip",onValueChange:K=>p(J=>({...J,[String(W)]:K==="skip"?"":K})),children:[e.jsx(ls,{className:"h-8 text-xs",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"skip",children:"— Skip —"}),Ltn.map(K=>e.jsx(Qe,{value:K,children:K.replace(/_/g," ")},K))]})]})}),e.jsx(ut,{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:((Y=o[0])==null?void 0:Y[String(W)])||"—"})]},W)})})]})}),!Object.values(h).includes("first_name")&&e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-sm",children:[e.jsx(Gi,{className:"h-4 w-4"}),' Map at least "first name" to proceed']}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>{T()},children:"Back"}),e.jsx(B,{onClick:M,disabled:_||!Object.values(h).includes("first_name"),children:_?"Importing...":`Import ${o.length} Prospects`})]})]}),j==="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(Ir,{className:"h-6 w-6 text-green-600"})}),e.jsxs("p",{className:"font-semibold",children:[S," prospects imported successfully!"]}),e.jsx(B,{onClick:()=>{T(),t(!1)},children:"Close"})]})]})})}function iNt({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=ZU(s),[o,c]=N.useState(!1),[d,u]=N.useState(),[h,p]=N.useState(null),[f,g]=N.useState(!1),[_,v]=N.useState(!1),[j,b]=N.useState(null);if(r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});const S=F=>n.filter(z=>z.stage_id===F),A=(F,z)=>{b(z),F.dataTransfer.effectAllowed="move"},T=F=>{F.preventDefault(),F.dataTransfer.dropEffect="move"},L=(F,z)=>{F.preventDefault(),j&&(i.mutate({id:j,stage_id:z}),b(null))},D=F=>{u(F),c(!0)},M=F=>{p(F),g(!0)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[n.length," prospect",n.length!==1?"s":""]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>v(!0),children:[e.jsx(Na,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(B,{onClick:()=>{u(void 0),c(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs(hi,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:t.length*300},children:t.map(F=>{const z=S(F.id);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:T,onDrop:V=>L(V,F.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:F.color}}),e.jsx("h3",{className:"font-semibold text-sm",children:F.name}),e.jsx(ze,{variant:"secondary",className:"text-xs h-5 px-1.5",children:z.length})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>D(F.id),children:e.jsx(Is,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"space-y-2 min-h-[200px] bg-muted/30 rounded-lg p-2",children:z.map(V=>e.jsx(fe,{className:"p-3 cursor-pointer hover:shadow-md transition-shadow border-l-4 group",style:{borderLeftColor:F.color},draggable:!0,onDragStart:W=>A(W,V.id),onClick:()=>M(V),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Fu,{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(Xi,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("span",{className:"font-medium text-sm truncate",children:[V.first_name," ",V.last_name]})]}),V.current_brokerage&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Va,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:V.current_brokerage})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[V.email&&e.jsx(Vs,{className:"h-3 w-3 text-muted-foreground"}),V.phone&&e.jsx(Ar,{className:"h-3 w-3 text-muted-foreground"}),V.experience_years!=null&&e.jsxs(ze,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[V.experience_years,"yr"]})]})]})]})},V.id))})]},F.id)})}),e.jsx(iU,{orientation:"horizontal"})]}),e.jsx(J2t,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:F=>a.mutate(F),isSubmitting:a.isPending}),e.jsx(rNt,{prospect:h,stages:t,brokerageId:s,open:f,onOpenChange:g,onUpdate:F=>{i.mutate(F),p(z=>z?{...z,...F}:null)},onDelete:F=>l.mutate(F)}),e.jsx(aNt,{open:_,onOpenChange:v,brokerageId:s,stages:t})]})}function Yge({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=ZU(s),{user:o}=ys(),c=Ht(),[d,u]=N.useState(!1),[h,p]=N.useState(null),[f,g]=N.useState(!1),[_,v]=N.useState(!1),[j,b]=N.useState(""),[S,A]=N.useState("all"),[T,L]=N.useState("all"),[D,M]=N.useState("all"),[F,z]=N.useState(null),[V,W]=N.useState("asc"),[Y,K]=N.useState(new Set),[J,ne]=N.useState(!1),[ie,he]=N.useState(""),ce=N.useMemo(()=>{const be=new Set;return n.forEach(Ze=>{Ze.current_brokerage&&be.add(Ze.current_brokerage)}),Array.from(be).sort()},[n]),{data:pe=[]}=ct({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:be,error:Ze}=await q.from("recruit_campaigns").select("id, name, warmth_level").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("name");if(Ze)throw Ze;return be}}),{data:le=[]}=ct({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let Ze=[],Ne=0;for(;;){const{data:it,error:je}=await q.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(Ne,Ne+1e3-1);if(je)throw je;if(Ze=Ze.concat(it??[]),!it||it.length<1e3)break;Ne+=1e3}return Ze}}),ve=N.useMemo(()=>{const be=new Map;return le.forEach(Ze=>{be.has(Ze.prospect_id)||be.set(Ze.prospect_id,new Set),be.get(Ze.prospect_id).add(Ze.campaign_id)}),be},[le]),ge=be=>{F===be?W(Ze=>Ze==="asc"?"desc":"asc"):(z(be),W("asc"))},Te=({column:be})=>F!==be?e.jsx(em,{className:"h-3.5 w-3.5 ml-1 text-muted-foreground/50"}):V==="asc"?e.jsx(Ru,{className:"h-3.5 w-3.5 ml-1 text-primary"}):e.jsx(am,{className:"h-3.5 w-3.5 ml-1 text-primary"}),Me=be=>t.find(Ze=>Ze.id===be),Ce=N.useMemo(()=>{let be=n.filter(Ze=>{var Be,Ye,We;const Ne=!j||`${Ze.first_name} ${Ze.last_name}`.toLowerCase().includes(j.toLowerCase())||((Be=Ze.email)==null?void 0:Be.toLowerCase().includes(j.toLowerCase()))||((Ye=Ze.current_brokerage)==null?void 0:Ye.toLowerCase().includes(j.toLowerCase())),it=S==="all"||Ze.stage_id===S,je=T==="all"||Ze.current_brokerage===T;let Ge=!0;return D==="in_campaign"?Ge=ve.has(Ze.id):D==="not_in_campaign"?Ge=!ve.has(Ze.id):D!=="all"&&(Ge=((We=ve.get(Ze.id))==null?void 0:We.has(D))??!1),Ne&&it&&je&&Ge});return F&&(be=[...be].sort((Ze,Ne)=>{var Be,Ye;let it=null,je=null;switch(F){case"name":it=`${Ze.first_name} ${Ze.last_name||""}`.toLowerCase(),je=`${Ne.first_name} ${Ne.last_name||""}`.toLowerCase();break;case"stage":it=((Be=Me(Ze.stage_id))==null?void 0:Be.sort_order)??999,je=((Ye=Me(Ne.stage_id))==null?void 0:Ye.sort_order)??999;break;case"brokerage":it=(Ze.current_brokerage||"").toLowerCase(),je=(Ne.current_brokerage||"").toLowerCase();break;case"experience":it=Ze.experience_years??-1,je=Ne.experience_years??-1;break;case"production":it=(Ze.annual_production||"").toLowerCase(),je=(Ne.annual_production||"").toLowerCase();break;case"source":it=(Ze.source||"").toLowerCase(),je=(Ne.source||"").toLowerCase();break;default:return 0}if(it===je)return 0;if(it==null)return 1;if(je==null)return-1;const Ge=it0&&Ce.every(be=>Y.has(be.id)),De=Ce.some(be=>Y.has(be.id)),Ie=()=>{K(Ae?new Set:new Set(Ce.map(be=>be.id)))},Fe=be=>{K(Ze=>{const Ne=new Set(Ze);return Ne.has(be)?Ne.delete(be):Ne.add(be),Ne})},qe=gt({mutationFn:async()=>{if(!ie||!(o!=null&&o.id))throw new Error("Select a campaign");const be=new Set(le.filter(it=>it.campaign_id===ie).map(it=>it.prospect_id)),Ze=Array.from(Y).filter(it=>!be.has(it)).map(it=>({prospect_id:it,campaign_id:ie,brokerage_id:s,assigned_by:o.id,status:"active",current_email_number:0}));if(Ze.length===0)throw new Error("All selected prospects are already in this campaign");const{error:Ne}=await q.from("recruit_campaign_assignments").insert(Ze);if(Ne)throw Ne;return Ze.length},onSuccess:be=>{ae.success(`${be} prospect(s) added to campaign`),ne(!1),K(new Set),he(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:be=>ae.error(be.message)});return r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm min-w-[200px]",children:[e.jsx(vr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search prospects...",value:j,onChange:be=>b(be.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[Y.size>0&&e.jsxs(B,{variant:"secondary",onClick:()=>ne(!0),className:"gap-1.5",children:[e.jsx(cr,{className:"h-4 w-4"})," Add ",Y.size," to Campaign"]}),e.jsxs(B,{variant:"outline",onClick:()=>v(!0),children:[e.jsx(Na,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(B,{onClick:()=>u(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Rv,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(ds,{value:S,onValueChange:A,children:[e.jsx(ls,{className:"w-[160px] h-8 text-xs",children:e.jsx(us,{placeholder:"All stages"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All stages"}),t.map(be=>e.jsx(Qe,{value:be.id,children:be.name},be.id))]})]}),e.jsxs(ds,{value:T,onValueChange:L,children:[e.jsxs(ls,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Va,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(us,{placeholder:"All brokerages"})]}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All brokerages"}),ce.map(be=>e.jsx(Qe,{value:be,children:be},be))]})]}),e.jsxs(ds,{value:D,onValueChange:M,children:[e.jsxs(ls,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Vs,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(us,{placeholder:"Campaign status"})]}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All contacts"}),e.jsx(Qe,{value:"in_campaign",children:"In any campaign"}),e.jsx(Qe,{value:"not_in_campaign",children:"Not in any campaign"}),pe.map(be=>e.jsxs(Qe,{value:be.id,children:["In: ",be.name]},be.id))]})]}),(S!=="all"||T!=="all"||D!=="all")&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 text-xs text-muted-foreground",onClick:()=>{A("all"),L("all"),M("all")},children:"Clear filters"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{className:"w-[40px]",children:e.jsx(ui,{checked:Ae,onCheckedChange:Ie,"aria-label":"Select all",...De&&!Ae?{"data-state":"indeterminate"}:{}})}),e.jsx(Ct,{className:"cursor-pointer select-none",onClick:()=>ge("name"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Name ",e.jsx(Te,{column:"name"})]})}),e.jsx(Ct,{className:"cursor-pointer select-none",onClick:()=>ge("stage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Stage ",e.jsx(Te,{column:"stage"})]})}),e.jsx(Ct,{className:"hidden md:table-cell cursor-pointer select-none",onClick:()=>ge("brokerage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Brokerage ",e.jsx(Te,{column:"brokerage"})]})}),e.jsx(Ct,{className:"hidden md:table-cell",children:"Contact"}),e.jsx(Ct,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>ge("experience"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Experience ",e.jsx(Te,{column:"experience"})]})}),e.jsx(Ct,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>ge("production"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Production ",e.jsx(Te,{column:"production"})]})}),e.jsx(Ct,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(Ct,{className:"w-[50px]"})]})}),e.jsx(ha,{children:Ce.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):Ce.map(be=>{const Ze=Me(be.stage_id),Ne=ve.get(be.id),it=(Ne==null?void 0:Ne.size)??0;return e.jsxs(Hs,{className:"cursor-pointer",onClick:()=>{p(be),g(!0)},children:[e.jsx(ut,{onClick:je=>je.stopPropagation(),children:e.jsx(ui,{checked:Y.has(be.id),onCheckedChange:()=>Fe(be.id),"aria-label":`Select ${be.first_name}`})}),e.jsxs(ut,{className:"font-medium",children:[be.first_name," ",be.last_name]}),e.jsx(ut,{children:Ze?e.jsxs(ze,{variant:"outline",className:"text-xs gap-1 whitespace-nowrap",style:{borderColor:Ze.color,color:Ze.color,backgroundColor:`${Ze.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:Ze.color}}),Ze.name]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx(ut,{className:"hidden md:table-cell",children:be.current_brokerage?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(Va,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[150px]",children:be.current_brokerage})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ut,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"flex items-center gap-2",children:[be.email&&e.jsx(Vs,{className:"h-3.5 w-3.5 text-muted-foreground"}),be.phone&&e.jsx(Ar,{className:"h-3.5 w-3.5 text-muted-foreground"}),!be.email&&!be.phone&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})}),e.jsx(ut,{className:"hidden lg:table-cell",children:be.experience_years!=null?`${be.experience_years} yr`:"—"}),e.jsx(ut,{className:"hidden lg:table-cell",children:be.annual_production||"—"}),e.jsx(ut,{className:"hidden lg:table-cell",children:it>0?e.jsxs(ze,{variant:"secondary",className:"text-xs",children:[it," campaign",it>1?"s":""]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"None"})}),e.jsx(ut,{children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:je=>{je.stopPropagation(),l.mutate(be.id)},children:e.jsx(_n,{className:"h-3.5 w-3.5"})})})]},be.id)})})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Y.size>0&&e.jsxs("span",{className:"font-medium text-foreground",children:[Y.size," selected · "]}),Ce.length," of ",n.length," prospects"]}),e.jsx(bs,{open:J,onOpenChange:ne,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Add to Campaign"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Add ",e.jsx("span",{className:"font-medium text-foreground",children:Y.size})," selected prospect(s) to a recruiting campaign drip."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Campaign"}),e.jsxs(ds,{value:ie,onValueChange:he,children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select a campaign..."})}),e.jsx(cs,{children:pe.map(be=>e.jsxs(Qe,{value:be.id,children:[be.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",be.warmth_level,")"]})]},be.id))})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>ne(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>qe.mutate(),disabled:!ie||qe.isPending,children:qe.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(J2t,{open:d,onOpenChange:u,stages:t,onSubmit:be=>a.mutate(be),isSubmitting:a.isPending}),e.jsx(rNt,{prospect:h,stages:t,brokerageId:s,open:f,onOpenChange:g,onUpdate:be=>{i.mutate(be),p(Ze=>Ze?{...Ze,...be}:null)},onDelete:be=>l.mutate(be)}),e.jsx(aNt,{open:_,onOpenChange:v,brokerageId:s,stages:t})]})}function oNt({brokerageId:s}){const{stages:t,prospects:n,isLoading:r}=ZU(s),a=N.useMemo(()=>{if(!t.length||!n.length)return null;const i=n.length,l=t.find(j=>j.name==="Signed"),o=t.find(j=>j.name==="Onboarded"),c=n.filter(j=>j.stage_id===(l==null?void 0:l.id)||j.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((j,b)=>j+Wv(u,new Date(b.created_at)),0)/i):0,p=t.map(j=>({...j,count:n.filter(b=>b.stage_id===j.id).length})),f={};n.forEach(j=>{const b=j.source||"unknown";f[b]=(f[b]||0)+1});const g=Object.entries(f).sort((j,b)=>b[1]-j[1]),_=new Date;_.setDate(_.getDate()-30);const v=n.filter(j=>new Date(j.created_at)>=_).length;return{total:i,signed:c,conversionRate:d,avgDays:h,byStage:p,bySrc:g,recentCount:v}},[t,n]);return r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):a?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsx(Ee,{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(Nn,{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(fe,{children:e.jsx(Ee,{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(mo,{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(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-amber-500/10 flex items-center justify-center",children:e.jsx(gr,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:[a.avgDays,"d"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Avg Days in Pipeline"})]})]})})}),e.jsx(fe,{children:e.jsx(Ee,{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(Oc,{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(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Pipeline Breakdown"})}),e.jsx(Ee,{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(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Ee,{className:"space-y-3",children:[a.bySrc.map(([i,l])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ze,{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 Dtn=["Outreach","Follow-up","Interview","Offer","Referral","Other"];function lNt({brokerageId:s}){const{toast:t}=Ba(),{user:n}=ys(),r=Ht(),[a,i]=N.useState(null),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(null),{data:p=[],isLoading:f}=ct({queryKey:["recruit-email-templates-manage",s],queryFn:async()=>{const{data:A,error:T}=await q.from("recruit_email_templates").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(T)throw T;return A}}),g=gt({mutationFn:async A=>{if(A.id){const{error:T}=await q.from("recruit_email_templates").update({category:A.category,title:A.title,subject:A.subject,body:A.body}).eq("id",A.id);if(T)throw T}else{const{error:T}=await q.from("recruit_email_templates").insert({brokerage_id:s,category:A.category||"Outreach",title:A.title,subject:A.subject,body:A.body,created_by:n==null?void 0:n.id,sort_order:100});if(T)throw T}},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template saved"}),d(!1),h(null)},onError:A=>t({title:"Save failed",description:A.message,variant:"destructive"})}),_=gt({mutationFn:async A=>{const{error:T}=await q.from("recruit_email_templates").delete().eq("id",A);if(T)throw T},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template deleted"})},onError:A=>t({title:"Delete failed",description:A.message,variant:"destructive"})}),v=(A,T)=>{navigator.clipboard.writeText(A),i(T),t({title:"Copied to clipboard!"}),setTimeout(()=>i(null),2e3)},j=()=>{h({category:"Outreach",title:"",subject:"",body:""}),d(!0)},b=A=>{h(A),d(!0)},S=Array.from(new Set(p.map(A=>A.category)));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pre-built and custom recruiting templates. Built-in templates are global; your custom ones are private to this brokerage."}),e.jsxs(B,{onClick:j,size:"sm",className:"gap-1.5",children:[e.jsx(Is,{className:"h-4 w-4"})," New Template"]})]}),f?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ts,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):S.map(A=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-2",children:[e.jsx(Vs,{className:"h-4 w-4"})," ",A]}),p.filter(T=>T.category===A).map(T=>{const L=T.brokerage_id!==null;return e.jsxs(fe,{className:`transition-all ${l===T.id?"ring-2 ring-primary/20":"hover:shadow-sm"}`,children:[e.jsx(Mt,{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(It,{className:"text-sm flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:T.title}),!L&&e.jsx(ze,{variant:"secondary",className:"text-[10px] shrink-0",children:"Built-in"}),L&&e.jsx(ze,{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(ze,{variant:"outline",className:"text-[10px] shrink-0",children:T.category})]})}),l===T.id&&e.jsxs(Ee,{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:()=>v(T.subject,T.id+"-s"),children:[a===T.id+"-s"?e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>v(T.body,T.id+"-b"),children:[a===T.id+"-b"?e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1"}),"Copy Body"]}),L&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>b(T),children:[e.jsx(_a,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&_.mutate(T.id)},children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-1"})," Delete"]})]})]})]})]},T.id)})]},A)),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsx(ws,{children:e.jsx(_s,{children:u!=null&&u.id?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Title"}),e.jsx(ye,{value:(u==null?void 0:u.title)||"",onChange:A=>h(T=>({...T,title:A.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Category"}),e.jsx("select",{value:(u==null?void 0:u.category)||"Outreach",onChange:A=>h(T=>({...T,category:A.target.value})),className:"mt-1 flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:Dtn.map(A=>e.jsx("option",{value:A,children:A},A))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subject"}),e.jsx(ye,{value:(u==null?void 0:u.subject)||"",onChange:A=>h(T=>({...T,subject:A.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Body"}),e.jsx(Es,{value:(u==null?void 0:u.body)||"",onChange:A=>h(T=>({...T,body:A.target.value})),rows:12,className:"mt-1 font-sans",placeholder:`Hi [First Name], ... Best, [Your Name]`}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Available placeholders: [First Name], [Your Name], [Brokerage Name]"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>g.mutate(u||{}),disabled:g.isPending||!(u!=null&&u.title)||!(u!=null&&u.subject)||!(u!=null&&u.body),children:[g.isPending&&e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Template"]})]})]})})]})}const TXe={call:Ar,email:Vs,text:Ei,meeting:yr,note:Nr};function cNt({brokerageId:s}){const{data:t,isLoading:n}=ct({queryKey:["recruit-activity-report",s],queryFn:async()=>{const{data:r,error:a}=await q.from("recruit_prospects").select("id, created_by").eq("brokerage_id",s);if(a)throw a;const i=(r==null?void 0:r.map(f=>f.id))||[];if(i.length===0)return{recruiters:[],recentActivities:[]};const{data:l,error:o}=await q.from("recruit_activities").select("*").in("prospect_id",i).order("created_at",{ascending:!1});if(o)throw o;const c=[...new Set([...r.map(f=>f.created_by),...(l||[]).map(f=>f.created_by)])],{data:d}=await q.from("profiles").select("id, name, email").in("id",c),u=Object.fromEntries((d||[]).map(f=>[f.id,f])),h=G9(new Date,30);return{recruiters:c.map(f=>{var b,S;const g=(l||[]).filter(A=>A.created_by===f),_=g.filter(A=>new Date(A.created_at)>=h),v={};_.forEach(A=>{v[A.activity_type]=(v[A.activity_type]||0)+1});const j=r.filter(A=>A.created_by===f).length;return{id:f,name:((b=u[f])==null?void 0:b.name)||"Unknown",email:((S=u[f])==null?void 0:S.email)||"",totalActivities:g.length,recentActivities:_.length,byType:v,prospectsCreated:j}}).sort((f,g)=>g.recentActivities-f.recentActivities),recentActivities:(l||[]).slice(0,20)}},enabled:!!s});return n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t!=null&&t.recruiters.length?e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Recruiter Leaderboard (Last 30 Days)"})}),e.jsx(Ee,{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(Xi,{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=TXe[i]||Nr;return e.jsxs(ze,{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(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Recent Activity"})}),e.jsx(Ee,{className:"space-y-3",children:t.recentActivities.map(r=>{const a=TXe[r.activity_type]||Nr;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:Ss(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 dNt({brokerageId:s}){const{toast:t}=Ba(),n=Ht(),[r,a]=N.useState(!1),[i,l]=N.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),{data:o=[],isLoading:c}=ct({queryKey:["recruit-referrals",s],queryFn:async()=>{const{data:v,error:j}=await q.from("recruit_referrals").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(j)throw j;return v}}),d=[...new Set(o.map(v=>v.referred_by))],{data:u=[]}=ct({queryKey:["referral-profiles",d],queryFn:async()=>{if(!d.length)return[];const{data:v}=await q.from("profiles").select("id, name, email").in("id",d);return v||[]},enabled:d.length>0}),h=Object.fromEntries(u.map(v=>[v.id,v])),p=gt({mutationFn:async v=>{const{data:{user:j}}=await q.auth.getUser();if(!j)throw new Error("Not authenticated");const{error:b}=await q.from("recruit_referrals").insert({brokerage_id:s,referred_by:j.id,referee_first_name:v.first_name,referee_last_name:v.last_name||null,referee_email:v.email||null,referee_phone:v.phone||null,referee_current_brokerage:v.current_brokerage||null,notes:v.notes||null});if(b)throw b},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-referrals",s]}),t({title:"Referral submitted!"}),l({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),a(!1)},onError:v=>t({title:"Error",description:v.message,variant:"destructive"})}),f=gt({mutationFn:async({id:v,status:j,incentive_status:b})=>{const S={updated_at:new Date().toISOString()};j&&(S.status=j),b&&(S.incentive_status=b);const{error:A}=await q.from("recruit_referrals").update(S).eq("id",v);if(A)throw A},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-referrals",s]})}),g=v=>v==="approved"||v==="signed"?e.jsx(Ir,{className:"h-3 w-3"}):v==="rejected"?e.jsx(Hc,{className:"h-3 w-3"}):e.jsx(gr,{className:"h-3 w-3"}),_=v=>v==="approved"||v==="signed"||v==="paid"?"bg-green-500/10 text-green-600 border-green-200":v==="rejected"?"bg-red-500/10 text-red-600 border-red-200":"bg-amber-500/10 text-amber-600 border-amber-200";return c?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," referral",o.length!==1?"s":""]}),e.jsxs(B,{onClick:()=>a(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(fe,{className:"py-12 text-center",children:[e.jsx(Fo,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No referrals yet. Agents can refer potential recruits here."})]}):e.jsx("div",{className:"space-y-3",children:o.map(v=>{var j;return e.jsx(fe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium",children:[v.referee_first_name," ",v.referee_last_name]}),e.jsxs(ze,{variant:"outline",className:_(v.status),children:[g(v.status)," ",v.status]}),v.incentive_status&&e.jsxs(ze,{variant:"outline",className:_(v.incentive_status),children:[e.jsx(Oi,{className:"h-3 w-3 mr-1"})," ",v.incentive_status]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5",children:[v.referee_email&&e.jsx("p",{children:v.referee_email}),v.referee_phone&&e.jsx("p",{children:v.referee_phone}),v.referee_current_brokerage&&e.jsxs("p",{children:["Currently at: ",v.referee_current_brokerage]}),e.jsxs("p",{children:["Referred by: ",((j=h[v.referred_by])==null?void 0:j.name)||"Unknown"," • ",Ss(new Date(v.created_at),"MMM d, yyyy")]})]}),v.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic",children:v.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(ds,{value:v.status,onValueChange:b=>f.mutate({id:v.id,status:b}),children:[e.jsx(ls,{className:"h-7 text-xs w-[110px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"pending",children:"Pending"}),e.jsx(Qe,{value:"contacted",children:"Contacted"}),e.jsx(Qe,{value:"approved",children:"Approved"}),e.jsx(Qe,{value:"signed",children:"Signed"}),e.jsx(Qe,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(ds,{value:v.incentive_status||"pending",onValueChange:b=>f.mutate({id:v.id,incentive_status:b}),children:[e.jsx(ls,{className:"h-7 text-xs w-[100px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"pending",children:"Unpaid"}),e.jsx(Qe,{value:"paid",children:"Paid"}),e.jsx(Qe,{value:"n/a",children:"N/A"})]})]})]})]})},v.id)})}),e.jsx(bs,{open:r,onOpenChange:a,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Submit a Recruit Referral"})}),e.jsxs("form",{onSubmit:v=>{v.preventDefault(),p.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:v=>l(j=>({...j,first_name:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last Name"}),e.jsx(ye,{value:i.last_name,onChange:v=>l(j=>({...j,last_name:v.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:v=>l(j=>({...j,email:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:i.phone,onChange:v=>l(j=>({...j,phone:v.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Current Brokerage"}),e.jsx(ye,{value:i.current_brokerage,onChange:v=>l(j=>({...j,current_brokerage:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Es,{value:i.notes,onChange:v=>l(j=>({...j,notes:v.target.value})),rows:2})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:p.isPending,children:"Submit"})]})]})]})})]})}function uNt({brokerageId:s}){const{toast:t}=Ba(),n=Ht(),[r,a]=N.useState(!1),{data:i}=ct({queryKey:["brokerage-recruit-form",s],queryFn:async()=>{const{data:p,error:f}=await q.from("brokerages").select("id, name, recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(f)throw f;return p}}),{data:l=[]}=ct({queryKey:["recruit-interest-submissions",s],queryFn:async()=>{const{data:p,error:f}=await q.from("recruit_interest_submissions").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(f)throw f;return p}}),o=gt({mutationFn:async p=>{const{error:f}=await q.from("brokerages").update({recruit_form_enabled:p}).eq("id",s);if(f)throw f},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-recruit-form",s]}),t({title:i!=null&&i.recruit_form_enabled?"Form disabled":"Form enabled"})}}),c=gt({mutationFn:async({id:p,status:f})=>{const{error:g}=await q.from("recruit_interest_submissions").update({status:f}).eq("id",p);if(g)throw g},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-interest-submissions",s]})}),d=`https://bestbrokerage.relevelup.com/join-brokerage/${(i==null?void 0:i.recruit_form_slug)||""}`,u=()=>{navigator.clipboard.writeText(d),a(!0),t({title:"Link copied!"}),setTimeout(()=>a(!1),2e3)},h=p=>p==="contacted"||p==="converted"?"bg-green-500/10 text-green-600":p==="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(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Public Interest Form"})}),e.jsxs(Ee,{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(bn,{checked:(i==null?void 0:i.recruit_form_enabled)||!1,onCheckedChange:p=>o.mutate(p)})]}),(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(Ir,{className:"h-3.5 w-3.5"}):e.jsx(Xr,{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(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"text-base",children:["Interest Submissions (",l.length,")"]})}),e.jsx(Ee,{children:l.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Fo,{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(p=>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:[p.first_name," ",p.last_name]}),e.jsx(ze,{variant:"outline",className:h(p.status),children:p.status})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground",children:[p.email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vs,{className:"h-3 w-3"}),p.email]}),p.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ar,{className:"h-3 w-3"}),p.phone]}),p.current_brokerage&&e.jsxs("span",{children:["From: ",p.current_brokerage]}),p.experience_years&&e.jsxs("span",{children:[p.experience_years,"yr exp"]})]}),p.why_interested&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:['"',p.why_interested,'"']}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:Ss(new Date(p.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(ds,{value:p.status,onValueChange:f=>c.mutate({id:p.id,status:f}),children:[e.jsx(ls,{className:"h-7 text-xs w-[110px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"new",children:"New"}),e.jsx(Qe,{value:"contacted",children:"Contacted"}),e.jsx(Qe,{value:"converted",children:"Converted"}),e.jsx(Qe,{value:"dismissed",children:"Dismissed"})]})]})]},p.id))})})]})]})}function hNt({brokerageId:s}){const{toast:t}=Ba(),n=Ht(),[r,a]=N.useState(!1),[i,l]=N.useState({prospect_id:"",title:"",description:"",due_date:Ss(Bl(new Date,1),"yyyy-MM-dd'T'HH:mm")}),[o,c]=N.useState("pending"),{data:d=[]}=ct({queryKey:["recruit-prospects-list",s],queryFn:async()=>{const{data:T,error:L}=await q.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).order("first_name");if(L)throw L;return T}}),{data:u=[],isLoading:h}=ct({queryKey:["recruit-follow-ups",s],queryFn:async()=>{const T=d.map(M=>M.id);if(!T.length)return[];const{data:L,error:D}=await q.from("recruit_follow_ups").select("*").in("prospect_id",T).order("due_date");if(D)throw D;return L},enabled:d.length>0}),p=Object.fromEntries(d.map(T=>[T.id,T])),f=gt({mutationFn:async T=>{const{data:{user:L}}=await q.auth.getUser();if(!L)throw new Error("Not authenticated");const{error:D}=await q.from("recruit_follow_ups").insert({prospect_id:T.prospect_id,assigned_to:L.id,title:T.title,description:T.description||null,due_date:new Date(T.due_date).toISOString()});if(D)throw D},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-follow-ups",s]}),t({title:"Follow-up scheduled"}),l({prospect_id:"",title:"",description:"",due_date:Ss(Bl(new Date,1),"yyyy-MM-dd'T'HH:mm")}),a(!1)},onError:T=>t({title:"Error",description:T.message,variant:"destructive"})}),g=gt({mutationFn:async({id:T,completed:L})=>{const{error:D}=await q.from("recruit_follow_ups").update({completed_at:L?new Date().toISOString():null}).eq("id",T);if(D)throw D},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-follow-ups",s]})}),_=u.filter(T=>o==="pending"?!T.completed_at:o==="completed"?!!T.completed_at:!0),v=_.filter(T=>!T.completed_at&&ww(new Date(T.due_date))&&!cf(new Date(T.due_date))),j=_.filter(T=>!T.completed_at&&cf(new Date(T.due_date))),b=_.filter(T=>!T.completed_at&&!ww(new Date(T.due_date))&&!cf(new Date(T.due_date))),S=_.filter(T=>!!T.completed_at),A=T=>{const L=p[T.prospect_id],D=!T.completed_at&&ww(new Date(T.due_date))&&!cf(new Date(T.due_date));return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(ui,{checked:!!T.completed_at,onCheckedChange:M=>g.mutate({id:T.id,completed:M}),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm font-medium ${T.completed_at?"line-through text-muted-foreground":""}`,children:T.title}),T.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:T.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[L&&e.jsxs(ze,{variant:"secondary",className:"text-[10px]",children:[L.first_name," ",L.last_name]}),e.jsxs("span",{className:`flex items-center gap-1 ${D?"text-destructive font-medium":""}`,children:[D?e.jsx(Gi,{className:"h-3 w-3"}):e.jsx(yr,{className:"h-3 w-3"}),Ss(new Date(T.due_date),"MMM d, h:mm a")]}),T.is_automated&&e.jsx(ze,{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"&&v.length+j.length+b.length>0&&`(${v.length+j.length+b.length})`]},T))}),e.jsxs(B,{size:"sm",onClick:()=>a(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Follow-up"]})]}),o!=="completed"&&v.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-destructive flex items-center gap-1",children:[e.jsx(Gi,{className:"h-3.5 w-3.5"})," Overdue (",v.length,")"]}),v.map(A)]}),o!=="completed"&&j.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-amber-600 flex items-center gap-1",children:[e.jsx(gr,{className:"h-3.5 w-3.5"})," Today (",j.length,")"]}),j.map(A)]}),o!=="completed"&&b.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(yr,{className:"h-3.5 w-3.5"})," Upcoming (",b.length,")"]}),b.map(A)]}),o!=="pending"&&S.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(Ir,{className:"h-3.5 w-3.5"})," Completed (",S.length,")"]}),S.map(A)]}),_.length===0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-8",children:["No follow-ups ",o!=="all"?`(${o})`:""]}),e.jsx(bs,{open:r,onOpenChange:a,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Schedule Follow-up"})}),e.jsxs("form",{onSubmit:T=>{T.preventDefault(),f.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(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(L=>({...L,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(L=>({...L,title:T.target.value})),placeholder:"e.g. Follow-up call"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Details"}),e.jsx(Es,{value:i.description,onChange:T=>l(L=>({...L,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(L=>({...L,due_date:T.target.value}))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:f.isPending,children:"Schedule"})]})]})]})})]})}const Rtn=[{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 mNt({brokerageId:s}){const{toast:t}=Ba(),n=Ht(),[r,a]=N.useState(null),{data:i,isLoading:l}=ct({queryKey:["recruit-landing-settings",s],queryFn:async()=>{const{data:v,error:j}=await q.from("recruit_landing_page_settings").select("*").eq("brokerage_id",s).maybeSingle();if(j)throw j;return v}}),[o,c]=N.useState({brokerage_id:s,hero_headline:"Join Our Team",hero_subtext:"Take your real estate career to the next level.",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",benefits:Rtn,testimonials:[],gallery_images:[],calculator_enabled:!1,calculator_config:{headline:"See What You Could Earn With Us",subtext:"Confidential 60-second calculator — no signup required.",commission_split_pct:80,cap_amount:16e3,post_cap_split_pct:100,monthly_fee:99,transaction_fee:0,show_email_capture:!0,email_capture_label:"Want the full breakdown? Enter your email."},lead_magnet_enabled:!1,lead_magnet_config:{title:"Get the Full Comp Plan PDF",description:"See exactly how splits, caps, and fees work — no call required.",button_text:"Email Me the PDF",pdf_url:null},form_style:"classic",confidential_messaging:!0});N.useEffect(()=>{i&&c({id:i.id,brokerage_id:i.brokerage_id,hero_headline:i.hero_headline,hero_subtext:i.hero_subtext||"",hero_image_url:i.hero_image_url,logo_url:i.logo_url,primary_color:i.primary_color,accent_color:i.accent_color,benefits:i.benefits||[],testimonials:i.testimonials||[],gallery_images:i.gallery_images||[],calculator_enabled:i.calculator_enabled??!1,calculator_config:i.calculator_config||{},lead_magnet_enabled:i.lead_magnet_enabled??!1,lead_magnet_config:i.lead_magnet_config||{},form_style:i.form_style||"classic",confidential_messaging:i.confidential_messaging??!0})},[i]);const d=gt({mutationFn:async()=>{const v={brokerage_id:s,hero_headline:o.hero_headline,hero_subtext:o.hero_subtext,hero_image_url:o.hero_image_url,logo_url:o.logo_url,primary_color:o.primary_color,accent_color:o.accent_color,benefits:JSON.parse(JSON.stringify(o.benefits)),testimonials:JSON.parse(JSON.stringify(o.testimonials)),gallery_images:JSON.parse(JSON.stringify(o.gallery_images)),calculator_enabled:o.calculator_enabled,calculator_config:JSON.parse(JSON.stringify(o.calculator_config)),lead_magnet_enabled:o.lead_magnet_enabled,lead_magnet_config:JSON.parse(JSON.stringify(o.lead_magnet_config)),form_style:o.form_style,confidential_messaging:o.confidential_messaging,updated_at:new Date().toISOString()};if(o.id){const{error:j}=await q.from("recruit_landing_page_settings").update(v).eq("id",o.id);if(j)throw j}else{const{error:j}=await q.from("recruit_landing_page_settings").insert(v);if(j)throw j}},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-landing-settings",s]}),t({title:"Landing page saved!"})},onError:v=>t({title:"Error",description:v.message,variant:"destructive"})}),u=async(v,j)=>{const b=v.name.split(".").pop(),S=`${s}/${j}-${Date.now()}.${b}`,{error:A}=await q.storage.from("recruit-landing").upload(S,v);if(A)throw A;const{data:{publicUrl:T}}=q.storage.from("recruit-landing").getPublicUrl(S);return T},h=async(v,j)=>{var S;const b=(S=v.target.files)==null?void 0:S[0];if(b){a(j);try{const A=await u(b,j);c(T=>({...T,[j]:A})),t({title:"Image uploaded!"})}catch(A){t({title:"Upload failed",description:A.message,variant:"destructive"})}finally{a(null)}}},p=async v=>{var b;const j=(b=v.target.files)==null?void 0:b[0];if(j){a("gallery");try{const S=await u(j,"gallery");c(A=>({...A,gallery_images:[...A.gallery_images,S]})),t({title:"Gallery image added!"})}catch(S){t({title:"Upload failed",description:S.message,variant:"destructive"})}finally{a(null)}}},f=async(v,j)=>{var S;const b=(S=v.target.files)==null?void 0:S[0];if(b){a(`testimonial-${j}`);try{const A=await u(b,`testimonial-${j}`);c(T=>{const L=[...T.testimonials];return L[j]={...L[j],photo_url:A},{...T,testimonials:L}})}catch(A){t({title:"Upload failed",description:A.message,variant:"destructive"})}finally{a(null)}}},{data:g}=ct({queryKey:["brokerage-slug-for-landing",s],queryFn:async()=>{const{data:v,error:j}=await q.from("brokerages").select("recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(j)throw j;return v}}),_=`https://bestbrokerage.relevelup.com/join-brokerage/${(g==null?void 0:g.recruit_form_slug)||""}`;return l?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[(g==null?void 0:g.recruit_form_enabled)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 rounded-lg border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Live page:"}),e.jsx("code",{className:"text-xs flex-1 truncate",children:_}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:_,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Branding"})}),e.jsx(Ee,{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(Na,{className:"h-3.5 w-3.5 mr-1"}),r==="logo_url"?"Uploading...":"Upload Logo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:v=>h(v,"logo_url")})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(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:v=>c(j=>({...j,primary_color:v.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ye,{value:o.primary_color,onChange:v=>c(j=>({...j,primary_color:v.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:v=>c(j=>({...j,accent_color:v.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ye,{value:o.accent_color,onChange:v=>c(j=>({...j,accent_color:v.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Hero Section"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Headline"}),e.jsx(ye,{value:o.hero_headline,onChange:v=>c(j=>({...j,hero_headline:v.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Subtext"}),e.jsx(Es,{value:o.hero_subtext,onChange:v=>c(j=>({...j,hero_subtext:v.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(Na,{className:"h-3.5 w-3.5 mr-1"}),r==="hero_image_url"?"Uploading...":"Upload Image"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:v=>h(v,"hero_image_url")})]}),o.hero_image_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(v=>({...v,hero_image_url:null})),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(It,{className:"text-base",children:"Benefits / Why Join Us"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(v=>({...v,benefits:[...v.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Ee,{className:"space-y-3",children:[o.benefits.map((v,j)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Fu,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(ye,{value:v.icon,onChange:b=>{const S=[...o.benefits];S[j]={...v,icon:b.target.value},c(A=>({...A,benefits:S}))},className:"w-14 text-center"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(ye,{value:v.title,onChange:b=>{const S=[...o.benefits];S[j]={...v,title:b.target.value},c(A=>({...A,benefits:S}))},placeholder:"Benefit title"}),e.jsx(ye,{value:v.description,onChange:b=>{const S=[...o.benefits];S[j]={...v,description:b.target.value},c(A=>({...A,benefits:S}))},placeholder:"Short description"})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(b=>({...b,benefits:b.benefits.filter((S,A)=>A!==j)})),children:e.jsx(_n,{className:"h-3.5 w-3.5 text-destructive"})})]},j)),o.benefits.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No benefits added yet"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(It,{className:"text-base",children:"Testimonials"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(v=>({...v,testimonials:[...v.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Ee,{className:"space-y-3",children:[o.testimonials.map((v,j)=>{var b;return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[v.photo_url?e.jsx("img",{src:v.photo_url,alt:v.name,className:"h-10 w-10 rounded-full object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded-full bg-muted flex items-center justify-center text-xs text-muted-foreground",children:((b=v.name)==null?void 0:b[0])||"?"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("span",{className:"text-[10px] text-primary hover:underline",children:r===`testimonial-${j}`?"...":"Photo"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:S=>f(S,j)})]})]}),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:v.name,onChange:S=>{const A=[...o.testimonials];A[j]={...v,name:S.target.value},c(T=>({...T,testimonials:A}))},placeholder:"Name"}),e.jsx(ye,{value:v.role,onChange:S=>{const A=[...o.testimonials];A[j]={...v,role:S.target.value},c(T=>({...T,testimonials:A}))},placeholder:"Role / Title"})]}),e.jsx(Es,{value:v.quote,onChange:S=>{const A=[...o.testimonials];A[j]={...v,quote:S.target.value},c(T=>({...T,testimonials:A}))},placeholder:"What they say about working here...",rows:2})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(S=>({...S,testimonials:S.testimonials.filter((A,T)=>T!==j)})),children:e.jsx(_n,{className:"h-3.5 w-3.5 text-destructive"})})]},j)}),o.testimonials.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No testimonials added yet"})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(It,{className:"text-base",children:"Team & Culture Gallery"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{size:"sm",variant:"outline",asChild:!0,disabled:r==="gallery",children:e.jsxs("span",{children:[e.jsx(nl,{className:"h-3.5 w-3.5 mr-1"}),r==="gallery"?"Uploading...":"Add Photo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:p})]})]}),e.jsx(Ee,{children:o.gallery_images.length>0?e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:o.gallery_images.map((v,j)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:v,alt:`Gallery ${j+1}`,className:"h-24 w-full object-cover rounded-lg"}),e.jsx(B,{variant:"destructive",size:"sm",className:"absolute top-1 right-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>c(b=>({...b,gallery_images:b.gallery_images.filter((S,A)=>A!==j)})),children:e.jsx(_n,{className:"h-3 w-3"})})]},j))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No gallery images added yet"})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Application Form Style"}),e.jsxs(ds,{value:o.form_style,onValueChange:v=>c(j=>({...j,form_style:v})),children:[e.jsx(ls,{className:"mt-1.5",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"classic",children:"Classic — single-page form (all fields visible)"}),e.jsx(Qe,{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(Kc,{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(bn,{checked:o.confidential_messaging,onCheckedChange:v=>c(j=>({...j,confidential_messaging:v}))})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(fw,{className:"h-4 w-4 text-primary"})," Split & Income Calculator"]}),e.jsx(bn,{checked:o.calculator_enabled,onCheckedChange:v=>c(j=>({...j,calculator_enabled:v}))})]}),o.calculator_enabled&&e.jsxs(Ee,{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:v=>c(j=>({...j,calculator_config:{...j.calculator_config,headline:v.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:v=>c(j=>({...j,calculator_config:{...j.calculator_config,subtext:v.target.value}})),placeholder:"Confidential 60-second calculator"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Pre-Cap Split % (agent keeps)"}),e.jsx(ye,{type:"number",value:o.calculator_config.commission_split_pct??80,onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,commission_split_pct:parseFloat(v.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 80 for an 80/20"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Cap Amount ($)"}),e.jsx(ye,{type:"number",value:o.calculator_config.cap_amount??16e3,onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,cap_amount:parseFloat(v.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Annual cap to brokerage"})]}),e.jsxs("div",{children:[e.jsx(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:v=>c(j=>({...j,calculator_config:{...j.calculator_config,post_cap_split_pct:parseFloat(v.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 95 for 95/5 after cap, 100 for 100%"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Monthly Fee ($)"}),e.jsx(ye,{type:"number",value:o.calculator_config.monthly_fee??99,onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,monthly_fee:parseFloat(v.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:v=>c(j=>({...j,calculator_config:{...j.calculator_config,transaction_fee:parseFloat(v.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Multiplied by # of transactions"})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{children:[e.jsx(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(bn,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,show_email_capture:v}}))})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(CA,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(bn,{checked:o.lead_magnet_enabled,onCheckedChange:v=>c(j=>({...j,lead_magnet_enabled:v}))})]}),o.lead_magnet_enabled&&e.jsxs(Ee,{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:v=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,title:v.target.value}})),placeholder:"Get the Full Comp Plan PDF"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Description"}),e.jsx(Es,{rows:2,value:o.lead_magnet_config.description||"",onChange:v=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,description:v.target.value}})),placeholder:"See exactly how splits, caps, and fees work..."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Button Text"}),e.jsx(ye,{value:o.lead_magnet_config.button_text||"",onChange:v=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,button_text:v.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:v=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,pdf_url:v.target.value||null}})),placeholder:"https://...",className:"flex-1"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:r==="lead_magnet_pdf",children:e.jsxs("span",{children:[e.jsx(Na,{className:"h-3.5 w-3.5 mr-1"}),r==="lead_magnet_pdf"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"application/pdf,.pdf,.doc,.docx",className:"hidden",onChange:async v=>{var b;const j=(b=v.target.files)==null?void 0:b[0];if(j){a("lead_magnet_pdf");try{const S=await u(j,"lead-magnet");c(A=>({...A,lead_magnet_config:{...A.lead_magnet_config,pdf_url:S}})),t({title:"PDF uploaded!"})}catch(S){t({title:"Upload failed",description:S.message,variant:"destructive"})}finally{a(null)}}}})]})]})]})]})]})]}),e.jsx(Otn,{brokerageId:s}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:()=>d.mutate(),disabled:d.isPending,size:"lg",children:[e.jsx(qo,{className:"h-4 w-4 mr-2"}),d.isPending?"Saving...":"Save Landing Page"]})})]})}function Otn({brokerageId:s}){const{data:t=[]}=ct({queryKey:["lead-magnet-downloads",s],queryFn:async()=>{const{data:n,error:r}=await q.from("recruit_lead_magnet_downloads").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(100);if(r)throw r;return n}});return t.length===0?null:e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Pa,{className:"h-4 w-4 text-primary"})," Lead Magnet Downloads (",t.length,")"]})}),e.jsx(Ee,{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:[Ss(new Date(n.created_at),"MMM d, yyyy h:mm a")," · via ",n.source]})]})},n.id))})})]})}function pNt({brokerageId:s,trigger:t,initialProspectId:n,open:r,onOpenChange:a}){const[i,l]=N.useState(!1),o=r??i,c=a??l,[d,u]=N.useState("pick-recipients"),[h,p]=N.useState(new Set(n?[n]:[])),[f,g]=N.useState("all"),[_,v]=N.useState(""),[j,b]=N.useState(null),[S,A]=N.useState(""),[T,L]=N.useState(0),[D,M]=N.useState(0),[F,z]=N.useState(""),[V,W]=N.useState(""),{data:Y}=obe(),[K,J]=N.useState("default");N.useEffect(()=>{J(Y!=null&&Y.massEmail?"mass_email":Y!=null&&Y.gmail?"gmail":"default")},[Y==null?void 0:Y.massEmail,Y==null?void 0:Y.gmail]);const[ne,ie]=N.useState(null),{prospects:he,stages:ce}=ZU(s),pe=tNt(),le=IN(),{data:ve=[]}=ct({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:be,error:Ze}=await q.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, created_at, owner_user_id, share_token").eq("touch_type","recruiting").eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(Ze)throw Ze;return be??[]},enabled:o&&d==="pick-video"}),ge=N.useCallback(()=>{u("pick-recipients"),p(new Set(n?[n]:[])),g("all"),v(""),b(null),A(""),L(0),M(0),z(""),W(""),J("default"),ie(null)},[n]),Te=be=>{!be&&(d==="uploading"||d==="processing"||d==="sending")||(c(be),be||setTimeout(ge,200))},Me=N.useMemo(()=>he.filter(be=>{if(!be.email||f!=="all"&&be.stage_id!==f)return!1;if(_){const Ze=_.toLowerCase();if(!`${be.first_name} ${be.last_name??""}`.toLowerCase().includes(Ze)&&!be.email.toLowerCase().includes(Ze))return!1}return!0}),[he,f,_]),Ce=be=>{p(Ze=>{const Ne=new Set(Ze);return Ne.has(be)?Ne.delete(be):Ne.add(be),Ne})},Ae=()=>{h.size===Me.length?p(new Set):p(new Set(Me.map(be=>be.id)))},De=N.useCallback(async(be,Ze)=>{u("uploading");try{const Ne=`Recruiting blast (${h.size} recipients)`,{videoId:it,libraryId:je}=await i6(Ne),{uploadUrl:Ge,apiKey:Be}=await o6(it),Ye=new XMLHttpRequest;Ye.upload.onprogress=vt=>{vt.lengthComputable&&L(vt.loaded/vt.total*100)},await new Promise((vt,Bt)=>{Ye.onload=()=>Ye.status>=200&&Ye.status<300?vt():Bt(new Error("Upload failed")),Ye.onerror=()=>Bt(new Error("Upload failed")),Ye.open("PUT",Ge),Ye.setRequestHeader("AccessKey",Be),Ye.send(be)}),u("processing");const We=`https://iframe.mediadelivery.net/embed/${je}/${it}`;let rt=0;const tt=Date.now(),at=9e4;for(;rt<4&&(await new Promise(Bt=>setTimeout(Bt,3e3)),!(Date.now()-tt>at));){const vt=await $w(it);if(rt=vt.status,M(vt.encodeProgress||0),rt===5||rt===6)throw new Error("Video processing failed")}const He=await $w(it),dt=(He.storageSize||be.size)/(1024*1024),bt=await le.mutateAsync({bunny_video_id:it,playback_url:He.directPlayUrl||We,thumbnail_url:He.thumbnailUrl,preview_url:He.previewUrl||null,duration_seconds:He.length||Ze,file_size_mb:dt,title:Ne,status:rt>=4?"ready":"processing",touch_type:"recruiting"});b(bt.id),A(Ne),u("compose")}catch(Ne){ae.error((Ne==null?void 0:Ne.message)||"Failed to upload video"),u("pick-video")}},[h.size,le]),Ie=N.useCallback(async()=>{if(!(!j||h.size===0)){u("sending");try{const be=[];for(const it of h){const je=await pe.mutateAsync({prospect_id:it,video_id:j,brokerage_id:s,message:V||void 0});be.push(je.id)}const{data:Ze,error:Ne}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:be,brokerage_id:s,subject_override:F||void 0,message_override:V||void 0,send_via:K}});if(Ne)throw new Error(Ne.message);ie({sent:(Ze==null?void 0:Ze.sent)??0,total:(Ze==null?void 0:Ze.total)??be.length}),u("done"),ae.success(`Sent ${(Ze==null?void 0:Ze.sent)??0} of ${(Ze==null?void 0:Ze.total)??be.length} videos`)}catch(be){ae.error((be==null?void 0:be.message)||"Failed to send"),u("compose")}}},[j,h,s,V,F,K,pe]),Fe=h.size,qe=he.filter(be=>!be.email).length;return e.jsxs(bs,{open:o,onOpenChange:Te,children:[t&&e.jsx(Ai,{asChild:!0,children:t}),e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(br,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",Fe>0&&e.jsxs(ze,{variant:"secondary",className:"ml-2",children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),Fe," ",Fe===1?"recipient":"recipients"]})]})}),d==="pick-recipients"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search prospects...",value:_,onChange:be=>v(be.target.value),className:"pl-9"})]}),e.jsxs(ds,{value:f,onValueChange:g,children:[e.jsx(ls,{className:"w-48",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All stages"}),ce.map(be=>e.jsx(Qe,{value:be.id,children:be.name},be.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("button",{onClick:Ae,className:"hover:underline",children:[h.size===Me.length&&Me.length>0?"Deselect all":"Select all"," ","(",Me.length,")"]}),qe>0&&e.jsxs("span",{children:[qe," prospect(s) hidden — no email on file"]})]}),e.jsx(hi,{className:"flex-1 border rounded-md",children:Me.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"No prospects match. Make sure prospects have email addresses."}):e.jsx("div",{className:"divide-y",children:Me.map(be=>{const Ze=h.has(be.id),Ne=ce.find(it=>it.id===be.stage_id);return e.jsxs("label",{className:"flex items-center gap-3 p-3 hover:bg-muted/30 cursor-pointer",children:[e.jsx(ui,{checked:Ze,onCheckedChange:()=>Ce(be.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:[be.first_name," ",be.last_name]}),Ne&&e.jsx(ze,{variant:"outline",className:"text-[10px]",style:{borderColor:Ne.color,color:Ne.color},children:Ne.name})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[be.email," ",be.current_brokerage&&`· ${be.current_brokerage}`]})]})]},be.id)})})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Te(!1),children:"Cancel"}),e.jsx(B,{disabled:Fe===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(Br,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(Fr,{className:"self-start",children:[e.jsxs(Kt,{value:"record",children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(Kt,{value:"library",children:[e.jsx(Hg,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(is,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(Ah,{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 ",Fe," ",Fe===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs(B,{onClick:()=>u("record"),children:[e.jsx(br,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(is,{value:"library",className:"flex-1 overflow-auto",children:ve.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:ve.map(be=>e.jsxs("button",{onClick:()=>{b(be.id),A(be.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:lw(be)?e.jsx("img",{src:lw(be),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(br,{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:be.title||"Untitled"})})]},be.id))})})]}),e.jsx(Xn,{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(u6,{maxDurationSeconds:600,onRecordingComplete:De}),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(ts,{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(pi,{value:d==="uploading"?T:D,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(d==="uploading"?T:D),"%"]})]}),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(xr,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("span",{className:"font-medium",children:S})," selected · sending to ",e.jsx("strong",{children:Fe})," recipient",Fe===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(ye,{value:F,onChange:be=>z(be.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(Es,{value:V,onChange:be=>W(be.target.value),placeholder:"Hey there — wanted to share a quick thought on what we're building here...",rows:5,className:"mt-1"})]}),e.jsx(C8e,{value:K,onChange:J}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>u("pick-video"),children:"Back"}),e.jsxs(B,{onClick:Ie,disabled:!j||Fe===0,children:[e.jsx(cr,{className:"h-4 w-4 mr-2"})," Send to ",Fe," ",Fe===1?"prospect":"prospects"]})]})]}),d==="sending"&&e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx(ts,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending to ",Fe," recipient",Fe===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&ne&&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 ${ne.sent===ne.total?"bg-primary/10":"bg-muted"}`,children:ne.sent===ne.total?e.jsx(xr,{className:"h-8 w-8 text-primary"}):e.jsx(Gi,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-lg",children:[ne.sent," of ",ne.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:()=>Te(!1),children:"Done"})]})]})]})}function Ftn(s){if(!s)return"—";const t=Math.floor(s/60),n=s%60;return t>0?`${t}m ${n}s`:`${n}s`}function ztn({video:s}){return s.cta_clicked_at?e.jsx(ze,{className:"bg-emerald-500/10 text-emerald-600 border-emerald-200",children:"CTA Clicked"}):s.view_count>0?e.jsxs(ze,{className:"bg-blue-500/10 text-blue-600 border-blue-200",children:[e.jsx(Er,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs(ze,{variant:"secondary",children:[e.jsx(cr,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs(ze,{variant:"outline",children:[e.jsx(gr,{className:"h-3 w-3 mr-1"}),"Draft"]})}function fNt({brokerageId:s}){var S,A,T,L;const{data:t=[],isLoading:n}=Stn(s),{data:r=[]}=nNt(s),a=Ttn(),i=Etn(),l=sNt(),[o,c]=N.useState(""),[d,u]=N.useState(!1),[h,p]=N.useState({title:"",script_text:"",category:"general"}),[f,g]=N.useState(null),_=t.filter(D=>{var F,z,V,W;return o?`${((F=D.prospect)==null?void 0:F.first_name)||""} ${((z=D.prospect)==null?void 0:z.last_name)||""}`.toLowerCase().includes(o.toLowerCase())||((W=(V=D.video)==null?void 0:V.title)==null?void 0:W.toLowerCase().includes(o.toLowerCase())):!0}),v={total:t.length,sent:t.filter(D=>D.sent_at).length,viewed:t.filter(D=>D.view_count>0).length,ctaClicked:t.filter(D=>D.cta_clicked_at).length},j=N.useCallback(D=>{if(!D)return;const M=`${window.location.origin}/recruit-video/${D}`;navigator.clipboard.writeText(M),ae.success("Share link copied")},[]);N.useCallback((D,M)=>{l.mutate({id:D,sent_via:M})},[l]);const b=()=>{!h.title.trim()||!h.script_text.trim()||a.mutate({brokerage_id:s,...h},{onSuccess:()=>{p({title:"",script_text:"",category:"general"}),u(!1)}})};return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[{label:"Total Videos",value:v.total,icon:br,color:"text-primary"},{label:"Sent",value:v.sent,icon:cr,color:"text-blue-500"},{label:"Viewed",value:v.viewed,icon:Er,color:"text-amber-500"},{label:"CTA Clicked",value:v.ctaClicked,icon:xr,color:"text-emerald-500"}].map(D=>e.jsx(fe,{children:e.jsxs(Ee,{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 ${D.color}`,children:e.jsx(D.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:D.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:D.label})]})]})},D.label))}),e.jsxs(Br,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(Fr,{children:[e.jsxs(Kt,{value:"videos",children:[e.jsx(br,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(Kt,{value:"scripts",children:[e.jsx(Nr,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(Kt,{value:"analytics",children:[e.jsx(yo,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(is,{value:"videos",children:e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(It,{className:"text-lg",children:"Video Outreach"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-64",children:[e.jsx(vr,{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:D=>c(D.target.value),className:"pl-9"})]}),e.jsx(pNt,{brokerageId:s,trigger:e.jsxs(B,{size:"sm",className:"gap-1.5",children:[e.jsx(Vs,{className:"h-4 w-4"})," Send Video Email"]})})]})]})}),e.jsx(Ee,{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"})}):_.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(br,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No 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:_.map(D=>{var M,F,z,V,W,Y,K;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:[lw(D.video)?e.jsx("img",{src:lw(D.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(br,{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:Ftn(((M=D.video)==null?void 0:M.duration_seconds)??null)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium truncate",children:[(F=D.prospect)==null?void 0:F.first_name," ",(z=D.prospect)==null?void 0:z.last_name]}),e.jsx(ztn,{video:D})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:((V=D.video)==null?void 0:V.title)||"Untitled video"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Ss(new Date(D.created_at),"MMM d, yyyy"),((W=D.prospect)==null?void 0:W.current_brokerage)&&` · ${D.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:()=>j(D.share_token),title:"Copy share link",children:e.jsx(Xr,{className:"h-4 w-4"})}),e.jsxs(B,{variant:D.sent_at?"ghost":"default",size:"sm",className:"h-8 gap-1.5",onClick:()=>g(D),disabled:!((Y=D.prospect)!=null&&Y.email),title:(K=D.prospect)!=null&&K.email?"Email this video to the prospect":"Prospect has no email",children:[e.jsx(Vs,{className:"h-4 w-4"}),D.sent_at?"Resend":"Email"]}),D.share_token&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>window.open(`/recruit-video/${D.share_token}`,"_blank"),title:"Preview landing page",children:e.jsx(tr,{className:"h-4 w-4"})})]})]},D.id)})})})]})}),e.jsx(is,{value:"scripts",children:e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(It,{className:"text-lg",children:"Recruiting Scripts"}),e.jsxs(bs,{open:d,onOpenChange:u,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{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:D=>p(M=>({...M,title:D.target.value})),placeholder:"e.g., Why Switch to Our Brokerage"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Category"}),e.jsxs(ds,{value:h.category,onValueChange:D=>p(M=>({...M,category:D})),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:CTe.map(D=>e.jsx(Qe,{value:D.value,children:D.label},D.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Script"}),e.jsx(Es,{value:h.script_text,onChange:D=>p(M=>({...M,script_text:D.target.value})),placeholder:"Hi [Name], I noticed you've been doing great work at [Brokerage]...",rows:8})]}),e.jsx(B,{onClick:b,disabled:!h.title.trim()||!h.script_text.trim(),className:"w-full",children:"Save Script"})]})]})]})]})}),e.jsx(Ee,{children:r.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Nr,{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(D=>{var F;const M=((F=CTe.find(z=>z.value===D.category))==null?void 0:F.label)||D.category;return e.jsx(fe,{className:"relative group",children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(ze,{variant:"outline",className:"text-[10px] mb-2",children:M}),e.jsx("h4",{className:"font-medium text-sm",children:D.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(D.id),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-3",children:D.script_text}),D.is_global&&e.jsx(ze,{variant:"secondary",className:"mt-2 text-[10px]",children:"Template"})]})},D.id)})})})]})}),e.jsx(is,{value:"analytics",children:e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-lg",children:"Engagement Funnel"})}),e.jsxs(Ee,{children:[e.jsx("div",{className:"space-y-4",children:[{label:"Videos Created",count:v.total,pct:100,color:"bg-primary"},{label:"Sent to Prospects",count:v.sent,pct:v.total?Math.round(v.sent/v.total*100):0,color:"bg-blue-500"},{label:"Viewed by Prospect",count:v.viewed,pct:v.sent?Math.round(v.viewed/v.sent*100):0,color:"bg-amber-500"},{label:"CTA Clicked",count:v.ctaClicked,pct:v.viewed?Math.round(v.ctaClicked/v.viewed*100):0,color:"bg-emerald-500"}].map(D=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:D.label}),e.jsxs("span",{className:"font-medium",children:[D.count," (",D.pct,"%)"]})]}),e.jsx("div",{className:"h-3 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${D.color} rounded-full transition-all`,style:{width:`${D.pct}%`}})})]},D.label))}),t.filter(D=>D.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(D=>D.view_count>0).sort((D,M)=>M.view_count-D.view_count).slice(0,5).map(D=>{var M,F;return e.jsxs("div",{className:"flex items-center justify-between text-sm p-2 rounded-md bg-muted/30",children:[e.jsxs("span",{className:"font-medium",children:[(M=D.prospect)==null?void 0:M.first_name," ",(F=D.prospect)==null?void 0:F.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(Er,{className:"h-3.5 w-3.5"})," ",D.view_count]}),D.cta_clicked_at&&e.jsx(xr,{className:"h-4 w-4 text-emerald-500"})]})]},D.id)})})]})]})]})})]}),f&&e.jsx(eNt,{open:!!f,onOpenChange:D=>{D||g(null)},recruitVideoId:f.id,brokerageId:s,prospectName:`${((S=f.prospect)==null?void 0:S.first_name)||""} ${((A=f.prospect)==null?void 0:A.last_name)||""}`.trim(),prospectEmail:(T=f.prospect)==null?void 0:T.email,videoTitle:(L=f.video)==null?void 0:L.title,defaultMessage:f.message})]})}function xNt({brokerageId:s}){const{toast:t}=Ba(),n=Ht(),{stages:r,prospects:a}=ZU(s),[i,l]=N.useState(!1),[o,c]=N.useState({title:"",target_count:"10",target_stage_id:"",period_start:Ss(new Date,"yyyy-MM-dd"),period_end:Ss(new Date(new Date().getFullYear(),new Date().getMonth()+3,0),"yyyy-MM-dd")}),{data:d=[],isLoading:u}=ct({queryKey:["recruit-goals",s],queryFn:async()=>{const{data:g,error:_}=await q.from("recruit_goals").select("*").eq("brokerage_id",s).order("period_end",{ascending:!1});if(_)throw _;return g}}),h=gt({mutationFn:async g=>{const{data:{user:_}}=await q.auth.getUser();if(!_)throw new Error("Not authenticated");const{error:v}=await q.from("recruit_goals").insert({brokerage_id:s,title:g.title,target_count:parseInt(g.target_count),target_stage_id:g.target_stage_id||null,period_start:g.period_start,period_end:g.period_end,created_by:_.id});if(v)throw v},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:g=>t({title:"Error",description:g.message,variant:"destructive"})}),p=gt({mutationFn:async g=>{const{error:_}=await q.from("recruit_goals").delete().eq("id",g);if(_)throw _},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal removed"})}}),f=g=>{const _=r.find(j=>j.id===g.target_stage_id);return{count:a.filter(j=>Z1(new Date(j.created_at),{start:new Date(g.period_start),end:new Date(g.period_end)})?g.target_stage_id?j.stage_id===g.target_stage_id:!0:!1).length,stage:_}};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(Is,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(fe,{className:"py-12 text-center",children:[e.jsx(Oc,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No goals set. Create a recruiting target to track progress."})]}):e.jsx("div",{className:"grid md:grid-cols-2 gap-4",children:d.map(g=>{const{count:_,stage:v}=f(g),j=Math.min(100,_/g.target_count*100),b=Z1(new Date,{start:new Date(g.period_start),end:new Date(g.period_end)});return e.jsxs(fe,{className:b?"":"opacity-60",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{className:"text-sm",children:g.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Ss(new Date(g.period_start),"MMM d")," – ",Ss(new Date(g.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[b?e.jsx(ze,{className:"text-[10px]",children:"Active"}):e.jsx(ze,{variant:"secondary",className:"text-[10px]",children:"Ended"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground",onClick:()=>p.mutate(g.id),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Ee,{className:"space-y-2",children:[v&&e.jsxs(ze,{variant:"outline",className:"text-[10px]",style:{borderColor:v.color,color:v.color},children:["Stage: ",v.name]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-bold text-lg",children:_}),e.jsxs("span",{className:"text-muted-foreground",children:["/ ",g.target_count]})]}),e.jsx(pi,{value:j,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[j.toFixed(0),"% complete"]})]})]},g.id)})}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Create Recruiting Goal"})}),e.jsxs("form",{onSubmit:g=>{g.preventDefault(),h.mutate(o)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Goal Title *"}),e.jsx(ye,{required:!0,value:o.title,onChange:g=>c(_=>({..._,title:g.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:g=>c(_=>({..._,target_count:g.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:g=>c(_=>({..._,target_stage_id:g.target.value})),children:[e.jsx("option",{value:"",children:"All stages (total prospects)"}),r.map(g=>e.jsx("option",{value:g.id,children:g.name},g.id))]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Count prospects that reach this stage"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Start Date"}),e.jsx(ye,{type:"date",required:!0,value:o.period_start,onChange:g=>c(_=>({..._,period_start:g.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"End Date"}),e.jsx(ye,{type:"date",required:!0,value:o.period_end,onChange:g=>c(_=>({..._,period_end:g.target.value}))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:h.isPending,children:"Create Goal"})]})]})]})})]})}const Btn={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function gNt({email:s,mergeValues:t=Btn,selectedSubjectIndex:n,onClose:r}){var c;const a=d=>d.replace(/\{\{first_name\}\}/g,t.first_name).replace(/\{\{brokerage_name\}\}/g,t.brokerage_name).replace(/\{\{city\}\}/g,t.city).replace(/\{\{sender_name\}\}/g,t.sender_name).replace(/\{\{landing_page_link\}\}/g,"https://bestbrokerage.relevelup.com/join-brokerage/your-slug"),i=((c=s.subject_line_options)==null?void 0:c.length)>0?s.subject_line_options:[s.subject_line],l=n??0,o=i[l]||s.subject_line;return e.jsx(bs,{open:!0,onOpenChange:()=>r(),children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto p-0",children:[e.jsxs(ws,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(_s,{className:"text-base",children:["Email #",s.email_number," — ",s.title]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsxs(ze,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),s.email_number===1?"Sent immediately":`Day ${s.delay_days}`]}),i.length>1&&e.jsxs(ze,{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 T8e({brokerageId:s}){const t=Ht(),{user:n}=ys(),[r,a]=N.useState(""),[i,l]=N.useState(!1),[o,c]=N.useState({brokerage_id:s,sender_name:"LevelUp",sender_email:"recruiting@relevelup.com",reply_to_email:"",merge_fields:{city:"",broker_name:""}}),{data:d}=ct({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:g,error:_}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(_)throw _;return g}}),{data:u}=ct({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:g,error:_}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(_)throw _;return g}});N.useEffect(()=>{d?c({...d,merge_fields:d.merge_fields||{city:"",broker_name:""}}):u&&c(g=>({...g,merge_fields:{...g.merge_fields,brokerage_name:u.name,city:u.city||""}}))},[d,u]),N.useEffect(()=>{n!=null&&n.id&&q.from("profiles").select("recruit_cta_url").eq("id",n.id).single().then(({data:g})=>a((g==null?void 0:g.recruit_cta_url)||""))},[n==null?void 0:n.id]);const h=async()=>{if(!(n!=null&&n.id))return;l(!0);const{error:g}=await q.from("profiles").update({recruit_cta_url:r.trim()||null}).eq("id",n.id);l(!1),g?ae.error(g.message):ae.success("Scheduling link saved!")},p=gt({mutationFn:async()=>{const g={brokerage_id:s,sender_name:o.sender_name,sender_email:o.sender_email,reply_to_email:o.reply_to_email||null,merge_fields:o.merge_fields,updated_at:new Date().toISOString()};if(d!=null&&d.id){const{error:_}=await q.from("brokerage_recruit_settings").update(g).eq("id",d.id);if(_)throw _}else{const{error:_}=await q.from("brokerage_recruit_settings").insert(g);if(_)throw _}},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-recruit-settings",s]}),ae.success("Recruiting email settings saved!")},onError:g=>ae.error(g.message)}),f=(g,_)=>{c(v=>({...v,merge_fields:{...v.merge_fields,[g]:_}}))};return e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure the sender identity and merge fields for recruiting emails sent to this brokerage's prospects."}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yr,{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:g=>a(g.target.value),placeholder:"https://calendly.com/your-name/intro"}),e.jsxs(B,{onClick:h,disabled:i,size:"sm",children:[e.jsx(qo,{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:g=>c({...o,sender_name:g.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:g=>c({...o,sender_email:g.target.value}),placeholder:"recruiting@relevelup.com"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Must be a verified SES identity. Verify your own address below to send from it."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Reply-To Email (optional)"}),e.jsx(ye,{value:o.reply_to_email,onChange:g=>c({...o,reply_to_email:g.target.value}),placeholder:"jeremy@relevelup.com"})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(sg,{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(W2t,{brokerageId:s,onVerifiedSelect:g=>{c(_=>({..._,sender_email:g})),ae.success(`Sender set to ${g}`)}})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Default Merge Fields"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"These values will auto-fill in campaign emails for this brokerage."}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"{{brokerage_name}}"}),e.jsx(ye,{value:o.merge_fields.brokerage_name||"",onChange:g=>f("brokerage_name",g.target.value),placeholder:(u==null?void 0:u.name)||"Brokerage Name"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"{{city}}"}),e.jsx(ye,{value:o.merge_fields.city||"",onChange:g=>f("city",g.target.value),placeholder:"e.g. Austin"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"{{sender_name}}"}),e.jsx(ye,{value:o.merge_fields.sender_name||"",onChange:g=>f("sender_name",g.target.value),placeholder:"e.g. Jeremy"})]})]})]}),e.jsxs(B,{onClick:()=>p.mutate(),disabled:p.isPending,className:"w-full",children:[e.jsx(qo,{className:"h-4 w-4 mr-1"})," Save Settings"]})]})}const $tn=Eb.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",mu(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()}}}),EXe=[{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 Qp({onClick:s,active:t,disabled:n,icon:r,tooltip:a}){return e.jsxs(Ec,{children:[e.jsx(Ac,{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(vc,{side:"bottom",className:"text-xs",children:a})]})}function Utn({content:s,onChange:t}){const n=Z6e({extensions:[X6e.configure({heading:{levels:[1,2,3]}}),$tn,lIe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),cIe.configure({types:["heading","paragraph"]}),dIe,b_t],content:s,editorProps:{attributes:{class:"prose prose-sm max-w-none focus:outline-none min-h-[350px] px-5 py-4",style:"font-size: 15px; line-height: 1.75; color: #1a1a1a;"}},onUpdate:({editor:i})=>{t(i.getHTML())}});N.useEffect(()=>{n&&s!==n.getHTML()&&n.commands.setContent(s)},[s,n]);const r=N.useCallback(()=>{if(!n)return;const i=n.getAttributes("link").href,l=window.prompt("Enter URL",i);if(l!==null){if(l===""){n.chain().focus().extendMarkRange("link").unsetLink().run();return}n.chain().focus().extendMarkRange("link").setLink({href:l}).run()}},[n]),a=N.useCallback(i=>{n&&n.chain().focus().insertContent(`{{${i}}}`).run()},[n]);return n?e.jsx(Ww,{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(Qp,{onClick:()=>n.chain().focus().toggleBold().run(),active:n.isActive("bold"),icon:KS,tooltip:"Bold"}),e.jsx(Qp,{onClick:()=>n.chain().focus().toggleItalic().run(),active:n.isActive("italic"),icon:JS,tooltip:"Italic"}),e.jsx(Qp,{onClick:()=>n.chain().focus().toggleUnderline().run(),active:n.isActive("underline"),icon:_L,tooltip:"Underline"}),e.jsx(Qp,{onClick:()=>n.chain().focus().toggleStrike().run(),active:n.isActive("strike"),icon:M9,tooltip:"Strikethrough"}),e.jsx(ll,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Qp,{onClick:()=>n.chain().focus().toggleHeading({level:1}).run(),active:n.isActive("heading",{level:1}),icon:nL,tooltip:"Heading 1"}),e.jsx(Qp,{onClick:()=>n.chain().focus().toggleHeading({level:2}).run(),active:n.isActive("heading",{level:2}),icon:rL,tooltip:"Heading 2"}),e.jsx(Qp,{onClick:()=>n.chain().focus().toggleHeading({level:3}).run(),active:n.isActive("heading",{level:3}),icon:o9,tooltip:"Heading 3"}),e.jsx(ll,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Qp,{onClick:()=>n.chain().focus().toggleBulletList().run(),active:n.isActive("bulletList"),icon:Tp,tooltip:"Bullet List"}),e.jsx(Qp,{onClick:()=>n.chain().focus().toggleOrderedList().run(),active:n.isActive("orderedList"),icon:Ov,tooltip:"Numbered List"}),e.jsx(Qp,{onClick:()=>n.chain().focus().toggleBlockquote().run(),active:n.isActive("blockquote"),icon:gb,tooltip:"Blockquote"}),e.jsx(Qp,{onClick:()=>n.chain().focus().setHorizontalRule().run(),icon:fb,tooltip:"Divider"}),e.jsx(ll,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Qp,{onClick:()=>n.chain().focus().setTextAlign("left").run(),active:n.isActive({textAlign:"left"}),icon:_A,tooltip:"Align Left"}),e.jsx(Qp,{onClick:()=>n.chain().focus().setTextAlign("center").run(),active:n.isActive({textAlign:"center"}),icon:bA,tooltip:"Align Center"}),e.jsx(Qp,{onClick:()=>n.chain().focus().setTextAlign("right").run(),active:n.isActive({textAlign:"right"}),icon:wA,tooltip:"Align Right"}),e.jsx(ll,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Qp,{onClick:r,active:n.isActive("link"),icon:Jo,tooltip:"Insert Link"}),e.jsx(ll,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Qp,{onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),icon:d4,tooltip:"Undo"}),e.jsx(Qp,{onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),icon:o4,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(wc,{children:[e.jsx(jc,{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(wL,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(cc,{align:"end",className:"w-56",children:EXe.map(i=>e.jsxs(Qr,{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(K6e,{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:"}),EXe.map(i=>e.jsx(ze,{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 qtn({open:s,onClose:t,campaignName:n,stat:r}){return e.jsx(bs,{open:s,onOpenChange:a=>!a&&t(),children:e.jsxs(vs,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(mo,{className:"h-5 w-5 text-primary"}),n," — Engagement Stats"]}),e.jsx(Qn,{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(cr,{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(IG,{icon:Vs,color:"text-blue-500",label:"Total Sent",value:r.sent.toLocaleString()}),e.jsx(IG,{icon:Er,color:"text-amber-500",label:"Opens",value:`${r.opened.toLocaleString()}`,sub:`${r.openRate.toFixed(1)}% open rate`}),e.jsx(IG,{icon:oc,color:"text-green-500",label:"Clicks",value:`${r.clicked.toLocaleString()}`,sub:`${r.clickRate.toFixed(1)}% click rate`}),e.jsx(IG,{icon:$l,color:"text-destructive",label:"Failed",value:r.failed.toLocaleString()})]}),r.lastSentAt&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(gr,{className:"h-3 w-3"})," Last sent: ",Ss(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(fe,{className:"overflow-hidden",children:e.jsxs(Ee,{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(ze,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(Vs,{className:"h-2.5 w-2.5"})," ",a.sent_count.toLocaleString()," sent"]}),e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600",children:[e.jsx(Er,{className:"h-2.5 w-2.5"})," ",a.opened_count.toLocaleString()," (",i.toFixed(1),"%)"]}),e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600",children:[e.jsx(oc,{className:"h-2.5 w-2.5"})," ",a.clicked_count.toLocaleString()," (",l.toFixed(1),"%)"]}),a.failed_count>0&&e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1 border-destructive/30 text-destructive",children:[e.jsx($l,{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 IG({icon:s,color:t,label:n,value:r,sub:a}){return e.jsx(fe,{children:e.jsx(Ee,{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 yNt(s){return ct({queryKey:["recruit-campaign-stats",s],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:t,error:n}=await q.from("recruit_campaign_email_stats").select("*").eq("brokerage_id",s);if(n)throw n;const r=t??[],a={};for(const i of r){a[i.campaign_id]||(a[i.campaign_id]={campaign_id:i.campaign_id,sent:0,opened:0,clicked:0,failed:0,openRate:0,clickRate:0,byEmail:[],lastSentAt:null});const l=a[i.campaign_id];l.sent+=i.sent_count,l.opened+=i.opened_count,l.clicked+=i.clicked_count,l.failed+=i.failed_count,l.byEmail.push(i),i.last_sent_at&&(!l.lastSentAt||i.last_sent_at>l.lastSentAt)&&(l.lastSentAt=i.last_sent_at)}return Object.values(a).forEach(i=>{i.openRate=i.sent>0?i.opened/i.sent*100:0,i.clickRate=i.sent>0?i.clicked/i.sent*100:0,i.byEmail.sort((l,o)=>l.email_number-o.email_number)}),a}})}const AXe={cold:{icon:Ev,color:"text-blue-500",bg:"bg-blue-50 dark:bg-blue-950/30",label:"Cold — Curiosity"},warm:{icon:yb,color:"text-amber-500",bg:"bg-amber-50 dark:bg-amber-950/30",label:"Warm — Growth"},hot:{icon:Dc,color:"text-red-500",bg:"bg-red-50 dark:bg-red-950/30",label:"Hot — Private Invite"}};function vNt({brokerageId:s}){var Ae,De,Ie,Fe;const{user:t}=ys(),n=Ht(),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,p]=N.useState(!1),[f,g]=N.useState("editor"),[_,v]=N.useState(null),[j,b]=N.useState(null),{data:S={}}=yNt(s),[A,T]=N.useState({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""}),{data:L}=ct({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:qe,error:be}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(be)throw be;return qe}}),{data:D}=ct({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:qe,error:be}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(be)throw be;return qe}}),M={first_name:"Sarah",brokerage_name:((Ae=D==null?void 0:D.merge_fields)==null?void 0:Ae.brokerage_name)||(L==null?void 0:L.name)||"Your Brokerage",city:((De=D==null?void 0:D.merge_fields)==null?void 0:De.city)||(L==null?void 0:L.city)||"Your City",sender_name:((Ie=D==null?void 0:D.merge_fields)==null?void 0:Ie.sender_name)||(D==null?void 0:D.sender_name)||"Your Name"},F=qe=>qe.replace(/\{\{first_name\}\}/g,M.first_name).replace(/\{\{brokerage_name\}\}/g,M.brokerage_name).replace(/\{\{city\}\}/g,M.city).replace(/\{\{sender_name\}\}/g,M.sender_name),{data:z=[],isLoading:V}=ct({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:qe,error:be}=await q.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(be)throw be;return qe}}),{data:W={}}=ct({queryKey:["recruit-campaign-emails",s],enabled:z.length>0,queryFn:async()=>{const qe=z.map(it=>it.id),{data:be,error:Ze}=await q.from("recruit_campaign_emails").select("*").in("campaign_id",qe).order("email_number");if(Ze)throw Ze;const Ne={};return be.forEach(it=>{Ne[it.campaign_id]||(Ne[it.campaign_id]=[]),Ne[it.campaign_id].push(it)}),Ne}}),Y=Object.values(W).flat().map(qe=>qe.id),{data:K=[]}=ct({queryKey:["recruit-subject-overrides",s],enabled:Y.length>0,queryFn:async()=>{const{data:qe,error:be}=await q.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(be)throw be;return qe}}),J={};K.forEach(qe=>{J[qe.campaign_email_id]=qe.selected_subject_index});const ne=gt({mutationFn:async({campaignEmailId:qe,selectedIndex:be})=>{const{error:Ze}=await q.from("recruit_brokerage_subject_overrides").upsert({brokerage_id:s,campaign_email_id:qe,selected_subject_index:be,updated_at:new Date().toISOString()},{onConflict:"brokerage_id,campaign_email_id"});if(Ze)throw Ze},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-subject-overrides",s]}),ae.success("Subject line updated for your brokerage")},onError:qe=>ae.error(qe.message)}),ie=gt({mutationFn:async qe=>{const{error:be}=await q.from("recruit_campaign_emails").update({title:qe.title,subject_line:qe.subject_line,subject_line_options:qe.subject_line_options,body_html:qe.body_html,body_text:qe.body_text,delay_days:qe.delay_days,updated_at:new Date().toISOString()}).eq("id",qe.id);if(be)throw be},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Email template saved!"),l(null)},onError:qe=>ae.error(qe.message)}),he=gt({mutationFn:async()=>{const qe=A.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:be,error:Ze}=await q.from("recruit_campaigns").insert({name:A.name,slug:qe,description:A.description||null,theme:A.theme||null,goal:A.goal||null,primary_cta:A.primary_cta||"Learn more",warmth_level:A.warmth_level,brokerage_id:s,created_by:t==null?void 0:t.id,sender_name:A.sender_name||null,sender_email:A.sender_email||null,reply_to_email:A.reply_to_email||null,is_active:!0,sort_order:z.length+1}).select().single();if(Ze)throw Ze;const Ne=[{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:it}=await q.from("recruit_campaign_emails").insert(Ne.map(je=>({campaign_id:be.id,...je,body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",subject_line_options:[],is_active:!0})));if(it)throw it;return be},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Campaign created with 4 starter emails!"),p(!1),T({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""})},onError:qe=>ae.error(qe.message)}),ce=gt({mutationFn:async qe=>{const{error:be}=await q.from("recruit_campaigns").update({name:qe.name,description:qe.description,theme:qe.theme,goal:qe.goal,primary_cta:qe.primary_cta,warmth_level:qe.warmth_level,sender_name:qe.sender_name,sender_email:qe.sender_email,reply_to_email:qe.reply_to_email,updated_at:new Date().toISOString()}).eq("id",qe.id);if(be)throw be},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),ae.success("Campaign settings saved!"),v(null)},onError:qe=>ae.error(qe.message)}),pe=gt({mutationFn:async qe=>{var Ge,Be;const{data:be}=await q.from("recruit_campaign_emails").select("email_number, delay_days").eq("campaign_id",qe).order("email_number",{ascending:!1}).limit(1),Ze=((Ge=be==null?void 0:be[0])==null?void 0:Ge.email_number)??0,Ne=((Be=be==null?void 0:be[0])==null?void 0:Be.delay_days)??0,it=Ze+1,{error:je}=await q.from("recruit_campaign_emails").insert({campaign_id:qe,email_number:it,title:`Email ${it}`,subject_line:"Hey {{first_name}}",subject_line_options:[],body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",delay_days:Ne+7,is_active:!0});if(je)throw je},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Email added to campaign!")},onError:qe=>ae.error(qe.message)}),le=gt({mutationFn:async qe=>{const{error:be}=await q.from("recruit_campaigns").delete().eq("id",qe);if(be)throw be},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Campaign deleted")},onError:qe=>ae.error(qe.message)}),ve=gt({mutationFn:async qe=>{const{error:be}=await q.from("recruit_campaign_emails").delete().eq("id",qe);if(be)throw be},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Email removed from campaign")},onError:qe=>ae.error(qe.message)}),ge=gt({mutationFn:async({emailId:qe,delay_days:be})=>{const{error:Ze}=await q.from("recruit_campaign_emails").update({delay_days:be,updated_at:new Date().toISOString()}).eq("id",qe);if(Ze)throw Ze},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Send delay updated")},onError:qe=>ae.error(qe.message)});if(V)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 Te=z.filter(qe=>!qe.brokerage_id),Me=z.filter(qe=>qe.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(Xo,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs(B,{size:"sm",onClick:()=>p(!0),className:"gap-1.5",children:[e.jsx(Is,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(fe,{className:"border-primary/20 bg-primary/5",children:e.jsx(Ee,{className:"py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(un,{className:"h-5 w-5 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-semibold",children:"Per-Campaign Email Settings"}),e.jsxs("p",{className:"text-muted-foreground",children:["Each campaign can override the default sender name, email, and reply-to. Click the ",e.jsx(Xo,{className:"inline h-3.5 w-3.5"})," icon on any campaign to customize."]})]})]})})}),Me.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(d9,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:Me.map(qe=>Ce(qe,!0))})]}),Te.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:Te.map(qe=>Ce(qe,!1))})]}),z.length===0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Vs,{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:()=>p(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(qtn,{open:!!j,onClose:()=>b(null),campaignName:(j==null?void 0:j.name)||"",stat:j&&S[j.id]||null}),o&&e.jsx(gNt,{email:o,mergeValues:M,selectedSubjectIndex:J[o.id],onClose:()=>c(null)}),e.jsx(bs,{open:!!i,onOpenChange:qe=>!qe&&l(null),children:e.jsxs(vs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(ws,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(XS,{className:"h-5 w-5 text-primary"}),"Edit Email #",i==null?void 0:i.email_number]}),e.jsx(Qn,{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:qe=>l({...i,title:qe.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:qe=>l({...i,delay_days:parseInt(qe.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:qe=>l({...i,subject_line:qe.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(Es,{value:((Fe=i.subject_line_options)==null?void 0:Fe.join(` `))||"",onChange:qe=>l({...i,subject_line_options:qe.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(Br,{value:f,onValueChange:qe=>g(qe),children:e.jsxs(Fr,{className:"h-7",children:[e.jsx(Kt,{value:"editor",className:"text-xs px-3 h-6",children:"Editor"}),e.jsx(Kt,{value:"preview",className:"text-xs px-3 h-6",children:"Preview"})]})})]}),f==="editor"?e.jsx(Utn,{content:i.body_html,onChange:qe=>l({...i,body_html:qe})}):e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"bg-muted/50 px-4 py-2 border-b space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium w-12",children:"From:"}),e.jsxs("span",{children:[M.sender_name," "]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium w-12",children:"To:"}),e.jsxs("span",{children:[M.first_name," "]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium w-12 text-muted-foreground",children:"Subject:"}),e.jsx("span",{className:"font-medium",children:F(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:F(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:()=>ie.mutate(i),disabled:ie.isPending,className:"gap-1.5",children:[e.jsx(qo,{className:"h-3.5 w-3.5"})," Save Changes"]})]})]})]})]})}),e.jsx(bs,{open:h,onOpenChange:p,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Is,{className:"h-5 w-5 text-primary"})," Create Custom Campaign"]}),e.jsx(Qn,{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:A.name,onChange:qe=>T({...A,name:qe.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(ds,{value:A.warmth_level,onValueChange:qe=>T({...A,warmth_level:qe}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"cold",children:"❄️ Cold — Curiosity"}),e.jsx(Qe,{value:"warm",children:"☀️ Warm — Growth"}),e.jsx(Qe,{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:A.primary_cta,onChange:qe=>T({...A,primary_cta:qe.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(Es,{value:A.description,onChange:qe=>T({...A,description:qe.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:A.goal,onChange:qe=>T({...A,goal:qe.target.value}),placeholder:"e.g. Convert warm leads to meetings"})]}),e.jsxs(dy,{children:[e.jsx(uy,{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(Vs,{className:"h-3.5 w-3.5"})," Email Settings Override"]}),e.jsx(io,{className:"h-3.5 w-3.5"})]})}),e.jsxs(hy,{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:A.sender_name,onChange:qe=>T({...A,sender_name:qe.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:A.sender_email,onChange:qe=>T({...A,sender_email:qe.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:A.reply_to_email,onChange:qe=>T({...A,reply_to_email:qe.target.value}),placeholder:"e.g. jeremy@mybrokerage.com"})]})]})]}),e.jsxs(B,{className:"w-full",disabled:!A.name.trim()||he.isPending,onClick:()=>he.mutate(),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(bs,{open:!!_,onOpenChange:qe=>!qe&&v(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Xo,{className:"h-5 w-5 text-primary"})," Campaign Email Settings"]}),e.jsx(Qn,{children:"Override the default sender for this campaign. Leave blank to use brokerage defaults."})]}),_&&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:_.name,onChange:qe=>v({..._,name:qe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(ds,{value:_.warmth_level,onValueChange:qe=>v({..._,warmth_level:qe}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"cold",children:"❄️ Cold"}),e.jsx(Qe,{value:"warm",children:"☀️ Warm"}),e.jsx(Qe,{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:_.goal||"",onChange:qe=>v({..._,goal:qe.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(Vs,{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:_.sender_name||"",onChange:qe=>v({..._,sender_name:qe.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:_.sender_email||"",onChange:qe=>v({..._,sender_email:qe.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:_.reply_to_email||"",onChange:qe=>v({..._,reply_to_email:qe.target.value}),placeholder:"Uses brokerage default"})]})]}),e.jsxs(B,{className:"w-full",onClick:()=>ce.mutate(_),disabled:ce.isPending,children:[e.jsx(qo,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(bs,{open:d,onOpenChange:u,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Default Recruiting Email Settings"}),e.jsx(Qn,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(T8e,{brokerageId:s})]})})]});function Ce(qe,be){const Ze=AXe[qe.warmth_level]||AXe.cold,Ne=Ze.icon,it=W[qe.id]||[],je=r===qe.id,Ge=!!(qe.sender_name||qe.sender_email||qe.reply_to_email),Be=S[qe.id];return e.jsxs(fe,{className:"overflow-hidden transition-shadow hover:shadow-md",children:[e.jsx(Mt,{className:"cursor-pointer hover:bg-muted/40 transition-colors py-4",onClick:()=>a(je?null:qe.id),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`h-11 w-11 rounded-xl ${Ze.bg} flex items-center justify-center`,children:e.jsx(Ne,{className:`h-5 w-5 ${Ze.color}`})}),e.jsxs("div",{children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[qe.name,e.jsx(ze,{variant:qe.is_active?"default":"secondary",className:"text-[10px] px-1.5",children:qe.is_active?"Active":"Draft"}),be&&e.jsx(ze,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),Ge&&e.jsxs(ze,{variant:"outline",className:"text-[10px] px-1.5 border-primary/30 text-primary",children:[e.jsx(Vs,{className:"h-2.5 w-2.5 mr-0.5"})," Custom Sender"]})]}),e.jsx(Vn,{className:"text-xs mt-0.5",children:qe.theme||qe.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:Ye=>{Ye.stopPropagation(),v({...qe})},children:e.jsx(Xo,{className:"h-4 w-4 text-muted-foreground"})}),be&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:Ye=>{Ye.stopPropagation(),confirm("Delete this campaign and all its emails? This cannot be undone.")&&le.mutate(qe.id)},children:e.jsx(_n,{className:"h-4 w-4"})}),Be&&Be.sent>0&&e.jsxs("div",{className:"hidden md:flex items-center gap-1.5",children:[e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1 font-medium",title:"Total emails sent",children:[e.jsx(Vs,{className:"h-2.5 w-2.5"})," ",Be.sent.toLocaleString()]}),e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600 font-medium",title:`${Be.openRate.toFixed(1)}% open rate`,children:[e.jsx(Er,{className:"h-2.5 w-2.5"})," ",Be.opened.toLocaleString()," (",Be.openRate.toFixed(0),"%)"]}),e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600 font-medium",title:`${Be.clickRate.toFixed(1)}% click rate`,children:[e.jsx(oc,{className:"h-2.5 w-2.5"})," ",Be.clicked.toLocaleString()," (",Be.clickRate.toFixed(1),"%)"]})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1 text-xs",onClick:Ye=>{Ye.stopPropagation(),b(qe)},title:"View detailed engagement stats",children:[e.jsx(yo,{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(Vs,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[it.length," emails"]})]}),e.jsx("div",{className:"h-7 w-7 rounded-md flex items-center justify-center",children:je?e.jsx(tx,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(io,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),je&&e.jsxs(Ee,{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:qe.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:qe.primary_cta||"—"})]})]}),Ge&&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(Vs,{className:"h-3 w-3"})," Campaign Sender Override"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-muted-foreground",children:[qe.sender_name&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Name:"})," ",qe.sender_name]}),qe.sender_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Email:"})," ",qe.sender_email]}),qe.reply_to_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Reply-To:"})," ",qe.reply_to_email]})]})]}),e.jsx("div",{className:"relative",children:it.map((Ye,We)=>{var rt,tt;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[Weat.stopPropagation(),onBlur:at=>{const He=parseInt(at.target.value)||0;He!==Ye.delay_days&&ge.mutate({emailId:Ye.id,delay_days:He})},onKeyDown:at=>{at.key==="Enter"&&at.target.blur()}}),"days"]})]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),Ye.email_number===1?"Sent immediately":`Day ${Ye.delay_days}`]}),e.jsx("span",{className:"text-border",children:"•"}),e.jsxs("span",{className:"truncate",children:["Subject: ",F(((rt=Ye.subject_line_options)==null?void 0:rt.length)>0&&Ye.subject_line_options[J[Ye.id]??0]||Ye.subject_line)]})]}),((tt=Ye.subject_line_options)==null?void 0:tt.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(ds,{value:String(J[Ye.id]??0),onValueChange:at=>ne.mutate({campaignEmailId:Ye.id,selectedIndex:parseInt(at)}),children:[e.jsx(ls,{className:"h-7 text-xs w-full max-w-sm",children:e.jsx(us,{placeholder:"Choose subject line"})}),e.jsx(cs,{children:Ye.subject_line_options.map((at,He)=>e.jsxs(Qe,{value:String(He),className:"text-xs",children:[e.jsxs("span",{className:"font-medium mr-1.5",children:[He===0?"Primary":`Alt ${He}`,":"]}),F(at)]},He))})]})})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(Ye),children:e.jsx(Er,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({...Ye}),g("editor")},children:e.jsx(_a,{className:"h-4 w-4"})}),be&&it.length>1&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>{confirm("Delete this email from the sequence?")&&ve.mutate(Ye.id)},children:e.jsx(_n,{className:"h-4 w-4"})})]})]})})]},Ye.id)})}),be&&e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>pe.mutate(qe.id),disabled:pe.isPending,children:[e.jsx(Is,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},qe.id)}}const MXe={active:{icon:Al,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:bf,color:"bg-amber-500/10 text-amber-600",label:"Paused"},completed:{icon:Ri,color:"bg-blue-500/10 text-blue-600",label:"Completed"},cancelled:{icon:Hc,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},IXe={sent:{icon:Vs,color:"text-blue-500"},opened:{icon:Er,color:"text-amber-500"},clicked:{icon:oc,color:"text-green-500"},failed:{icon:$l,color:"text-destructive"}};function bNt({brokerageId:s}){var Fe,qe,be,Ze,Ne;const{user:t}=ys(),n=Ht(),[r,a]=N.useState(!1),[i,l]=N.useState(""),[o,c]=N.useState(new Set),[d,u]=N.useState("assignments"),[h,p]=N.useState(null),[f,g]=N.useState(""),[_,v]=N.useState("all"),[j,b]=N.useState("all"),[S,A]=N.useState(!1),{data:T}=C1e(),{data:L={}}=ct({queryKey:["recruit-campaign-emails-for-preview",s],queryFn:async()=>{const{data:it,error:je}=await q.from("recruit_campaign_emails").select("*").order("email_number");if(je)throw je;const Ge={};return(it??[]).forEach(Be=>{Ge[Be.campaign_id]||(Ge[Be.campaign_id]=[]),Ge[Be.campaign_id].push(Be)}),Ge}}),{data:D}=ct({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:it,error:je}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(je)throw je;return it}}),{data:M}=ct({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:it,error:je}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(je)throw je;return it}}),{data:F=[]}=ct({queryKey:["recruit-subject-overrides",s],queryFn:async()=>{const{data:it,error:je}=await q.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(je)throw je;return it}}),z={};F.forEach(it=>{z[it.campaign_email_id]=it.selected_subject_index});const V={first_name:((Fe=h==null?void 0:h.prospect)==null?void 0:Fe.first_name)||"Sarah",brokerage_name:((qe=M==null?void 0:M.merge_fields)==null?void 0:qe.brokerage_name)||(D==null?void 0:D.name)||"Your Brokerage",city:((be=M==null?void 0:M.merge_fields)==null?void 0:be.city)||(D==null?void 0:D.city)||"Your City",sender_name:((Ze=M==null?void 0:M.merge_fields)==null?void 0:Ze.sender_name)||(M==null?void 0:M.sender_name)||"Your Name"},W=it=>{const je=L[it.campaign_id]||[],Ge=it.current_email_number+1;return je.find(Be=>Be.email_number===Ge)||null},{data:Y=[],isLoading:K}=ct({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let je=[],Ge=0;for(;;){const{data:Be,error:Ye}=await q.from("recruit_campaign_assignments").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign:recruit_campaigns(name, warmth_level) `).eq("brokerage_id",s).order("created_at",{ascending:!1}).range(Ge,Ge+1e3-1);if(Ye)throw Ye;if(je=je.concat(Be??[]),!Be||Be.length<1e3)break;Ge+=1e3}return je}}),{data:J=[]}=ct({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{const{data:it,error:je}=await q.from("recruit_campaign_sends").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign_email:recruit_campaign_emails(title, campaign_id) `).eq("brokerage_id",s).neq("status","failed").order("sent_at",{ascending:!1}).limit(500);if(je)throw je;return it}}),{data:ne=[]}=ct({queryKey:["recruit-campaigns"],queryFn:async()=>{const{data:it,error:je}=await q.from("recruit_campaigns").select("id, name, warmth_level").eq("is_active",!0).order("sort_order");if(je)throw je;return it}}),{data:ie=[]}=ct({queryKey:["recruit-prospects-for-assign",s],queryFn:async()=>{let je=[],Ge=0;for(;;){const{data:Be,error:Ye}=await q.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s).order("first_name").range(Ge,Ge+1e3-1);if(Ye)throw Ye;if(je=je.concat(Be??[]),!Be||Be.length<1e3)break;Ge+=1e3}return je}}),he=new Set(Y.map(it=>`${it.prospect_id}-${it.campaign_id}`)),ce=gt({mutationFn:async()=>{if(!i||o.size===0)throw new Error("Select a campaign and at least one prospect");const it=new Date,je=Array.from(o).filter(Be=>!he.has(`${Be}-${i}`)).map(Be=>({prospect_id:Be,campaign_id:i,brokerage_id:s,assigned_by:t.id,status:"active",current_email_number:0,next_send_at:it.toISOString(),started_at:it.toISOString()}));if(je.length===0)throw new Error("All selected prospects are already assigned to this campaign");const{error:Ge}=await q.from("recruit_campaign_assignments").insert(je);if(Ge)throw Ge},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ae.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:it=>ae.error(it.message)}),pe=gt({mutationFn:async({id:it,newStatus:je})=>{const{error:Ge}=await q.from("recruit_campaign_assignments").update({status:je,updated_at:new Date().toISOString()}).eq("id",it);if(Ge)throw Ge},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ae.success("Assignment updated")}}),le=gt({mutationFn:async()=>{const{data:it,error:je}=await q.functions.invoke("ses-recruit-drip",{body:{action:"process_drips"}});if(je)throw je;return it},onSuccess:it=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),n.invalidateQueries({queryKey:["recruit-campaign-sends",s]}),ae.success(`Wave sent! ${it.sent} emails delivered, ${it.skipped} skipped, ${it.failed} failed`)},onError:it=>ae.error(`Send failed: ${it.message}`)}),ve=Y.filter(it=>it.status==="active").length;Y.filter(it=>it.status==="completed").length;const ge=Y.filter(it=>it.status==="active"&&it.next_send_at&&new Date(it.next_send_at)<=new Date).length,{data:Te={}}=yNt(s),Me=Y.reduce((it,je)=>it+Math.max(0,je.current_email_number||0),0),Ce=Object.values(Te).reduce((it,je)=>it+je.opened,0),Ae=Object.values(Te).reduce((it,je)=>it+je.clicked,0);Object.values(Te).reduce((it,je)=>it+je.failed,0);const De=Me>0?Math.round(Ce/Me*100):0,Ie=Me>0?Ae/Me*100:0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Campaign Assignments"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Assign recruiting campaigns to prospects — emails auto-send weekly via SES"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ge>0&&e.jsxs(B,{variant:"outline",onClick:()=>{le.mutate()},disabled:le.isPending,className:"border-amber-500/50 text-amber-600 hover:bg-amber-500/10",children:[e.jsx(hh,{className:"h-4 w-4 mr-1"}),le.isPending?"Sending...":`Send Next Wave (${ge})`]}),e.jsxs(B,{onClick:()=>a(!0),children:[e.jsx(cr,{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(fe,{children:e.jsxs(Ee,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Nn,{className:"h-7 w-7 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:Y.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assigned"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Al,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:ve}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Vs,{className:"h-7 w-7 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:Me.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Er,{className:"h-7 w-7 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[De,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Open Rate (",Ce.toLocaleString(),")"]})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(oc,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Ie.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",Ae.toLocaleString(),")"]})]})]})})]}),e.jsxs(Br,{value:d,onValueChange:u,children:[e.jsxs(Fr,{children:[e.jsxs(Kt,{value:"assignments",children:["Active Drips (",ve,")"]}),e.jsxs(Kt,{value:"history",children:["Send History (",Me.toLocaleString(),")"]})]}),e.jsx(is,{value:"assignments",className:"mt-4",children:K?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"})}):Y.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(cr,{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:Y.map(it=>{var rt,tt,at,He;const je=MXe[it.status]||MXe.active,Ge=je.icon,Ye=(L[it.campaign_id]||[]).length||4,We=W(it);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(ze,{className:`text-xs ${je.color} border-0`,children:[e.jsx(Ge,{className:"h-3 w-3 mr-1"}),je.label]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(rt=it.prospect)==null?void 0:rt.first_name," ",(tt=it.prospect)==null?void 0:tt.last_name,e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:(at=it.prospect)==null?void 0:at.email})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(He=it.campaign)==null?void 0:He.name," · Email ",it.current_email_number,"/",Ye,it.next_send_at&&it.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(gr,{className:"h-3 w-3 inline"})," Next: ",Ss(new Date(it.next_send_at),"MMM d, h:mm a"),new Date(it.next_send_at)<=new Date&&e.jsx(ze,{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:[We&&e.jsx(B,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>p(it),children:e.jsx(Er,{className:"h-3.5 w-3.5"})}),it.status==="active"&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>pe.mutate({id:it.id,newStatus:"paused"}),children:e.jsx(bf,{className:"h-3.5 w-3.5"})}),it.status==="paused"&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>pe.mutate({id:it.id,newStatus:"active"}),children:e.jsx(Al,{className:"h-3.5 w-3.5"})}),(it.status==="active"||it.status==="paused")&&e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>pe.mutate({id:it.id,newStatus:"cancelled"}),children:e.jsx(Hc,{className:"h-3.5 w-3.5"})})]})]},it.id)})})}),e.jsxs(is,{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(ds,{value:_,onValueChange:v,children:[e.jsx(ls,{className:"w-[220px] h-8 text-xs",children:e.jsx(us,{placeholder:"All campaigns"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All campaigns"}),ne.map(it=>e.jsx(Qe,{value:it.id,children:it.name},it.id))]})]}),e.jsxs(ds,{value:j,onValueChange:b,children:[e.jsx(ls,{className:"w-[160px] h-8 text-xs",children:e.jsx(us,{placeholder:"All statuses"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All statuses"}),e.jsx(Qe,{value:"sent",children:"Sent (no engagement)"}),e.jsx(Qe,{value:"opened",children:"Opened"}),e.jsx(Qe,{value:"clicked",children:"Clicked"})]})]}),(_!=="all"||j!=="all")&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{v("all"),b("all")},children:"Clear"})]}),(()=>{var je;const it=J.filter(Ge=>{var Be;return!(_!=="all"&&((Be=Ge.campaign_email)==null?void 0:Be.campaign_id)!==_||j==="opened"&&!Ge.opened_at||j==="clicked"&&!Ge.clicked_at||j==="sent"&&(Ge.opened_at||Ge.clicked_at))});return it.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Vs,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:J.length===0?"No emails sent yet":"No emails match these filters"}),e.jsx("p",{className:"text-sm",children:J.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 ",it.length," of ",J.length," recent sends",_!=="all"&&` · ${(je=ne.find(Ge=>Ge.id===_))==null?void 0:je.name}`]}),e.jsx("div",{className:"space-y-1",children:it.map(Ge=>{var rt,tt,at;const Be=IXe[Ge.status]||IXe.sent,Ye=Be.icon,We=(rt=ne.find(He=>{var dt;return He.id===((dt=Ge.campaign_email)==null?void 0:dt.campaign_id)}))==null?void 0:rt.name;return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(Ye,{className:`h-4 w-4 flex-shrink-0 ${Be.color}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(tt=Ge.prospect)==null?void 0:tt.first_name," ",(at=Ge.prospect)==null?void 0:at.last_name,e.jsxs("span",{className:"text-muted-foreground font-normal ml-2",children:["Email #",Ge.email_number]}),We&&e.jsx(ze,{variant:"outline",className:"ml-2 text-[10px] px-1.5 py-0 font-normal",children:We})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ge.subject})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-shrink-0",children:[Ge.opened_at&&e.jsxs("span",{className:"flex items-center gap-1 text-amber-500",children:[e.jsx(Er,{className:"h-3 w-3"})," ",Ss(new Date(Ge.opened_at),"MMM d")]}),Ge.clicked_at&&e.jsxs("span",{className:"flex items-center gap-1 text-green-500",children:[e.jsx(oc,{className:"h-3 w-3"})," ",Ss(new Date(Ge.clicked_at),"MMM d")]}),e.jsx("span",{children:Ss(new Date(Ge.sent_at),"MMM d, h:mm a")})]})]},Ge.id)})})]})})()]})]}),e.jsx(bs,{open:r,onOpenChange:it=>{a(it),it||(g(""),c(new Set),l(""))},children:e.jsxs(vs,{className:"max-w-lg max-h-[85vh] flex flex-col p-0",children:[e.jsxs(ws,{className:"px-6 pt-6 pb-4",children:[e.jsx(_s,{children:"Assign Campaign to Prospects"}),e.jsx(Qn,{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(ds,{value:i,onValueChange:l,children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Choose a campaign..."})}),e.jsx(cs,{children:ne.map(it=>e.jsx(Qe,{value:it.id,children:it.name},it.id))})]})]}),i&&(()=>{const it=f.toLowerCase(),je=ie.filter(Ye=>`${Ye.first_name} ${Ye.last_name}`.toLowerCase().includes(it)||Ye.email.toLowerCase().includes(it)),Ge=je.filter(Ye=>!he.has(`${Ye.id}-${i}`)),Be=Ge.length>0&&Ge.every(Ye=>o.has(Ye.id));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-sm font-medium",children:"2. Select Prospects"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[o.size," selected"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:f,onChange:Ye=>g(Ye.target.value),className:"pl-9 h-9"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if(Be){const Ye=new Set(o);Ge.forEach(We=>Ye.delete(We.id)),c(Ye)}else{const Ye=new Set(o);Ge.forEach(We=>Ye.add(We.id)),c(Ye)}},children:[e.jsx(Z7,{className:"h-3.5 w-3.5 mr-1"}),Be?"Deselect All":`Select All (${Ge.length})`]})]}),e.jsx("div",{className:"border rounded-lg max-h-60 overflow-y-auto divide-y",children:je.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:f?"No prospects match your search":"No prospects found for this brokerage"}):je.map(Ye=>{const We=he.has(`${Ye.id}-${i}`);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 hover:bg-muted/50 cursor-pointer ${We?"opacity-40":""}`,children:[e.jsx(ui,{checked:o.has(Ye.id),disabled:We,onCheckedChange:rt=>{const tt=new Set(o);rt?tt.add(Ye.id):tt.delete(Ye.id),c(tt)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Ye.first_name," ",Ye.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ye.email})]}),We&&e.jsx(ze,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},Ye.id)})}),je.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",je.length," of ",ie.length," prospects",Ge.length0&&e.jsx(fe,{className:"bg-primary/5 border-primary/20",children:e.jsxs(Ee,{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:(Ne=ne.find(it=>it.id===i))==null?void 0:Ne.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(Xn,{className:"px-6 py-4 border-t",children:[e.jsx(B,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>{ce.mutate()},disabled:ce.isPending||!i||o.size===0,children:[e.jsx(cr,{className:"h-4 w-4 mr-1"}),ce.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),h&&(()=>{const it=W(h);return it?e.jsx(gNt,{email:it,mergeValues:V,selectedSubjectIndex:z[it.id],onClose:()=>p(null)}):null})(),e.jsx(T1e,{open:S,onOpenChange:A,hasPending:T==null?void 0:T.hasPendingSes,pendingEmails:T==null?void 0:T.pendingEmails})]})}function _Nt({brokerageId:s}){const t=Ht(),[n,r]=N.useState([]),[a,i]=N.useState([]),[l,o]=N.useState(!1),c=N.useRef(!1),{data:d,isLoading:u}=ct({queryKey:["recruit-stages-editor",s],queryFn:async()=>{const{data:v,error:j}=await q.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(j)throw j;return v},enabled:!!s});N.useEffect(()=>{if(d){if(c.current){c.current=!1;return}r(d.map(v=>({id:v.id,name:v.name,color:v.color,sort_order:v.sort_order}))),i([]),o(!1)}},[d]);const h=gt({mutationFn:async()=>{for(const b of a){const{error:S}=await q.from("recruit_pipeline_stages").delete().eq("id",b);if(S)throw S}const v=n.filter(b=>b.id&&!b.isNew),j=n.filter(b=>!b.id||b.isNew);for(const b of v){const{error:S}=await q.from("recruit_pipeline_stages").update({name:b.name,color:b.color,sort_order:b.sort_order}).eq("id",b.id);if(S)throw S}if(j.length>0){const{error:b}=await q.from("recruit_pipeline_stages").insert(j.map(S=>({brokerage_id:s,name:S.name,color:S.color,sort_order:S.sort_order})));if(b)throw b}},onSuccess:()=>{i([]),t.invalidateQueries({queryKey:["recruit-stages-editor",s]}),t.invalidateQueries({queryKey:["recruit-stages",s]}),ae.success("Pipeline stages saved!"),o(!1)},onError:v=>ae.error(v.message)}),p=(v,j,b)=>{r(S=>S.map((A,T)=>T===v?{...A,[j]:b}:A)),o(!0)},f=()=>{const v=n.length>0?Math.max(...n.map(j=>j.sort_order)):0;r(j=>[...j,{name:"",color:"#6366f1",sort_order:v+1,isNew:!0}]),o(!0)},g=v=>{const j=n[v];j.id&&!j.isNew&&i(b=>[...b,j.id]),r(b=>b.filter((S,A)=>A!==v)),o(!0)},_=(v,j)=>{const b=v+j;if(b<0||b>=n.length)return;const S=[...n];[S[v],S[b]]=[S[b],S[v]],S.forEach((A,T)=>A.sort_order=T+1),r(S),o(!0)};return u?e.jsx("div",{className:"text-sm text-muted-foreground py-8 text-center",children:"Loading stages…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Pipeline Stages"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Customize the recruiting pipeline stages for this brokerage. Changes will apply to the Kanban board and all prospect tracking."})]}),e.jsx("div",{className:"space-y-2",children:n.map((v,j)=>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:()=>_(j,-1),disabled:j===0,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▲"}),e.jsx("button",{type:"button",onClick:()=>_(j,1),disabled:j===n.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▼"})]}),e.jsx(Fu,{className:"h-4 w-4 text-muted-foreground/50 shrink-0"}),e.jsx("input",{type:"color",value:v.color,onChange:b=>p(j,"color",b.target.value),className:"h-8 w-8 rounded cursor-pointer border-0 p-0 shrink-0"}),e.jsx(ye,{value:v.name,onChange:b=>p(j,"name",b.target.value),placeholder:"Stage name…",className:"flex-1"}),e.jsx("span",{className:"text-xs text-muted-foreground w-6 text-center shrink-0",children:j+1}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>g(j),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(_n,{className:"h-4 w-4"})})]},v.id||`new-${j}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:f,className:"gap-1",children:[e.jsx(Is,{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(qo,{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 Vtn({brokerageId:s}){const{data:t=[],isLoading:n}=ct({queryKey:["recruit-unsubscribed",s],queryFn:async()=>{const{data:r,error:a}=await q.from("recruit_prospects").select("id, first_name, last_name, email, unsubscribed_at, unsubscribe_reason, current_brokerage").eq("brokerage_id",s).not("unsubscribed_at","is",null).order("unsubscribed_at",{ascending:!1}).limit(500);if(a)throw a;return r||[]},enabled:!!s});return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(BA,{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(ze,{variant:"secondary",className:"text-base px-3 py-1",children:[t.length," total"]})]}),t.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(BA,{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(fe,{className:"hover:shadow-sm transition-shadow",children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"text-base",children:[r.first_name," ",r.last_name]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vs,{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(yr,{className:"h-3 w-3"}),r.unsubscribed_at&&Ss(new Date(r.unsubscribed_at),"MMM d, yyyy")]})]})}),r.unsubscribe_reason&&e.jsx(Ee,{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 Htn(){var o;const[s,t]=N.useState(""),[n,r]=N.useState("board"),{data:a=[],isLoading:i}=ct({queryKey:["all-brokerages"],queryFn:async()=>{const{data:c,error:d}=await q.from("brokerages").select("id, name").order("name");if(d)throw d;return c}}),l=s||((o=a[0])==null?void 0:o.id)||"";return i?e.jsx(Ts,{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(Ts,{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(ds,{value:l,onValueChange:t,children:[e.jsxs(ls,{className:"w-[280px]",children:[e.jsx(Va,{className:"mr-2 h-4 w-4"}),e.jsx(us,{placeholder:"Select brokerage"})]}),e.jsx(cs,{children:a.map(c=>e.jsx(Qe,{value:c.id,children:c.name},c.id))})]})]}):e.jsx("div",{}),l&&e.jsx(pNt,{brokerageId:l,trigger:e.jsxs(B,{size:"sm",className:"gap-1.5",children:[e.jsx(br,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs(Br,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(Fr,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Kt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Kt,{value:"contacts",children:[e.jsx(Nn,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Kt,{value:"video-outreach",children:[e.jsx(br,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Kt,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Kt,{value:"referrals",children:"Referrals"}),e.jsx(Kt,{value:"interest",children:"Interest Form"}),e.jsx(Kt,{value:"landing-page",children:"Landing Page"}),e.jsx(Kt,{value:"goals",children:"Goals"}),e.jsx(Kt,{value:"metrics",children:"Metrics"}),e.jsx(Kt,{value:"templates",children:"Email Templates"}),e.jsxs(Kt,{value:"campaigns",children:[e.jsx(Vs,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Kt,{value:"drip-assignments",children:[e.jsx(cr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(Kt,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Kt,{value:"email-settings",children:[e.jsx(Xo,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Kt,{value:"pipeline-stages",children:[e.jsx(l4,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(Kt,{value:"unsubscribed",children:[e.jsx(BA,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(is,{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(yf,{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(vL,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(iNt,{brokerageId:l}):e.jsx(Yge,{brokerageId:l})]}),e.jsx(is,{value:"contacts",children:e.jsx(Yge,{brokerageId:l})}),e.jsx(is,{value:"video-outreach",children:e.jsx(fNt,{brokerageId:l})}),e.jsx(is,{value:"follow-ups",children:e.jsx(hNt,{brokerageId:l})}),e.jsx(is,{value:"referrals",children:e.jsx(dNt,{brokerageId:l})}),e.jsx(is,{value:"interest",children:e.jsx(uNt,{brokerageId:l})}),e.jsx(is,{value:"landing-page",children:e.jsx(mNt,{brokerageId:l})}),e.jsx(is,{value:"goals",children:e.jsx(xNt,{brokerageId:l})}),e.jsx(is,{value:"metrics",children:e.jsx(oNt,{brokerageId:l})}),e.jsx(is,{value:"templates",children:e.jsx(lNt,{brokerageId:l})}),e.jsx(is,{value:"campaigns",children:e.jsx(vNt,{brokerageId:l})}),e.jsx(is,{value:"drip-assignments",children:e.jsx(bNt,{brokerageId:l})}),e.jsx(is,{value:"activity",children:e.jsx(cNt,{brokerageId:l})}),e.jsx(is,{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(T8e,{brokerageId:l})]})}),e.jsx(is,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(_Nt,{brokerageId:l})})}),e.jsx(is,{value:"unsubscribed",children:e.jsx(Vtn,{brokerageId:l})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Va,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found. Create a brokerage first."})]})]})})}function Gtn({brokerageId:s}){const[t,n]=N.useState(""),[r,a]=N.useState("all"),{data:i,isLoading:l}=ct({queryKey:["recruit-sent-emails",s],queryFn:async()=>{var v;const{data:d,error:u}=await q.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s);if(u)throw u;const h=new Map((d||[]).map(j=>[j.id,j]));if(Array.from(h.keys()).length===0)return[];const{data:f}=await q.from("recruit_videos").select("id, prospect_id, share_token, sent_at, sent_via, view_count, first_viewed_at, cta_clicked_at, video:agent_videos(title)").eq("brokerage_id",s).not("sent_at","is",null).order("sent_at",{ascending:!1}),{data:g}=await q.from("recruit_campaign_sends").select("id, prospect_id, subject, status, sent_at, opened_at, clicked_at, error_message, email_number").eq("brokerage_id",s).order("sent_at",{ascending:!1,nullsFirst:!1}),_=[];for(const j of f||[]){const b=h.get(j.prospect_id);b&&_.push({id:`v-${j.id}`,kind:"video",prospect_id:j.prospect_id,prospect_name:`${b.first_name||""} ${b.last_name||""}`.trim()||"—",prospect_email:b.email,subject:(v=j.video)!=null&&v.title?`Video: ${j.video.title}`:"Recruiting Video",status:j.cta_clicked_at?"clicked":j.first_viewed_at?"viewed":"sent",sent_at:j.sent_at,opened_at:j.first_viewed_at,clicked_at:j.cta_clicked_at,view_count:j.view_count,share_token:j.share_token})}for(const j of g||[]){if(!j.sent_at)continue;const b=h.get(j.prospect_id);b&&_.push({id:`c-${j.id}`,kind:"campaign",prospect_id:j.prospect_id,prospect_name:`${b.first_name||""} ${b.last_name||""}`.trim()||"—",prospect_email:b.email,subject:j.subject||`Email #${j.email_number}`,status:j.status||"sent",sent_at:j.sent_at,opened_at:j.opened_at,clicked_at:j.clicked_at,error:j.error_message})}return _.sort((j,b)=>new Date(b.sent_at).getTime()-new Date(j.sent_at).getTime()),_}}),o=N.useMemo(()=>{const d=i||[];return{total:d.length,videos:d.filter(u=>u.kind==="video").length,campaigns:d.filter(u=>u.kind==="campaign").length,opened:d.filter(u=>u.opened_at).length,clicked:d.filter(u=>u.clicked_at).length}},[i]),c=N.useMemo(()=>(i||[]).filter(u=>{if(r!=="all"&&u.kind!==r)return!1;if(!t)return!0;const h=t.toLowerCase();return u.prospect_name.toLowerCase().includes(h)||(u.prospect_email||"").toLowerCase().includes(h)||u.subject.toLowerCase().includes(h)}),[i,t,r]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[{label:"Total Sent",value:o.total,icon:cr,color:"text-primary"},{label:"Video Emails",value:o.videos,icon:br,color:"text-blue-500"},{label:"Campaign Emails",value:o.campaigns,icon:Vs,color:"text-violet-500"},{label:"Opened / Viewed",value:o.opened,icon:Er,color:"text-amber-500"},{label:"Clicked",value:o.clicked,icon:oc,color:"text-emerald-500"}].map(d=>e.jsx(fe,{children:e.jsxs(Ee,{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(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(It,{className:"text-lg",children:"Sent Emails"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Br,{value:r,onValueChange:d=>a(d),children:e.jsxs(Fr,{className:"h-8",children:[e.jsx(Kt,{value:"all",className:"text-xs h-7",children:"All"}),e.jsx(Kt,{value:"video",className:"text-xs h-7",children:"Video"}),e.jsx(Kt,{value:"campaign",className:"text-xs h-7",children:"Campaign"})]})}),e.jsxs("div",{className:"relative w-56",children:[e.jsx(vr,{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(Ee,{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(Vs,{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(ze,{variant:"outline",className:"gap-1",children:[e.jsx(br,{className:"h-3 w-3"}),"Video"]}):e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Vs,{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(ze,{variant:"destructive",className:"gap-1",children:[e.jsx(Gi,{className:"h-3 w-3"}),d.status]}):d.clicked_at?e.jsxs(ze,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(oc,{className:"h-3 w-3"}),"Clicked"]}):d.opened_at?e.jsxs(ze,{className:"bg-blue-500/15 text-blue-700 border-blue-200 gap-1",children:[e.jsx(Er,{className:"h-3 w-3"}),"Opened"]}):e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(cr,{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:[Ss(new Date(d.sent_at),"MMM d, yyyy"),e.jsx("div",{className:"text-[10px]",children:Ss(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(Er,{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 Wtn(){var l;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:n}=ys(),[r,a]=N.useState("board"),i=t||((l=s[0])==null?void 0:l.id)||"";return s.length===0?e.jsx(Ts,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Va,{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(Ts,{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(ds,{value:i,onValueChange:n,children:[e.jsxs(ls,{className:"w-[280px]",children:[e.jsx(Va,{className:"mr-2 h-4 w-4"}),e.jsx(us,{placeholder:"Select brokerage"})]}),e.jsx(cs,{children:s.map(o=>e.jsx(Qe,{value:o.id,children:o.name},o.id))})]})]}),i?e.jsxs(Br,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(Fr,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Kt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Kt,{value:"contacts",children:[e.jsx(Nn,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Kt,{value:"video-outreach",children:[e.jsx(br,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Kt,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Kt,{value:"referrals",children:"Referrals"}),e.jsx(Kt,{value:"interest",children:"Interest Form"}),e.jsx(Kt,{value:"landing-page",children:"Landing Page"}),e.jsx(Kt,{value:"goals",children:"Goals"}),e.jsx(Kt,{value:"metrics",children:"Metrics"}),e.jsx(Kt,{value:"templates",children:"Email Templates"}),e.jsxs(Kt,{value:"campaigns",children:[e.jsx(Vs,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Kt,{value:"drip-assignments",children:[e.jsx(cr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsxs(Kt,{value:"sent-emails",children:[e.jsx(Y2,{className:"h-3.5 w-3.5 mr-1"}),"Sent Emails"]}),e.jsx(Kt,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Kt,{value:"email-settings",children:[e.jsx(Xo,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Kt,{value:"pipeline-stages",children:[e.jsx(l4,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]})]}),e.jsxs(is,{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(yf,{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(vL,{className:"h-3.5 w-3.5"})," Table"]})]})}),r==="board"?e.jsx(iNt,{brokerageId:i}):e.jsx(Yge,{brokerageId:i})]}),e.jsx(is,{value:"contacts",children:e.jsx(Yge,{brokerageId:i})}),e.jsx(is,{value:"video-outreach",children:e.jsx(fNt,{brokerageId:i})}),e.jsx(is,{value:"follow-ups",children:e.jsx(hNt,{brokerageId:i})}),e.jsx(is,{value:"referrals",children:e.jsx(dNt,{brokerageId:i})}),e.jsx(is,{value:"interest",children:e.jsx(uNt,{brokerageId:i})}),e.jsx(is,{value:"landing-page",children:e.jsx(mNt,{brokerageId:i})}),e.jsx(is,{value:"goals",children:e.jsx(xNt,{brokerageId:i})}),e.jsx(is,{value:"metrics",children:e.jsx(oNt,{brokerageId:i})}),e.jsx(is,{value:"templates",children:e.jsx(lNt,{brokerageId:i})}),e.jsx(is,{value:"campaigns",children:e.jsx(vNt,{brokerageId:i})}),e.jsx(is,{value:"drip-assignments",children:e.jsx(bNt,{brokerageId:i})}),e.jsx(is,{value:"sent-emails",children:e.jsx(Gtn,{brokerageId:i})}),e.jsx(is,{value:"activity",children:e.jsx(cNt,{brokerageId:i})}),e.jsx(is,{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(T8e,{brokerageId:i})]})}),e.jsx(is,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(_Nt,{brokerageId:i})})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Va,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found."})]})]})})}function Ktn(){const[s,t]=N.useState(""),{data:n,isLoading:r}=ct({queryKey:["admin-brokerage-content-activity"],queryFn:async()=>{const{data:o}=await q.from("brokerages").select("id, name");if(!o)return[];const{data:c}=await q.from("brokerage_content").select("id, brokerage_id, content_type, created_at"),{data:d}=await q.from("brokerage_content_categories").select("id, brokerage_id"),u=c||[],h=d||[],p=o.map(f=>{const g=u.filter(j=>j.brokerage_id===f.id),_=h.filter(j=>j.brokerage_id===f.id),v=g.length>0?g.reduce((j,b)=>b.created_at>j?b.created_at:j,g[0].created_at):null;return{brokerage_id:f.id,brokerage_name:f.name,total_items:g.length,videos:g.filter(j=>j.content_type==="video").length,pdfs:g.filter(j=>j.content_type==="pdf").length,links:g.filter(j=>j.content_type==="link"||j.content_type==="canva_link").length,events:g.filter(j=>j.content_type==="event").length,graphics:g.filter(j=>j.content_type==="graphic").length,latest_item_date:v,categories:_.length}});return p.sort((f,g)=>g.total_items-f.total_items),p}}),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(Ts,{title:"Brokerage Content Activity",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ud,{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(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Active Brokerages"})}),e.jsxs(Ee,{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(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total Content Items"})}),e.jsxs(Ee,{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(fe,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total Brokerages"})}),e.jsxs(Ee,{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"registered"})]})]})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search brokerages...",value:s,onChange:o=>t(o.target.value),className:"pl-9"})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Hs,{children:[e.jsx(Ct,{children:"Brokerage"}),e.jsx(Ct,{className:"text-center",children:"Total"}),e.jsx(Ct,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(br,{className:"h-3 w-3"})," Videos"]})}),e.jsx(Ct,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Nr,{className:"h-3 w-3"})," PDFs"]})}),e.jsx(Ct,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(El,{className:"h-3 w-3"})," Links"]})}),e.jsx(Ct,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Tl,{className:"h-3 w-3"})," Events"]})}),e.jsx(Ct,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(nl,{className:"h-3 w-3"})," Graphics"]})}),e.jsx(Ct,{className:"text-center",children:"Categories"}),e.jsx(Ct,{children:"Last Upload"})]})}),e.jsx(ha,{children:r?e.jsx(Hs,{children:e.jsx(ut,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(Hs,{children:e.jsx(ut,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No brokerages found"})}):a.map(o=>e.jsxs(Hs,{className:o.total_items===0?"opacity-50":"",children:[e.jsx(ut,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Va,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:o.brokerage_name})]})}),e.jsx(ut,{className:"text-center",children:o.total_items>0?e.jsx(ze,{variant:"secondary",className:"font-bold",children:o.total_items}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ut,{className:"text-center",children:o.videos||"–"}),e.jsx(ut,{className:"text-center",children:o.pdfs||"–"}),e.jsx(ut,{className:"text-center",children:o.links||"–"}),e.jsx(ut,{className:"text-center",children:o.events||"–"}),e.jsx(ut,{className:"text-center",children:o.graphics||"–"}),e.jsx(ut,{className:"text-center",children:o.categories||"–"}),e.jsx(ut,{children:o.latest_item_date?e.jsx("span",{className:"text-sm text-muted-foreground",children:Ss(new Date(o.latest_item_date),"MMM d, yyyy")}):e.jsx("span",{className:"text-muted-foreground",children:"–"})})]},o.brokerage_id))})]})})})]})})}const Ytn=[{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:"📉"}],PXe=[{value:"instagram-square",label:"Instagram Post",dimensions:"1080×1080",icon:e.jsx(du,{className:"h-4 w-4"})},{value:"instagram-story",label:"Instagram Story",dimensions:"1080×1920",icon:e.jsx(du,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook Post",dimensions:"1200×630",icon:e.jsx(Lh,{className:"h-4 w-4"})}],Ztn=[{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:"📰"}],LXe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),DXe={"luxury-dark":$Ie,"modern-clean":UIe,"bold-colorful":qIe,editorial:VIe};function Qtn(){const[s,t]=N.useState(""),[n,r]=N.useState("address"),[a,i]=N.useState(!1),[l,o]=N.useState([]),[c,d]=N.useState(null),[u,h]=N.useState(0),[p,f]=N.useState("just-listed"),[g,_]=N.useState(["instagram-square"]),[v,j]=N.useState("luxury-dark"),[b,S]=N.useState(!1),[A,T]=N.useState(""),[L,D]=N.useState(""),[M,F]=N.useState(""),[z,V]=N.useState(!1),[W,Y]=N.useState(!1),[K,J]=N.useState([]),[ne,ie]=N.useState("search"),he=N.useRef({});N.useEffect(()=>{(async()=>{const{data:{user:De}}=await q.auth.getUser();if(!De)return;const{data:Ie}=await q.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",De.id).single();if(Ie){T(Ie.name||""),F(Ie.avatar_url||"");const Fe=Ie.brokerages;D((Fe==null?void 0:Fe.name)||"")}})()},[]);const ce=async()=>{var Ae;if(s.trim()){i(!0),o([]);try{const{data:De,error:Ie}=await q.functions.invoke("repliers-mls-search",{body:{searchType:n,query:s.trim()}});if(Ie)throw Ie;if(De.error)throw new Error(De.error);o(De.listings||[]),((Ae=De.listings)==null?void 0:Ae.length)===0&&ae.info("No listings found. Try a different search.")}catch(De){ae.error(De.message||"Search failed")}finally{i(!1)}}},pe=Ae=>{var De;d(Ae),h(0),ie("customize"),Ae.soldDate||(De=Ae.status)!=null&&De.toLowerCase().includes("sold")?f("just-sold"):f("just-listed")},le=Ae=>{_(De=>De.includes(Ae)?De.filter(Ie=>Ie!==Ae):[...De,Ae])},ve=N.useCallback(async()=>{if(!(!c||g.length===0)){V(!0),J([]),ie("generate");try{await new Promise(De=>setTimeout(De,500));const Ae=[];for(const De of g){const Ie=`${v}-${De}`,Fe=he.current[Ie];if(!Fe)continue;const qe=RS[De],be=await BIe(Fe,{width:qe.width,height:qe.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Ae.push({format:De,imageUrl:be})}J(Ae),ae.success(`Generated ${Ae.length} social post${Ae.length>1?"s":""}!`)}catch(Ae){ae.error(Ae.message||"Generation failed")}finally{V(!1)}}},[c,g,v,u,b,A,L,M,p]),ge=async()=>{if(!(!c||g.length===0)){V(!0),J([]),ie("generate");try{const Ae={...c,photos:c.photos.length>0?[c.photos[u]]:[]},De=[];for(const Ie of g){const{data:Fe,error:qe}=await q.functions.invoke("generate-listing-social-post",{body:{listing:Ae,postType:p,format:Ie,branding:b?{enabled:!0,agentName:A,brokerage:L}:{enabled:!1}}});if(qe)throw qe;if(Fe.error)throw new Error(Fe.error);De.push({format:Ie,imageUrl:Fe.imageUrl})}J(De),ae.success(`Generated ${De.length} AI post${De.length>1?"s":""}!`)}catch(Ae){ae.error(Ae.message||"AI generation failed")}finally{V(!1)}}},Te=()=>W?ge():ve(),Me=(Ae,De)=>{var Fe;const Ie=document.createElement("a");Ie.href=Ae,Ie.download=`${((Fe=c==null?void 0:c.address)==null?void 0:Fe.replace(/\s+/g,"-"))||"listing"}-${p}-${De}.png`,document.body.appendChild(Ie),Ie.click(),document.body.removeChild(Ie)},Ce=c?{listing:c,postType:p,format:"instagram-square",branding:b?{enabled:!0,agentName:A,brokerage:L,agentPhotoUrl:M||void 0}:{enabled:!1},selectedPhotoIndex:u}:null;return e.jsx(Ts,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Ud,{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:()=>ie("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${ne==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[e.jsx(vr,{className:"h-3.5 w-3.5"})," 1. Find Listing"]}),e.jsx(xa,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>c&&ie("customize"),disabled:!c,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${ne==="customize"?"bg-primary text-primary-foreground":c?"bg-muted text-muted-foreground hover:text-foreground":"bg-muted text-muted-foreground/50 cursor-not-allowed"}`,children:[e.jsx(un,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(xa,{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 ${ne==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(nl,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),ne==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(vr,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx(lpt,{})]}),e.jsx(Vn,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx(Br,{value:n,onValueChange:Ae=>r(Ae),children:e.jsxs(Fr,{children:[e.jsxs(Kt,{value:"address",children:[e.jsx(ka,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Kt,{value:"mls",children:[e.jsx(uh,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:s,onChange:Ae=>t(Ae.target.value),placeholder:n==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Ae=>Ae.key==="Enter"&&ce()}),e.jsxs(B,{onClick:ce,disabled:a||!s.trim(),children:[a?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(vr,{className:"h-4 w-4"})," Search"]})]})]})]}),l.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[l.length," listing",l.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:l.map((Ae,De)=>{var Ie;return e.jsx(fe,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>pe(Ae),children:e.jsx(Ee,{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:(Ie=Ae.photos)!=null&&Ie[0]?e.jsx("img",{src:Ae.photos[0],alt:Ae.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(Or,{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:LXe(Ae.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Ae.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ae.city,", ",Ae.state," ",Ae.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Ae.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(H2,{className:"h-3 w-3"})," ",Ae.bedrooms]}),Ae.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Cp,{className:"h-3 w-3"})," ",Ae.bathrooms]}),Ae.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(RA,{className:"h-3 w-3"})," ",Ae.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ze,{variant:"outline",className:"text-[10px]",children:Ae.mlsNumber}),e.jsx(ze,{variant:"outline",className:"text-[10px]",children:Ae.status})]})]})]})})},Ae.mlsNumber||De)})})]})]}),ne==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"lg:col-span-1",children:[e.jsx(Mt,{className:"pb-3",children:e.jsx(It,{className:"text-base",children:"Selected Listing"})}),e.jsxs(Ee,{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(Ae=>Math.max(0,Ae-1)),disabled:u===0,children:e.jsx(pl,{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(Ae=>Math.min(c.photos.length-1,Ae+1)),disabled:u===c.photos.length-1,children:e.jsx(xa,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:LXe(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:()=>{ie("search"),d(null)},children:[e.jsx(cm,{className:"h-3.5 w-3.5 mr-1.5"})," Choose Different Listing"]})]})]}),e.jsxs(fe,{className:"lg:col-span-2",children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(Vn,{children:"Choose template, post type, format, and branding"})]}),e.jsxs(Ee,{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(fl,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:W?"AI Custom Generation":"Template-Based (Free)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:W?"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(bn,{checked:W,onCheckedChange:Y}),W&&e.jsx(Dm,{className:"h-4 w-4 text-purple-500"})]})]}),!W&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(fl,{className:"h-4 w-4"})," Template Style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Ztn.map(Ae=>e.jsxs("button",{onClick:()=>j(Ae.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${v===Ae.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:Ae.preview}),e.jsx("span",{className:"text-sm font-medium",children:Ae.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:Ae.description})]},Ae.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:Ytn.map(Ae=>e.jsxs("button",{onClick:()=>f(Ae.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${p===Ae.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:Ae.icon})," ",Ae.label]},Ae.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:PXe.map(Ae=>e.jsxs("button",{onClick:()=>le(Ae.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${g.includes(Ae.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Ae.icon,e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium",children:Ae.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Ae.dimensions})]})]},Ae.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(Xi,{className:"h-4 w-4"})," Agent Branding"]}),e.jsx(bn,{checked:b,onCheckedChange:S})]}),b&&e.jsxs("div",{className:"space-y-3 pl-6 border-l-2 border-primary/20",children:[M&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:M,alt:"Agent",className:"w-12 h-12 rounded-full object-cover border-2 border-primary/30"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Profile photo will appear on the post"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Agent Name"}),e.jsx(ye,{value:A,onChange:Ae=>T(Ae.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:L,onChange:Ae=>D(Ae.target.value),placeholder:"XYZ Realty"})]})]})]})]}),!W&&Ce&&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*(RS[g[0]||"instagram-square"].height/RS[g[0]||"instagram-square"].width)},children:(()=>{const Ae=DXe[v],De=g[0]||"instagram-square";return e.jsx(Ae,{...Ce,format:De})})()})})]}),e.jsx(B,{onClick:Te,disabled:g.length===0||z,size:"lg",className:"w-full gap-2",children:z?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-5 w-5 animate-spin"})," Generating ",g.length," post",g.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[W?e.jsx(Dm,{className:"h-5 w-5"}):e.jsx(un,{className:"h-5 w-5"}),"Generate ",g.length," Social Post",g.length>1?"s":"",W&&e.jsx(ze,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),ne==="generate"&&e.jsxs("div",{className:"space-y-4",children:[z&&e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(ts,{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:W?"AI is creating your unique designs":"Rendering templates to high-res images"})]})}),K.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:()=>ie("customize"),children:[e.jsx(cm,{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:K.map((Ae,De)=>{const Ie=PXe.find(Fe=>Fe.value===Ae.format);return e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:Ae.imageUrl,alt:`${Ae.format} social post`,className:"w-full rounded"})}),e.jsxs(Ee,{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:[Ie==null?void 0:Ie.icon,e.jsx("span",{className:"text-sm font-medium",children:Ie==null?void 0:Ie.label})]}),e.jsx(ze,{variant:"outline",className:"text-[10px]",children:Ie==null?void 0:Ie.dimensions})]}),e.jsxs(B,{size:"sm",className:"w-full gap-1.5",onClick:()=>Me(Ae.imageUrl,Ae.format),children:[e.jsx(Pa,{className:"h-3.5 w-3.5"})," Download"]})]})]},De)})})]})]}),ne==="generate"&&!W&&c&&Ce&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:g.map(Ae=>{const De=DXe[v],Ie=RS[Ae];return e.jsx("div",{style:{width:Ie.width,height:Ie.height},children:e.jsx(De,{ref:Fe=>{he.current[`${v}-${Ae}`]=Fe},...Ce,format:Ae})},`${v}-${Ae}`)})})]})})}function Xtn(){return ct({queryKey:["lms-courses-admin"],queryFn:async()=>{const{data:s,error:t}=await q.from("lms_courses").select("*, modules:lms_modules(count), access:lms_course_access(*)").order("sort_order");if(t)throw t;return s}})}function Jtn(s){return ct({queryKey:["lms-course-admin",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*)), access:lms_course_access(*)").eq("id",s).single();if(n)throw n;return t!=null&&t.modules&&(t.modules.sort((r,a)=>r.sort_order-a.sort_order),t.modules.forEach(r=>{r.resources&&r.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function esn(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("lms_courses").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function wNt(){const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("lms_courses").update({...n,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-courses-admin"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function tsn(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("lms_courses").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function ssn(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("lms_modules").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function nsn(){const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("lms_modules").update({...n,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function rsn(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("lms_modules").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function asn(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.from("lms_module_resources").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function isn(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("lms_module_resources").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function osn(){const s=Ht();return gt({mutationFn:async({courseId:t,accessRules:n})=>{const{error:r}=await q.from("lms_course_access").delete().eq("course_id",t);if(r)throw r;if(n.length>0){const a=n.map(l=>({...l,course_id:t})),{error:i}=await q.from("lms_course_access").insert(a);if(i)throw i}},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]})}})}function lsn(){return ct({queryKey:["lms-courses-agent"],queryFn:async()=>{const{data:s,error:t}=await q.from("lms_courses").select("*, modules:lms_modules(id)").eq("is_published",!0).order("sort_order");if(t)throw t;return s}})}function csn(s){return ct({queryKey:["lms-course-agent",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*))").eq("id",s).single();if(n)throw n;return t!=null&&t.modules&&(t.modules.sort((r,a)=>r.sort_order-a.sort_order),t.modules.forEach(r=>{r.resources&&r.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function jNt(s){return ct({queryKey:["lms-progress",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("lms_progress").select("*").eq("course_id",s);if(n)throw n;return t},enabled:!!s})}function dsn(){const s=Ht();return gt({mutationFn:async({courseId:t,moduleId:n,userId:r})=>{const{data:a,error:i}=await q.from("lms_progress").upsert({user_id:r,course_id:t,module_id:n,completed:!0,completed_at:new Date().toISOString()},{onConflict:"user_id,module_id"}).select().single();if(i)throw i;return a},onSuccess:()=>s.invalidateQueries({queryKey:["lms-progress"]})})}function usn(){const{user:s}=ys(),t=Mn(),{data:n,isLoading:r}=Xtn(),a=esn(),i=wNt(),l=tsn(),[o,c]=N.useState(!1),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,g]=N.useState(!0),_=async()=>{if(!(!d.trim()||!s))try{const b=await a.mutateAsync({title:d.trim(),description:h.trim()||void 0,is_sequential:f,created_by:s.id});ae.success("Course created"),c(!1),u(""),p(""),g(!0),t(`/admin/lms/${b.id}`)}catch{ae.error("Failed to create course")}},v=async b=>{try{await i.mutateAsync({id:b.id,is_published:!b.is_published}),ae.success(b.is_published?"Course unpublished":"Course published")}catch{ae.error("Failed to update course")}},j=async b=>{if(confirm("Delete this course and all its modules? This cannot be undone."))try{await l.mutateAsync(b),ae.success("Course deleted")}catch{ae.error("Failed to delete")}};return e.jsxs(Ts,{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(_d,{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(yo,{className:"h-4 w-4 mr-2"}),"Analytics"]}),e.jsxs(B,{onClick:()=>c(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"New Course"]})]})]}),r?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:[1,2,3].map(b=>e.jsx(fe,{className:"animate-pulse",children:e.jsxs(Mt,{children:[e.jsx("div",{className:"h-5 bg-muted rounded w-2/3"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2 mt-2"})]})},b))}):n!=null&&n.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:n.map(b=>{var L,D;const S=((D=(L=b.modules)==null?void 0:L[0])==null?void 0:D.count)??0,A=b.access||[],T=A.length===0?"No access set":A.some(M=>M.access_type==="all")?"All agents":`${A.length} rule(s)`;return e.jsxs(fe,{className:"group hover:shadow-md transition-all hover:border-primary/50 cursor-pointer",onClick:()=>t(`/admin/lms/${b.id}`),children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(It,{className:"text-base truncate",children:b.title}),b.description&&e.jsx(Vn,{className:"mt-1 line-clamp-2",children:b.description})]}),e.jsx(ze,{variant:b.is_published?"default":"secondary",className:"ml-2 shrink-0",children:b.is_published?"Published":"Draft"})]})}),e.jsxs(Ee,{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(Ou,{className:"h-3.5 w-3.5"}),S," module",S!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[b.is_sequential?e.jsx(Ov,{className:"h-3.5 w-3.5"}):e.jsx($A,{className:"h-3.5 w-3.5"}),b.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"}),T]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsxs(B,{size:"sm",variant:"ghost",onClick:M=>{M.stopPropagation(),v(b)},children:[b.is_published?e.jsx(xf,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Er,{className:"h-3.5 w-3.5 mr-1"}),b.is_published?"Unpublish":"Publish"]}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-destructive",onClick:M=>{M.stopPropagation(),j(b.id)},children:e.jsx(_n,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex-1"}),e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground"})]})]})]},b.id)})}):e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Ou,{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(Is,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create New Course"}),e.jsx(Qn,{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:b=>u(b.target.value),placeholder:"e.g. LevelUp Onboarding"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Es,{value:h,onChange:b=>p(b.target.value),placeholder:"What will agents learn?",rows:3})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sequential Learning"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents must complete modules in order"})]}),e.jsx(bn,{checked:f,onCheckedChange:g})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{onClick:_,disabled:!d.trim()||a.isPending,children:a.isPending?"Creating...":"Create Course"})]})]})})]})}function hsn(){const{courseId:s}=bi(),t=Mn(),{data:n,isLoading:r}=Jtn(s),a=wNt(),i=ssn(),l=nsn(),o=rsn(),c=asn(),d=isn(),u=osn(),{data:h}=ct({queryKey:["all-brokerages"],queryFn:async()=>{const{data:tt}=await q.from("brokerages").select("id, name").order("name");return tt||[]}}),[p,f]=N.useState(null),[g,_]=N.useState(!1),[v,j]=N.useState({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),[b,S]=N.useState(null),[A,T]=N.useState({title:"",resource_type:"link",url:""}),[L,D]=N.useState(new Set),[M,F]=N.useState(null),[z,V]=N.useState(0),[W,Y]=N.useState(!1),K=N.useRef(null),J=N.useRef(null),[ne,ie]=N.useState(!1),[he,ce]=N.useState(""),[pe,le]=N.useState(""),[ve,ge]=N.useState(""),[Te,Me]=N.useState(!1);if(r)return e.jsx(Ts,{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(Ts,{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(Hr,{className:"h-4 w-4 mr-2"})," Back to Courses"]})]})});const Ce=n.modules||[],Ae=n.access||[],De=Ae.some(tt=>tt.access_type==="all"),Ie=Ae.filter(tt=>tt.access_type==="brokerage").map(tt=>tt.brokerage_id),Fe=(h||[]).filter(tt=>tt.name.toLowerCase().includes(he.toLowerCase())),qe=tt=>{const at=new Set(L);at.has(tt)?at.delete(tt):at.add(tt),D(at)},be=async()=>{if(!M)return null;Y(!0),V(0);try{const{data:tt,error:at}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:M.name}});if(at)throw new Error(at.message);const{videoId:He,libraryId:dt}=tt,{data:bt,error:vt}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:He,libraryId:dt}});if(vt)throw new Error(vt.message);const Bt=new XMLHttpRequest;return await new Promise((Zt,Fs)=>{Bt.upload.onprogress=Rs=>{Rs.lengthComputable&&V(Math.round(Rs.loaded/Rs.total*100))},Bt.onload=()=>Bt.status>=200&&Bt.status<300?Zt():Fs(new Error(`Upload failed: ${Bt.status}`)),Bt.onerror=()=>Fs(new Error("Upload failed")),Bt.open("PUT",bt.uploadUrl),Bt.setRequestHeader("AccessKey",bt.apiKey),Bt.send(M)}),`https://iframe.mediadelivery.net/embed/${dt}/${He}`}catch(tt){return console.error("Bunny upload error:",tt),ae.error("Video upload failed"),null}finally{Y(!1),V(0)}},Ze=async()=>{if(v.title.trim())try{let tt=v.video_url.trim()||void 0;if(M){const at=await be();if(!at)return;tt=at}await i.mutateAsync({course_id:n.id,title:v.title.trim(),description:v.description.trim()||void 0,video_url:tt,text_content:v.text_content.trim()||void 0,duration_minutes:v.duration_minutes?parseInt(v.duration_minutes):void 0,sort_order:Ce.length}),ae.success("Module added"),_(!1),j({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),F(null)}catch{ae.error("Failed to add module")}},Ne=async()=>{if(p)try{let tt=v.video_url.trim()||null;if(M){const at=await be();if(!at)return;tt=at}await l.mutateAsync({id:p.id,title:v.title.trim(),description:v.description.trim()||null,video_url:tt,text_content:v.text_content.trim()||null,duration_minutes:v.duration_minutes?parseInt(v.duration_minutes):null}),ae.success("Module updated"),f(null),F(null)}catch{ae.error("Failed to update")}},it=async tt=>{if(confirm("Delete this module?"))try{await o.mutateAsync(tt),ae.success("Module deleted")}catch{ae.error("Failed to delete")}},je=async tt=>{if(A.title.trim())try{await c.mutateAsync({module_id:tt,title:A.title.trim(),resource_type:A.resource_type,url:A.url.trim()||void 0}),ae.success("Resource added"),S(null),T({title:"",resource_type:"link",url:""})}catch{ae.error("Failed to add resource")}},Ge=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[{access_type:"all"}]}),ae.success("Access updated: All brokerages / all agents")}catch{ae.error("Failed to update access")}},Be=async tt=>{const at=Ae.filter(vt=>vt.access_type==="brokerage").map(vt=>vt.brokerage_id),He=at.includes(tt);let dt;He?dt=at.filter(vt=>vt!==tt):dt=[...at,tt];const bt=dt.map(vt=>({access_type:"brokerage",brokerage_id:vt}));try{await u.mutateAsync({courseId:n.id,accessRules:bt}),ae.success(He?"Brokerage removed":"Brokerage added")}catch{ae.error("Failed to update access")}},Ye=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[]}),ae.success("Access cleared")}catch{ae.error("Failed")}},We=async(tt,at)=>{const He=at==="up"?tt-1:tt+1;if(!(He<0||He>=Ce.length))try{await Promise.all([l.mutateAsync({id:Ce[tt].id,sort_order:He}),l.mutateAsync({id:Ce[He].id,sort_order:tt})])}catch{ae.error("Failed to reorder")}},rt=async()=>{try{await a.mutateAsync({id:n.id,title:pe,description:ve||null}),ae.success("Course updated"),Me(!1)}catch{ae.error("Failed to update")}};return e.jsxs(Ts,{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(Hr,{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(ze,{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(Ov,{className:"h-3.5 w-3.5"}):e.jsx($A,{className:"h-3.5 w-3.5"}),n.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{children:[Ce.length," module",Ce.length!==1?"s":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{le(n.title),ge(n.description||""),Me(!0)},children:[e.jsx(_a,{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(()=>ae.success(n.is_published?"Unpublished":"Published")),children:[n.is_published?e.jsx(xf,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Er,{className:"h-3.5 w-3.5 mr-1"}),n.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs(Br,{defaultValue:"modules",className:"w-full",children:[e.jsxs(Fr,{children:[e.jsx(Kt,{value:"modules",children:"Modules"}),e.jsx(Kt,{value:"access",children:"Access & Permissions"}),e.jsx(Kt,{value:"settings",children:"Settings"})]}),e.jsxs(is,{value:"modules",className:"mt-6 space-y-4",children:[Ce.map((tt,at)=>e.jsxs(fe,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>qe(tt.id),children:[e.jsx("span",{className:"flex items-center gap-1 text-muted-foreground",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("button",{onClick:He=>{He.stopPropagation(),We(at,"up")},disabled:at===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(tx,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:He=>{He.stopPropagation(),We(at,"down")},disabled:at===Ce.length-1,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(io,{className:"h-3.5 w-3.5"})})]})}),e.jsx(ze,{variant:"outline",className:"shrink-0 font-mono text-xs",children:at+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:tt.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[tt.video_url&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(br,{className:"h-3 w-3"})," Video"]}),tt.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Nr,{className:"h-3 w-3"})," Text"]}),tt.duration_minutes&&e.jsxs("span",{children:[tt.duration_minutes," min"]}),tt.resources&&tt.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(El,{className:"h-3 w-3"})," ",tt.resources.length," resource(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:He=>{var dt;He.stopPropagation(),f(tt),j({title:tt.title,description:tt.description||"",video_url:tt.video_url||"",text_content:tt.text_content||"",duration_minutes:((dt=tt.duration_minutes)==null?void 0:dt.toString())||""})},children:e.jsx(_a,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-destructive",onClick:He=>{He.stopPropagation(),it(tt.id)},children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]}),L.has(tt.id)&&e.jsxs("div",{className:"border-t bg-muted/30 p-4 space-y-3",children:[tt.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:tt.description}),tt.video_url&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Video: "}),e.jsx("a",{href:tt.video_url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline break-all",children:tt.video_url})]}),tt.text_content&&e.jsx("div",{className:"text-sm bg-background rounded-md p-3 border max-h-40 overflow-auto whitespace-pre-wrap",children:tt.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:()=>{S(tt.id),T({title:"",resource_type:"link",url:""})},children:[e.jsx(Is,{className:"h-3 w-3 mr-1"})," Add Resource"]})]}),tt.resources&&tt.resources.length>0?e.jsx("div",{className:"space-y-1",children:tt.resources.map(He=>e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-background rounded p-2 border",children:[e.jsx(ze,{variant:"outline",className:"text-[10px]",children:He.resource_type}),e.jsx("span",{className:"flex-1 truncate",children:He.title}),He.url&&e.jsx("a",{href:He.url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline text-xs",children:"Open"}),e.jsx(B,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-destructive",onClick:()=>d.mutateAsync(He.id),children:e.jsx(Bn,{className:"h-3 w-3"})})]},He.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No resources yet"})]})]})]},tt.id)),e.jsxs(B,{variant:"outline",className:"w-full border-dashed",onClick:()=>{_(!0),j({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(is,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(Ee,{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",De?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"),onClick:Ge,children:[e.jsx("div",{className:Et("h-10 w-10 rounded-full flex items-center justify-center shrink-0",De?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(lc,{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(bn,{checked:De,onCheckedChange:Ge})]}),!De&&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:Ie.length===0?"No brokerages selected — agents won't see this course":`${Ie.length} brokerage${Ie.length!==1?"s":""} selected`})]}),Ie.length>0&&e.jsx(B,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:Ye,children:"Clear all"})]}),e.jsx(ye,{placeholder:"Search brokerages...",value:he,onChange:tt=>ce(tt.target.value),className:"h-9"}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[360px] overflow-auto",children:Fe.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):Fe.map(tt=>{const at=Ie.includes(tt.id);return e.jsxs("div",{className:Et("flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors",at?"bg-primary/5":"hover:bg-muted/50"),onClick:()=>Be(tt.id),children:[e.jsx("div",{className:Et("h-5 w-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors",at?"bg-primary border-primary":"border-muted-foreground/30"),children:at&&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(Va,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:tt.name}),at&&e.jsx(ze,{variant:"secondary",className:"text-[10px] shrink-0",children:"Active"})]},tt.id)})})]})]})]})}),e.jsxs(is,{value:"settings",className:"mt-6 space-y-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Course Thumbnail"})}),e.jsx(Ee,{children:e.jsxs("div",{className:"flex items-start gap-6",children:[n.thumbnail_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:n.thumbnail_url,alt:"Course thumbnail",className:"w-48 h-28 object-cover rounded-lg border"}),e.jsx("button",{onClick:()=>a.mutateAsync({id:n.id,thumbnail_url:null}).then(()=>ae.success("Thumbnail removed")),className:"absolute -top-2 -right-2 bg-destructive text-destructive-foreground rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Bn,{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(ry,{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:J,type:"file",accept:"image/*",className:"hidden",onChange:async tt=>{var He;const at=(He=tt.target.files)==null?void 0:He[0];if(!(!at||!n)){ie(!0);try{const dt=at.name.split(".").pop(),bt=`${n.id}/thumbnail.${dt}`,{error:vt}=await q.storage.from("lms-thumbnails").upload(bt,at,{upsert:!0});if(vt)throw vt;const{data:Bt}=q.storage.from("lms-thumbnails").getPublicUrl(bt),Zt=`${Bt.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:n.id,thumbnail_url:Zt}),ae.success("Thumbnail uploaded")}catch{ae.error("Failed to upload thumbnail")}finally{ie(!1),J.current&&(J.current.value="")}}}}),e.jsxs(B,{variant:"outline",size:"sm",disabled:ne,onClick:()=>{var tt;return(tt=J.current)==null?void 0:tt.click()},children:[ne?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Na,{className:"h-4 w-4 mr-2"}),ne?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Course Settings"})}),e.jsxs(Ee,{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(bn,{checked:n.is_sequential,onCheckedChange:tt=>a.mutateAsync({id:n.id,is_sequential:tt}).then(()=>ae.success("Updated"))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this course visible to agents with access"})]}),e.jsx(bn,{checked:n.is_published,onCheckedChange:tt=>a.mutateAsync({id:n.id,is_published:tt}).then(()=>ae.success("Updated"))})]})]})]})]})]})]}),e.jsx(bs,{open:g||!!p,onOpenChange:tt=>{tt||(_(!1),f(null))},children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:p?"Edit Module":"Add Module"}),e.jsx(Qn,{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:v.title,onChange:tt=>j(at=>({...at,title:tt.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Es,{value:v.description,onChange:tt=>j(at=>({...at,description:tt.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",M?"border-primary bg-primary/5":"border-muted-foreground/25"),onClick:()=>{var tt;return(tt=K.current)==null?void 0:tt.click()},children:[e.jsx("input",{ref:K,type:"file",accept:"video/*",className:"hidden",onChange:tt=>{var He;const at=(He=tt.target.files)==null?void 0:He[0];at&&(F(at),j(dt=>({...dt,video_url:""})))}}),M?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(br,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-primary",children:M.name}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:tt=>{tt.stopPropagation(),F(null)},children:e.jsx(Bn,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"flex flex-col items-center gap-1 text-muted-foreground",children:[e.jsx(Na,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Click to upload a video file"})]})]}),W&&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(ts,{className:"h-3.5 w-3.5 animate-spin"}),e.jsxs("span",{children:["Uploading to Bunny.net... ",z,"%"]})]}),e.jsx(pi,{value:z,className:"h-1.5"})]}),!M&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("div",{className:"flex-1 h-px bg-border"}),e.jsx("span",{children:"or paste a URL"}),e.jsx("div",{className:"flex-1 h-px bg-border"})]}),e.jsx(ye,{value:v.video_url,onChange:tt=>j(at=>({...at,video_url:tt.target.value})),placeholder:"YouTube, Vimeo, or Bunny.net URL"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Text Content"}),e.jsx(Es,{value:v.text_content,onChange:tt=>j(at=>({...at,text_content:tt.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:v.duration_minutes,onChange:tt=>j(at=>({...at,duration_minutes:tt.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>{_(!1),f(null),F(null)},children:"Cancel"}),e.jsxs(B,{onClick:p?Ne:Ze,disabled:!v.title.trim()||W,children:[W?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(qo,{className:"h-4 w-4 mr-2"}),W?"Uploading...":p?"Save Changes":"Add Module"]})]})]})}),e.jsx(bs,{open:!!b,onOpenChange:tt=>{tt||S(null)},children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Add Resource"}),e.jsx(Qn,{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:A.title,onChange:tt=>T(at=>({...at,title:tt.target.value})),placeholder:"Resource title"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Type"}),e.jsxs(ds,{value:A.resource_type,onValueChange:tt=>T(at=>({...at,resource_type:tt})),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"link",children:"Link"}),e.jsx(Qe,{value:"pdf",children:"PDF"}),e.jsx(Qe,{value:"template",children:"Template"}),e.jsx(Qe,{value:"worksheet",children:"Worksheet"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"URL"}),e.jsx(ye,{value:A.url,onChange:tt=>T(at=>({...at,url:tt.target.value})),placeholder:"https://..."})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>S(null),children:"Cancel"}),e.jsx(B,{onClick:()=>b&&je(b),disabled:!A.title.trim(),children:"Add Resource"})]})]})}),e.jsx(bs,{open:Te,onOpenChange:Me,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Edit Course"}),e.jsx(Qn,{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:pe,onChange:tt=>le(tt.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Es,{value:ve,onChange:tt=>ge(tt.target.value),rows:3})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Me(!1),children:"Cancel"}),e.jsx(B,{onClick:rt,disabled:!pe.trim(),children:"Save"})]})]})})]})}function msn(){return ct({queryKey:["lms-stats-overview"],queryFn:async()=>{const{data:s,error:t}=await q.rpc("get_lms_stats");if(t)throw t;return s}})}function psn(){return ct({queryKey:["lms-stats-courses"],queryFn:async()=>{const{data:s,error:t}=await q.rpc("get_lms_course_stats");if(t)throw t;return s||[]}})}function fsn(s){return ct({queryKey:["lms-stats-agents",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.rpc("get_lms_agent_progress",{p_course_id:s});if(n)throw n;return t||[]},enabled:!!s})}function xsn(){const s=Mn(),{data:t,isLoading:n}=msn(),{data:r,isLoading:a}=psn(),[i,l]=N.useState(null),{data:o,isLoading:c}=fsn(i),[d,u]=N.useState(""),h=r==null?void 0:r.find(g=>g.course_id===i),p=o==null?void 0:o.filter(g=>{var _,v;return!d||((_=g.agent_name)==null?void 0:_.toLowerCase().includes(d.toLowerCase()))||((v=g.email)==null?void 0:v.toLowerCase().includes(d.toLowerCase()))}),f=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:Ou,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon:xr,color:"text-emerald-500"},{label:"Enrolled Agents",value:(t==null?void 0:t.total_enrollments)??0,icon:Nn,color:"text-blue-500"},{label:"Modules Completed",value:(t==null?void 0:t.total_completions)??0,icon:vo,color:"text-amber-500"},{label:"Active (30d)",value:(t==null?void 0:t.active_learners)??0,icon:mo,color:"text-violet-500"},{label:"Total Modules",value:(t==null?void 0:t.total_modules)??0,icon:yo,color:"text-rose-500"}];return e.jsx(Ts,{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(Hr,{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(_d,{className:"h-7 w-7 text-primary"}),"LevelUp U — Analytics"]}),e.jsx("p",{className:"text-muted-foreground text-sm mt-0.5",children:"Track enrollment, progress, and completion across all courses"})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3",children:f.map(g=>e.jsx(fe,{className:Et("transition-all",n&&"animate-pulse"),children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(g.icon,{className:Et("h-4 w-4",g.color)}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:g.label})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:n?"—":g.value})]})},g.label))}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-5 gap-6",children:[e.jsxs("div",{className:"xl:col-span-2 space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(yo,{className:"h-5 w-5 text-primary"}),"Course Breakdown"]}),a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(g=>e.jsx(fe,{className:"animate-pulse",children:e.jsx(Ee,{className:"p-4",children:e.jsx("div",{className:"h-16 bg-muted rounded"})})},g))}):r!=null&&r.length?e.jsx("div",{className:"space-y-2",children:r.map(g=>{const _=i===g.course_id;return e.jsx(fe,{className:Et("cursor-pointer transition-all hover:shadow-md",_?"border-primary ring-1 ring-primary/30 shadow-md":"hover:border-primary/40"),onClick:()=>l(_?null:g.course_id),children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold text-sm text-foreground truncate",children:g.course_title}),e.jsx(ze,{variant:g.is_published?"default":"secondary",className:"shrink-0 text-[10px] px-1.5 py-0",children:g.is_published?"Live":"Draft"})]})}),e.jsx(xa,{className:Et("h-4 w-4 text-muted-foreground transition-transform shrink-0 ml-2",_&&"rotate-90")})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:g.enrolled_agents}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Enrolled"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:g.total_completions}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Completed"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:g.total_modules}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Modules"})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg. Completion"}),e.jsxs("span",{className:"font-semibold text-foreground",children:[g.avg_completion_pct,"%"]})]}),e.jsx(pi,{value:g.avg_completion_pct,className:"h-2"})]})]})},g.course_id)})}):e.jsx(fe,{className:"border-dashed",children:e.jsx(Ee,{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(bb,{className:"h-5 w-5 text-primary"}),h?`Agent Progress — ${h.course_title}`:"Agent Progress"]}),i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:d,onChange:g=>u(g.target.value),placeholder:"Search agents...",className:"pl-9"})]}),c?e.jsx("div",{className:"space-y-2",children:[1,2,3,4].map(g=>e.jsx(fe,{className:"animate-pulse",children:e.jsx(Ee,{className:"p-4",children:e.jsx("div",{className:"h-12 bg-muted rounded"})})},g))}):p!=null&&p.length?e.jsx("div",{className:"space-y-2 max-h-[600px] overflow-y-auto pr-1",children:p.map((g,_)=>{const v=g.completion_pct>=100;return e.jsx(fe,{className:Et("transition-all",v&&"border-emerald-200 bg-emerald-50/30 dark:border-emerald-900/40 dark:bg-emerald-950/10"),children:e.jsx(Ee,{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",_===0?"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400":_===1?"bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400":_===2?"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400":"bg-muted text-muted-foreground"),children:_+1}),e.jsxs(ra,{className:"h-9 w-9 shrink-0",children:[e.jsx(ni,{src:g.avatar_url||void 0}),e.jsx(aa,{className:"text-xs bg-primary/10 text-primary",children:(g.agent_name||g.email||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:g.agent_name||g.email}),v&&e.jsxs(ze,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-emerald-500 hover:bg-emerald-600 shrink-0",children:[e.jsx(xr,{className:"h-3 w-3 mr-0.5"})," Complete"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[e.jsxs("span",{children:[g.modules_completed,"/",g.total_modules," modules"]}),g.last_activity&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),Ss(new Date(g.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",v?"text-emerald-600 dark:text-emerald-400":"text-foreground"),children:[g.completion_pct,"%"]}),e.jsx(pi,{value:g.completion_pct,className:"h-1.5 mt-1"})]})]})})},g.user_id)})}):e.jsx(fe,{className:"border-dashed",children:e.jsx(Ee,{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(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"py-16 text-center",children:[e.jsx(Nn,{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 gsn(){const{user:s}=ys(),t=Mn(),{data:n,isLoading:r}=lsn();return e.jsx(Ts,{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(_d,{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(fe,{className:"animate-pulse",children:e.jsxs(Ee,{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(ysn,{course:a,userId:s==null?void 0:s.id,onClick:()=>t(`/levelup-u/${a.id}`)},a.id))}):e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Ou,{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 ysn({course:s,userId:t,onClick:n}){var o;const r=((o=s.modules)==null?void 0:o.length)??0,{data:a}=jNt(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(fe,{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(_d,{className:"h-10 w-10 text-primary/40"})}),e.jsxs(Ee,{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(Ou,{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(Ov,{className:"h-3.5 w-3.5"}):e.jsx($A,{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(pi,{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(xa,{className:"h-3.5 w-3.5"})]})})]})]})}function vsn(){const{courseId:s}=bi(),t=Mn(),{user:n}=ys(),{data:r,isLoading:a}=csn(s),{data:i}=jNt(s),l=dsn(),[o,c]=N.useState(null),d=(r==null?void 0:r.modules)||[],u=new Set((i==null?void 0:i.filter(b=>b.completed).map(b=>b.module_id))||[]),h=u.size,p=d.length>0?Math.round(h/d.length*100):0;N.useEffect(()=>{if(d.length>0&&!o){const b=d.find(S=>!u.has(S.id));c((b==null?void 0:b.id)||d[0].id)}},[d,o,u]);const f=d.find(b=>b.id===o),g=d.findIndex(b=>b.id===o),_=(b,S)=>{if(!(r!=null&&r.is_sequential)||S===0)return!1;for(let A=0;A{if(!(!f||!n||!s))try{await l.mutateAsync({courseId:s,moduleId:f.id,userId:n.id}),ae.success("Module completed! 🎉"),g{const S=b.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(S)return`https://www.youtube.com/embed/${S[1]}`;const A=b.match(/vimeo\.com\/(\d+)/);if(A)return`https://player.vimeo.com/video/${A[1]}`;const T=b.match(/(?:iframe\.mediadelivery\.net|video\.bunnycdn\.com)\/(?:play|embed)\/(\d+)\/([a-f0-9-]+)/);return T?`https://iframe.mediadelivery.net/embed/${T[1]}/${T[2]}?responsive=true`:b};return a?e.jsx(Ts,{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(Ts,{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(Hr,{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:[p,"%"]})]})]}),e.jsx("div",{className:"w-32",children:e.jsx(pi,{value:p,className:"h-2"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] gap-4 items-start",children:[e.jsx(fe,{className:"lg:sticky lg:top-4",children:e.jsxs(Ee,{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(hi,{className:"max-h-[calc(100vh-280px)]",children:e.jsx("div",{className:"p-1",children:d.map((b,S)=>{const A=_(b,S),T=u.has(b.id),L=b.id===o;return e.jsxs("button",{disabled:A,onClick:()=>!A&&c(b.id),className:Et("w-full flex items-center gap-3 p-3 rounded-lg text-left transition-all text-sm",L?"bg-primary/10 text-primary":"hover:bg-muted/50",A&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"shrink-0",children:A?e.jsx(Kc,{className:"h-4 w-4 text-muted-foreground"}):T?e.jsx(xr,{className:"h-4 w-4 text-green-500"}):e.jsx(lm,{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",L&&"text-primary"),children:[S+1,". ",b.title]}),b.duration_minutes&&e.jsxs("span",{className:"text-[11px] text-muted-foreground flex items-center gap-0.5 mt-0.5",children:[e.jsx(gr,{className:"h-3 w-3"})," ",b.duration_minutes," min"]})]})]},b.id)})})})]})}),e.jsx("div",{className:"space-y-4",children:f?e.jsxs(e.Fragment,{children:[f.video_url&&e.jsx(fe,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:j(f.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:f.title}),f.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:f.description})]}),u.has(f.id)?e.jsxs(ze,{className:"bg-green-500/15 text-green-600 border-green-500/30 shrink-0",children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-1"})," Completed"]}):e.jsxs(B,{size:"sm",onClick:v,disabled:l.isPending,children:[e.jsx(xr,{className:"h-4 w-4 mr-1"}),"Mark Complete"]})]}),f.text_content&&e.jsx("div",{className:"prose prose-sm max-w-none text-foreground border-t pt-4 whitespace-pre-wrap",children:f.text_content}),f.resources&&f.resources.length>0&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Resources"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:f.resources.map(b=>e.jsxs("a",{href:b.url||b.file_url||"#",target:"_blank",rel:"noreferrer",className:"flex items-center gap-2 p-3 rounded-lg border hover:bg-muted/50 transition-colors text-sm",children:[b.resource_type==="pdf"?e.jsx(Nr,{className:"h-4 w-4 text-red-500 shrink-0"}):b.resource_type==="template"?e.jsx(_d,{className:"h-4 w-4 text-purple-500 shrink-0"}):e.jsx(El,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("span",{className:"flex-1 truncate",children:b.title}),e.jsx(tr,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})]},b.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[e.jsxs(B,{variant:"outline",size:"sm",disabled:g===0,onClick:()=>g>0&&c(d[g-1].id),children:[e.jsx(Hr,{className:"h-3.5 w-3.5 mr-1"})," Previous"]}),gc(d[g+1].id),children:["Next ",e.jsx(xa,{className:"h-3.5 w-3.5 ml-1"})]}):p===100&&e.jsx(ze,{className:"bg-green-500/15 text-green-600 border-green-500/30 text-sm px-3 py-1.5",children:"🎉 Course Complete!"})]})]})})]}):e.jsx(fe,{children:e.jsx(Ee,{className:"flex items-center justify-center py-16 text-muted-foreground",children:"Select a module to begin"})})})]})]})}):e.jsx(Ts,{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(Hr,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function bsn({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(Yn.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(Yn.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(Yn.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(Yn.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(Yn.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.7,delay:.9},className:"flex flex-col sm:flex-row items-center justify-center gap-4",children:[e.jsxs("a",{href:"#apply",className:"group inline-flex items-center gap-3 px-10 py-4 rounded-full text-lg font-semibold shadow-2xl transition-all duration-300 hover:scale-105 hover:shadow-3xl",style:{backgroundColor:"white",color:r},children:["Get In Touch",e.jsx(Oa,{className:"h-5 w-5 transition-transform group-hover:translate-x-1"})]}),e.jsx("a",{href:"#benefits",className:"inline-flex items-center gap-2 px-8 py-4 rounded-full text-base font-medium text-white/90 border border-white/30 backdrop-blur-sm transition-all duration-300 hover:bg-white/10 hover:border-white/50",children:"Learn More"})]})]}),e.jsx(Yn.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 jy({children:s,className:t="",delay:n=0,direction:r="up"}){const a=N.useRef(null),i=xJt(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(Yn.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 _sn({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(jy,{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(jy,{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 wsn({images:s,primaryColor:t,accentColor:n}){const[r,a]=N.useState(null);return s.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"py-24 md:py-32 px-6 bg-gray-50",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsx(jy,{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(Nn,{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(jy,{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(Bn,{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 jsn({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(jy,{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(jy,{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(gb,{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 Nsn({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(jy,{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(jy,{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(Es,{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(Oa,{className:"h-4 w-4 transition-transform group-hover:translate-x-1"})]})}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-gray-400 pt-1",children:[e.jsx(dh,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Your information is confidential and will not be shared."})]})]})})]})]})}function ksn({form:s,setForm:t,onSubmit:n,isPending:r,primaryColor:a,accentColor:i,showConfidentialBadges:l=!0}){const[o,c]=N.useState(1),[d,u]=N.useState(""),h=3,p=!!s.first_name&&!!s.email,f=g=>{u(g),t(_=>({..._,why_interested:g})),setTimeout(()=>c(2),200)};return e.jsxs("section",{id:"apply",className:"py-24 md:py-32 px-6 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 top-0 h-1/2",style:{background:`linear-gradient(160deg, ${i}, ${a})`}}),e.jsx("div",{className:"absolute inset-0 top-1/2 bg-gray-50"}),e.jsxs("div",{className:"relative z-10 max-w-xl mx-auto",children:[e.jsx(jy,{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(Kc,{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(jy,{delay:.15,children:e.jsxs("div",{className:"bg-white rounded-3xl shadow-2xl p-8 md:p-10",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-7",children:[[1,2,3].map(g=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-colors duration-500",style:{backgroundColor:g<=o?a:"#e5e7eb"}},g)),e.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[o,"/",h]})]}),e.jsxs(Eye,{mode:"wait",children:[o===1&&e.jsxs(Yn.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-3",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"What's most important to you?"}),e.jsx("p",{className:"text-sm text-gray-500 mb-5",children:"Pick the one that resonates most. We'll tailor the conversation."}),[{val:"Better commission split / cap",label:"Better Splits & Caps",icon:"💰"},{val:"Better technology and tools",label:"Better Tech & Tools",icon:"🛠️"},{val:"Better training and mentorship",label:"Better Training",icon:"📚"},{val:"Better culture and team",label:"Better Culture",icon:"🤝"},{val:"Just exploring options confidentially",label:"Just Exploring",icon:"🔍"}].map(g=>e.jsxs("button",{type:"button",onClick:()=>f(g.val),className:"w-full flex items-center gap-3 p-4 rounded-xl border-2 border-gray-100 hover:border-gray-300 transition-all text-left group",children:[e.jsx("span",{className:"text-2xl",children:g.icon}),e.jsx("span",{className:"font-medium text-gray-700 group-hover:text-gray-900 flex-1",children:g.label}),e.jsx(Oa,{className:"h-4 w-4 text-gray-300 group-hover:text-gray-500 group-hover:translate-x-1 transition-all"})]},g.val))]},"step1"),o===2&&e.jsxs(Yn.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:g=>t(_=>({..._,first_name:g.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:g=>t(_=>({..._,last_name:g.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:g=>t(_=>({..._,email:g.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:g=>t(_=>({..._,phone:g.target.value})),className:"h-11",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{type:"button",variant:"ghost",onClick:()=>c(1),className:"h-11",children:[e.jsx(Hr,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsxs(B,{type:"button",disabled:!p,onClick:()=>c(3),className:"flex-1 h-11 text-white font-semibold",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:["Continue ",e.jsx(Oa,{className:"h-4 w-4 ml-1"})]})]})]},"step2"),o===3&&e.jsxs(Yn.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:g=>t(_=>({..._,current_brokerage:g.target.value})),className:"h-11",placeholder:"(stays private)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(ye,{type:"number",min:"0",value:s.experience_years,onChange:g=>t(_=>({..._,experience_years:g.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:g=>t(_=>({..._,annual_production:g.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(Es,{value:s.why_interested,onChange:g=>t(_=>({..._,why_interested:g.target.value})),rows:2,className:"resize-none",placeholder:"Optional message..."})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{type:"button",variant:"ghost",onClick:()=>c(2),className:"h-11",children:[e.jsx(Hr,{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(Ir,{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(dh,{className:"h-3 w-3"})," Confidential"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Ei,{className:"h-3 w-3"})," Text first"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Ar,{className:"h-3 w-3"})," No spam"]})]})]})})]})]})}function Ssn({config:s,primaryColor:t,accentColor:n,brokerageId:r,brokerageName:a}){const{toast:i}=Ba(),[l,o]=N.useState("250000"),[c,d]=N.useState("12"),[u,h]=N.useState("70"),[p,f]=N.useState("150"),[g,_]=N.useState(""),[v,j]=N.useState(!1),[b,S]=N.useState(!1),A=s.commission_split_pct??80,T=s.cap_amount??16e3,L=s.post_cap_split_pct??100,D=s.monthly_fee??99,M=s.transaction_fee??0,F=N.useMemo(()=>{const W=parseFloat(l)||0,Y=Math.max(0,parseInt(c,10)||0),K=parseFloat(u)||0,J=parseFloat(p)||0,ne=W*(K/100)-J*12-M*Y,ie=1-A/100,he=ie>0?T/ie:W,ce=Math.min(W,he),pe=Math.max(0,W-he),le=ce*ie+pe*(1-L/100),ve=W-le-D*12-M*Y,ge=ve-ne;return{currentNet:ne,newNet:ve,diff:ge}},[l,c,u,p,A,T,L,D,M]),z=W=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(W),V=async W=>{if(W.preventDefault(),!!g){S(!0);try{const{error:Y}=await q.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:g,source:"calculator"});if(Y)throw Y;const{error:K}=await q.functions.invoke("send-calculator-breakdown",{body:{brokerage_id:r,brokerage_name:a,email:g,inputs:{gci:parseFloat(l)||0,transactions:parseInt(c,10)||0,current_split_pct:parseFloat(u)||0,current_monthly_fee:parseFloat(p)||0},plan:{commission_split_pct:A,cap_amount:T,post_cap_split_pct:L,monthly_fee:D,transaction_fee:M},result:F,primary_color:t,accent_color:n}});K&&console.error("Breakdown email failed:",K),j(!0),i({title:"Sent!",description:"Check your email for the full breakdown."})}catch(Y){i({title:"Error",description:Y.message,variant:"destructive"})}finally{S(!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(jy,{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(Kc,{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(jy,{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(fw,{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:W=>o(W.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:W=>d(W.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:W=>h(W.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:p,onChange:W=>f(W.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(mo,{className:"h-5 w-5"}),e.jsxs("h3",{className:"font-semibold",children:["Your Earnings at ",a]})]}),e.jsxs("div",{className:"space-y-4 mb-6",children:[e.jsxs("div",{className:"flex items-baseline justify-between border-b border-white/20 pb-3",children:[e.jsx("span",{className:"text-white/70 text-sm",children:"Current take-home"}),e.jsx("span",{className:"text-xl font-semibold",children:z(F.currentNet)})]}),e.jsxs("div",{className:"flex items-baseline justify-between border-b border-white/20 pb-3",children:[e.jsx("span",{className:"text-white/70 text-sm",children:"With us"}),e.jsx("span",{className:"text-xl font-semibold",children:z(F.newNet)})]})]}),e.jsxs(Yn.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:F.diff>=0?"You could earn":"Difference"}),e.jsxs("p",{className:"text-4xl font-bold mb-1",children:[F.diff>=0?"+":"",z(F.diff)]}),e.jsx("p",{className:"text-white/70 text-xs",children:F.diff>=0?"more per year":"per year"})]},F.diff),s.show_email_capture&&!v&&e.jsxs("form",{onSubmit:V,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:g,onChange:W=>_(W.target.value),placeholder:"you@email.com",className:"bg-white/95 border-0 text-gray-900 h-10 text-sm"}),e.jsx(B,{type:"submit",disabled:b,className:"h-10 bg-white text-gray-900 hover:bg-white/90 text-sm font-semibold",children:"Send"})]})]}),v&&e.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-white/90 bg-white/10 rounded-lg p-3",children:[e.jsx(Ir,{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 Csn({config:s,primaryColor:t,accentColor:n,brokerageId:r}){const{toast:a}=Ba(),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(!1),[h,p]=N.useState(!1),f=async g=>{g.preventDefault(),p(!0);try{const{error:_}=await q.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:i,first_name:o||null,source:"lead_magnet",user_agent:navigator.userAgent,referrer:document.referrer||null});if(_)throw _;u(!0),s.pdf_url&&window.open(s.pdf_url,"_blank","noopener,noreferrer")}catch(_){a({title:"Error",description:_.message,variant:"destructive"})}finally{p(!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(jy,{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(CA,{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(Kc,{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(Ir,{className:"h-5 w-5 shrink-0"}),e.jsxs("span",{children:["Sent! ",s.pdf_url?"Your download should open in a new tab.":"Check your email shortly."]})]}):e.jsxs("form",{onSubmit:f,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(ye,{value:o,onChange:g=>c(g.target.value),placeholder:"First name (optional)",className:"h-11"}),e.jsx(ye,{type:"email",required:!0,value:i,onChange:g=>l(g.target.value),placeholder:"your@email.com",className:"h-11"})]}),e.jsxs(B,{type:"submit",disabled:h,className:"w-full sm:w-auto h-12 px-6 text-white font-semibold",style:{background:`linear-gradient(135deg, ${t}, ${n})`},children:[e.jsx(CA,{className:"h-4 w-4 mr-2"}),h?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function Tsn(){const{slug:s}=bi(),{toast:t}=Ba(),[n,r]=N.useState(!1),[a,i]=N.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",experience_years:"",annual_production:"",license_number:"",why_interested:""});N.useEffect(()=>{document.body.classList.add("recruit-landing-page");const F=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(Y=>document.querySelectorAll(Y).forEach(K=>K.style.display="none"))};F();const z=[setTimeout(F,500),setTimeout(F,1500),setTimeout(F,3e3)],V=new MutationObserver(F);return V.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-landing-page"),z.forEach(clearTimeout),V.disconnect()}},[]);const{data:l,isLoading:o,error:c}=ct({queryKey:["recruit-form-brokerage",s],queryFn:async()=>{const{data:F,error:z}=await q.from("brokerages").select("id, name, recruit_form_enabled").eq("recruit_form_slug",s).single();if(z)throw z;return F},enabled:!!s}),{data:d}=ct({queryKey:["recruit-landing-public",l==null?void 0:l.id],queryFn:async()=>{const{data:F,error:z}=await q.from("recruit_landing_page_settings").select("*").eq("brokerage_id",l.id).single();if(z&&z.code!=="PGRST116")throw z;return F},enabled:!!(l!=null&&l.id)}),u=gt({mutationFn:async()=>{const F={brokerage_id:l.id,first_name:a.first_name,last_name:a.last_name||null,email:a.email,phone:a.phone||null,current_brokerage:a.current_brokerage||null,experience_years:a.experience_years?parseInt(a.experience_years):null,annual_production:a.annual_production||null,license_number:a.license_number||null,why_interested:a.why_interested||null},{error:z}=await q.from("recruit_interest_submissions").insert(F);if(z)throw z;q.functions.invoke("recruit-lead-notify",{body:{lead:F,brokerage_id:l.id}}).catch(V=>console.error("Lead notification error:",V))},onSuccess:()=>r(!0),onError:F=>t({title:"Error",description:F.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(Va,{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,p=(h==null?void 0:h.primary_color)||"#406E71",f=(h==null?void 0:h.accent_color)||"#2a4c64",g=(h==null?void 0:h.benefits)||[],_=(h==null?void 0:h.testimonials)||[],v=(h==null?void 0:h.gallery_images)||[],j=(h==null?void 0:h.hero_headline)||`Join ${l.name}`,b=(h==null?void 0:h.hero_subtext)||"Take your real estate career to the next level with a brokerage that invests in your growth.",S=(h==null?void 0:h.calculator_enabled)===!0,A=(h==null?void 0:h.calculator_config)||{},T=(h==null?void 0:h.lead_magnet_enabled)===!0,L=(h==null?void 0:h.lead_magnet_config)||{},D=(h==null?void 0:h.form_style)||"classic",M=(h==null?void 0:h.confidential_messaging)!==!1;return n?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs(Yn.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, ${p}, ${f})`},children:e.jsx(Ir,{className:"h-10 w-10 text-white"})}),e.jsx("h2",{className:"text-3xl font-bold mb-3 tracking-tight",style:{color:f},children:"Thank You!"}),e.jsxs("p",{className:"text-gray-500 text-lg leading-relaxed mb-8",children:["Your interest in joining ",e.jsx("span",{className:"font-semibold",style:{color:f},children:l.name})," has been received. A member of our recruitment team will be in touch shortly."]}),e.jsx("div",{className:"w-16 h-1 mx-auto rounded-full",style:{backgroundColor:p}})]})}):e.jsxs("div",{className:"min-h-screen bg-white",style:{"--recruit-primary":p,"--recruit-accent":f},children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-40 bg-white/80 backdrop-blur-lg border-b border-gray-100/50",children:e.jsxs("div",{className:"max-w-6xl mx-auto px-6 h-14 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[(h==null?void 0:h.logo_url)&&e.jsx("img",{src:h.logo_url,alt:l.name,className:"h-8 w-auto"}),e.jsx("span",{className:"font-semibold text-sm tracking-tight",style:{color:f},children:l.name})]}),e.jsxs("a",{href:"#apply",className:"inline-flex items-center gap-2 px-5 py-2 rounded-full text-sm font-semibold text-white transition-all duration-300 hover:shadow-md hover:scale-105",style:{background:`linear-gradient(135deg, ${p}, ${f})`},children:["Apply Now ",e.jsx(Oa,{className:"h-3.5 w-3.5"})]})]})}),e.jsx(bsn,{headline:j,subtext:b,primaryColor:p,accentColor:f,heroImageUrl:h==null?void 0:h.hero_image_url,logoUrl:h==null?void 0:h.logo_url,brokerageName:l.name}),e.jsx(_sn,{benefits:g,accentColor:f,primaryColor:p}),e.jsx(wsn,{images:v,primaryColor:p,accentColor:f}),e.jsx(jsn,{testimonials:_,primaryColor:p,accentColor:f}),S&&e.jsx(Ssn,{config:A,primaryColor:p,accentColor:f,brokerageId:l.id,brokerageName:l.name}),T&&e.jsx(Csn,{config:L,primaryColor:p,accentColor:f,brokerageId:l.id}),D==="multi_step"?e.jsx(ksn,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:p,accentColor:f,showConfidentialBadges:M}):e.jsx(Nsn,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:p,accentColor:f}),e.jsx("footer",{className:"py-10 text-center bg-white border-t border-gray-100",children:e.jsxs("p",{className:"text-sm text-gray-400",children:["© ",new Date().getFullYear()," ",l.name,". All rights reserved."]})})]})}function Esn(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 Asn(){var p,f,g,_;const{shareToken:s}=bi(),t=N.useRef(!1),{data:n,isLoading:r,error:a}=ct({queryKey:["public-recruit-video",s],queryFn:async()=>{var T;if(!s)throw new Error("No token");const{data:v,error:j}=await q.from("recruit_videos").select(` *, prospect:recruit_prospects(first_name, last_name), video:agent_videos(id, title, playback_url, thumbnail_url, duration_seconds, owner_user_id) `).eq("share_token",s).single();if(j)throw j;const{data:b}=await q.from("profiles").select("name, avatar_url, title, recruit_cta_url").eq("id",(T=v.video)==null?void 0:T.owner_user_id).single(),{data:S}=await q.from("brokerages").select("name").eq("id",v.brokerage_id).single(),{data:A}=await q.from("recruit_landing_page_settings").select("logo_url, primary_color, accent_color, hero_headline").eq("brokerage_id",v.brokerage_id).maybeSingle();return{rv:v,profile:b,brokerage:S,settings:A}},enabled:!!s});if(N.useEffect(()=>{var v;!((v=n==null?void 0:n.rv)!=null&&v.id)||t.current||(t.current=!0,q.rpc("log_recruit_video_view",{p_recruit_video_id:n.rv.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null}).then(()=>{}))},[(p=n==null?void 0:n.rv)==null?void 0:p.id]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});if(a||!n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("p",{className:"text-muted-foreground",children:"This video is no longer available."})});const{rv:i,profile:l,brokerage:o,settings:c}=n,d=(c==null?void 0:c.primary_color)||"#3b82f6",u=((f=i.prospect)==null?void 0:f.first_name)||"there",h=(g=i.video)!=null&&g.playback_url?Esn(i.video.playback_url):null;return e.jsxs(e.Fragment,{children:[e.jsx(Go,{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:((_=l==null?void 0:l.name)==null?void 0:_.charAt(0))||"?"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-semibold",children:l==null?void 0:l.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(l==null?void 0:l.title)||"Recruiter"," · ",o==null?void 0:o.name]})]})]}),(l==null?void 0:l.recruit_cta_url)&&e.jsx("div",{className:"text-center",children:e.jsx(B,{size:"lg",asChild:!0,className:"text-white shadow-lg hover:shadow-xl transition-shadow px-8",style:{backgroundColor:d},onClick:()=>{q.from("recruit_videos").update({cta_clicked_at:new Date().toISOString()}).eq("id",i.id).then(()=>{})},children:e.jsxs("a",{href:l.recruit_cta_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(yr,{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 Msn="relzejiswnotikjgvjhz",RXe=`https://${Msn}.supabase.co/functions/v1/recruit-unsubscribe`;function Isn(){const[s]=gl(),t=s.get("token")||"",[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState({});N.useEffect(()=>{document.body.classList.add("recruit-unsubscribe-page");const f=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(j=>document.querySelectorAll(j).forEach(b=>b.style.display="none"))};f();const g=[setTimeout(f,500),setTimeout(f,1500),setTimeout(f,3e3)],_=new MutationObserver(f);return _.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-unsubscribe-page"),g.forEach(clearTimeout),_.disconnect()}},[]),N.useEffect(()=>{if(!t){h({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${RXe}?token=${encodeURIComponent(t)}`).then(async f=>{const g=await f.json();if(!f.ok)throw new Error(g.error||"Lookup failed");h(g),g.already_unsubscribed&&o(!0)}).catch(f=>h({error:f.message||"Could not load status"})).finally(()=>r(!1))},[t]);const p=async()=>{i(!0);try{const f=await fetch(RXe,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,reason:c.trim()||null})}),g=await f.json();if(!f.ok)throw new Error(g.error||"Failed");o(!0)}catch(f){h({...u,error:f.message||"Could not unsubscribe"})}finally{i(!1)}};return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsx("div",{className:"w-full max-w-lg bg-white rounded-2xl shadow-xl border border-slate-200 p-8 sm:p-10",children:n?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(ts,{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(Gi,{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(xr,{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(sg,{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(sg,{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(Es,{id:"reason",value:c,onChange:f=>d(f.target.value),placeholder:"e.g. Not currently looking, too many emails, already moved…",rows:3,className:"resize-none"})]}),e.jsx(B,{onClick:p,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(ts,{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 Psn="relzejiswnotikjgvjhz",OXe=`https://${Psn}.supabase.co/functions/v1/event-invite-unsubscribe`;function Lsn(){const[s]=gl(),t=s.get("token")||"",[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState({});N.useEffect(()=>(document.body.classList.add("event-invite-unsubscribe-page"),()=>{document.body.classList.remove("event-invite-unsubscribe-page")}),[]),N.useEffect(()=>{if(!t){d({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${OXe}?token=${encodeURIComponent(t)}`).then(async h=>{const p=await h.json();if(!h.ok)throw new Error(p.error||"Lookup failed");d(p),p.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(OXe,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})}),p=await h.json();if(!h.ok)throw new Error(p.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(ts,{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(Gi,{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(xr,{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(sg,{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(Y7,{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(ts,{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 Dsn(){const s=Mn(),t=Ht(),{isAdmin:n}=ys(),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState(null),{data:d,isLoading:u}=ct({queryKey:["my-social-accounts"],queryFn:async()=>{const{data:{user:T},error:L}=await q.auth.getUser();if(L)throw L;if(!T)return[];const{data:D,error:M}=await q.from("social_accounts").select("*").eq("user_id",T.id).order("created_at",{ascending:!1});if(M)throw M;return D}}),h=gt({mutationFn:async T=>{const{data:{user:L},error:D}=await q.auth.getUser();if(D)throw D;if(!L)throw new Error("Not authenticated");const{error:M}=await q.from("social_accounts").delete().eq("id",T).eq("user_id",L.id);if(M)throw M},onSuccess:()=>{t.invalidateQueries({queryKey:["my-social-accounts"]}),t.invalidateQueries({queryKey:["social-accounts-for-post"]}),ae.success("Account disconnected successfully")},onError:()=>{ae.error("Failed to disconnect account")}}),p=async T=>{a(!0);try{const{data:L,error:D}=await q.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:T}});if(D)throw D;if(L!=null&&L.authUrl)window.location.href=L.authUrl;else throw new Error("Failed to get authorization URL")}catch(L){console.error("Meta OAuth error:",L),ae.error("Failed to start connection. Please try again."),a(!1)}},f=async()=>{a(!0);try{const{data:T,error:L}=await q.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(L)throw L;if(T!=null&&T.authUrl)window.location.href=T.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(T){console.error("LinkedIn OAuth error:",T),ae.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},g=async()=>{a(!0);try{const{data:T,error:L}=await q.functions.invoke("google-business-oauth",{body:{action:"get_auth_url"}});if(L)throw L;if(T!=null&&T.authUrl)window.location.href=T.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(T){console.error("Google OAuth error:",T),ae.error("Failed to start Google connection. Please try again."),a(!1)}},_=(d==null?void 0:d.filter(T=>T.platform==="facebook"))||[],v=(d==null?void 0:d.filter(T=>T.platform==="instagram"))||[],j=(d==null?void 0:d.filter(T=>T.platform==="linkedin"))||[],b=(d==null?void 0:d.filter(T=>T.platform==="google_business"))||[],S=((d==null?void 0:d.length)||0)>0,A=async(T,L)=>{l(T),c(null);try{const{data:D,error:M}=await q.functions.invoke("meta-api-test",{body:{testType:"all",accountId:T}});if(M)throw M;c(D.results||[]),ae.success(D.summary||"API tests completed")}catch(D){console.error("Meta API test error:",D),ae.error("Failed to run API tests")}finally{l(null)}};return e.jsx(Ts,{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(ze,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"Post directly from Social Swag"]})}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold mb-2",children:"Connect Your Social Accounts"}),e.jsx("p",{className:"text-white/90 max-w-xl",children:"Link your Facebook Pages and Instagram Business accounts to post content directly from Social Swag with one click."})]})]}),e.jsxs(B,{variant:"ghost",onClick:()=>s("/social-swag-2"),className:"gap-2",children:[e.jsx(Hr,{className:"h-4 w-4"}),"Back to Social Swag"]}),S&&e.jsx(fe,{className:"border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-900",children:e.jsxs(Ee,{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:"rounded-full bg-green-500 p-2",children:e.jsx(Ri,{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(fe,{children:[e.jsx(Mt,{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(Lh,{className:"h-6 w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:"Facebook"}),e.jsx(Vn,{children:"Connect your Facebook Pages"})]})]})}),e.jsxs(Ee,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ti,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):_.length>0?e.jsx("div",{className:"space-y-3",children:_.map(T=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ra,{className:"h-10 w-10",children:[e.jsx(ni,{src:T.profile_picture_url||""}),e.jsx(aa,{children:e.jsx(Lh,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:T.page_name||T.platform_username||"Facebook Page"}),e.jsx(ze,{variant:T.is_active?"default":"secondary",className:"text-xs",children:T.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Facebook?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>h.mutate(T.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},T.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Facebook pages connected yet"}),e.jsxs(B,{onClick:()=>p("facebook"),disabled:r,className:"w-full gap-2",variant:_.length>0?"outline":"default",children:[r?e.jsx(Ti,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{className:"h-4 w-4"}),_.length>0?"Connect Another Page":"Connect Facebook Page"]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{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(du,{className:"h-6 w-6 text-pink-600"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:"Instagram"}),e.jsx(Vn,{children:"Connect Instagram Business accounts"})]})]})}),e.jsxs(Ee,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ti,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length>0?e.jsx("div",{className:"space-y-3",children:v.map(T=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ra,{className:"h-10 w-10",children:[e.jsx(ni,{src:T.profile_picture_url||""}),e.jsx(aa,{children:e.jsx(du,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["@",T.platform_username||"Instagram Account"]}),e.jsx(ze,{variant:T.is_active?"default":"secondary",className:"text-xs",children:T.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Instagram?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>h.mutate(T.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},T.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Instagram accounts connected yet"}),e.jsxs(B,{onClick:()=>p("instagram"),disabled:r,className:"w-full gap-2",variant:v.length>0?"outline":"default",children:[r?e.jsx(Ti,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{className:"h-4 w-4"}),v.length>0?"Connect Another Account":"Connect Instagram Professional"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Use Instagram login for Business or Creator accounts; Facebook Page login is only needed if you want to connect Pages."})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{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(vf,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:"LinkedIn"}),e.jsx(Vn,{children:"Connect your LinkedIn profile"})]})]})}),e.jsxs(Ee,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ti,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):j.length>0?e.jsx("div",{className:"space-y-3",children:j.map(T=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ra,{className:"h-10 w-10",children:[e.jsx(ni,{src:T.profile_picture_url||""}),e.jsx(aa,{children:e.jsx(vf,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:T.platform_username||"LinkedIn Account"}),e.jsx(ze,{variant:T.is_active?"default":"secondary",className:"text-xs",children:T.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect LinkedIn?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>h.mutate(T.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},T.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No LinkedIn account connected yet"}),e.jsxs(B,{onClick:f,disabled:r,className:"w-full gap-2",variant:j.length>0?"outline":"default",children:[r?e.jsx(Ti,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{className:"h-4 w-4"}),j.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(fe,{className:`relative overflow-hidden ${n?"":"opacity-75"}`,children:[!n&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(ze,{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(ze,{variant:"secondary",className:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",children:"Admin Testing"})}),e.jsx(Mt,{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(ka,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:"Google Business"}),e.jsx(Vn,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(Ee,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ti,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length>0?e.jsx("div",{className:"space-y-3",children:b.map(T=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ra,{className:"h-10 w-10",children:[e.jsx(ni,{src:T.profile_picture_url||""}),e.jsx(aa,{children:e.jsx(ka,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:T.page_name||T.platform_username||"Google Business"}),e.jsx(ze,{variant:T.is_active?"default":"secondary",className:"text-xs",children:T.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Oo,{children:[e.jsx(Ph,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Google Business?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>h.mutate(T.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},T.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:n?"No Google Business account connected yet":"Google Business Profile integration is coming soon!"}),e.jsxs(B,{onClick:n?g:void 0,disabled:!n||r,className:"w-full gap-2",variant:b.length>0?"outline":"default",children:[r?e.jsx(Ti,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{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&&(_.length>0||v.length>0)&&e.jsxs(fe,{className:"border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-900",children:[e.jsx(Mt,{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(QS,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:"Meta API Testing (Admin Only)"}),e.jsx(Vn,{children:"Run API tests to trigger all required permissions for Meta App Review"})]})]})}),e.jsxs(Ee,{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:[_.map(T=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border bg-background p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Lh,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"font-medium",children:T.page_name||"Facebook Page"})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>A(T.id),disabled:i===T.id,children:i===T.id?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(QS,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-fb-${T.id}`)),v.map(T=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border bg-background p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(du,{className:"h-5 w-5 text-pink-600"}),e.jsxs("span",{className:"font-medium",children:["@",T.platform_username||"Instagram"]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>A(T.id),disabled:i===T.id,children:i===T.id?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(QS,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-ig-${T.id}`))]}),o&&o.length>0&&e.jsxs("div",{className:"mt-4 rounded-lg border bg-background p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:"Test Results"}),e.jsx("div",{className:"space-y-2",children:o.map((T,L)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[T.status==="success"?e.jsx(xr,{className:"h-4 w-4 text-green-600 mt-0.5 shrink-0"}):T.status==="pending"?e.jsx(ts,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}):e.jsx(Hc,{className:"h-4 w-4 text-red-600 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-mono text-xs bg-muted px-1 rounded",children:T.test}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:T.details})]})]},L))})]}),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(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-lg",children:"How it works"})}),e.jsx(Ee,{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 Rsn(){const[s]=gl(),t=Mn(),[n,r]=N.useState("loading"),[a,i]=N.useState("Processing your connection...");return N.useEffect(()=>{(async()=>{var h;const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:p,error:f}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:u,callbackPath:"/social-connections/callback"}});if(f)throw f;if(p!=null&&p.success)r("success"),i(`Successfully connected ${((h=p.accounts)==null?void 0:h.length)||0} account(s)!`),ae.success("Social accounts connected successfully!");else throw new Error((p==null?void 0:p.error)||"Unknown error")}catch(p){console.error("OAuth callback error:",p),r("error"),i(p instanceof Error?p.message:"Failed to connect accounts"),ae.error("Failed to connect: "+(p instanceof Error?p.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[n==="loading"&&e.jsx(ts,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Ri,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Hc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(It,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:a})]}),e.jsx(Ee,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"View Connected Accounts":"Try Again"})})]})})}function Osn(){const[s]=gl(),t=Mn(),[n,r]=N.useState("loading"),[a,i]=N.useState("Connecting your Google Business Profile...");return N.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:h,error:p}=await q.functions.invoke("google-business-oauth",{body:{action:"exchange_code",code:o,state:u}});if(p)throw p;if(h!=null&&h.success)r("success"),i(h.message||"Successfully connected Google Business Profile!"),ae.success("Google Business Profile connected!");else throw new Error((h==null?void 0:h.error)||"Unknown error")}catch(h){console.error("Google OAuth callback error:",h),r("error"),i(h instanceof Error?h.message:"Failed to connect Google Business Profile"),ae.error("Failed to connect: "+(h instanceof Error?h.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[n==="loading"&&e.jsx(ts,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Ri,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Hc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(It,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:a})]}),e.jsx(Ee,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/social-connections"),children:n==="success"?"View Connected Accounts":"Try Again"})})]})})}function Fsn(){const[s]=gl(),t=Mn(),[n,r]=N.useState("loading"),[a,i]=N.useState("Connecting your LinkedIn account...");return N.useEffect(()=>{(async()=>{var h;const o=s.get("code"),c=s.get("state"),d=s.get("error"),u=s.get("error_description");if(d){console.error("LinkedIn OAuth error:",d,u),r("error"),i(u||"Failed to connect LinkedIn account"),ae.error(u||"Failed to connect LinkedIn");return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:p,error:f}=await q.functions.invoke("linkedin-oauth",{body:{action:"exchange_code",code:o,state:c,callbackPath:"/social-connections/linkedin-callback"}});if(f)throw f;if(p!=null&&p.success)r("success"),i(`Successfully connected ${((h=p.accounts)==null?void 0:h.length)||1} LinkedIn account`),ae.success("LinkedIn connected successfully!");else throw new Error((p==null?void 0:p.error)||"Failed to connect LinkedIn account")}catch(p){console.error("LinkedIn callback error:",p),r("error"),i(p instanceof Error?p.message:"Failed to connect LinkedIn account"),ae.error("Failed to connect LinkedIn")}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center p-4 bg-background",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(Mt,{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(ts,{className:"h-8 w-8 animate-spin text-blue-600"}),n==="success"&&e.jsx(Ri,{className:"h-8 w-8 text-green-600"}),n==="error"&&e.jsx(Hc,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(It,{className:"flex items-center justify-center gap-2",children:[e.jsx(vf,{className:"h-5 w-5 text-blue-600"}),n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:a})]}),e.jsx(Ee,{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 zsn(){const s=Mn(),[t,n]=N.useState(null),{data:r,isLoading:a}=Z2t(t||void 0,!0),{data:i,isLoading:l}=S8e(!0),{cartItems:o}=$ye(),c=o.reduce((u,h)=>u+h.quantity,0),d=u=>{s(`/marketplace/${u.id}`)};return a||l?e.jsx(Ts,{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(Ws,{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(Ws,{className:"h-72 w-full"},u))})]})}):e.jsx(Ts,{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(Og,{className:"h-4 w-4 mr-2"}),"Cart",c>0&&e.jsx(ze,{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(fe,{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(p=>p.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(Rc,{className:"h-12 w-12 text-muted-foreground"})}),u.category&&e.jsx(ze,{className:"absolute top-2 left-2",variant:"secondary",children:u.category.name})]}),e.jsxs(Ee,{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(Rc,{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 NNt=N.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));NNt.displayName="Breadcrumb";const kNt=N.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}));kNt.displayName="BreadcrumbList";const ope=N.forwardRef(({className:s,...t},n)=>e.jsx("li",{ref:n,className:Et("inline-flex items-center gap-1.5",s),...t}));ope.displayName="BreadcrumbItem";const TTe=N.forwardRef(({asChild:s,className:t,...n},r)=>{const a=s?iAe:"a";return e.jsx(a,{ref:r,className:Et("transition-colors hover:text-foreground",t),...n})});TTe.displayName="BreadcrumbLink";const SNt=N.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}));SNt.displayName="BreadcrumbPage";const ETe=({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(xa,{})});ETe.displayName="BreadcrumbSeparator";function Bsn(){var Y,K;const{productId:s}=bi(),t=Mn(),{data:n,isLoading:r}=Ien(s||""),{addToCart:a,cartItems:i}=$ye(),[l,o]=N.useState(null),[c,d]=N.useState(1),[u,h]=N.useState(0),[p,f]=N.useState(null),[g,_]=N.useState(!1),[v,j]=N.useState(!1),b=(Y=n==null?void 0:n.variants)==null?void 0:Y.find(J=>J.id===l),S=((K=n==null?void 0:n.variants)==null?void 0:K.filter(J=>J.is_active))||[],A=Number((n==null?void 0:n.base_price)||0),T=b?Number(b.price_adjustment):0,L=A+T,D=Number((n==null?void 0:n.shipping_fee)||0),M=i.reduce((J,ne)=>J+ne.quantity,0),F=async J=>{if(!J.target.files||J.target.files.length===0)return;_(!0);const ne=J.target.files[0],ie=ne.name.split(".").pop(),he=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${ie}`;try{const{error:ce}=await q.storage.from("marketplace").upload(he,ne);if(ce)throw ce;const{data:{publicUrl:pe}}=q.storage.from("marketplace").getPublicUrl(he);f(pe),ae.success("Artwork uploaded successfully")}catch(ce){ae.error("Failed to upload artwork: "+ce.message)}finally{_(!1)}},z=()=>{if(n){if(S.length>0&&!l){ae.error("Please select an option");return}a(n,b||void 0,c,p||void 0),j(!0),ae.success("Added to cart!"),setTimeout(()=>j(!1),2e3)}},V=()=>{n!=null&&n.images&&h(J=>(J+1)%n.images.length)},W=()=>{n!=null&&n.images&&h(J=>(J-1+n.images.length)%n.images.length)};return r?e.jsx(Ts,{title:"Product",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsx(Ws,{className:"aspect-square w-full"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-8 w-3/4"}),e.jsx(Ws,{className:"h-6 w-1/4"}),e.jsx(Ws,{className:"h-24 w-full"}),e.jsx(Ws,{className:"h-12 w-full"})]})]})}):n?e.jsxs(Ts,{title:n.name,children:[e.jsx(NNt,{className:"mb-6",children:e.jsxs(kNt,{children:[e.jsx(ope,{children:e.jsx(TTe,{asChild:!0,children:e.jsx(Ln,{to:"/marketplace",children:"Marketplace"})})}),n.category&&e.jsxs(e.Fragment,{children:[e.jsx(ETe,{}),e.jsx(ope,{children:e.jsx(TTe,{asChild:!0,children:e.jsx(Ln,{to:`/marketplace?category=${n.category.id}`,children:n.category.name})})})]}),e.jsx(ETe,{}),e.jsx(ope,{children:e.jsx(SNt,{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:W,children:e.jsx(pl,{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:V,children:e.jsx(xa,{className:"h-6 w-6"})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Rc,{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((J,ne)=>e.jsx("button",{onClick:()=>h(ne),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${ne===u?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:J.image_url,alt:"",className:"w-full h-full object-cover"})},J.id))}),n.video&&e.jsx(fe,{children:e.jsxs(Ee,{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(ze,{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:["$",L.toFixed(2)]}),D>0&&e.jsxs("span",{className:"text-muted-foreground",children:["+ $",D.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})}),S.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:S.map(J=>e.jsxs(B,{variant:l===J.id?"default":"outline",onClick:()=>o(J.id),children:[J.name,Number(J.price_adjustment)!==0&&e.jsxs("span",{className:"ml-1 opacity-70",children:["(",Number(J.price_adjustment)>0?"+":"","$",Number(J.price_adjustment).toFixed(2),")"]})]},J.id))})]}),n.allow_artwork_upload&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Upload Your Artwork (Optional)"}),p?e.jsxs("div",{className:"relative inline-block",children:[e.jsx("img",{src:p,alt:"Your artwork",className:"h-24 w-auto rounded-lg border"}),e.jsx(B,{variant:"ghost",size:"sm",className:"absolute -top-2 -right-2",onClick:()=>f(null),children:"×"})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6",children:[e.jsx("input",{type:"file",accept:"image/*,.pdf,.ai,.eps",onChange:F,className:"hidden",id:"artwork-upload",disabled:g}),e.jsxs("label",{htmlFor:"artwork-upload",className:"flex flex-col items-center cursor-pointer",children:[e.jsx(Na,{className:"h-8 w-8 text-muted-foreground mb-2"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:g?"Uploading...":"Click to upload artwork"}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"Supported: JPG, PNG, PDF, AI, EPS"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Quantity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>d(J=>Math.max(1,J-1)),children:"-"}),e.jsx(ye,{type:"number",value:c,onChange:J=>d(Math.max(1,parseInt(J.target.value)||1)),className:"w-20 text-center",min:"1"}),e.jsx(B,{variant:"outline",size:"icon",onClick:()=>d(J=>J+1),children:"+"})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx(B,{size:"lg",className:"flex-1",onClick:z,disabled:v,children:v?e.jsxs(e.Fragment,{children:[e.jsx(Ir,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(Og,{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(Og,{className:"h-5 w-5"}),M>0&&e.jsx(ze,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:M})]})]}),n.requires_proof_approval&&e.jsx("p",{className:"text-sm text-muted-foreground bg-muted p-3 rounded-lg",children:"📋 This product requires proof approval before production. You'll receive a proof to review after your order is placed."})]})]})]}):e.jsx(Ts,{title:"Product Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Rc,{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 $sn(){const s=Mn(),{cartItems:t,removeFromCart:n,updateQuantity:r,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=$ye(),[d,u]=N.useState(!1),[h,p]=N.useState(""),f=async()=>{if(t.length===0){ae.error("Your cart is empty");return}u(!0);try{const{data:g,error:_}=await q.functions.invoke("marketplace-checkout",{body:{items:t.map(v=>{var j;return{product_id:v.product.id,variant_id:((j=v.variant)==null?void 0:j.id)||null,quantity:v.quantity,artwork_url:v.artworkUrl||null}}),notes:h.trim()||null}});if(_)throw _;if(g!=null&&g.url)c(),window.open(g.url,"_blank");else throw new Error("No checkout URL received")}catch(g){ae.error("Checkout failed: "+g.message)}finally{u(!1)}};return t.length===0?e.jsx(Ts,{title:"Shopping Cart",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(_w,{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(Ts,{title:"Shopping Cart",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-4",children:[t.map(g=>{var _,v;return e.jsx(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[e.jsx("div",{className:"w-24 h-24 flex-shrink-0 bg-muted rounded-lg overflow-hidden",children:g.product.images&&g.product.images.length>0?e.jsx("img",{src:((_=g.product.images.find(j=>j.is_primary))==null?void 0:_.image_url)||g.product.images[0].image_url,alt:g.product.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(_w,{className:"h-8 w-8 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:g.product.name}),g.variant&&e.jsx("p",{className:"text-sm text-muted-foreground",children:g.variant.name}),e.jsxs("p",{className:"font-medium mt-1",children:["$",a(g).toFixed(2),Number(g.product.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["+ $",Number(g.product.shipping_fee).toFixed(2)," shipping"]})]}),g.artworkUrl&&e.jsx("div",{className:"mt-2",children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"Artwork uploaded ✓"})})]}),e.jsxs("div",{className:"flex flex-col items-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{var j;return n(g.product.id,(j=g.variant)==null?void 0:j.id)},children:e.jsx(_n,{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 j;return r(g.product.id,(j=g.variant)==null?void 0:j.id,g.quantity-1)},disabled:g.quantity<=1,children:e.jsx(fb,{className:"h-3 w-3"})}),e.jsx(ye,{type:"number",value:g.quantity,onChange:j=>{var b;return r(g.product.id,(b=g.variant)==null?void 0:b.id,parseInt(j.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 j;return r(g.product.id,(j=g.variant)==null?void 0:j.id,g.quantity+1)},children:e.jsx(Is,{className:"h-3 w-3"})})]})]})]})})},`${g.product.id}-${((v=g.variant)==null?void 0:v.id)||"base"}`)}),e.jsx(B,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(fe,{className:"sticky top-4",children:[e.jsx(Mt,{children:e.jsx(It,{children:"Order Summary"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:["Subtotal (",t.reduce((g,_)=>g+_.quantity,0)," items)"]}),e.jsxs("span",{children:["$",i().toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",l().toFixed(2)]})]}),e.jsx(ll,{}),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(ll,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"orderNotes",children:"Order Notes (Optional)"}),e.jsx(Es,{id:"orderNotes",placeholder:"Add any special instructions, design notes, or comments for your order...",value:h,onChange:g=>p(g.target.value),rows:3,className:"resize-none"})]}),e.jsx(B,{className:"w-full",size:"lg",onClick:f,disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-5 w-5 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:["Checkout",e.jsx(Oa,{className:"h-5 w-5 ml-2"})]})}),e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"Secure checkout powered by Stripe"})]})]})})]})})}function Usn(){const s=Mn(),{data:t,isLoading:n}=qen();return n?e.jsx(Ts,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(r=>e.jsx(Ws,{className:"h-32 w-full"},r))})}):!t||t.length===0?e.jsx(Ts,{title:"My Orders",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Rc,{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(Ts,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:t.map(r=>{var a,i,l;return e.jsx(fe,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>s(`/marketplace/orders/${r.id}`),children:e.jsxs(Ee,{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:Ss(new Date(r.created_at),"MMM d, yyyy")})]}),e.jsx(ze,{className:k8e[r.status],children:HL[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(xa,{className:"h-5 w-5 text-muted-foreground"})]})]})]})},r.id)})})})}const FXe=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function qsn({currentStatus:s,statusHistory:t}){const n=FXe.indexOf(s);return e.jsx("div",{className:"space-y-3",children:FXe.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(xr,{className:"h-4 w-4"}):o?e.jsx(gr,{className:"h-4 w-4"}):e.jsx("span",{className:"text-xs",children:a+1})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`font-medium ${c?"text-muted-foreground":""}`,children:HL[r]}),i&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ss(new Date(i.created_at),"MMM d, yyyy h:mm a"),i.notes&&` — ${i.notes}`]})]})]},r)})})}function Vsn(){var j;const{orderId:s}=bi(),t=Mn(),{data:n,isLoading:r,refetch:a}=Ven(s||""),i=Wen(),l=Ken(),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(""),[f,g]=N.useState(null),_=async b=>{g(b);try{await i.mutateAsync({orderId:s,itemId:b}),ae.success("Proof approved!"),a()}catch{ae.error("Failed to approve proof")}finally{g(null)}},v=async()=>{if(d){g(d);try{await l.mutateAsync({orderId:s,itemId:d,reason:h}),ae.success("Revision requested"),c(!1),p(""),u(null),a()}catch{ae.error("Failed to request revision")}finally{g(null)}}};return r?e.jsx(Ts,{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(Ws,{className:"h-64 w-full"}),e.jsx(Ws,{className:"h-48 w-full"})]}),e.jsx(Ws,{className:"h-96 w-full"})]})}):n?e.jsxs(Ts,{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(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(It,{children:"Order Status"}),e.jsx(ze,{className:k8e[n.status],children:HL[n.status]})]}),e.jsx(Ee,{children:e.jsx(qsn,{currentStatus:n.status,statusHistory:n.status_history})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"Items"})}),e.jsx(Ee,{className:"space-y-4",children:(j=n.items)==null?void 0:j.map(b=>e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-3",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold",children:b.product_name}),b.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:b.variant_name}),e.jsxs("p",{className:"text-sm",children:["Qty: ",b.quantity," × $",Number(b.unit_price).toFixed(2)]})]}),e.jsxs("p",{className:"font-semibold",children:["$",(Number(b.unit_price)*b.quantity).toFixed(2)]})]}),b.artwork_url&&e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Your Artwork:"}),e.jsxs("a",{href:b.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline",children:[e.jsx(W2,{className:"h-4 w-4"}),"View Artwork",e.jsx(tr,{className:"h-3 w-3"})]})]}),b.proof_url&&e.jsxs("div",{className:"bg-muted rounded-lg p-3",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Proof Ready for Review"}),e.jsxs("a",{href:b.proof_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline mb-3",children:[e.jsx(W2,{className:"h-4 w-4"}),"View Proof",e.jsx(tr,{className:"h-3 w-3"})]}),b.proof_status==="pending"&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(B,{size:"sm",onClick:()=>_(b.id),disabled:f===b.id,children:[f===b.id?e.jsx(ts,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Vm,{className:"h-4 w-4 mr-1"}),"Approve"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{u(b.id),c(!0)},disabled:f===b.id,children:[e.jsx(L9,{className:"h-4 w-4 mr-1"}),"Request Changes"]})]}),b.proof_status==="approved"&&e.jsxs(ze,{className:"bg-green-100 text-green-800",children:[e.jsx(xr,{className:"h-3 w-3 mr-1"}),"Proof Approved"]}),b.proof_status==="rejected"&&b.proof_notes&&e.jsxs("div",{className:"mt-2",children:[e.jsx(ze,{variant:"destructive",className:"mb-2",children:"Revision Requested"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:b.proof_notes})]})]})]},b.id))})]}),n.shipping_name&&e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(R9,{className:"h-5 w-5"}),"Shipping"]})}),e.jsxs(Ee,{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(fe,{className:"sticky top-4",children:[e.jsx(Mt,{children:e.jsx(It,{children:"Order Summary"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Placed on ",Ss(new Date(n.created_at),"MMMM d, yyyy")]}),e.jsx(ll,{}),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(ll,{}),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(ll,{}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Order Notes"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n.notes})]})]})]})]})})]}),e.jsx(bs,{open:o,onOpenChange:c,children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Request Changes"}),e.jsx(Qn,{children:"Please describe what changes you'd like made to the proof."})]}),e.jsx(Es,{placeholder:"Describe the changes needed...",value:h,onChange:b=>p(b.target.value),rows:4}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:v,disabled:!h.trim()||f!==null,children:[f?e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Submit Request"]})]})]})})]}):e.jsx(Ts,{title:"Order Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Rc,{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 Hsn(){const s=Mn(),[t]=gl();return t.get("session_id"),N.useEffect(()=>{localStorage.removeItem("marketplace-cart")},[]),e.jsx(Ts,{title:"Order Confirmed",children:e.jsx("div",{className:"max-w-lg mx-auto text-center py-8",children:e.jsx(fe,{children:e.jsxs(Ee,{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(xr,{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(Rc,{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(Oa,{className:"h-4 w-4 ml-2"})]}),e.jsx(B,{variant:"outline",className:"flex-1",onClick:()=>s("/marketplace"),children:"Continue Shopping"})]})]})})})})}function Gsn(){const{user:s}=ys(),[t,n]=N.useState("store"),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(!1),[d,u]=N.useState(5),[h,p]=N.useState(""),[f,g]=N.useState(!1),[_,v]=N.useState(!1),[j,b]=N.useState(""),[S,A]=N.useState(null),[T,L]=N.useState(!1),{hasSubmittedReview:D,submitReview:M,markPostedToGoogle:F}=Dmt(),{data:z}=X2t(),{data:V,isLoading:W}=Q2t(),{data:Y,isLoading:K}=ttn(r),{data:J,isLoading:ne}=stn(s==null?void 0:s.id),{data:ie=0}=rtn(s==null?void 0:s.id),he=atn(),ce=new Set((J==null?void 0:J.map(Ce=>Ce.item_id))||[]),pe=async()=>{if(i)try{const Ce=await he.mutateAsync(i.id);i.item_type==="reelflow_credits"?ae.success(`🎬 ${i.max_quantity} ReelFlow credits added to your balance!`):ae.success(`Successfully purchased "${i.name}"!`),l(null)}catch(Ce){ae.error(Ce.message||"Failed to purchase item")}},le=async()=>{if(!h.trim()){ae.error("Please write a review");return}g(!0);const Ce=await M(d,h);g(!1),Ce.success?(ae.success("Thank you for your review! You earned 25 points!"),b(h),v(!0),p(""),u(5)):ae.error(Ce.error||"Failed to submit review")},ve=()=>{navigator.clipboard.writeText(j),ae.success("Review copied to clipboard!")},ge=()=>{F(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},Te=()=>{v(!1),c(!1),b("")};return W||K||ne?e.jsx(Ts,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{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(Ce=>e.jsx(Ws,{className:"h-64"},Ce))})]})}):e.jsxs(Ts,{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(fe,{className:"bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20",children:e.jsx(Ee,{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(ca,{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:ie.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(vo,{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(Dc,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{children:"Streak bonuses add extra points!"})]})]})]})})}),e.jsx(dy,{open:T,onOpenChange:L,children:e.jsxs(fe,{className:"border-primary/20",children:[e.jsx(uy,{asChild:!0,children:e.jsx(Mt,{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(vo,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-base",children:"How to Earn Points"}),e.jsx(Vn,{children:"See all the ways you can earn spendable points"})]})]}),T?e.jsx(tx,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(io,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(hy,{children:e.jsx(Ee,{className:"pt-0",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[z==null?void 0:z.filter(Ce=>Ce.is_active).map(Ce=>{const Ae=De=>{switch(De){case"event_attendance":return e.jsx(yr,{className:"h-5 w-5"});case"leave_review":return e.jsx(ca,{className:"h-5 w-5"});case"add_listing":return e.jsx(Or,{className:"h-5 w-5"});case"first_contact":return e.jsx(Nn,{className:"h-5 w-5"});case"first_video":return e.jsx(br,{className:"h-5 w-5"});case"first_community_post":return e.jsx(Ei,{className:"h-5 w-5"});default:return e.jsx(Oi,{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:Ae(Ce.action_key)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:Ce.action_name}),Ce.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ce.description})]}),e.jsxs(ze,{variant:"secondary",className:"font-bold shrink-0",children:["+",Ce.points]})]},Ce.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(Dc,{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(ze,{variant:"outline",className:"font-bold shrink-0 border-orange-500/50 text-orange-600",children:"+Bonus"})]})]})})})]})}),!D&&e.jsx(fe,{className:"bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border-yellow-500/20",children:e.jsx(Ee,{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(Ei,{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(ca,{className:"h-4 w-4 mr-2"}),"Leave Review"]})]})})}),e.jsxs(Br,{value:t,onValueChange:n,children:[e.jsxs(Fr,{children:[e.jsxs(Kt,{value:"store",className:"flex items-center gap-2",children:[e.jsx(_w,{className:"h-4 w-4"}),"Store"]}),e.jsxs(Kt,{value:"my-rewards",className:"flex items-center gap-2",children:[e.jsx(Rc,{className:"h-4 w-4"}),"My Rewards",J&&J.length>0&&e.jsx(ze,{variant:"secondary",className:"ml-1",children:J.length})]})]}),e.jsxs(is,{value:"store",className:"mt-6",children:[V&&V.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"}),V.map(Ce=>e.jsxs(B,{variant:r===Ce.id?"default":"outline",size:"sm",onClick:()=>a(Ce.id),children:[Ce.icon&&`${Ce.icon} `,Ce.name]},Ce.id))]}),!Y||Y.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Oi,{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:Y.map(Ce=>{const Ae=Ce.item_type==="reelflow_credits",De=!Ae&&ce.has(Ce.id),Ie=!Ae&&Ce.max_quantity!==null&&Ce.current_quantity===0,Fe=ie>=Ce.points_cost;return e.jsxs(fe,{className:`overflow-hidden transition-all cursor-pointer hover:shadow-lg ${De?"ring-2 ring-green-500/50 bg-green-500/5":""}`,onClick:()=>A(Ce),children:[Ce.preview_image_url?e.jsxs("div",{className:"aspect-video relative overflow-hidden bg-muted",children:[e.jsx("img",{src:Ce.preview_image_url,alt:Ce.name,className:"w-full h-full object-cover"}),De&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(ze,{className:"bg-green-500 text-white",children:[e.jsx(xr,{className:"h-3 w-3 mr-1"}),"Owned"]})}),Ie&&!De&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(ze,{variant:"destructive",children:"Sold Out"})})]}):e.jsxs("div",{className:"aspect-video bg-muted flex items-center justify-center relative",children:[e.jsx(Oi,{className:"h-12 w-12 text-muted-foreground/50"}),De&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(ze,{className:"bg-green-500 text-white",children:[e.jsx(xr,{className:"h-3 w-3 mr-1"}),"Owned"]})})]}),e.jsxs(Mt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx(It,{className:"text-lg",children:Ce.name}),e.jsxs(ze,{variant:"secondary",className:"font-bold shrink-0",children:[e.jsx(ca,{className:"h-3 w-3 mr-1"}),Ce.points_cost]})]}),Ce.category&&e.jsxs(ze,{variant:"outline",className:"w-fit",children:[Ce.category.icon&&`${Ce.category.icon} `,Ce.category.name]})]}),e.jsxs(Ee,{children:[e.jsx(Vn,{className:"mb-4 line-clamp-2",children:Ce.description||"No description available"}),Ce.max_quantity!==null&&!De&&!Ae&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[Ce.current_quantity," of ",Ce.max_quantity," remaining"]}),Ae&&e.jsxs("p",{className:"text-xs text-violet-600 font-medium mb-3",children:["🎬 Grants ",Ce.max_quantity," ReelFlow credits per purchase"]}),De?e.jsx(B,{className:"w-full",onClick:qe=>{qe.stopPropagation(),Ce.file_url&&HNe(Ce.file_url,Ce.name)},disabled:!Ce.file_url,children:Ce.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Pa,{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:qe=>{qe.stopPropagation(),l(Ce)},disabled:Ie||!Fe,children:Ie?"Sold Out":Fe?e.jsxs(e.Fragment,{children:[e.jsx(_w,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${Ce.points_cost-ie} more pts`})]})]},Ce.id)})})]}),e.jsx(is,{value:"my-rewards",className:"mt-6",children:!J||J.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Rc,{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:J.map(Ce=>{var Ae,De,Ie,Fe,qe,be,Ze;return e.jsxs(fe,{className:"overflow-hidden",children:[(Ae=Ce.item)!=null&&Ae.preview_image_url?e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted",children:e.jsx("img",{src:Ce.item.preview_image_url,alt:((De=Ce.item)==null?void 0:De.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(Oi,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(Mt,{className:"pb-2",children:[e.jsx(It,{className:"text-lg",children:((Ie=Ce.item)==null?void 0:Ie.name)||"Unknown Item"}),e.jsxs(Vn,{className:"text-xs",children:["Purchased for ",Ce.points_spent," points • ",new Date(Ce.purchased_at).toLocaleDateString()]})]}),e.jsx(Ee,{children:((Fe=Ce.item)==null?void 0:Fe.item_type)==="reelflow_credits"?e.jsxs(B,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(xr,{className:"h-4 w-4 mr-2 text-green-500"}),(qe=Ce.item)==null?void 0:qe.max_quantity," Credits Applied"]}):e.jsx(B,{className:"w-full",onClick:()=>{var Ne,it;(Ne=Ce.item)!=null&&Ne.file_url&&HNe(Ce.item.file_url,(it=Ce.item)==null?void 0:it.name)},disabled:!((be=Ce.item)!=null&&be.file_url),children:((Ze=Ce.item)==null?void 0:Ze.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Access"]})})})]},Ce.id)})})})]})]}),e.jsx(Oo,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Confirm Purchase"}),e.jsxs(Mo,{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:[ie," points"]}),". After this purchase, you'll have"," ",e.jsxs("strong",{children:[ie-((i==null?void 0:i.points_cost)||0)," points"]})," remaining."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:pe,disabled:he.isPending,children:he.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(bs,{open:o,onOpenChange:Ce=>{!Ce&&_?Te():c(Ce)},children:e.jsx(vs,{children:_?e.jsxs(e.Fragment,{children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(xr,{className:"h-5 w-5 text-green-500"}),"Thank You for Your Review!"]}),e.jsx(Qn,{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:['"',j,'"']})]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:ve,children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(Xn,{className:"flex-col sm:flex-row gap-2",children:[e.jsx(B,{variant:"outline",onClick:Te,children:"Maybe Later"}),e.jsxs(B,{onClick:ge,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(ws,{children:[e.jsx(_s,{children:"Leave a Review"}),e.jsx(Qn,{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(Ce=>e.jsx("button",{type:"button",onClick:()=>u(Ce),className:"focus:outline-none",children:e.jsx(ca,{className:`h-8 w-8 transition-colors ${d>=Ce?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-yellow-400"}`})},Ce))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Review"}),e.jsx(Es,{placeholder:"What do you love about LevelUp? How has it helped your business?",value:h,onChange:Ce=>p(Ce.target.value),rows:4})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{onClick:le,disabled:f,className:"bg-yellow-600 hover:bg-yellow-700",children:f?"Submitting...":"Submit & Earn 25 Points"})]})]})})}),e.jsx(bs,{open:!!S,onOpenChange:()=>A(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[S==null?void 0:S.name,e.jsxs(ze,{variant:"secondary",className:"font-bold",children:[e.jsx(ca,{className:"h-3 w-3 mr-1"}),S==null?void 0:S.points_cost]})]}),(S==null?void 0:S.category)&&e.jsxs(ze,{variant:"outline",className:"w-fit",children:[S.category.icon&&`${S.category.icon} `,S.category.name]})]}),(S==null?void 0:S.preview_image_url)&&e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted rounded-lg",children:e.jsx("img",{src:S.preview_image_url,alt:S.name,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:(S==null?void 0:S.description)||"No description available"}),(S==null?void 0:S.item_type)==="reelflow_credits"&&e.jsxs("p",{className:"text-sm text-violet-600 font-medium",children:["🎬 Grants ",S==null?void 0:S.max_quantity," ReelFlow credits per purchase"]}),(S==null?void 0:S.item_type)!=="reelflow_credits"&&(S==null?void 0:S.max_quantity)!==null&&!ce.has((S==null?void 0:S.id)||"")&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[S==null?void 0:S.current_quantity," of ",S==null?void 0:S.max_quantity," remaining"]})]}),e.jsx(Xn,{children:S&&S.item_type!=="reelflow_credits"&&ce.has(S.id)?e.jsx(B,{className:"w-full",onClick:()=>{S.file_url&&HNe(S.file_url,S.name)},disabled:!S.file_url,children:S.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Access"]})}):S&&e.jsx(B,{className:"w-full",onClick:()=>{A(null),l(S)},disabled:S.item_type!=="reelflow_credits"&&S.max_quantity!==null&&S.current_quantity===0||ie{s&&ne()},[s==null?void 0:s.id]);const ne=async()=>{if(!s)return;o(!0),j(!1),_(!0);const{data:qe}=await q.from("point_reward_settings").select("action_key, points").in("action_key",["referral_signup","referral_paid"]);qe==null||qe.forEach(it=>{it.action_key==="referral_signup"&&h(it.points),it.action_key==="referral_paid"&&f(it.points)});const{data:be}=await q.from("profiles").select("name").eq("id",s.id).maybeSingle();be!=null&&be.name&&S(be.name);let{data:Ze}=await q.from("agent_referral_codes").select("code").eq("user_id",s.id).maybeSingle();if(!Ze){const{data:it}=await q.rpc("generate_agent_referral_code",{_user_id:s.id}),je=it||`agent${s.id.slice(0,6)}`,{data:Ge,error:Be}=await q.from("agent_referral_codes").insert({user_id:s.id,code:je}).select("code").maybeSingle();!Be&&Ge&&(Ze=Ge)}i((Ze==null?void 0:Ze.code)??null);const{data:Ne}=await q.from("agent_referrals").select("id, referred_user_id, status, signed_up_at, qualified_at, signup_points_awarded, paid_points_awarded").eq("referrer_user_id",s.id).order("signed_up_at",{ascending:!1});if(Ne&&Ne.length>0){const it=Ne.map(Be=>Be.referred_user_id),{data:je}=await q.from("profiles").select("id, name, email").in("id",it),Ge=new Map((je==null?void 0:je.map(Be=>[Be.id,Be]))??[]);d(Ne.map(Be=>({...Be,referred_profile:Ge.get(Be.referred_user_id)??null})))}else d([]);o(!1)},ie=N.useMemo(()=>a?`${Wsn}/trial?ref=${a}`:"",[a]),he=c.length,ce=c.filter(qe=>qe.status==="qualified").length,pe=c.filter(qe=>qe.signup_points_awarded).length*u+c.filter(qe=>qe.paid_points_awarded).length*p,le=async()=>{ie&&(await navigator.clipboard.writeText(ie),ae.success("Referral link copied!"))},ve=()=>{const qe=encodeURIComponent("Join me on LevelUp"),be=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: ${ie} Let me know if you have any questions!`);window.location.href=`mailto:?subject=${qe}&body=${be}`},ge=()=>{const qe=encodeURIComponent(`Hey! I think you'd love LevelUp for your business — sign up with my link: ${ie}`);window.location.href=`sms:?&body=${qe}`},Te=async()=>{if(navigator.share&&ie)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:ie})}catch{}else le()},Me=qe=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(qe.trim()),Ce=qe=>{const be=(qe??L).trim().replace(/,$/,"");if(!be)return;const Ze=be.split(/[\s,;]+/).filter(Boolean),Ne=[...M];let it=0;for(const je of Ze){if(!Me(je)){ae.error(`Invalid email: ${je}`);continue}Ne.includes(je)||(Ne.push(je),it++)}F(Ne),it>0&&D("")},Ae=qe=>F(M.filter(be=>be!==qe)),De=()=>{Y(`${b?b.split(" ")[0]+" invited you to":"Join me on"} LevelUp`),V("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)},Ie=qe=>{const be=qe.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),Ze=b||"A fellow agent",Ne="https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/levelup-logo-email.png",it=ie;return`
LevelUp
You're Invited

${Ze} thinks you'd love LevelUp 🎉

${be}

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

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

`.trim()},Fe=async()=>{if(M.length===0&&(L.trim()&&Ce(),M.length===0)){ae.error("Add at least one recipient");return}if(!W.trim()){ae.error("Subject is required");return}J(!0);const qe=Ie(z);let be=0,Ze=0;for(const Ne of M)try{const{data:it,error:je}=await q.functions.invoke("gmail-send",{body:{to:Ne,subject:W,body:qe,source:"referral_invite"}});if(je||it!=null&&it.error)throw new Error((je==null?void 0:je.message)||(it==null?void 0:it.error));be++}catch(it){console.error("Gmail send failed for",Ne,it),Ze++}J(!1),be>0?(ae.success(`Invite sent to ${be} ${be===1?"person":"people"}`+(Ze>0?` (${Ze} failed)`:"")),F([]),D(""),T(!1)):ae.error("Failed to send invites")};return!v&&!g?e.jsx(Ts,{title:"Refer & Earn",children:e.jsxs("div",{className:"container max-w-3xl mx-auto p-4 md:p-8",children:[e.jsx(Go,{children:e.jsx("title",{children:"Refer & Earn | LevelUp"})}),e.jsxs(fe,{className:"border-2 border-dashed",children:[e.jsxs(Mt,{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(Kc,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx(It,{children:"Refer & Earn is for active members"}),e.jsx(Vn,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(Ee,{className:"flex justify-center",children:e.jsx(B,{onClick:()=>t("/subscription"),children:"View Subscription"})})]})]})}):e.jsxs(Ts,{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(Go,{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(Oi,{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:[p," more"]})," when they activate a paid plan."]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx(Nn,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:he}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Friends signed up"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx(xr,{className:"h-5 w-5 text-emerald-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ce}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Activated paid plan"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx(vo,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:pe.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(Vn,{children:"Anyone who signs up through this link is credited to you."})]}),e.jsxs(Ee,{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…":ie,className:"font-mono text-sm",onFocus:qe=>qe.currentTarget.select()}),e.jsxs(B,{onClick:le,disabled:!ie,children:[e.jsx(Xr,{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:De,disabled:!ie,className:"bg-primary hover:bg-primary/90",children:[e.jsx(cr,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ve,disabled:!ie,children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ge,disabled:!ie,children:[e.jsx(Ei,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:Te,disabled:!ie,children:[e.jsx(Hl,{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(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Your Referrals"}),e.jsx(Vn,{children:"Track who joined and when they upgrade."})]}),e.jsx(Ee,{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(Nn,{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(qe=>{var Ne,it;const be=((Ne=qe.referred_profile)==null?void 0:Ne.name)||((it=qe.referred_profile)==null?void 0:it.email)||"New agent",Ze=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(qe.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:be}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Joined ",Ze]})]}),qe.status==="qualified"?e.jsxs(ze,{className:"bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100",children:[e.jsx(xr,{className:"h-3 w-3 mr-1"})," Paid · +",u+p," pts"]}):e.jsxs(ze,{variant:"secondary",children:[e.jsx(gr,{className:"h-3 w-3 mr-1"})," Signed up · +",u," pts"]})]},qe.id)})})})]}),e.jsx(fe,{className:"bg-muted/30",children:e.jsxs(Ee,{className:"p-6",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"})," How it works"]}),e.jsxs("ol",{className:"text-sm text-muted-foreground space-y-2 list-decimal list-inside",children:[e.jsx("li",{children:"Share your unique link with peers, mentees, or other agents."}),e.jsxs("li",{children:["They sign up — you instantly earn ",e.jsxs("strong",{className:"text-foreground",children:[u," points"]}),"."]}),e.jsxs("li",{children:["When they activate a paid plan, you earn another ",e.jsxs("strong",{className:"text-foreground",children:[p," points"]}),"."]}),e.jsxs("li",{children:["Redeem points in the ",e.jsx("a",{href:"/reward-store",className:"text-primary underline",children:"Reward Store"}),"."]})]})]})}),e.jsx(ll,{className:"opacity-0"})]}),e.jsx(bs,{open:A,onOpenChange:T,children:e.jsxs(vs,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(cr,{className:"h-5 w-5 text-primary"})," Send referral invites via Gmail"]}),e.jsxs(Qn,{children:["Sending from ",e.jsx("span",{className:"font-medium text-foreground",children:r}),". We'll deliver a branded LevelUp invite with your personal note."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Recipients"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 p-2 border rounded-md min-h-[44px] bg-background",children:[M.map(qe=>e.jsxs(ze,{variant:"secondary",className:"gap-1 pr-1",children:[qe,e.jsx("button",{type:"button",onClick:()=>Ae(qe),className:"hover:bg-muted-foreground/20 rounded-full p-0.5","aria-label":`Remove ${qe}`,children:e.jsx(Bn,{className:"h-3 w-3"})})]},qe)),e.jsx("input",{type:"email",value:L,onChange:qe=>D(qe.target.value),onKeyDown:qe=>{qe.key==="Enter"||qe.key===","||qe.key===" "?(qe.preventDefault(),Ce()):qe.key==="Backspace"&&!L&&M.length>0&&F(M.slice(0,-1))},onBlur:()=>L.trim()&&Ce(),onPaste:qe=>{const be=qe.clipboardData.getData("text");/[\s,;]/.test(be)&&(qe.preventDefault(),Ce(be))},placeholder:M.length===0?"name@example.com, another@example.com":"Add another…",className:"flex-1 min-w-[160px] bg-transparent outline-none text-sm"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Press Enter, comma, or space to add. You can paste multiple emails at once."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"email-subject",children:"Subject"}),e.jsx(ye,{id:"email-subject",value:W,onChange:qe=>Y(qe.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(Es,{id:"personal-note",value:z,onChange:qe=>V(qe.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: ",W||"(no subject)"]})]}),e.jsx("iframe",{title:"Email preview",srcDoc:Ie(z),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>T(!1),disabled:K,children:"Cancel"}),e.jsxs(B,{onClick:Fe,disabled:K,children:[e.jsx(cr,{className:"h-4 w-4 mr-2"}),K?"Sending…":`Send${M.length>0?` to ${M.length}`:""}`]})]})]})})]})}const CNt=()=>{const{user:s}=ys(),t=Ht(),n=ct({queryKey:["smart-presentations",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await q.from("smart_presentations").select("*").eq("owner_user_id",s.id).neq("status","archived").order("created_at",{ascending:!1});if(u)throw u;return d||[]},enabled:!!s}),r=ct({queryKey:["smart-presentation-templates",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await q.from("smart_presentation_templates").select("*").eq("is_active",!0).order("created_at",{ascending:!0});if(u)throw u;return d||[]},enabled:!!s}),a=gt({mutationFn:async d=>{const{data:u,error:h}=await q.from("smart_presentations").insert({owner_user_id:s.id,...d}).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),i=gt({mutationFn:async({id:d,...u})=>{const{data:h,error:p}=await q.from("smart_presentations").update(u).eq("id",d).select().single();if(p)throw p;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),l=gt({mutationFn:async d=>{const{data:u,error:h}=await q.from("smart_presentations").update({status:"published",published_at:new Date().toISOString()}).eq("id",d).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),ae.success("Presentation published!")}}),o=gt({mutationFn:async d=>{const{error:u}=await q.from("smart_presentations").update({status:"archived"}).eq("id",d);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),ae.success("Presentation archived")}}),c=gt({mutationFn:async d=>{const{error:u}=await q.from("smart_presentation_templates").insert({owner_user_id:s.id,name:d.title+" Template",description:"Created from "+d.title,template_type:"custom",icon:"📄",sections:d.sections,cta_config:{type:d.cta_type,label:d.cta_label},is_system:!1});if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentation-templates"]}),ae.success("Saved as template!")}});return{presentations:n.data||[],templates:r.data||[],isLoading:n.isLoading,templatesLoading:r.isLoading,createPresentation:a,updatePresentation:i,publishPresentation:l,archivePresentation:o,saveAsTemplate:c}},Ysn=()=>{const s=Mn(),{presentations:t,isLoading:n,archivePresentation:r,saveAsTemplate:a}=CNt(),i=o=>o.status==="draft"?e.jsx(ze,{variant:"outline",className:"text-xs",children:"Draft"}):o.view_count>1?e.jsx(ze,{className:"text-xs bg-emerald-100 text-emerald-700 border-emerald-200",children:"Revisited"}):o.view_count===1?e.jsx(ze,{className:"text-xs bg-blue-100 text-blue-700 border-blue-200",children:"Opened"}):e.jsx(ze,{variant:"secondary",className:"text-xs",children:"Not Opened"}),l=o=>{const c=`https://presentations.relevelup.com/${o}`;navigator.clipboard.writeText(c),ae.success("Link copied!")};return e.jsx(Ts,{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(Is,{className:"h-4 w-4"}),"Create Presentation"]})]}),n?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(o=>e.jsx(Ws,{className:"h-20 w-full rounded-lg"},o))}):t.length===0?e.jsx(fe,{children:e.jsxs(Ee,{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(iy,{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(Is,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(fe,{className:"hover:shadow-sm transition-shadow",children:e.jsx(Ee,{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(Nr,{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 ",Ss(new Date(o.created_at),"MMM d, yyyy")]}),o.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Er,{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(Xr,{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(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Ig,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",children:[o.status==="published"&&o.share_token&&e.jsxs(Qr,{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(Qr,{onClick:()=>a.mutate(o),children:[e.jsx(Nr,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(Qr,{onClick:()=>r.mutate(o.id),className:"text-destructive",children:[e.jsx(rm,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},zXe={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."}]},Zsn=[{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 Qsn(s){const t=zXe[s];if(t)return t;const n=s.toLowerCase();for(const[r,a]of Object.entries(zXe))if(n.includes(r.toLowerCase())||r.toLowerCase().includes(n))return a;return Zsn}function Xsn({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=N.useState(!1),[i,l]=N.useState("script"),[o,c]=N.useState(0),[d,u]=N.useState(0),{canRecord:h}=O_t(),p=IN(),[f,g]=N.useState(""),[_,v]=N.useState(!1),[j,b]=N.useState(!0),[S,A]=N.useState(!1),[T,L]=N.useState(null),D=Qsn(s),M=()=>{l("script"),c(0),u(0),g(""),v(!1),b(!0),A(!1),L(null)},F=K=>{!K&&(i==="uploading"||i==="processing")||(a(K),K||M())},z=K=>{L(K),g(D[K].text),v(!1)},V=()=>{l("record"),b(f.trim().length>0)},W=()=>{g(""),b(!1),l("record")},Y=N.useCallback(async(K,J)=>{l("uploading");try{const ne=s||"Presentation Video",{videoId:ie,uploadUrl:he,libraryId:ce}=await i6(ne),{apiKey:pe}=await o6(ie),le=new XMLHttpRequest;le.upload.onprogress=Ce=>{Ce.lengthComputable&&c(Ce.loaded/Ce.total*100)},await new Promise((Ce,Ae)=>{le.onload=()=>le.status>=200&&le.status<300?Ce():Ae(new Error("Upload failed")),le.onerror=()=>Ae(new Error("Upload failed")),le.open("PUT",he),le.setRequestHeader("AccessKey",pe),le.send(K)}),l("processing");let ve=0;const ge=Date.now(),Te=9e4;let Me=null;for(;ve<4;){if(await new Promise(Ae=>setTimeout(Ae,3e3)),Date.now()-ge>Te){const Ae=K.size/1048576,De=`https://iframe.mediadelivery.net/embed/${ce}/${ie}?responsive=true`;await p.mutateAsync({bunny_video_id:ie,playback_url:De,file_size_mb:Ae,title:ne,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(De),ae.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const Ce=await $w(ie);if(ve=Ce.status,u(Ce.encodeProgress||0),ve===4)Me={playbackUrl:Ce.directPlayUrl,thumbnailUrl:Ce.thumbnailUrl,previewUrl:Ce.previewUrl||null,duration:Ce.length||J,fileSizeMb:(Ce.storageSize||K.size)/(1024*1024)};else if(ve===5||ve===6)throw new Error("Video processing failed")}if(!Me)throw new Error("No video data");await p.mutateAsync({bunny_video_id:ie,contact_id:t||void 0,playback_url:Me.playbackUrl,thumbnail_url:Me.thumbnailUrl,preview_url:Me.previewUrl,duration_seconds:Me.duration,file_size_mb:Me.fileSizeMb,title:ne,status:"ready",touch_type:"presentation"}),n(Me.playbackUrl),ae.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(ne){console.error("Recording upload error:",ne),ae.error("Failed to process video. Please try again."),l("record")}},[s,t,n,p]);return e.jsxs(bs,{open:r,onOpenChange:F,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Record a video",children:[e.jsx(br,{className:"h-3.5 w-3.5"}),"Record"]})}),e.jsxs(vs,{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(ws,{children:e.jsxs(_s,{children:[i==="script"&&`Prepare your script for "${s}"`,i==="record"&&`Record video for "${s}"`,i==="uploading"&&"Uploading...",i==="processing"&&"Processing...",i==="done"&&"Done!"]})}),i==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a starter script below, edit it to make it yours, or skip and speak freely."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Starter Scripts"}),e.jsx("div",{className:"grid gap-2",children:D.map((K,J)=>e.jsxs("button",{onClick:()=>z(J),className:Et("text-left p-3 rounded-lg border transition-all hover:bg-accent/50",T===J?"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(Nr,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm font-medium",children:K.label})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 ml-5.5",children:K.text})]},J))})]}),f&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Your Script"}),!_&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>v(!0),className:"h-7 text-xs gap-1",children:[e.jsx(_a,{className:"h-3 w-3"}),"Edit"]})]}),_?e.jsx(Es,{value:f,onChange:K=>g(K.target.value),rows:5,placeholder:"Type your script here...",className:"text-sm"}):e.jsx("div",{className:"p-3 rounded-lg bg-muted/50 text-sm text-foreground leading-relaxed",children:f})]}),!f&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Or Write Your Own"}),e.jsx(Es,{value:f,onChange:K=>{g(K.target.value),L(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:W,className:"text-muted-foreground",children:"Skip — no teleprompter"}),e.jsx(B,{onClick:V,disabled:!1,children:f.trim()?"Continue with Script":"Continue Without Script"})]})]}),!h&&i==="record"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[e.jsx($l,{className:"h-10 w-10 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You've reached your video storage limit. Delete some videos to free up space."})]}):i==="record"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Record up to 5 minutes. Saved to your library & auto-attached."}),f.trim()&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>b(!j),className:"h-7 text-xs gap-1",children:[j?e.jsx(xf,{className:"h-3 w-3"}):e.jsx(Er,{className:"h-3 w-3"}),j?"Hide Script":"Show Script"]})]}),e.jsx(u6,{maxDurationSeconds:600,onRecordingComplete:Y,onRecordingStateChange:A,onError:K=>ae.error(K),teleprompterContent:f.trim()?e.jsx(v8e,{text:f,isVisible:j,onToggleVisibility:()=>b(!j),isRecording:S,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(ts,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(pi,{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(ts,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(pi,{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(Ri,{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 Jsn({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState("idle"),[d,u]=N.useState(0),h=N.useRef(null),p=IN(),{data:f}=D1e(),g=(f==null?void 0:f.total_storage_mb)||0,v=((f==null?void 0:f.max_storage_mb)||1024)-g,j=()=>{l(null),c("idle"),u(0)},b=D=>{!D&&o!=="idle"&&o!=="done"||(a(D),D||j())},S=D=>{var z;const M=(z=D.target.files)==null?void 0:z[0];if(!M)return;if(!M.type.startsWith("video/")){ae.error("Please select a video file");return}const F=M.size/(1024*1024);if(F>500){ae.error("Video file must be less than 500MB");return}if(F>v){ae.error(`Not enough storage. You have ${v.toFixed(1)} MB remaining.`);return}l(M)},A=N.useCallback(async()=>{if(i){c("creating"),u(0);try{const D=s||i.name,{data:M,error:F}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:D,isAgentVideo:!0}});if(F)throw new Error(F.message);const{videoId:z,libraryId:V}=M;c("uploading");const{data:W,error:Y}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:z,isAgentVideo:!0}});if(Y)throw new Error(Y.message);await new Promise((ne,ie)=>{const he=new XMLHttpRequest;he.upload.addEventListener("progress",ce=>{ce.lengthComputable&&u(Math.round(ce.loaded/ce.total*100))}),he.addEventListener("load",()=>he.status>=200&&he.status<300?ne():ie(new Error(`Upload failed (${he.status})`))),he.addEventListener("error",()=>ie(new Error("Upload failed"))),he.open("PUT",W.uploadUrl),he.setRequestHeader("AccessKey",W.apiKey),he.send(i)}),c("processing");const K=i.size/(1024*1024),J=`https://iframe.mediadelivery.net/embed/${V}/${z}`;await p.mutateAsync({bunny_video_id:z,playback_url:J,file_size_mb:K,title:D,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(J),c("done"),ae.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(D){console.error("Upload error:",D),ae.error(D instanceof Error?D.message:"Failed to upload video"),c("idle")}}},[i,s,t,n,p]),T=()=>{switch(o){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${d}%`;case"processing":return"Saving video...";case"done":return"Done!";default:return""}},L=o!=="idle"&&o!=="done";return e.jsxs(bs,{open:r,onOpenChange:b,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Upload a video file",children:[e.jsx(Na,{className:"h-3.5 w-3.5"}),"Upload"]})}),e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(ws,{children:e.jsxs(_s,{children:['Upload Video for "',s,'"']})}),e.jsxs("div",{className:"space-y-4 py-2",children:[i?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(br,{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"]})]}),!L&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(null),children:e.jsx(Bn,{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 D;return(D=h.current)==null?void 0:D.click()},children:[e.jsx(Na,{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:S,disabled:L}),L&&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(ts,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:T()})]}),e.jsx(pi,{value:o==="uploading"?d:o==="processing"?100:10})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>b(!1),disabled:L,children:"Cancel"}),e.jsx(B,{onClick:A,disabled:!i||L,children:L?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Na,{className:"h-4 w-4 mr-2"}),"Upload & Attach"]})})]})]})]})}const BXe=[{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"}],$Xe=()=>{const s=Mn(),{id:t}=bi(),{user:n}=ys(),{templates:r,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=CNt(),{isGmailConnected:c,gmailEmail:d}=Oh(),[u,h]=N.useState(!1),[p,f]=N.useState("client"),[g,_]=N.useState(!1),[v,j]=N.useState(""),[b,S]=N.useState([]),[A,T]=N.useState(!1),[L,D]=N.useState(null),[M,F]=N.useState(!1),[z,V]=N.useState(""),[W,Y]=N.useState(""),[K,J]=N.useState(""),[ne,ie]=N.useState("buyer"),[he,ce]=N.useState(""),[pe,le]=N.useState(null),[ve,ge]=N.useState(""),[Te,Me]=N.useState([]),[Ce,Ae]=N.useState("schedule_call"),[De,Ie]=N.useState("Schedule a Call"),[Fe,qe]=N.useState(""),[be,Ze]=N.useState(""),[Ne,it]=N.useState(null),[je,Ge]=N.useState(t||null),[Be,Ye]=N.useState(null),[We,rt]=N.useState(!1),tt=async(ft,Vt)=>{if(!n)return;const Ms=5*1024*1024;if(ft.size>Ms){ae.error("Image must be under 5MB");return}if(!ft.type.startsWith("image/")){ae.error("Please upload an image file");return}it(Vt);try{const Xt=ft.name.split(".").pop()||"jpg",Js=`${n.id}/${Date.now()}.${Xt}`,{error:Cs}=await q.storage.from("listing-photos").upload(Js,ft);if(Cs)throw Cs;const{data:{publicUrl:As}}=q.storage.from("listing-photos").getPublicUrl(Js);Bt(Vt,{image_url:As}),ae.success("Image uploaded")}catch{ae.error("Failed to upload image")}finally{it(null)}};N.useEffect(()=>{t&&at(t)},[t]);const at=async ft=>{const{data:Vt,error:Ms}=await q.from("smart_presentations").select("*").eq("id",ft).single();if(Ms||!Vt)return;const Xt=Vt;if(_(!0),ge(Xt.title),V(Xt.client_name||""),ce(Xt.property_address||""),Me(Xt.sections||[]),Ae(Xt.cta_type||"schedule_call"),Ie(Xt.cta_label||"Schedule a Call"),qe(Xt.cta_url||""),Ze(Xt.heading||""),Ye(Xt.share_token),rt(Xt.status==="published"),Ge(Xt.id),f("builder"),Xt.contact_id){const{data:Js}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("id",Xt.contact_id).maybeSingle();Js&&(D(Js),Y(Js.email||""),J(Js.phone||""))}};N.useEffect(()=>{if(!n||v.length<1){S([]);return}const ft=setTimeout(async()=>{T(!0);const{data:Vt}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, lead_source").eq("owner_user_id",n.id).or(`first_name.ilike.%${v}%,last_name.ilike.%${v}%,email.ilike.%${v}%`).limit(10);S(Vt||[]),T(!1)},300);return()=>clearTimeout(ft)},[v,n]);const He=ft=>{D(ft),V(`${ft.first_name} ${ft.last_name||""}`.trim()),Y(ft.email||""),J(ft.phone||""),F(!1)},dt=async()=>{if(!z.trim()){ae.error("Client name is required");return}const ft=z.trim().split(" "),Vt=ft[0],Ms=ft.slice(1).join(" ")||null,{data:Xt,error:Js}=await q.from("innercircle_contacts").insert({owner_user_id:n.id,first_name:Vt,last_name:Ms,email:W||null,phone:K||null,lead_source:"Smart Presentation"}).select().single();if(Js){ae.error("Failed to create client");return}D(Xt),ae.success("Client created & saved to Agent OS"),f("template")},bt=ft=>{le(ft);const Vt=(ft.sections||[]).map(Ms=>({...Ms,is_visible:!0,video_url:"",text:""}));if(Me(Vt),ge(ft.name+(z?` for ${z}`:"")),ft.cta_config){const Ms=ft.cta_config;Ae(Ms.type||"schedule_call"),Ie(Ms.label||"Schedule a Call")}f("builder")},vt=()=>{Me([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),ge(z?`Presentation for ${z}`:"New Presentation"),f("builder")},Bt=(ft,Vt)=>{Me(Ms=>Ms.map((Xt,Js)=>Js===ft?{...Xt,...Vt}:Xt))},Zt=ft=>{Bt(ft,{is_visible:!Te[ft].is_visible})},Fs=()=>{Me(ft=>[...ft,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},Rs=ft=>{Me(Vt=>Vt.filter((Ms,Xt)=>Xt!==ft))},ms=async()=>{if(!ve.trim()){ae.error("Title is required");return}try{if(je){const ft=await l.mutateAsync({id:je,title:ve,sections:Te,client_name:z,property_address:he||null,cta_type:Ce,cta_label:De,cta_url:Fe||null,heading:be||null});ae.success("Saved")}else{const ft=await i.mutateAsync({title:ve,contact_id:(L==null?void 0:L.id)||void 0,client_name:z,property_address:he||void 0,template_id:(pe==null?void 0:pe.id)||void 0,sections:Te,cta_type:Ce,cta_label:De,cta_url:Fe||void 0,heading:be||void 0});Ge(ft.id),Ye(ft.share_token),ae.success("Presentation created!")}}catch(ft){console.error("Failed to save presentation:",ft);const Vt=(ft==null?void 0:ft.message)||(ft==null?void 0:ft.toString())||"Unknown error";ae.error(`Failed to save: ${Vt}`)}},Pt=async()=>{try{await ms();const ft=je;if(ft){const Vt=await o.mutateAsync(ft);Ye(Vt.share_token),rt(!0),f("share")}}catch(ft){console.error("Failed to publish presentation:",ft),ae.error(`Failed to publish: ${(ft==null?void 0:ft.message)||"Unknown error"}`)}},Jt=Be?`https://presentations.relevelup.com/${Be}`:"";return e.jsx(Ts,{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(Hr,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-serif font-bold text-foreground",children:g?"Edit Presentation":"Create Smart Presentation"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[p==="client"&&"Who is this presentation for?",p==="template"&&"Choose a starting template",p==="builder"&&"Customize your presentation",p==="share"&&"Share with your client"]})]})]}),!g&&e.jsx("div",{className:"flex items-center gap-2",children:["client","template","builder","share"].map((ft,Vt)=>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",p===ft?"bg-primary text-primary-foreground":Vt<["client","template","builder","share"].indexOf(p)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:Vt<["client","template","builder","share"].indexOf(p)?e.jsx(Ir,{className:"h-4 w-4"}):Vt+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:ft}),Vt<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},ft))}),p==="client"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{onClick:()=>{D(null),V(""),Y(""),J(""),F(!1),f("template")},className:"w-full group flex items-center justify-between gap-4 rounded-xl border border-dashed border-primary/30 bg-primary/5 hover:bg-primary/10 transition-all p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(cr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-semibold text-foreground text-sm",children:"Skip — Use as Lead Gen Tool"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"No specific client. Share broadly to capture new leads."})]})]}),e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors shrink-0"})]}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(vr,{className:"h-4 w-4 text-muted-foreground"}),"Select Existing Client"]})}),e.jsxs(Ee,{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:v,onChange:ft=>j(ft.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"space-y-2 max-h-56 overflow-y-auto",children:[A&&e.jsx(Ws,{className:"h-12 w-full"}),b.map(ft=>e.jsxs("button",{onClick:()=>He(ft),className:Et("w-full text-left p-3 rounded-lg border transition-colors",(L==null?void 0:L.id)===ft.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[ft.first_name," ",ft.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ft.email||ft.phone||"No contact info"})]},ft.id)),!v&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Start typing to search your contacts"}),v&&b.length===0&&!A&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No clients found"})]}),L&&e.jsxs(B,{onClick:()=>f("template"),className:"w-full gap-2",children:["Continue with ",L.first_name,e.jsx(Oa,{className:"h-4 w-4"})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Fo,{className:"h-4 w-4 text-muted-foreground"}),"Add New Client"]})}),e.jsxs(Ee,{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:z,onChange:ft=>{V(ft.target.value),F(!0),D(null)},placeholder:"Sarah & Mike Johnson"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Email"}),e.jsx(ye,{value:W,onChange:ft=>Y(ft.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Phone"}),e.jsx(ye,{value:K,onChange:ft=>J(ft.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Client Type"}),e.jsxs(ds,{value:ne,onValueChange:ie,children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"buyer",children:"Buyer"}),e.jsx(Qe,{value:"seller",children:"Seller"}),e.jsx(Qe,{value:"recruit",children:"Recruit"}),e.jsx(Qe,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Property Address"}),e.jsx(ye,{value:he,onChange:ft=>ce(ft.target.value),placeholder:"Optional"})]})]}),M&&z&&e.jsxs(B,{onClick:dt,className:"w-full gap-2",children:["Create Client & Continue",e.jsx(Oa,{className:"h-4 w-4"})]})]})]})]})]}),p==="template"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Br,{defaultValue:"system",children:[e.jsxs(Fr,{children:[e.jsx(Kt,{value:"mine",children:"My Core Templates"}),e.jsx(Kt,{value:"system",children:"LevelUp Smart Templates"}),e.jsx(Kt,{value:"blank",children:"+ Start Blank"})]}),e.jsx(is,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(ft=>e.jsx(Ws,{className:"h-32"},ft))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(ft=>!ft.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(ft=>!ft.is_system).map(ft=>e.jsx(UXe,{template:ft,onSelect:bt},ft.id))})}),e.jsx(is,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(ft=>ft.is_system).map(ft=>e.jsx(UXe,{template:ft,onSelect:bt},ft.id))})}),e.jsx(is,{value:"blank",className:"mt-4",children:e.jsx(fe,{children:e.jsxs(Ee,{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:vt,children:"Start from Scratch"})]})})})]}),e.jsxs(B,{variant:"outline",onClick:()=>f("client"),className:"gap-2",children:[e.jsx(Hr,{className:"h-4 w-4"}),"Back"]})]}),p==="builder"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Presentation Title"}),e.jsx(ye,{value:ve,onChange:ft=>ge(ft.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Page Heading"}),e.jsx(ye,{value:be,onChange:ft=>Ze(ft.target.value),placeholder:z?`Welcome, ${z}!`:"e.g. Welcome! or Your Custom Listing Plan"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:['The main heading visitors see. Leave blank for "Welcome, ',"",'!"']})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Client Name"}),e.jsx(ye,{value:z,onChange:ft=>V(ft.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Property Address"}),e.jsx(ye,{value:he,onChange:ft=>ce(ft.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:Fs,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:Te.map((ft,Vt)=>e.jsx(fe,{className:Et(!ft.is_visible&&"opacity-50"),children:e.jsx(Ee,{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(Fu,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:ft.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:ft.title,onChange:Ms=>Bt(Vt,{title:Ms.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:()=>Zt(Vt),children:ft.is_visible?e.jsx(Er,{className:"h-4 w-4"}):e.jsx(xf,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Rs(Vt),className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})]})]}),e.jsx(ye,{value:ft.description||"",onChange:Ms=>Bt(Vt,{description:Ms.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:ft.video_url||"",onChange:Ms=>Bt(Vt,{video_url:Ms.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(Xsn,{sectionTitle:ft.title,contactId:L==null?void 0:L.id,onVideoReady:Ms=>Bt(Vt,{video_url:Ms})}),e.jsx(Jsn,{sectionTitle:ft.title,contactId:L==null?void 0:L.id,onVideoReady:Ms=>Bt(Vt,{video_url:Ms})}),e.jsx(a6,{userId:n==null?void 0:n.id,onSelect:Ms=>Bt(Vt,{video_url:Ms})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),ft.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:ft.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:()=>Bt(Vt,{image_url:""}),children:e.jsx(Bn,{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:[Ne===Vt?e.jsx(ts,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(ry,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Ne===Vt?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:Ne===Vt,onChange:Ms=>{var Js;const Xt=(Js=Ms.target.files)==null?void 0:Js[0];Xt&&tt(Xt,Vt),Ms.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Text (optional)"}),e.jsx(Lb,{content:ft.text||"",onChange:Ms=>Bt(Vt,{text:Ms}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},Vt))})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Call to Action"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"CTA Type"}),e.jsxs(ds,{value:Ce,onValueChange:ft=>{Ae(ft);const Vt=BXe.find(Ms=>Ms.value===ft);Vt&&Ie(Vt.label)},children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:BXe.map(ft=>e.jsx(Qe,{value:ft.value,children:ft.label},ft.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Button Label"}),e.jsx(ye,{value:De,onChange:ft=>Ie(ft.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:Fe,onChange:ft=>qe(ft.target.value),placeholder:"https://calendly.com/..."}),!Fe&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Without a URL, clients will see a contact form — their info gets added to your contacts and you'll receive an email notification."})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[!g&&e.jsxs(B,{variant:"outline",onClick:()=>f("template"),className:"gap-2",children:[e.jsx(Hr,{className:"h-4 w-4"}),"Back"]}),e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsx(B,{variant:"outline",onClick:ms,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs(B,{onClick:Pt,disabled:o.isPending,className:"gap-2",children:[e.jsx(cr,{className:"h-4 w-4"}),We?"Update & Reshare":"Publish & Share"]})]})]})]}),p==="share"&&Be&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(fe,{children:e.jsxs(Ee,{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(Ir,{className:"h-8 w-8 text-emerald-600"})}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Your Presentation is Live!"}),e.jsxs("p",{className:"text-muted-foreground mb-6 max-w-md",children:["Share this link with ",z||"your client",". You'll be notified when they view it."]}),e.jsxs("div",{className:"flex items-center gap-2 w-full max-w-lg",children:[e.jsx(ye,{value:Jt,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx(B,{onClick:()=>{navigator.clipboard.writeText(Jt),ae.success("Link copied!")},children:e.jsx(Xr,{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 ft=`Hi ${z||""}! I put together something for you — check it out: ${Jt}`;navigator.clipboard.writeText(ft),ae.success("Message copied!")},children:[e.jsx(Ei,{className:"h-4 w-4"}),"Copy Text Message"]}),e.jsxs(B,{variant:"outline",className:"gap-2",onClick:()=>{c?h(!0):window.open(`mailto:${W||""}?subject=${encodeURIComponent(ve)}&body=${encodeURIComponent(`Hi ${(L==null?void 0:L.first_name)||(z==null?void 0:z.split(" ")[0])||""}, I put together a personalized presentation for you: ${Jt} Looking forward to connecting!`)}`)},children:[e.jsx(Vs,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx(t1,{open:u,onOpenChange:h,contact:L?{id:L.id,first_name:L.first_name,last_name:L.last_name,email:W||L.email||""}:W?{id:"",first_name:(z==null?void 0:z.split(" ")[0])||"",last_name:(z==null?void 0:z.split(" ").slice(1).join(" "))||"",email:W}:void 0,defaultSubject:ve,defaultBody:`Hi ${(L==null?void 0:L.first_name)||(z==null?void 0:z.split(" ")[0])||""}, I put together a personalized presentation for you: ${Jt} Looking forward to connecting!`,gmailEmail:d})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs(B,{variant:"outline",onClick:()=>f("builder"),children:[e.jsx(Hr,{className:"h-4 w-4 mr-2"}),"Edit Presentation"]}),e.jsx(B,{onClick:()=>s("/mission-control/presentations"),children:"Done"})]})]})]})})},UXe=({template:s,onSelect:t})=>e.jsx(fe,{className:"hover:shadow-sm transition-shadow",children:e.jsxs(Ee,{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(ze,{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"})]})}),enn=()=>{var _;const{shareToken:s}=bi(),[t,n]=N.useState(null),[r,a]=N.useState(!0),[i,l]=N.useState(0),[o,c]=N.useState(!1);N.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]),N.useEffect(()=>{s&&d()},[s]);const d=async()=>{const{data:v,error:j}=await q.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(j||!v){c(!0),a(!1);return}const{data:b}=await q.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",v.owner_user_id).single();let S;if(b!=null&&b.brokerage_id){const{data:T}=await q.from("brokerages").select("name").eq("id",b.brokerage_id).single();S=(T==null?void 0:T.name)||void 0}let A=null;if(v.contact_id){const{data:T}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",v.contact_id).single();A=T}n({...v,owner_name:b==null?void 0:b.name,owner_email:b==null?void 0:b.email,owner_phone:b==null?void 0:b.phone,owner_avatar:b==null?void 0:b.avatar_url,owner_title:(b==null?void 0:b.title)||void 0,brokerage_name:S,contact_name:A?[A.first_name,A.last_name].filter(Boolean).join(" "):void 0,contact_email:(A==null?void 0:A.email)||void 0,contact_phone:(A==null?void 0:A.phone)||void 0}),a(!1);try{await q.rpc("log_presentation_view",{p_presentation_id:v.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await q.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}};if(r)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[e.jsx(Ws,{className:"h-12 w-3/4 mx-auto"}),e.jsx(Ws,{className:"h-64 w-full"}),e.jsx(Ws,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const h=t.sections.filter(v=>v.is_visible!==!1),p=h[i],f=v=>{const j=v.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(j)return`https://www.youtube.com/embed/${j[1]}?rel=0`;if(v.includes("iframe.mediadelivery.net/play/")){const A=v.replace("/play/","/embed/"),T=A.includes("?")?"&":"?";return`${A}${T}responsive=true`}if(v.includes("iframe.mediadelivery.net")){if(v.match(/\/embed\/(\d+)\/([a-f0-9-]+)/)){const T=v.includes("?")?"&":"?";return`${v}${T}responsive=true`}return""}const b=v.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(b)return`https://www.loom.com/embed/${b[1]}`;const S=v.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return S?`https://iframe.mediadelivery.net/embed/${S[1]}/${S[2]}?responsive=true`:v},g=!!((_=t.cta_url)!=null&&_.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:[p!=null&&p.video_url&&f(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:f(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:h.map((v,j)=>e.jsx("button",{onClick:()=>l(j),className:Et("w-full text-left p-4 rounded-xl border transition-all",i===j?"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(j+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:v.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:v.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:v.description})]})]})},j))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),g?e.jsxs(B,{size:"lg",onClick:u,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[t.cta_label,e.jsx(tr,{className:"h-5 w-5 ml-2"})]}):e.jsx("div",{className:"max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6",children:e.jsx(bct,{presentationId:t.id,ctaLabel:t.cta_label,agentName:t.owner_name||void 0,prefillName:t.contact_name,prefillEmail:t.contact_email,prefillPhone:t.contact_phone})})]})]}),e.jsx("footer",{className:"border-t border-gray-100 bg-white mt-12 py-6 text-center text-xs text-gray-400",children:"Powered by LevelUp"})]})};function tnn({openHouseId:s,enableSurvey:t,onToggleSurvey:n}){const{data:r,isLoading:a}=aBt(s),i=cBt(),l=dBt(),o=uBt(),c=hBt(),[d,u]=N.useState(""),[h,p]=N.useState("rating"),f=async j=>{n(j),j&&(!r||r.length===0)&&await c.mutateAsync(s)},g=async()=>{if(!d.trim())return;const j=(r==null?void 0:r.reduce((b,S)=>Math.max(b,S.sort_order),0))??0;await i.mutateAsync({open_house_id:s,question_type:h,question_text:d.trim(),sort_order:j+1}),u("")},_=async j=>{await l.mutateAsync({id:j.id,open_house_id:s,is_active:!j.is_active})},v=async j=>{await o.mutateAsync({id:j.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(Dv,{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(bn,{checked:t,onCheckedChange:f})]}),t&&e.jsx("div",{className:"space-y-3 pt-2 border-t border-border",children:a?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ts,{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(j=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/20",children:[e.jsx(Fu,{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:j.question_text}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:j.question_type.replace("_"," ")})]}),e.jsx(bn,{checked:j.is_active,onCheckedChange:()=>_(j),className:"scale-75"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>v(j),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]},j.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:j=>u(j.target.value),placeholder:"e.g. How did you hear about this listing?",className:"mt-1 h-9 text-sm",onKeyDown:j=>j.key==="Enter"&&g()})]}),e.jsxs(ds,{value:h,onValueChange:p,children:[e.jsx(ls,{className:"w-28 h-9 text-xs",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"rating",children:"Rating"}),e.jsx(Qe,{value:"open_text",children:"Text"})]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:g,disabled:!d.trim()||i.isPending,className:"h-9",children:e.jsx(Is,{className:"h-3.5 w-3.5"})})]})]})})]})}function snn({openHouseId:s}){const{user:t}=ys(),{data:n=[],isLoading:r}=xBt(s),a=yBt(),[i,l]=N.useState(""),[o,c]=N.useState(!1),d=async()=>{const u=i.trim();if(u){c(!0);try{await a.mutateAsync({open_house_id:s,name:u,sort_order:n.length}),l("")}finally{c(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(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(ts,{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(nnn,{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(ts,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function nnn({room:s,index:t,total:n,userId:r,openHouseId:a}){const i=vBt(),l=bBt(),o=_Bt(),c=wBt(),d=N.useRef(null),[u,h]=N.useState(!0),[p,f]=N.useState(s.name),[g,_]=N.useState(s.description||""),[v,j]=N.useState(!1),b=N.useMemo(()=>s.media.filter(F=>F.kind==="video"&&F.agent_video_id).map(F=>F.agent_video_id),[s.media]),{data:S={}}=ct({queryKey:["room-video-statuses",s.id,b.join(",")],enabled:b.length>0,queryFn:async()=>{const{data:F,error:z}=await q.from("agent_videos").select("id, status, bunny_video_id, thumbnail_url, preview_url").in("id",b);if(z)throw z;const V=F||[],W=V.filter(K=>K.status==="processing"&&K.bunny_video_id);await Promise.all(W.map(async K=>{try{const{data:J}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:K.bunny_video_id,isAgentVideo:!0}});J&&J.status===4&&(await q.from("agent_videos").update({status:"ready",playback_url:J.directPlayUrl,thumbnail_url:J.thumbnailUrl,preview_url:J.previewUrl,duration_seconds:J.length||void 0,updated_at:new Date().toISOString()}).eq("id",K.id),K.status="ready",K.thumbnail_url=J.thumbnailUrl,K.preview_url=J.previewUrl)}catch{}}));const Y={};return V.forEach(K=>{Y[K.id]={status:K.status,thumbnail_url:K.thumbnail_url,preview_url:K.preview_url}}),Y},refetchInterval:F=>{const z=F.state.data;return z?Object.values(z).some(V=>V.status!=="ready"&&V.status!=="failed")?5e3:!1:5e3}}),A=()=>{p.trim()&&p!==s.name&&i.mutate({id:s.id,open_house_id:a,name:p.trim()})},T=()=>{g!==(s.description||"")&&i.mutate({id:s.id,open_house_id:a,description:g.trim()||null})},L=()=>{confirm(`Delete "${s.name}" and all its media?`)&&l.mutate({id:s.id,open_house_id:a})},D=F=>{i.mutate({id:s.id,open_house_id:a,sort_order:t+F})},M=async F=>{const z=Array.from(F.target.files||[]);if(!(!z.length||!r)){j(!0);try{for(const V of z){const W=V.type.startsWith("video/"),Y=W?500*1024*1024:15*1024*1024;if(V.size>Y){Pr({title:`${V.name} is too large`,description:W?"Videos must be under 500MB":"Photos must be under 15MB",variant:"destructive"});continue}if(W){try{const he=`${s.name} – ${V.name.replace(/\.[^/.]+$/,"")}`,{data:ce,error:pe}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:he,isAgentVideo:!0}});if(pe||!ce)throw new Error((pe==null?void 0:pe.message)||"Could not start upload");const{videoId:le,libraryId:ve}=ce,{data:ge,error:Te}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:le,isAgentVideo:!0}});if(Te||!ge)throw new Error((Te==null?void 0:Te.message)||"Could not get upload URL");await new Promise((Ie,Fe)=>{const qe=new XMLHttpRequest;qe.addEventListener("load",()=>{qe.status>=200&&qe.status<300?Ie():Fe(new Error(`Upload failed (${qe.status})`))}),qe.addEventListener("error",()=>Fe(new Error("Upload failed"))),qe.open("PUT",ge.uploadUrl),qe.setRequestHeader("AccessKey",ge.apiKey),qe.send(V)});const Me=`https://iframe.mediadelivery.net/embed/${ve}/${le}`,Ce=V.size/(1024*1024),{data:Ae,error:De}=await q.from("agent_videos").insert({owner_user_id:r,bunny_video_id:le,playback_url:Me,file_size_mb:Ce,title:he,status:"processing",touch_type:"open_house_tour",category:"open_house",page_template:"default"}).select().single();if(De)throw De;await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:Me,sort_order:s.media.length,agent_video_id:Ae.id}),Pr({title:"Video uploaded",description:"Processing in the background — it’ll appear in your Video Library too."})}catch(he){Pr({title:"Video upload failed",description:(he==null?void 0:he.message)||"Try again",variant:"destructive"})}continue}const K=V.name.split(".").pop()||"jpg",J=`${r}/${a}/rooms/${s.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.${K}`,{error:ne}=await q.storage.from("open-house-tour-media").upload(J,V,{upsert:!1,contentType:V.type});if(ne){Pr({title:"Upload failed",description:ne.message,variant:"destructive"});continue}const{data:ie}=q.storage.from("open-house-tour-media").getPublicUrl(J);await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:ie.publicUrl,sort_order:s.media.length})}}finally{j(!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(Fu,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>h(F=>!F),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:()=>D(-1),disabled:t===0,children:e.jsx(tx,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>D(1),disabled:t===n-1,children:e.jsx(io,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:L,children:e.jsx(_n,{className:"h-4 w-4"})})]}),u&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx(ye,{value:p,onChange:F=>f(F.target.value),onBlur:A,placeholder:"Room name",className:"h-9"}),e.jsx(Es,{value:g,onChange:F=>_(F.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(F=>{const z=F.agent_video_id?S[F.agent_video_id]:void 0,V=z==null?void 0:z.status,W=F.kind==="video"&&V&&V!=="ready"&&V!=="failed",Y=F.kind==="video"&&V==="failed",K=(z==null?void 0:z.thumbnail_url)||(z==null?void 0:z.preview_url);return e.jsxs("div",{className:"relative aspect-square rounded-md overflow-hidden bg-muted group",children:[F.kind==="video"?e.jsxs(e.Fragment,{children:[K?e.jsx("img",{src:K,alt:"",className:"w-full h-full object-cover"}):/iframe\.mediadelivery\.net\/embed\//.test(F.url)?e.jsx("div",{className:"w-full h-full bg-slate-800"}):e.jsx("video",{src:F.url,className:"w-full h-full object-cover"}),!W&&!Y&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(br,{className:"h-6 w-6 text-white"})}),W&&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(ts,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide",children:"Processing"})]}),Y&&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:F.url,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>c.mutate({id:F.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(Bn,{className:"h-3.5 w-3.5"})})]},F.id)})}),e.jsx("input",{ref:d,type:"file",accept:"image/*,video/*",multiple:!0,onChange:M,className:"hidden"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{var F;return(F=d.current)==null?void 0:F.click()},disabled:v,className:"flex-1",children:v?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Na,{className:"h-4 w-4 mr-2"})," Upload"]})}),e.jsx(a6,{userId:r,triggerLabel:"From Video Library",triggerClassName:"gap-1.5 flex-1 justify-center",onSelect:()=>{},onSelectVideo:async F=>{try{await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:F.playback_url||"",sort_order:s.media.length,agent_video_id:F.id}),Pr({title:"Video added to room"})}catch(z){Pr({title:"Failed to add video",description:z==null?void 0:z.message,variant:"destructive"})}}})]})]})]})}function rnn({open:s,onOpenChange:t,openHouse:n}){const r=wct(),{user:a}=ys(),i=N.useRef(null),l=N.useRef(null),o=N.useRef(null),c=n.kind==="virtual",[d,u]=N.useState(n.auto_forward_to_card??!1),[h,p]=N.useState(n.disclosure_pdf_url??""),[f,g]=N.useState(n.enable_survey??!1),[_,v]=N.useState(n.ask_visitor_intent??!0),[j,b]=N.useState(n.ask_visitor_address??!1),[S,A]=N.useState(n.photo_url??""),[T,L]=N.useState(!1),[D,M]=N.useState(!1),[F,z]=N.useState(!1),[V,W]=N.useState(n.hero_video_url??""),[Y,K]=N.useState(!1),[J,ne]=N.useState(n.price!=null?String(n.price):""),[ie,he]=N.useState(n.beds!=null?String(n.beds):""),[ce,pe]=N.useState(n.baths!=null?String(n.baths):""),[le,ve]=N.useState(n.sqft!=null?String(n.sqft):""),[ge,Te]=N.useState(n.enable_question??!0),[Me,Ce]=N.useState(n.enable_showing??!0),[Ae,De]=N.useState(n.enable_disclosures??!0),[Ie,Fe]=N.useState(n.enable_offer??!0),[qe,be]=N.useState(n.brand_color_override??""),[Ze,Ne]=N.useState(n.property_description??""),it=async rt=>{var vt;const tt=(vt=rt.target.files)==null?void 0:vt[0];if(!tt||!a)return;if(tt.size>200*1024*1024){Pr({title:"Video must be under 200MB",variant:"destructive"});return}if(!tt.type.startsWith("video/")){Pr({title:"Please upload a video file",variant:"destructive"});return}K(!0);const at=tt.name.split(".").pop()||"mp4",He=`${a.id}/${n.id}/hero-${Date.now()}.${at}`,{error:dt}=await q.storage.from("open-house-tour-media").upload(He,tt,{upsert:!0,contentType:tt.type});if(dt){Pr({title:"Upload failed",description:dt.message,variant:"destructive"}),K(!1);return}const{data:bt}=q.storage.from("open-house-tour-media").getPublicUrl(He);W(bt.publicUrl),K(!1),Pr({title:"Video uploaded!"})},je=async rt=>{var vt;const tt=(vt=rt.target.files)==null?void 0:vt[0];if(!tt||!a)return;if(tt.size>10*1024*1024){Pr({title:"Image must be under 10MB",variant:"destructive"});return}if(!tt.type.startsWith("image/")){Pr({title:"Please upload an image file",variant:"destructive"});return}M(!0);const at=tt.name.split(".").pop()||"jpg",He=`${a.id}/${n.id}-${Date.now()}.${at}`,{error:dt}=await q.storage.from("open-house-photos").upload(He,tt,{upsert:!0});if(dt){Pr({title:"Upload failed",description:dt.message,variant:"destructive"}),M(!1);return}const{data:bt}=q.storage.from("open-house-photos").getPublicUrl(He);A(bt.publicUrl),M(!1),Pr({title:"Photo updated!"})},Ge=()=>{A(""),l.current&&(l.current.value="")},Be=async rt=>{var bt;const tt=(bt=rt.target.files)==null?void 0:bt[0];if(!tt||!a)return;if(tt.size>20*1024*1024){Pr({title:"File must be under 20MB",variant:"destructive"});return}if(tt.type!=="application/pdf"){Pr({title:"Only PDF files are accepted",variant:"destructive"});return}L(!0);const at=`${a.id}/disclosures/${n.id}-${Date.now()}.pdf`,{error:He}=await q.storage.from("open-house-photos").upload(at,tt,{upsert:!0});if(He){Pr({title:"Upload failed",description:He.message,variant:"destructive"}),L(!1);return}const{data:dt}=q.storage.from("open-house-photos").getPublicUrl(at);p(dt.publicUrl),L(!1),Pr({title:"PDF uploaded!"})},Ye=()=>{p(""),i.current&&(i.current.value="")},We=async()=>{z(!0);try{const rt={id:n.id,auto_forward_to_card:d,disclosure_pdf_url:h||null,enable_survey:f,ask_visitor_intent:_,ask_visitor_address:j,photo_url:S||null};c&&(rt.hero_video_url=V||null,rt.price=J.trim()?Number(J):null,rt.beds=ie.trim()?parseInt(ie,10):null,rt.baths=ce.trim()?Number(ce):null,rt.sqft=le.trim()?parseInt(le,10):null,rt.enable_question=ge,rt.enable_showing=Me,rt.enable_disclosures=Ae,rt.enable_offer=Ie,rt.brand_color_override=qe.trim()||null,rt.property_description=Ze.trim()||null),await r.mutateAsync(rt),Pr({title:"Settings saved!"}),t(!1)}catch{Pr({title:"Failed to save",variant:"destructive"})}finally{z(!1)}};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:c?"Virtual Open House Settings":"Guest Book Settings"}),e.jsx(Qn,{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(br,{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:it,className:"hidden"}),V?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border bg-black",children:[e.jsx("video",{src:V,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:Y,children:Y?e.jsx(ts,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Na,{className:"h-3.5 w-3.5 mr-1"}),"Replace"]})}),e.jsx(B,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:()=>W(""),children:e.jsx(Bn,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var rt;return(rt=o.current)==null?void 0:rt.click()},disabled:Y,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:Y?e.jsx(ts,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(br,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(snn,{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:J,onChange:rt=>ne(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:le,onChange:rt=>ve(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:ie,onChange:rt=>he(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:ce,onChange:rt=>pe(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(Es,{value:Ze,onChange:rt=>Ne(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(bn,{checked:ge,onCheckedChange:Te})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Schedule a private showing"}),e.jsx(bn,{checked:Me,onCheckedChange:Ce})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(bn,{checked:Ae,onCheckedChange:De})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Make an offer / express interest"}),e.jsx(bn,{checked:Ie,onCheckedChange:Fe})]})]}),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:qe||"#0f172a",onChange:rt=>be(rt.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(ye,{value:qe,onChange:rt=>be(rt.target.value),placeholder:"#0f172a",className:"flex-1 font-mono text-sm"}),qe&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>be(""),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:()=>be(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:je,className:"hidden"}),S?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:S,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:D,children:[D?e.jsx(ts,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Na,{className:"h-3.5 w-3.5 mr-1"}),D?"":"Replace"]}),e.jsx(B,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:Ge,children:e.jsx(Bn,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var rt;return(rt=l.current)==null?void 0:rt.click()},disabled:D,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:D?e.jsx(ts,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(nl,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload property photo (max 10MB)"})]})})]}),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(bn,{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:Be,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(Nr,{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(Bn,{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(ts,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Na,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload 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(bn,{checked:_,onCheckedChange:v})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(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(bn,{checked:j,onCheckedChange:b})]})}),e.jsx(tnn,{openHouseId:n.id,enableSurvey:f,onToggleSurvey:g}),e.jsx(B,{onClick:We,disabled:F,className:"w-full",children:F?"Saving...":"Save Settings"})]})]})})}const TNt={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function ann({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:TNt[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 inn({openHouseId:s}){const{data:t,isLoading:n}=lBt(s),{data:r}=_ct(s),a=N.useMemo(()=>{const h={};return r==null||r.forEach(p=>{h[p.id]=p}),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(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Dv,{className:"h-4 w-4"}),"Survey Results"]})}),e.jsx(Ee,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No survey responses yet."})})]}):e.jsxs(fe,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Dv,{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(Ee,{children:e.jsxs(Br,{defaultValue:"summary",children:[e.jsxs(Fr,{className:"mb-4",children:[e.jsxs(Kt,{value:"summary",className:"text-xs gap-1",children:[e.jsx(yo,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(Kt,{value:"individual",className:"text-xs gap-1",children:[e.jsx(Xi,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(is,{value:"summary",className:"space-y-6",children:[o.map(h=>e.jsx(ann,{question:h,responses:l},h.id)),c.map(h=>{const p=l.filter(f=>f.question_id===h.id&&f.text_value);return p.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:p.map(f=>{const g=a[f.visitor_id];return e.jsxs("div",{className:"text-sm p-2 bg-muted/30 rounded-lg",children:[e.jsxs("span",{className:"text-muted-foreground text-xs",children:[g?`${g.first_name} ${g.last_name||""}`.trim():"Visitor",":"]}),e.jsx("p",{className:"mt-0.5",children:f.text_value})]},f.id)})})]},h.id)})]}),e.jsx(is,{value:"individual",className:"space-y-4",children:d.map(h=>{const p=a[h],f=l.filter(g=>g.visitor_id===h);return e.jsxs("div",{className:"p-3 rounded-lg border border-border space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:[p?`${p.first_name} ${p.last_name||""}`.trim():"Unknown Visitor",(p==null?void 0:p.email)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:p.email})]}),e.jsx("div",{className:"space-y-1",children:f.map(g=>{const _=i.find(v=>v.id===g.question_id);return _?e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:_.question_text}),e.jsx("span",{className:"font-medium",children:g.rating_value!=null?TNt[g.rating_value]||g.rating_value:g.text_value})]},g.id):null})})]},h)})})]})})]})}const onn={question:{label:"Question",icon:Ei,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:yr,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:Nr,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:Zl,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},qXe={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 lnn({openHouseId:s}){const{data:t=[],isLoading:n}=jBt(s),r=NBt(),[a,i]=N.useState(null),[l,o]=N.useState("all"),c=t.filter(h=>l==="all"?!0:l==="new"?h.status==="new":h.action_type===l),d={all:t.length,new:t.filter(h=>h.status==="new").length,question:t.filter(h=>h.action_type==="question").length,showing:t.filter(h=>h.action_type==="showing").length,disclosure:t.filter(h=>h.action_type==="disclosure").length,offer:t.filter(h=>h.action_type==="offer").length},u=(h,p)=>{r.mutate({id:h,status:p,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(Y2,{className:"h-4 w-4"}),"Virtual Open House Leads",e.jsx(ze,{variant:"secondary",className:"ml-1",children:d.all}),d.new>0&&e.jsxs(ze,{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,p,f])=>e.jsxs("button",{onClick:()=>o(h),className:`text-xs px-2.5 py-1 rounded-full transition-colors ${l===h?"bg-foreground text-background":"bg-background hover:bg-muted text-muted-foreground"}`,children:[p," ",e.jsx("span",{className:"opacity-60",children:f})]},h))})]}),c.length===0?e.jsx("div",{className:"px-4 py-10 text-center text-sm text-muted-foreground",children:t.length===0?"No leads yet. Share your virtual open house link to start capturing leads.":"No leads match this filter."}):e.jsx("ul",{className:"divide-y",children:c.map(h=>{const p=onn[h.action_type],f=p.icon,g=h.payload||{},_=a===h.id,v=h.status==="contacted",j=h.status==="archived";return e.jsxs("li",{className:`transition-colors ${j?"opacity-60":""} ${h.status==="new"?"bg-emerald-50/40 dark:bg-emerald-950/10":""}`,children:[e.jsxs("button",{onClick:()=>i(_?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 ${p.bg}`,children:e.jsx(f,{className:`h-4 w-4 ${p.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm truncate",children:g.visitor_name||"Visitor"}),e.jsx(ze,{variant:"outline",className:`text-[10px] ${p.color}`,children:p.label}),h.status==="new"&&e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase tracking-wide",children:"New"}),v&&e.jsxs("span",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(xr,{className:"h-3 w-3"}),"Contacted"]})]}),g.message&&e.jsxs("p",{className:"text-sm text-muted-foreground line-clamp-1 mt-0.5 italic",children:['"',g.message,'"']}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),Ss(new Date(h.created_at),"MMM d, h:mm a")]}),g.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(Vs,{className:"h-3 w-3"}),g.email]}),g.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ar,{className:"h-3 w-3"}),g.phone]})]})]}),_?e.jsx(io,{className:"h-4 w-4 mt-1 text-muted-foreground"}):e.jsx(xa,{className:"h-4 w-4 mt-1 text-muted-foreground"})]}),_&&e.jsxs("div",{className:"px-4 pb-4 pl-16 space-y-3",children:[g.message&&e.jsxs("div",{className:"bg-muted/40 rounded-md p-3 text-sm border-l-2 border-foreground/30",children:['"',g.message,'"']}),Object.keys(qXe).some(b=>g[b]!=null&&g[b]!==""&&!(Array.isArray(g[b])&&g[b].length===0))&&e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm",children:Object.entries(qXe).map(([b,S])=>{const A=g[b];return A==null||A===""||Array.isArray(A)&&A.length===0?null:e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:S}),e.jsx("div",{className:"font-medium",children:Array.isArray(A)?A.join(", "):String(A)})]},b)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[g.email&&e.jsx("a",{href:`mailto:${g.email}?subject=${encodeURIComponent("Re: your open house inquiry")}`,children:e.jsxs(B,{size:"sm",variant:"default",className:"gap-1.5",children:[e.jsx(Vs,{className:"h-3.5 w-3.5"}),"Reply"]})}),g.phone&&e.jsx("a",{href:`tel:${String(g.phone).replace(/[^0-9+]/g,"")}`,children:e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(Ar,{className:"h-3.5 w-3.5"}),"Call"]})}),!v&&e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>u(h.id,"contacted"),children:[e.jsx(xr,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),j?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(rm,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},h.id)})})]})}function cnn({open:s,onOpenChange:t,openHouse:n}){const{isGmailConnected:r,gmailEmail:a}=Oh(),i=ma(),[l,o]=N.useState([]),[c,d]=N.useState([]),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[g,_]=N.useState(""),[v,j]=N.useState(""),[b,S]=N.useState(""),[A,T]=N.useState(!1),[L,D]=N.useState(!1),[M,F]=N.useState(!1),z=`https://guestbook.relevelup.com/${n.slug}`;N.useEffect(()=>{s&&(j(`Take a virtual tour of ${n.property_address}`),S(`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([]),_(""),T(r),l.length===0&&V())},[s,n.id,r]);const V=async()=>{if(i){f(!0);try{const{data:ce,error:pe}=await q.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(pe)throw pe;o(ce||[])}catch{ae.error("Failed to load contacts")}finally{f(!1)}}},W=ce=>`${ce.first_name} ${ce.last_name||""}`.trim(),Y=ce=>{d(pe=>pe.find(le=>le.id===ce.id)?pe.filter(le=>le.id!==ce.id):[...pe,ce])},K=()=>{const ce=g.trim();if(!ce)return;if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ce)){ae.error("Invalid email");return}d(le=>[...le,{id:`manual-${ce}`,first_name:ce.split("@")[0],last_name:null,email:ce}]),_("")},J=N.useMemo(()=>c.filter(ce=>!!ce.email).map(ce=>({email:ce.email,name:W(ce)})),[c]),ne=ce=>{const pe=ce?`Hi ${ce},`:"Hi there,",le=b.split(/\n\n+/).map(ve=>`

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

`).join("");return`

${pe}

${le}

▶ Start Virtual Tour

Or copy this link: ${z}

`},ie=async()=>{var ce;if(J.length===0){ae.error("Add at least one recipient");return}D(!0);try{if(A&&r){let pe=0;for(const le of J){const{data:ve,error:ge}=await q.functions.invoke("gmail-send",{body:{to:le.email,subject:v,body:ne((ce=le.name)==null?void 0:ce.split(" ")[0])}});!ge&&(ve!=null&&ve.success)?pe+=1:console.warn("gmail-send error",ge,ve)}if(pe===0)throw new Error("Gmail send failed");ae.success(`Sent to ${pe} of ${J.length} via Gmail`)}else{const{data:pe,error:le}=await q.functions.invoke("send-virtual-tour-invite",{body:{openHouseId:n.id,recipients:J,subject:v,personalMessage:b}});if(le)throw le;if(!(pe!=null&&pe.success))throw new Error((pe==null?void 0:pe.error)||"Send failed");ae.success(`Sent to ${pe.sent} of ${pe.total} recipient${pe.total===1?"":"s"}`)}t(!1)}catch(pe){ae.error((pe==null?void 0:pe.message)||"Failed to send")}finally{D(!1)}},he=async()=>{await navigator.clipboard.writeText(z),F(!0),setTimeout(()=>F(!1),1500)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-[560px] w-[calc(100vw-2rem)] max-h-[90vh] overflow-y-auto overflow-x-hidden",children:[e.jsxs(ws,{className:"min-w-0",children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5 text-primary"}),"Share Virtual Tour"]}),e.jsx(Qn,{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(Jo,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("code",{className:"flex-1 min-w-0 text-xs truncate",children:z}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:he,className:"shrink-0 h-7 gap-1",children:[M?e.jsx(Ir,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(Xr,{className:"h-3.5 w-3.5"}),M?"Copied":"Copy"]})]}),r&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{type:"button",variant:A?"default":"outline",size:"sm",onClick:()=>T(!0),className:"gap-1.5",children:[e.jsx(Vs,{className:"h-3.5 w-3.5"}),"Send from Gmail"]}),e.jsx(B,{type:"button",variant:A?"outline":"default",size:"sm",onClick:()=>T(!1),className:"gap-1.5",children:"Send from LevelUp"})]}),A&&a&&e.jsxs("p",{className:"text-xs text-muted-foreground -mt-2",children:["Sending as ",e.jsx("span",{className:"font-medium",children:a})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{className:"flex items-center gap-1.5",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"}),"Recipients"]}),e.jsxs(el,{open:u,onOpenChange:h,modal:!0,children:[e.jsx(tl,{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(qg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ho,{className:"w-[440px] max-w-[calc(100vw-2rem)] p-0",align:"start",children:e.jsxs(Qg,{children:[e.jsx(Xg,{placeholder:"Search contacts..."}),e.jsxs(Jg,{className:"max-h-[300px] overflow-y-auto",children:[e.jsx(e0,{children:p?"Loading...":"No contacts found."}),e.jsx(t0,{children:l.map(ce=>{const pe=!!c.find(ge=>ge.id===ce.id),le=W(ce).slice(0,80),ve=(ce.email||"").slice(0,80);return e.jsxs(Jf,{value:`${le} ${ve}`,onSelect:()=>Y(ce),className:"py-2",children:[e.jsx(Ir,{className:Et("mr-2 h-4 w-4 shrink-0",pe?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:le||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:ve})]})]},ce.id)})})]})]})})]}),c.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:c.map(ce=>e.jsxs(ze,{variant:"secondary",className:"gap-1 pl-2 pr-1 py-0.5",children:[e.jsx("span",{className:"text-xs",children:W(ce)}),e.jsx("button",{onClick:()=>Y(ce),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx(Bn,{className:"h-3 w-3"})})]},ce.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(ye,{value:g,onChange:ce=>_(ce.target.value),placeholder:"Or type an email...",type:"email",onKeyDown:ce=>{ce.key==="Enter"&&(ce.preventDefault(),K())}}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:K,children:"Add"})]})]}),e.jsx(ll,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"vt-subject",children:"Subject"}),e.jsx(ye,{id:"vt-subject",value:v,onChange:ce=>j(ce.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"vt-message",children:"Personal Message"}),e.jsx(Es,{id:"vt-message",value:b,onChange:ce=>S(ce.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:L,children:"Cancel"}),e.jsxs(B,{onClick:ie,disabled:L||J.length===0||!v.trim(),className:"gap-2",children:[L?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(cr,{className:"h-4 w-4"}),L?"Sending...":`Send${J.length?` to ${J.length}`:""}`]})]})]})]})})}const ATe="guestbook.relevelup.com";function dnn(){const{data:s,isLoading:t}=tBt(),n=sBt(),r=wct(),a=nBt(),[i,l]=N.useState(!1),[o,c]=N.useState(null),{user:d}=ys(),u=ma(),[h,p]=N.useState(null),[f,g]=N.useState(null),[_,v]=N.useState(!1),j=N.useRef(null),[b,S]=N.useState({property_address:"",city:"",state:"",zip:"",event_date:Ss(new Date,"yyyy-MM-dd"),start_time:"10:00",end_time:"14:00",agent_greeting:"Welcome! Please sign in below.",event_type:"property",kind:"physical",tour_mode:"rooms"}),A=M=>{var z;const F=(z=M.target.files)==null?void 0:z[0];if(F){if(F.size>5*1024*1024){Pr({title:"Photo must be under 5MB",variant:"destructive"});return}p(F),g(URL.createObjectURL(F))}},T=()=>{p(null),g(null),j.current&&(j.current.value="")},L=async()=>{if(!b.property_address){Pr({title:b.event_type==="community"?"Event name is required":"Address is required",variant:"destructive"});return}let M;if(h&&d){v(!0);const z=h.name.split(".").pop(),V=`${u}/${Date.now()}.${z}`,{error:W}=await q.storage.from("open-house-photos").upload(V,h,{upsert:!0});if(W){Pr({title:"Photo upload failed",description:W.message,variant:"destructive"}),v(!1);return}const{data:Y}=q.storage.from("open-house-photos").getPublicUrl(V);M=Y.publicUrl,v(!1)}const F=b.kind==="virtual"?{...b,start_time:void 0,end_time:void 0,photo_url:M}:{...b,photo_url:M};await n.mutateAsync(F),l(!1),S({property_address:"",city:"",state:"",zip:"",event_date:Ss(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()},D=M=>{navigator.clipboard.writeText(`https://${ATe}/${M}`),Pr({title:"Link copied!"})};return e.jsxs(Ts,{title:"Guest Book",children:[e.jsx(Go,{children:e.jsx("title",{children:"Guest Book | LevelUp"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold font-serif text-foreground",children:"Guest Book"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"The modern open house sign-in experience"})]}),e.jsxs(bs,{open:i,onOpenChange:l,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"New Open House"]})}),e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Create Open House"}),e.jsx(Qn,{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:()=>S(M=>({...M,kind:"physical"})),className:`p-3 rounded-lg border text-left transition-all ${b.kind==="physical"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:"text-sm font-semibold",children:"Physical Open House"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"In-person sign-in at the property"})]}),e.jsxs("button",{type:"button",onClick:()=>S(M=>({...M,kind:"virtual",event_type:"property"})),className:`p-3 rounded-lg border text-left transition-all ${b.kind==="virtual"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsxs("div",{className:"text-sm font-semibold flex items-center gap-1.5",children:["Virtual Open House ",e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-primary/10 text-primary uppercase tracking-wide",children:"New"})]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"Always-on branded tour via link or QR"})]})]})]}),b.kind==="physical"&&e.jsx("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border bg-muted/30",children:e.jsxs("div",{className:"flex gap-1 flex-1",children:[e.jsx("button",{type:"button",onClick:()=>S(M=>({...M,event_type:"property"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${b.event_type==="property"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Single Property"}),e.jsx("button",{type:"button",onClick:()=>S(M=>({...M,event_type:"community"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${b.event_type==="community"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Community Event"})]})}),b.kind==="virtual"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(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:()=>S(M=>({...M,tour_mode:"rooms"})),className:`p-3 rounded-lg border text-left transition-all ${b.tour_mode==="rooms"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:"text-sm font-semibold",children:"Room-by-room"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"Photos & videos per room"})]}),e.jsxs("button",{type:"button",onClick:()=>S(M=>({...M,tour_mode:"single_video"})),className:`p-3 rounded-lg border text-left transition-all ${b.tour_mode==="single_video"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:"text-sm font-semibold",children:"Single video"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"One walkthrough video"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"You can add the video or room media in settings after creating."})]}),e.jsxs("div",{children:[e.jsx(se,{children:b.event_type==="community"?"Event Name *":"Property Address *"}),e.jsx(ye,{value:b.property_address,onChange:M=>S(F=>({...F,property_address:M.target.value})),placeholder:b.event_type==="community"?"Spring Festival at Riverside Estates":"123 Main Street"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"City"}),e.jsx(ye,{value:b.city,onChange:M=>S(F=>({...F,city:M.target.value})),placeholder:"Austin"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"State"}),e.jsx(ye,{value:b.state,onChange:M=>S(F=>({...F,state:M.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"ZIP"}),e.jsx(ye,{value:b.zip,onChange:M=>S(F=>({...F,zip:M.target.value})),placeholder:"78701"})]})]}),b.kind==="virtual"?e.jsxs("div",{className:"rounded-lg border border-dashed border-muted-foreground/30 bg-muted/20 p-3 text-xs text-muted-foreground",children:["🕒 Virtual open houses are ",e.jsx("span",{className:"font-medium text-foreground",children:"always on"})," — no date or time needed. Visitors can tour any time via your link or QR code."]}):e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Date"}),e.jsx(ye,{type:"date",value:b.event_date,onChange:M=>S(F=>({...F,event_date:M.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Start Time"}),e.jsx(ye,{type:"time",value:b.start_time,onChange:M=>S(F=>({...F,start_time:M.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"End Time"}),e.jsx(ye,{type:"time",value:b.end_time,onChange:M=>S(F=>({...F,end_time:M.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Welcome Message"}),e.jsx(Es,{value:b.agent_greeting,onChange:M=>S(F=>({...F,agent_greeting:M.target.value})),placeholder:"Welcome! Please sign in below."})]}),e.jsxs("div",{children:[e.jsx(se,{children:b.event_type==="community"?"Event Photo":"Property Photo"}),e.jsx("input",{ref:j,type:"file",accept:"image/*",onChange:A,className:"hidden"}),f?e.jsxs("div",{className:"relative mt-1 rounded-xl overflow-hidden border border-border",children:[e.jsx("img",{src:f,alt:"Property preview",className:"w-full h-40 object-cover"}),e.jsx("button",{type:"button",onClick:T,className:"absolute top-2 right-2 bg-black/60 hover:bg-black/80 text-white rounded-full p-1 transition-colors",children:e.jsx(Bn,{className:"h-4 w-4"})})]}):e.jsxs("button",{type:"button",onClick:()=>{var M;return(M=j.current)==null?void 0:M.click()},className:"mt-1 w-full h-32 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(ry,{className:"h-6 w-6"}),e.jsxs("span",{className:"text-sm",children:["Add a ",b.event_type==="community"?"cover":"property"," photo"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Max 5MB"})]})]}),e.jsx(B,{onClick:L,disabled:n.isPending||_,className:"w-full",children:_?"Uploading photo...":n.isPending?"Creating...":b.kind==="virtual"?"Create Virtual Open House":b.event_type==="community"?"Create Community Event":"Create Open House"})]})]})]})]}),t?e.jsx("div",{className:"grid gap-4",children:[1,2].map(M=>e.jsx(fe,{className:"animate-pulse",children:e.jsxs(Mt,{children:[e.jsx("div",{className:"h-5 bg-muted rounded w-48"}),e.jsx("div",{className:"h-4 bg-muted rounded w-32 mt-2"})]})},M))}):s!=null&&s.length?e.jsx("div",{className:"space-y-4",children:s.map(M=>e.jsx(unn,{openHouse:M,isExpanded:o===M.id,onToggle:()=>c(o===M.id?null:M.id),onCopyLink:()=>D(M.slug||""),onToggleActive:()=>r.mutate({id:M.id,is_active:!M.is_active}),onDelete:()=>a.mutate(M.id)},M.id))}):e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{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(oy,{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(Is,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function unn({openHouse:s,isExpanded:t,onToggle:n,onCopyLink:r,onToggleActive:a,onDelete:i}){const{data:l}=_ct(t?s.id:void 0),{data:o}=ct({queryKey:["agent-profile-flyer",s.agent_id],queryFn:async()=>{const{data:D,error:M}=await q.from("profiles").select("name, avatar_url, phone, title, brokerages:brokerage_id(name)").eq("id",s.agent_id).single();if(M)throw M;const F=D.brokerages;return{...D,brokerage_name:(F==null?void 0:F.name)||null}},enabled:!!s.agent_id}),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[g,_]=N.useState(!1),v=N.useRef(null),j=`https://${ATe}/${s.slug}`,b=D=>{if(!D)return"";const[M,F]=D.split(":"),z=parseInt(M),V=z>=12?"PM":"AM";return`${z>12?z-12:z||12}:${F} ${V}`},S=()=>{if(!(l!=null&&l.length))return;const D=["First Name","Last Name","Email","Phone","Address","Intent","Wants Market Updates","Message","Signed In"],M=l.map(Y=>[Y.first_name,Y.last_name||"",Y.email||"",Y.phone||"",Y.visitor_address||"",Y.visitor_intent||"",Y.wants_market_updates?"Yes":"No",(Y.message||"").replace(/"/g,'""'),Ss(new Date(Y.created_at),"MM/dd/yyyy h:mm a")]),F=[D,...M].map(Y=>Y.map(K=>`"${K}"`).join(",")).join(` `),z=new Blob([F],{type:"text/csv"}),V=URL.createObjectURL(z),W=document.createElement("a");W.href=V,W.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-visitors.csv`,W.click(),URL.revokeObjectURL(V)},A=N.useCallback(()=>{if(!v.current)return;const D=v.current.querySelector("svg");if(!D)return;const M=new XMLSerializer().serializeToString(D),F=document.createElement("canvas");F.width=1024,F.height=1024;const z=F.getContext("2d"),V=new Image;V.onload=()=>{z==null||z.drawImage(V,0,0,1024,1024);const W=document.createElement("a");W.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-qr.png`,W.href=F.toDataURL("image/png"),W.click()},V.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(M)))},[s.property_address]),T=N.useCallback(()=>{var Ne;if(!v.current)return;const D=v.current.querySelector("svg");if(!D)return;const M=new XMLSerializer().serializeToString(D),F="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(M))),z=Ss(new Date(s.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy"),V=s.start_time?`${b(s.start_time)}${s.end_time?" – "+b(s.end_time):""}`:"",W=[s.city,s.state].filter(Boolean).join(", "),Y=s.agent_greeting||"Welcome! Please sign in below.",K=!!s.photo_url,J=!!o,ne=K||J,ie=K&&J,he=ie?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",ce=ie?"28px":"34px",pe=ie?"0.2in 0.75in":ne?"0.3in 0.75in":"0.4in 0.75in",le=ne?"0.15in":"0.3in",ve=ne?"0.15in":"0.3in",ge=ie?"14px 36px":"22px 44px",Te=ie?"20px":"24px",Me=ne?"0.2in":"0.35in",Ce=ie?"1.8in":"2.4in",Ae=ne?"0.15in":"0.3in",De=ie?"140px":ne?"160px":"200px",Ie=ie?"16px":"24px",Fe=ie?"10px 20px":"16px 28px",qe=ie?"44px":"56px",be="0.15in",Ze=window.open("","_blank");Ze&&(Ze.document.write(` Open House – ${s.property_address}
${s.event_type==="community"?"Community Event":"Open House"}
${s.property_address}
${W?`
${W}${s.zip?" "+s.zip:""}
`:""}
Date
${z}
${V?`
Time
${V}
`:""}
${Y}
${o?`
${o.avatar_url?`${o.name}`:`
${((Ne=o.name)==null?void 0:Ne.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
`),Ze.document.close(),setTimeout(()=>{Ze.focus(),Ze.print()},500))},[s,j,o]),L=async()=>{_(!0);try{const{error:D}=await q.functions.invoke("guestbook-email-link",{body:{openHouseId:s.id}});if(D)throw D;Pr({title:"Email sent!",description:"Check your inbox for the guest book link."})}catch(D){Pr({title:"Failed to send",description:D.message,variant:"destructive"})}finally{_(!1)}};return e.jsxs(fe,{className:`transition-all ${s.is_active?"border-primary/30":"opacity-75"}`,children:[e.jsx(Mt,{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(It,{className:"text-base leading-snug break-words",children:s.property_address}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1.5 flex-wrap",children:[e.jsx(ze,{variant:s.is_active?"default":"secondary",className:"shrink-0 text-[11px]",children:s.is_active?"Active":"Inactive"}),s.kind==="virtual"?e.jsxs(ze,{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(Er,{className:"h-3 w-3"}),"Virtual"]}):e.jsxs(ze,{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(ka,{className:"h-3 w-3"}),"In-Person"]}),s.agent_name&&e.jsxs(ze,{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(Xi,{className:"h-3 w-3"}),s.agent_name]}),s.event_type==="community"&&e.jsxs(ze,{variant:"outline",className:"shrink-0 gap-1 text-[11px]",children:[e.jsx(Va,{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(tx,{className:"h-4 w-4"}):e.jsx(io,{className:"h-4 w-4"})})]}),e.jsxs(Vn,{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(ka,{className:"h-3 w-3"}),s.city,s.state?`, ${s.state}`:""]}),s.kind==="virtual"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(yr,{className:"h-3 w-3"}),Ss(new Date(s.event_date+"T00:00:00"),"MMM d, yyyy")]}),s.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),b(s.start_time),s.end_time?` – ${b(s.end_time)}`:""]})]}),e.jsxs("span",{className:"flex items-center gap-1 font-medium",children:[e.jsx(Nn,{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(oy,{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(_f,{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(Xr,{className:"h-3.5 w-3.5"}),"Copy"]}),s.kind==="virtual"&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>f(!0),title:"Share tour via email",className:"h-9 w-full justify-center gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10 sm:h-8 sm:w-auto",children:[e.jsx(Hl,{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(Er,{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(oy,{className:"h-3.5 w-3.5"}),"QR"]}),s.kind!=="virtual"&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(`${j}?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(bL,{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(Xo,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>window.open(j,"_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(xf,{className:"h-3.5 w-3.5"}):e.jsx(Er,{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(_n,{className:"h-3.5 w-3.5"})})]})]})}),t&&e.jsxs(Ee,{className:"pt-0",children:[e.jsx(ll,{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://",ATe,"/",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:S,className:"h-7 text-xs gap-1",children:[e.jsx(Pa,{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(D=>e.jsxs("tr",{className:"border-t border-border/50",children:[e.jsxs("td",{className:"p-2 font-medium",children:[D.first_name,D.last_name?` ${D.last_name}`:""]}),e.jsxs("td",{className:"p-2 text-muted-foreground hidden sm:table-cell",children:[D.email&&e.jsx("div",{className:"truncate max-w-[180px]",children:D.email}),D.phone&&e.jsx("div",{className:"text-xs",children:D.phone}),D.visitor_address&&e.jsx("div",{className:"text-xs truncate max-w-[180px]",children:D.visitor_address})]}),e.jsx("td",{className:"p-2 hidden md:table-cell",children:D.visitor_intent?e.jsx(ze,{variant:"outline",className:"text-xs capitalize",children:D.visitor_intent}):D.partial_signin?e.jsx(ze,{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:Ss(new Date(D.created_at),"h:mm a")})]},D.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(lnn,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(inn,{openHouseId:s.id})})]}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"sm:max-w-sm",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"QR Code"}),e.jsx(Qn,{className:"truncate",children:s.property_address})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx("div",{ref:v,className:"bg-white p-4 rounded-xl",children:e.jsx(YU,{value:j,size:240,level:"H"})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:j}),e.jsxs("div",{className:"flex gap-2 w-full",children:[e.jsxs(B,{variant:"outline",className:"flex-1",onClick:A,children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:T,children:[e.jsx(_9,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs(B,{variant:"default",className:"w-full",onClick:L,disabled:g,children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),g?"Sending...":"Email Link to Me"]})]})]})}),e.jsx(rnn,{open:u,onOpenChange:h,openHouse:s}),s.kind==="virtual"&&e.jsx(cnn,{open:p,onOpenChange:f,openHouse:{id:s.id,slug:s.slug,property_address:s.property_address,city:s.city,state:s.state}})]})}function hnn(){const{slug:s}=bi();return s?e.jsx(Bht,{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 ENt({photoUrl:s,videoUrl:t,onPhotoChange:n,onVideoChange:r,contactId:a}){const{user:i}=ys(),l=IN(),o=N.useRef(null),c=N.useRef(null),[d,u]=N.useState(!1),[h,p]=N.useState(!1),[f,g]=N.useState(0),_=async j=>{if(i){u(!0);try{const b=j.name.split(".").pop()||"jpg",S=`${i.id}/card-${Date.now()}.${b}`,{error:A}=await q.storage.from("listing-photos").upload(S,j);if(A)throw A;const{data:{publicUrl:T}}=q.storage.from("listing-photos").getPublicUrl(S);n(T),ae.success("Photo uploaded")}catch(b){ae.error(b.message||"Failed to upload photo")}finally{u(!1)}}},v=async j=>{if(i){if(j.size>500*1024*1024){ae.error("Video must be under 500MB");return}p(!0),g(0);try{const{videoId:b,libraryId:S}=await i6(`Card Video - ${Date.now()}`),{uploadUrl:A,apiKey:T}=await o6(b);await new Promise((M,F)=>{const z=new XMLHttpRequest;z.upload.addEventListener("progress",V=>{V.lengthComputable&&g(Math.round(V.loaded/V.total*100))}),z.addEventListener("load",()=>{z.status>=200&&z.status<300?M():F(new Error("Upload failed"))}),z.addEventListener("error",()=>F(new Error("Upload failed"))),z.open("PUT",A),z.setRequestHeader("AccessKey",T),z.send(j)});const L=`https://iframe.mediadelivery.net/embed/${S}/${b}`;r(L);const D=parseFloat((j.size/(1024*1024)).toFixed(2));await l.mutateAsync({bunny_video_id:b,playback_url:`https://iframe.mediadelivery.net/play/${S}/${b}`,file_size_mb:D,title:"Card Video",status:"processing",touch_type:"video",contact_id:a||void 0}),ae.success("Video uploaded & added to your library")}catch(b){ae.error(b.message||"Failed to upload video")}finally{p(!1),g(0)}}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Media (optional)"}),e.jsxs(Br,{defaultValue:"photo",className:"w-full",children:[e.jsxs(Fr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Kt,{value:"photo",className:"gap-1.5 text-xs",children:[e.jsx(nl,{className:"h-3.5 w-3.5"}),"Photo"]}),e.jsxs(Kt,{value:"video",className:"gap-1.5 text-xs",children:[e.jsx(br,{className:"h-3.5 w-3.5"}),"Video"]})]}),e.jsxs(is,{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(Bn,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var j;return(j=o.current)==null?void 0:j.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(ts,{className:"h-6 w-6 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(mf,{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:j=>{var S;const b=(S=j.target.files)==null?void 0:S[0];b&&_(b),j.target.value=""}})]}),e.jsxs(is,{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(Bn,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var j;return(j=c.current)==null?void 0:j.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(ts,{className:"h-6 w-6 animate-spin"}),e.jsxs("span",{className:"text-xs",children:["Uploading... ",f,"%"]}),e.jsx("div",{className:"w-32 h-1.5 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary rounded-full transition-all",style:{width:`${f}%`}})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Na,{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(b8e,{contactId:a,onVideoReady:j=>r(j)})}),e.jsx("input",{ref:c,type:"file",accept:"video/*",className:"hidden",onChange:j=>{var S;const b=(S=j.target.files)==null?void 0:S[0];b&&v(b),j.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 mnn=[{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 pnn({onSelect:s}){return e.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:mnn.map((t,n)=>e.jsxs(Yn.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 RR={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 VXe({initialOpen:s,initialCardType:t,initialContactId:n,initialRecipientName:r,initialAddress:a,initialDate:i,onOpenChange:l}){const{user:o}=ys(),c=Ht(),[d,u]=N.useState(!1),[h,p]=N.useState("type"),[f,g]=N.useState(""),[_,v]=N.useState(null),[j,b]=N.useState(!1),[S,A]=N.useState("home_anniversary"),[T,L]=N.useState(""),[D,M]=N.useState(""),[F,z]=N.useState(""),[V,W]=N.useState(""),[Y,K]=N.useState("elegant"),[J,ne]=N.useState(null),[ie,he]=N.useState(null),ce=N.useState(!1);!ce[0]&&s&&t&&(ce[1](!0),u(!0),A(t),n&&v(n),r&&L(r),a&&M(a),i&&z(i),p(r?"details":"contact"));const{data:pe}=ct({queryKey:["contacts-for-card",o==null?void 0:o.id,f],queryFn:async()=>{let qe=q.from("innercircle_contacts").select("id, first_name, last_name, address, city, state, home_anniversary, wedding_anniversary, email, phone").eq("owner_user_id",o.id).order("first_name").limit(20);f&&(qe=qe.or(`first_name.ilike.%${f}%,last_name.ilike.%${f}%`));const{data:be,error:Ze}=await qe;if(Ze)throw Ze;return be},enabled:!!(o!=null&&o.id)&&d}),{data:le}=ct({queryKey:["agent-profile-card",o==null?void 0:o.id],queryFn:async()=>{const{data:qe,error:be}=await q.from("profiles").select("name, email, phone, avatar_url, brokerage:brokerages(name)").eq("id",o.id).single();if(be)throw be;return qe},enabled:!!(o!=null&&o.id)}),ve=qe=>{v(qe.id),L(`${qe.first_name}${qe.last_name?" "+qe.last_name:""}`),M([qe.address,qe.city,qe.state].filter(Boolean).join(", "));const be=S==="wedding_anniversary"?qe.wedding_anniversary:S==="home_anniversary"?qe.home_anniversary:"";z(be||""),p("details")},ge=qe=>{A(qe),p("contact")},Te=async()=>{var qe;if(!(!o||!le)){b(!0);try{const be={owner_user_id:o.id,contact_id:_,card_type:S,template:Y,recipient_name:T,property_address:D||null,home_anniversary_date:F||null,custom_message:V||null,property_photo_url:J||null,video_url:ie||null,agent_name:le.name||"Agent",agent_photo_url:le.avatar_url,agent_phone:le.phone,agent_email:le.email,agent_brokerage:((qe=le.brokerage)==null?void 0:qe.name)||null},{error:Ze}=await q.from("sendable_cards").insert(be);if(Ze)throw Ze;ae.success("Card created! Copy the link to share it."),c.invalidateQueries({queryKey:["sendable-cards"]}),Me()}catch(be){ae.error(be.message||"Failed to create card")}finally{b(!1)}}},Me=()=>{u(!1),p("type"),A("home_anniversary"),g(""),v(null),L(""),M(""),z(""),W(""),K("elegant"),ne(null),he(null)},Ce={home_anniversary:"Home Anniversary",wedding_anniversary:"Wedding Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"},Ae=RR[S],De=S==="home_anniversary"||S==="wedding_anniversary",Ie=S==="wedding_anniversary"?"Wedding Anniversary Date":"Home Anniversary Date",Fe=["home_anniversary","just_listed","just_sold"].includes(S);return e.jsxs(bs,{open:d,onOpenChange:qe=>{qe?u(!0):(Me(),l==null||l(!1))},children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Create Card"]})}),e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:h==="type"?"What type of card?":h==="contact"?`${Ce[S]} — Choose a Contact`:`${Ce[S]} — Customize`})}),h==="type"&&e.jsx(pnn,{onSelect:ge}),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:()=>p("type"),children:[e.jsx(Hr,{className:"h-3.5 w-3.5"})," Back to card types"]}),e.jsxs("div",{className:"relative",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search contacts...",value:f,onChange:qe=>g(qe.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[pe==null?void 0:pe.map(qe=>e.jsxs("button",{onClick:()=>ve(qe),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(Xi,{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:[qe.first_name," ",qe.last_name]}),qe.address&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate flex items-center gap-1",children:[e.jsx(Or,{className:"h-3 w-3"}),qe.address]})]}),(S==="home_anniversary"&&qe.home_anniversary||S==="wedding_anniversary"&&qe.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"})]},qe.id)),(pe==null?void 0:pe.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:()=>{p("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:()=>p("contact"),children:[e.jsx(Hr,{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:qe=>L(qe.target.value),placeholder:"John & Jane Smith"})]}),Fe&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Property Address"}),e.jsx(ye,{value:D,onChange:qe=>M(qe.target.value),placeholder:"123 Main St, Austin, TX"})]}),De&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:Ie}),e.jsx(ye,{type:"date",value:F,onChange:qe=>z(qe.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Personal Message (optional)"}),e.jsx(Es,{value:V,onChange:qe=>W(qe.target.value),placeholder:Ae.defaultMessage,rows:3})]}),e.jsx(ENt,{photoUrl:J,videoUrl:ie,onPhotoChange:ne,onVideoChange:he,contactId:_}),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:qe,label:be,gradient:Ze})=>e.jsxs("button",{onClick:()=>K(qe),className:`p-2 rounded-lg border-2 transition-all text-center ${Y===qe?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-10 rounded-md mb-1.5 ${Ze}`}),e.jsx("span",{className:"text-[10px] font-medium",children:be})]},qe))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>p("contact"),className:"flex-1",children:"Back"}),e.jsx(B,{onClick:Te,disabled:!T||j,className:"flex-1 gap-2",children:j?"Creating...":"Create Card"})]})]})]})]})}function fnn({open:s,onOpenChange:t}){const n=Mn(),r=a=>{t(!1),n(a)};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Set up an email sender"}),e.jsx(Qn,{children:"To send emails from the platform, connect Gmail or verify a Mass Email (Amazon SES) sender address. Either option lets you send from your own email."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("button",{onClick:()=>r("/integrations"),className:"w-full flex items-start gap-3 rounded-lg border p-4 text-left hover:bg-muted/50 transition",children:[e.jsx(Vs,{className:"h-5 w-5 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Connect Gmail"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Send from your Google account with your full inbox history."})]})]}),e.jsxs("button",{onClick:()=>r("/integrations"),className:"w-full flex items-start gap-3 rounded-lg border p-4 text-left hover:bg-muted/50 transition",children:[e.jsx(Y2,{className:"h-5 w-5 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Verify a Mass Email sender"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Send via Amazon SES from any verified email address you own."})]})]}),e.jsx("div",{className:"flex justify-end pt-2",children:e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Not now"})})]})]})})}const xnn={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 gnn({card:s}){const{user:t}=ys(),{isGmailConnected:n,hasVerifiedSes:r,canSendEmail:a,sendMethod:i}=Oh(),l=Ht(),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState("");N.useEffect(()=>{o&&s.contact_id&&!h&&q.from("innercircle_contacts").select("email").eq("id",s.contact_id).maybeSingle().then(({data:T})=>{T!=null&&T.email&&p(T.email)})},[o,s.contact_id]);const f={home_anniversary:`🏡 Happy Home Anniversary, ${s.recipient_name}!`,wedding_anniversary:`💍 Happy Anniversary, ${s.recipient_name}!`,just_listed:`🏠 Just Listed — Check This Out, ${s.recipient_name}!`,just_sold:`🎉 Just Sold! Congrats, ${s.recipient_name}!`,congratulations:`🏆 Congratulations, ${s.recipient_name}!`,birthday:`🎂 Happy Birthday, ${s.recipient_name}!`,holiday:`🎄 Happy Holidays, ${s.recipient_name}!`,thank_you:`💐 Thank You, ${s.recipient_name}!`,thinking_of_you:`💭 Thinking of You, ${s.recipient_name}!`},[g,_]=N.useState(f[s.card_type]||`A Special Card for ${s.recipient_name}!`),[v,j]=N.useState(""),b=`https://cardstudio.relevelup.com/c/${s.share_token}`,S=gt({mutationFn:async()=>{var F;if(!h)throw new Error("Recipient email is required");const T=`
${v?`

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


`:""}

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

${s.property_address?`

${s.property_address}

`:""}
`,{data:L}=await q.auth.getSession(),D=(F=L==null?void 0:L.session)==null?void 0:F.access_token,M=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/gmail-send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D}`},body:JSON.stringify({to:h,subject:g,body:T,contactId:s.contact_id||void 0})});if(!M.ok){const z=await M.json();throw new Error(z.error||"Failed to send")}return M.json()},onSuccess:async()=>{await q.from("sendable_cards").update({sent_at:new Date().toISOString(),sent_via:"gmail"}).eq("id",s.id),l.invalidateQueries({queryKey:["sendable-cards"]}),ae.success(`Card sent to ${h}!`),c(!1)},onError:T=>{ae.error(T.message||"Failed to send email")}}),A=i==="mass_email"?"Mass Email":"Gmail";return a?e.jsxs(bs,{open:o,onOpenChange:c,children:[e.jsx(Ai,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(cr,{className:"h-3 w-3"})})}),e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsx(ws,{children:e.jsxs(_s,{children:["Send Card via ",A]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"gmail-to",children:"To"}),e.jsx(S_t,{value:h,onChange:p,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:g,onChange:T=>_(T.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Personal Note (optional)"}),e.jsx(Es,{value:v,onChange:T=>j(T.target.value),placeholder:"Add a warm personal note before the card link...",rows:3})]}),e.jsxs("div",{className:"rounded-lg bg-muted/50 p-3 text-xs text-muted-foreground",children:[i==="mass_email"?e.jsx(e.Fragment,{children:"Sending via your verified Mass Email sender (Gmail isn't connected)."}):e.jsx(e.Fragment,{children:"The email will include a beautiful button linking to your card at:"}),e.jsx("br",{}),e.jsx("span",{className:"font-mono text-foreground",children:b})]}),e.jsx(B,{onClick:()=>S.mutate(),disabled:!h||S.isPending,className:"w-full gap-2",children:S.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cr,{className:"h-4 w-4"})," Send Card"]})})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",title:"Set up an email sender to send cards",onClick:()=>u(!0),children:e.jsx(cr,{className:"h-3 w-3"})}),e.jsx(fnn,{open:d,onOpenChange:u})]})}function ynn({card:s}){const t=Ht(),[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(s.recipient_name),[c,d]=N.useState(s.property_address||""),[u,h]=N.useState(s.home_anniversary_date||""),[p,f]=N.useState(s.custom_message||""),[g,_]=N.useState(s.template),[v,j]=N.useState(s.property_photo_url),[b,S]=N.useState(s.video_url||null),A=L=>{L&&(o(s.recipient_name),d(s.property_address||""),h(s.home_anniversary_date||""),f(s.custom_message||""),_(s.template),j(s.property_photo_url),S(s.video_url||null)),r(L)},T=async()=>{if(!l.trim()){ae.error("Recipient name is required");return}i(!0);try{const{error:L}=await q.from("sendable_cards").update({recipient_name:l.trim(),property_address:c.trim()||null,home_anniversary_date:u||null,custom_message:p.trim()||null,template:g,property_photo_url:v||null,video_url:b||null}).eq("id",s.id);if(L)throw L;t.invalidateQueries({queryKey:["sendable-cards"]}),ae.success("Card updated"),r(!1)}catch(L){ae.error(L.message||"Failed to update card")}finally{i(!1)}};return e.jsxs(bs,{open:n,onOpenChange:A,children:[e.jsx(Ai,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(_a,{className:"h-3 w-3"})})}),e.jsxs(vs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Edit Card"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Recipient Name"}),e.jsx(ye,{value:l,onChange:L=>o(L.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:L=>d(L.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:L=>h(L.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Personal Message (optional)"}),e.jsx(Es,{value:p,onChange:L=>f(L.target.value),placeholder:"Wishing you many more happy years in your beautiful home!",rows:3})]}),e.jsx(ENt,{photoUrl:v,videoUrl:b,onPhotoChange:j,onVideoChange:S,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(L=>e.jsxs("button",{onClick:()=>_(L),className:`p-3 rounded-lg border-2 transition-all text-center ${g===L?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-12 rounded-md mb-2 ${L==="elegant"?"bg-gradient-to-br from-slate-100 to-slate-200 dark:from-slate-800 dark:to-slate-700":L==="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:L})]},L))})]}),e.jsx(B,{onClick:T,disabled:!l.trim()||a,className:"w-full gap-2",children:a?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 animate-spin"})," Saving..."]}):"Save Changes"})]})]})]})}function vnn(){const{user:s}=ys(),t=Ht(),[n,r]=N.useState(""),[a,i]=gl(),l=a.get("cardType"),o=a.get("contactId"),c=a.get("name"),d=a.get("address"),u=a.get("date"),h=!!l,{data:p,isLoading:f}=ct({queryKey:["sendable-cards",s==null?void 0:s.id],queryFn:async()=>{const{data:S,error:A}=await q.from("sendable_cards").select("*").eq("owner_user_id",s.id).order("created_at",{ascending:!1});if(A)throw A;return S},enabled:!!(s!=null&&s.id)}),g=gt({mutationFn:async S=>{const{error:A}=await q.from("sendable_cards").delete().eq("id",S);if(A)throw A},onSuccess:()=>{t.invalidateQueries({queryKey:["sendable-cards"]}),ae.success("Card deleted")}}),_=S=>{const A=`https://cardstudio.relevelup.com/c/${S}`;navigator.clipboard.writeText(A),ae.success("Share link copied!")},v=p==null?void 0:p.filter(S=>{var A;return!n||S.recipient_name.toLowerCase().includes(n.toLowerCase())||((A=S.property_address)==null?void 0:A.toLowerCase().includes(n.toLowerCase()))}),j={elegant:"Elegant",bold:"Bold",warm:"Warm"},b={home_anniversary:"Home Anniversary",wedding_anniversary:"Wedding Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"};return e.jsx(Ts,{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(VXe,{initialOpen:h,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:u||void 0,onOpenChange:()=>i({})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search cards...",value:n,onChange:S=>r(S.target.value),className:"pl-9"})]}),f?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(S=>e.jsx(fe,{className:"animate-pulse",children:e.jsxs(Ee,{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"})]})},S))}):v!=null&&v.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:v.map(S=>e.jsxs(fe,{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 ${S.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":S.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:[S.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"})]}),S.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%)]"})]}),S.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:S.card_type==="home_anniversary"?"🏡":S.card_type==="wedding_anniversary"?"💍":S.card_type==="birthday"?"🎂":S.card_type==="just_sold"?"🎉":S.card_type==="just_listed"?"🏠":S.card_type==="thank_you"?"💐":S.card_type==="congratulations"?"🏆":S.card_type==="holiday"?"🎄":S.card_type==="thinking_of_you"?"💭":"✉️"}),e.jsx("p",{className:`text-[10px] uppercase tracking-[0.2em] mb-1 ${S.template==="bold"?"text-white/70":"text-muted-foreground"}`,children:b[S.card_type]||S.card_type}),e.jsx("p",{className:`font-semibold text-base ${S.template==="bold"?"text-white":"text-foreground"}`,children:S.recipient_name}),S.property_address&&e.jsx("p",{className:`text-xs mt-1 ${S.template==="bold"?"text-white/60":"text-muted-foreground"}`,children:S.property_address})]}),e.jsx("div",{className:"absolute top-2 right-2 z-10",children:e.jsx(ze,{variant:S.template==="bold"?"outline":"secondary",className:`text-[10px] ${S.template==="bold"?"border-white/30 text-white/80":""}`,children:j[S.template]||S.template})})]}),e.jsxs(Ee,{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(Er,{className:"h-3 w-3"}),S.view_count," views"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Vo(new Date(S.created_at),{addSuffix:!0})})]}),S.sent_at&&e.jsxs("p",{className:"text-[10px] text-emerald-600 mb-2",children:["Sent ",Ss(new Date(S.sent_at),"MMM d, yyyy")," via ",S.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:()=>_(S.share_token),children:[e.jsx(Xr,{className:"h-3 w-3"}),"Copy Link"]}),e.jsx(ynn,{card:S}),e.jsx(gnn,{card:S}),e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",onClick:()=>window.open(`https://cardstudio.relevelup.com/c/${S.share_token}`,"_blank"),children:e.jsx(tr,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive gap-1 text-xs",onClick:()=>g.mutate(S.id),children:e.jsx(_n,{className:"h-3 w-3"})})]})]})]},S.id))}):e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{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(Vs,{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(VXe,{initialOpen:h,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:u||void 0,onOpenChange:()=>i({})})]})})]})})}const PG=[{id:"mls",label:"MLS Description",tag:"Standard",icon:Or,accent:"from-sky-500 to-cyan-500",desc:"Polished MLS-ready listing",category:"listing"},{id:"luxury",label:"Luxury MLS",tag:"Premium",icon:ff,accent:"from-amber-500 to-orange-500",desc:"Evocative, high-end voice",category:"listing"},{id:"short",label:"Short MLS",tag:"Concise",icon:hh,accent:"from-violet-500 to-fuchsia-500",desc:"Punchy 60–90 words",category:"listing"},{id:"openHouse",label:"Open House",tag:"Promo",icon:xw,accent:"from-emerald-500 to-teal-500",desc:"Friendly invite copy",category:"listing",extras:["openHouse"]},{id:"newConstruction",label:"New Construction",tag:"Build",icon:r9,accent:"from-rose-500 to-pink-500",desc:"Builder-focused angle",category:"listing",extras:["newConstruction"]},{id:"investment",label:"Investment",tag:"ROI",icon:mo,accent:"from-indigo-500 to-blue-500",desc:"Cap rate & income hooks",category:"listing",extras:["investment"]},{id:"facebookPost",label:"Facebook Post",tag:"Social",icon:Lh,accent:"from-blue-600 to-blue-400",desc:"Engaging FB caption",category:"social"},{id:"instagramPost",label:"Instagram Post",tag:"Social",icon:du,accent:"from-pink-500 via-fuchsia-500 to-orange-400",desc:"IG caption + hashtags",category:"social"},{id:"linkedinPost",label:"LinkedIn Post",tag:"Social",icon:vf,accent:"from-sky-700 to-sky-500",desc:"Professional tone",category:"social"},{id:"justListed",label:"Just Listed",tag:"Announce",icon:$d,accent:"from-emerald-500 to-green-500",desc:"Hit the market announcement",category:"social"},{id:"comingSoon",label:"Coming Soon",tag:"Tease",icon:gr,accent:"from-amber-500 to-yellow-500",desc:"Build pre-market buzz",category:"social",extras:["comingSoon"]},{id:"priceImprovement",label:"Price Improvement",tag:"Update",icon:vb,accent:"from-orange-500 to-red-500",desc:"New price announcement",category:"social",extras:["priceImprovement"]},{id:"openHousePost",label:"Open House Post",tag:"Event",icon:Tl,accent:"from-teal-500 to-emerald-500",desc:"Social invite to OH",category:"social",extras:["openHouse"]},{id:"underContract",label:"Under Contract",tag:"Status",icon:e9,accent:"from-indigo-500 to-purple-500",desc:"Pending celebration",category:"social",extras:["underContract"]},{id:"justSold",label:"Just Sold",tag:"Celebrate",icon:ch,accent:"from-fuchsia-500 to-pink-500",desc:"Sold success post",category:"social",extras:["sold"]},{id:"propertyTourScript",label:"Property Tour",tag:"Script",icon:br,accent:"from-red-500 to-rose-500",desc:"Full walkthrough script",category:"video",extras:["signoff"]},{id:"reelScript",label:"Reel Script",tag:"Short",icon:Ah,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:Fv,accent:"from-violet-500 to-purple-500",desc:"5 scroll-stopping hooks",category:"video",extras:["vibe"]},{id:"luxuryWalkthrough",label:"Luxury Walkthrough",tag:"Premium",icon:ff,accent:"from-amber-500 to-yellow-500",desc:"Cinematic, refined tone",category:"video",extras:["signoff"]},{id:"droneScript",label:"Drone Script",tag:"Aerial",icon:v9,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:ka,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:Vs,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:lL,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:Nn,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:vb,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:WS,accent:"from-fuchsia-500 to-pink-500",desc:"Sold announcement email",category:"email",extras:["sold","signoff"]},{id:"neighborhoodEmail",label:"Neighborhood Email",tag:"Nurture",icon:ka,accent:"from-sky-500 to-indigo-500",desc:"Area update / market touch",category:"email",extras:["neighborhood","signoff"]}];function bnn(){var Hn,ta,Zr,ur,Mr,zi,Bi,Za,_i,qi,ga;const{user:s}=ys(),[t,n]=N.useState(""),[r,a]=N.useState(""),[i,l]=N.useState([]),[o,c]=N.useState(""),[d,u]=N.useState([]),[h,p]=N.useState(""),[f,g]=N.useState(""),[_,v]=N.useState(""),[j,b]=N.useState(""),[S,A]=N.useState(""),[T,L]=N.useState(""),[D,M]=N.useState(""),[F,z]=N.useState(null),[V,W]=N.useState(""),[Y,K]=N.useState(""),[J,ne]=N.useState(""),[ie,he]=N.useState(""),[ce,pe]=N.useState(""),[le,ve]=N.useState(""),[ge,Te]=N.useState(""),[Me,Ce]=N.useState(""),[Ae,De]=N.useState(""),[Ie,Fe]=N.useState(""),[qe,be]=N.useState(""),[Ze,Ne]=N.useState(""),[it,je]=N.useState(""),[Ge,Be]=N.useState(""),[Ye,We]=N.useState(""),[rt,tt]=N.useState(""),[at,He]=N.useState(""),[dt,bt]=N.useState(""),[vt,Bt]=N.useState(""),[Zt,Fs]=N.useState(""),[Rs,ms]=N.useState(""),[Pt,Jt]=N.useState(""),[ft,Vt]=N.useState(""),[Ms,Xt]=N.useState(""),[Js,Cs]=N.useState(""),[As,rn]=N.useState("listing"),[tn,er]=N.useState("mls"),[gn,In]=N.useState({}),[Zn,ea]=N.useState({}),[vi,Ls]=N.useState(!1),[fi,Lr]=N.useState(!1),Jn=wn=>{rn(wn);const Ta=PG.find(Yi=>Yi.category===wn);Ta&&er(Ta.id)},{data:js}=ct({queryKey:["listing-studio-listings",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&vi,queryFn:async()=>{const{data:wn,error:Ta}=await q.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, property_type, description").eq("agent_id",s.id).order("created_at",{ascending:!1}).limit(50);if(Ta)throw Ta;return wn||[]}}),Dn=()=>{const wn=o.trim();wn&&(l(Ta=>[...Ta,wn]),c(""))},wr=wn=>l(Ta=>Ta.filter((Yi,zo)=>zo!==wn)),$r=wn=>{var Ta,Yi,zo,rl;z(wn.id),n(wn.property_address||""),L(wn.city||""),M(wn.state||""),b(((Ta=wn.price)==null?void 0:Ta.toString())||""),p(((Yi=wn.bedrooms)==null?void 0:Yi.toString())||""),g(((zo=wn.bathrooms)==null?void 0:zo.toString())||""),v(((rl=wn.square_footage)==null?void 0:rl.toString())||""),A(wn.property_type||""),a(wn.description||""),Ls(!1),ae.success("Listing imported")},ss=async wn=>{if(!(!wn.target.files||!(s!=null&&s.id))){Lr(!0);try{const Ta=[];for(const Yi of Array.from(wn.target.files).slice(0,10)){const zo=`${s.id}/${Date.now()}-${Yi.name.replace(/[^\w.-]/g,"_")}`,{error:rl}=await q.storage.from("listing-photos").upload(zo,Yi,{upsert:!1});if(rl){console.error(rl);continue}const{data:po}=q.storage.from("listing-photos").getPublicUrl(zo);Ta.push(po.publicUrl)}u(Yi=>[...Yi,...Ta]),Ta.length&&ae.success(`${Ta.length} photo(s) uploaded`)}catch(Ta){ae.error(Ta.message||"Photo upload failed")}finally{Lr(!1)}}},Oe=PG.find(wn=>wn.id===tn),Xe=async wn=>{var Yi,zo,rl;const Ta=PG.find(po=>po.id===wn);if(!t.trim()&&!r.trim()&&i.length===0){ae.error("Add a property address, MLS remarks, or features first");return}if((Yi=Ta.extras)!=null&&Yi.includes("openHouse")&&(!V||!Y||!J)){ae.error("Add the open house date, start and end time");return}if((zo=Ta.extras)!=null&&zo.includes("priceImprovement")&&(!ie||!ce)){ae.error("Add previous and new price");return}if((rl=Ta.extras)!=null&&rl.includes("sold")&&!le){ae.error("Add the sold price");return}er(wn),ea(po=>({...po,[wn]:!0}));try{const{data:po,error:uc}=await q.functions.invoke("listing-studio-generate",{body:{copyType:wn,propertyAddress:t,mlsRemarks:r,features:i,photoUrls:d,listingId:F,bedrooms:h?Number(h):null,bathrooms:f?Number(f):null,squareFootage:_?Number(_):null,price:j?Number(j):null,propertyType:S||null,city:T||null,state:D||null,openHouseDate:V||null,openHouseStart:Y||null,openHouseEnd:J||null,previousPrice:ie?Number(ie):null,newPrice:ce?Number(ce):null,soldPrice:le?Number(le):null,soldDate:ge||null,comingSoonDate:Me||null,builderName:Ae||null,yearBuilt:Ie?Number(Ie):null,warrantyInfo:qe||null,monthlyRent:Ze?Number(Ze):null,capRate:it||null,occupancy:Ge||null,daysOnMarket:Ye?Number(Ye):null,offerCount:rt?Number(rt):null,originalListPrice:at?Number(at):null,soldDaysOnMarket:dt?Number(dt):null,commissionOffered:vt||null,refreshments:Zt||null,vibe:Rs||null,neighborhoodHighlights:Pt||null,agentName:ft||null,agentBrokerage:Ms||null,agentContact:Js||null}});if(uc)throw uc;if(po!=null&&po.error)throw new Error(po.error);In(hc=>({...hc,[wn]:po.content}))}catch(po){ae.error(po.message||"Generation failed")}finally{ea(po=>({...po,[wn]:!1}))}},ot=wn=>{navigator.clipboard.writeText(wn),ae.success("Copied to clipboard")},Nt=Oe.icon,Rt=gn[tn]?gn[tn].trim().split(/\s+/).length:0,qt=wn=>e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:PG.filter(Ta=>Ta.category===wn).map(Ta=>{const Yi=Ta.icon,zo=tn===Ta.id,rl=!!gn[Ta.id];return e.jsxs("button",{onClick:()=>er(Ta.id),className:Et("relative text-left p-4 rounded-2xl border transition-all overflow-hidden group",zo?"border-primary shadow-lg shadow-primary/10 bg-card":"border-border/60 hover:border-border bg-card/50 hover:bg-card"),children:[zo&&e.jsx("div",{className:Et("absolute inset-0 opacity-[0.07] bg-gradient-to-br",Ta.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",Ta.accent),children:e.jsx(Yi,{className:"h-4 w-4"})}),rl&&e.jsx("div",{className:"h-5 w-5 rounded-full bg-emerald-500/15 text-emerald-600 grid place-items-center",children:e.jsx(Ir,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-sm",children:Ta.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:Ta.desc})]})]})]},Ta.id)})}),xs=(Hn=Oe.extras)==null?void 0:Hn.includes("openHouse"),rs=(ta=Oe.extras)==null?void 0:ta.includes("priceImprovement"),ks=(Zr=Oe.extras)==null?void 0:Zr.includes("sold"),ln=(ur=Oe.extras)==null?void 0:ur.includes("comingSoon"),Gs=(Mr=Oe.extras)==null?void 0:Mr.includes("newConstruction"),Un=(zi=Oe.extras)==null?void 0:zi.includes("investment"),jr=(Bi=Oe.extras)==null?void 0:Bi.includes("underContract"),Sr=(Za=Oe.extras)==null?void 0:Za.includes("brokerOpen"),nr=(_i=Oe.extras)==null?void 0:_i.includes("vibe"),Ot=(qi=Oe.extras)==null?void 0:qi.includes("neighborhood"),fn=(ga=Oe.extras)==null?void 0:ga.includes("signoff"),sr=xs||rs||ks||ln||Gs||Un||jr||Sr||nr||Ot||fn;return e.jsx(Ts,{title:"Listing Studio",children:e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-3xl border bg-gradient-to-br from-fuchsia-500/10 via-violet-500/5 to-sky-500/10 dark:from-fuchsia-500/20 dark:via-violet-500/10 dark:to-sky-500/20",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_top_right,_hsl(var(--primary)/0.15),_transparent_60%)]"}),e.jsx("div",{className:"absolute -top-24 -right-24 h-72 w-72 rounded-full bg-fuchsia-500/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-24 -left-24 h-72 w-72 rounded-full bg-sky-500/20 blur-3xl"}),e.jsxs("div",{className:"relative px-6 py-8 sm:px-10 sm:py-12 flex flex-col md:flex-row md:items-center gap-6",children:[e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-background/60 backdrop-blur-sm border text-xs font-medium",children:[e.jsx(un,{className:"h-3.5 w-3.5 text-fuchsia-500"}),"AI-powered listing & social copy"]}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold tracking-tight bg-gradient-to-br from-foreground to-foreground/60 bg-clip-text",children:"Listing Studio"}),e.jsx("p",{className:"text-muted-foreground max-w-xl",children:"Drop in a property, generate magnetic MLS copy, luxury narratives, open-house promos, and ready-to-post social content — all in seconds."})]}),e.jsxs(bs,{open:vi,onOpenChange:Ls,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{size:"lg",variant:"secondary",className:"shadow-lg shadow-fuchsia-500/10",children:[e.jsx(Nr,{className:"h-4 w-4 mr-2"}),"Import from Listings"]})}),e.jsxs(vs,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Import from Listing Exchange"})}),e.jsxs("div",{className:"space-y-2 mt-2",children:[!(js!=null&&js.length)&&e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No listings found yet."}),js==null?void 0:js.map(wn=>e.jsxs("button",{onClick:()=>$r(wn),className:"w-full text-left p-4 border rounded-xl hover:border-primary hover:bg-accent/50 transition-all",children:[e.jsx("div",{className:"font-medium",children:wn.property_address||"Untitled listing"}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[[wn.city,wn.state].filter(Boolean).join(", "),wn.price?` · $${Number(wn.price).toLocaleString()}`:"",wn.bedrooms?` · ${wn.bedrooms}bd`:"",wn.bathrooms?` · ${wn.bathrooms}ba`:""]})]},wn.id))]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-6",children:[e.jsx(fe,{className:"lg:col-span-2 border-border/60 shadow-sm",children:e.jsxs(Ee,{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(Or,{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:wn=>n(wn.target.value),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"City"}),e.jsx(ye,{value:T,onChange:wn=>L(wn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"State"}),e.jsx(ye,{value:D,onChange:wn=>M(wn.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Price"}),e.jsx(ye,{type:"number",value:j,onChange:wn=>b(wn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsx(ye,{value:S,onChange:wn=>A(wn.target.value),placeholder:"Single Family"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Beds"}),e.jsx(ye,{type:"number",value:h,onChange:wn=>p(wn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Baths"}),e.jsx(ye,{type:"number",step:"0.5",value:f,onChange:wn=>g(wn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sqft"}),e.jsx(ye,{type:"number",value:_,onChange:wn=>v(wn.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"MLS Remarks / Notes"}),e.jsx(Es,{value:r,onChange:wn=>a(wn.target.value),placeholder:"Paste existing MLS remarks or rough notes...",rows:4,className:"resize-none"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Features"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:o,onChange:wn=>c(wn.target.value),onKeyDown:wn=>wn.key==="Enter"&&(wn.preventDefault(),Dn()),placeholder:"e.g. Quartz countertops"}),e.jsx(B,{type:"button",size:"icon",variant:"secondary",onClick:Dn,children:e.jsx(Is,{className:"h-4 w-4"})})]}),i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-2 animate-fade-in",children:i.map((wn,Ta)=>e.jsxs(ze,{variant:"secondary",className:"pl-3 pr-1 py-1 gap-1",children:[wn,e.jsx("button",{onClick:()=>wr(Ta),className:"ml-0.5 p-0.5 hover:bg-background/60 rounded-full",children:e.jsx(Bn,{className:"h-3 w-3"})})]},Ta))})]}),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(ry,{className:"h-4 w-4"}),fi?"Uploading…":"Click to upload photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:ss,disabled:fi,className:"hidden"})]}),d.length>0&&e.jsx("div",{className:"grid grid-cols-4 gap-2 mt-2",children:d.map((wn,Ta)=>e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden group",children:[e.jsx("img",{src:wn,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>u(Yi=>Yi.filter((zo,rl)=>rl!==Ta)),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(Bn,{className:"h-3 w-3"})})]},Ta))})]}),sr&&e.jsxs("div",{className:"space-y-4 p-4 rounded-xl border border-dashed border-primary/40 bg-primary/5 animate-fade-in",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"text-sm font-semibold",children:["Extra info for ",Oe.label]})]}),xs&&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:V,onChange:wn=>W(wn.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Start"}),e.jsx(ye,{type:"time",value:Y,onChange:wn=>K(wn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"End"}),e.jsx(ye,{type:"time",value:J,onChange:wn=>ne(wn.target.value)})]})]})]}),rs&&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:ie,onChange:wn=>he(wn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"New Price"}),e.jsx(ye,{type:"number",value:ce,onChange:wn=>pe(wn.target.value),placeholder:"$"})]})]}),ks&&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:le,onChange:wn=>ve(wn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Date"}),e.jsx(ye,{type:"date",value:ge,onChange:wn=>Te(wn.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Original List Price (optional)"}),e.jsx(ye,{type:"number",value:at,onChange:wn=>He(wn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(ye,{type:"number",value:dt,onChange:wn=>bt(wn.target.value)})]})]})]}),ln&&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:Me,onChange:wn=>Ce(wn.target.value)})]}),Gs&&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:Ae,onChange:wn=>De(wn.target.value),placeholder:"ABC Homes"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Year Built"}),e.jsx(ye,{type:"number",value:Ie,onChange:wn=>Fe(wn.target.value),placeholder:"2026"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Warranty / Energy / Smart-home (optional)"}),e.jsx(ye,{value:qe,onChange:wn=>be(wn.target.value),placeholder:"10-yr structural, ENERGY STAR, smart-home pkg"})]})]}),Un&&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:Ze,onChange:wn=>Ne(wn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Cap Rate (optional)"}),e.jsx(ye,{value:it,onChange:wn=>je(wn.target.value),placeholder:"6.5%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Occupancy"}),e.jsxs("select",{value:Ge,onChange:wn=>Be(wn.target.value),className:"w-full h-10 rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:"",children:"Select…"}),e.jsx("option",{value:"Vacant",children:"Vacant"}),e.jsx("option",{value:"Tenant-occupied",children:"Tenant-occupied"}),e.jsx("option",{value:"Owner-occupied",children:"Owner-occupied"}),e.jsx("option",{value:"Short-term rental",children:"Short-term rental"})]})]})]}),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:Ye,onChange:wn=>We(wn.target.value),placeholder:"e.g. 3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"# of Offers (optional)"}),e.jsx(ye,{type:"number",value:rt,onChange:wn=>tt(wn.target.value),placeholder:"e.g. 5"})]})]}),Sr&&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:vt,onChange:wn=>Bt(wn.target.value),placeholder:"2.5% buyer agent commission"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Refreshments / Perks (optional)"}),e.jsx(ye,{value:Zt,onChange:wn=>Fs(wn.target.value),placeholder:"Lunch + raffle for $100 gift card"})]})]}),nr&&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:Rs,onChange:wn=>ms(wn.target.value),className:"w-full h-10 rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:"",children:"Default"}),e.jsx("option",{value:"Energetic",children:"Energetic & fun"}),e.jsx("option",{value:"Luxury",children:"Luxury & cinematic"}),e.jsx("option",{value:"Cozy",children:"Warm & cozy"}),e.jsx("option",{value:"Humorous",children:"Humorous"}),e.jsx("option",{value:"Educational",children:"Educational"}),e.jsx("option",{value:"Bold",children:"Bold & confident"})]})]}),Ot&&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(Es,{value:Pt,onChange:wn=>Jt(wn.target.value),rows:3,placeholder:"Top schools, parks, coffee shops, restaurants, commute, walkability…"})]}),fn&&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:ft,onChange:wn=>Vt(wn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage"}),e.jsx(ye,{value:Ms,onChange:wn=>Xt(wn.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Phone / Email"}),e.jsx(ye,{value:Js,onChange:wn=>Cs(wn.target.value),placeholder:"555-123-4567 or you@brand.com"})]})]})]})]})}),e.jsxs("div",{className:"lg:col-span-3 space-y-6",children:[e.jsx("div",{className:"flex gap-2 p-1 rounded-xl bg-muted/60 border border-border/40 overflow-x-auto",children:[{key:"listing",label:"Listing Copy",icon:Nr},{key:"social",label:"Social Media",icon:du},{key:"video",label:"Video Scripts",icon:br},{key:"email",label:"Email Marketing",icon:Vs}].map(wn=>{const Ta=wn.icon,Yi=As===wn.key;return e.jsxs("button",{onClick:()=>Jn(wn.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",Yi?"bg-card shadow-sm text-foreground border border-border/60":"text-muted-foreground hover:text-foreground hover:bg-background/50"),children:[e.jsx(Ta,{className:"h-4 w-4"}),wn.label]},wn.key)})}),qt(As),e.jsxs(fe,{className:"border-border/60 shadow-sm overflow-hidden",children:[e.jsx("div",{className:Et("h-1 bg-gradient-to-r",Oe.accent)}),e.jsxs(Ee,{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",Oe.accent),children:e.jsx(Nt,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold flex items-center gap-2",children:[Oe.label,e.jsx(ze,{variant:"outline",className:"text-[10px] font-normal",children:Oe.tag})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:gn[tn]?`${Rt} words`:"Ready to generate"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[gn[tn]&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>ot(gn[tn]),children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"})," Copy"]}),e.jsx(B,{onClick:()=>Xe(tn),disabled:Zn[tn],className:Et("shadow-lg shadow-primary/10 bg-gradient-to-r text-white border-0 hover:opacity-90",Oe.accent),size:"sm",children:Zn[tn]?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"})," Generating"]}):gn[tn]?e.jsxs(e.Fragment,{children:[e.jsx(Ti,{className:"h-4 w-4 mr-2"})," Regenerate"]}):e.jsxs(e.Fragment,{children:[e.jsx(Dm,{className:"h-4 w-4 mr-2"})," Generate"]})})]})]}),gn[tn]?e.jsx(Es,{value:gn[tn],onChange:wn=>In(Ta=>({...Ta,[tn]:wn.target.value})),rows:16,className:"resize-none font-serif text-[15px] leading-relaxed bg-muted/30 border-border/60 animate-fade-in"}):e.jsxs("div",{className:"border border-dashed rounded-xl p-12 text-center bg-muted/20",children:[e.jsx("div",{className:Et("mx-auto h-14 w-14 rounded-2xl grid place-items-center text-white bg-gradient-to-br mb-4",Oe.accent),children:e.jsx(Dm,{className:"h-6 w-6"})}),e.jsxs("div",{className:"font-medium mb-1",children:["Generate a ",Oe.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 BF({delay:s,x:t,y:n,size:r}){return e.jsx(Yn.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 _nn(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:p}=s,f=RR[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(Yn.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(Yn.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(BF,{delay:0,x:"15%",y:"20%",size:8}),e.jsx(BF,{delay:1,x:"80%",y:"30%",size:6}),e.jsx(BF,{delay:2,x:"60%",y:"70%",size:10}),e.jsx(BF,{delay:.5,x:"25%",y:"80%",size:7}),e.jsx(BF,{delay:1.5,x:"70%",y:"15%",size:5})]}),e.jsxs(Yn.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(Yn.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(Yn.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(Yn.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(Yn.div,{className:"absolute inset-0 rounded-2xl border-2 border-slate-200/50 dark:border-slate-600/50",animate:{scale:[1,1.15,1],opacity:[.5,0,.5]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut"}}),e.jsx("span",{className:"text-4xl",children:f.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(Yn.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(Yn.h1,{className:"text-4xl font-light text-slate-800 dark:text-slate-100 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:f.title[0]}),f.title[1]&&e.jsx(Yn.h2,{className:"text-4xl font-bold text-slate-800 dark:text-slate-100 mb-8 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:f.title[1]}),e.jsxs(Yn.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(Yn.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(Yn.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"})}),p&&e.jsx(Yn.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:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Yn.p,{className:"text-sm text-slate-500 dark:text-slate-400 leading-relaxed max-w-xs mx-auto mb-8 italic",initial:{opacity:0},animate:{opacity:1},transition:{duration:.6,delay:1.3},children:i||f.defaultMessage}),e.jsxs(Yn.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(Yn.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(Yn.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(Ar,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Yn.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(Vs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Yn.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 GNe({delay:s,x:t,y:n,color:r,size:a}){return e.jsx(Yn.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 $F({delay:s,x:t,y:n}){return e.jsx(Yn.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 HXe={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 wnn(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:p}=s,f=RR[t],g=HXe[t]||HXe.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-br ${g.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx(GNe,{delay:0,x:"10%",y:"10%",color:g.orbs[0],size:200}),e.jsx(GNe,{delay:1,x:"70%",y:"60%",color:g.orbs[1],size:180}),e.jsx(GNe,{delay:2,x:"50%",y:"20%",color:g.orbs[2],size:150}),e.jsx($F,{delay:0,x:"20%",y:"25%"}),e.jsx($F,{delay:.8,x:"75%",y:"15%"}),e.jsx($F,{delay:1.6,x:"85%",y:"65%"}),e.jsx($F,{delay:2.4,x:"10%",y:"75%"}),e.jsx($F,{delay:.4,x:"45%",y:"85%"}),e.jsxs(Yn.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(Yn.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(Yn.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(Yn.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(Yn.div,{className:"absolute inset-0 rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-500",animate:{scale:[1,1.3,1],opacity:[.6,0,.6]},transition:{duration:2,repeat:1/0,ease:"easeInOut"}}),e.jsx("span",{className:"text-4xl relative z-10",children:f.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Yn.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(Yn.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(Yn.h1,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-violet-200 via-white to-fuchsia-200 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:f.title[0]}),f.title[1]&&e.jsx(Yn.h2,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-fuchsia-300 via-violet-200 to-purple-300 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:f.title[1]}),e.jsx(Yn.div,{className:"text-3xl mb-4",initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},transition:{duration:.4,delay:1,type:"spring",stiffness:300},children:f.emojis.slice(0,3).join("")}),e.jsxs(Yn.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(Or,{className:"h-3.5 w-3.5"}),r]})]}),h&&e.jsx(Yn.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"})}),p&&e.jsx(Yn.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:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Yn.div,{className:"bg-white/5 rounded-2xl p-5 border border-white/10 mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsx("p",{className:"text-sm text-violet-100/80 leading-relaxed",children:i||f.defaultMessage})}),e.jsxs(Yn.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(Yn.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(Yn.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(Ar,{className:"h-3.5 w-3.5"})," Call Me"]}),d&&e.jsxs(Yn.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(Vs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Yn.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 jnn({emoji:s,delay:t,x:n,duration:r}){return e.jsx(Yn.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 GXe={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 Nnn(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:p}=s,f=RR[t],g=GXe[t]||GXe.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${g.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[f.emojis.map((_,v)=>e.jsx(jnn,{emoji:_,delay:v*1.2,x:`${15+v*14}%`,duration:5+v%3},v)),e.jsx(Yn.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(Yn.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(Yn.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(Yn.div,{className:`h-28 bg-gradient-to-r ${g.header} relative overflow-hidden`,children:[e.jsx(Yn.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(Yn.div,{className:"absolute top-3 left-10 text-5xl",animate:{rotate:[0,10,-5,0],y:[0,-3,0]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:f.emojis[0]}),e.jsx(Yn.div,{className:"absolute top-2 right-14 text-3xl",animate:{scale:[1,1.3,1],rotate:[0,15,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut",delay:.5},children:f.emojis[1]}),e.jsx(Yn.div,{className:"absolute bottom-2 left-1/2 -translate-x-1/2 text-3xl",animate:{y:[0,-5,0],scale:[1,1.1,1]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut",delay:1},children:f.emojis[2]})]}),e.jsxs("div",{className:"px-8 py-8 text-center -mt-10 relative",children:[e.jsx(Yn.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(Yn.div,{animate:{scale:[1,1.2,1]},transition:{duration:1.5,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-3xl",children:f.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(Yn.div,{className:"mb-3",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{delay:.6},children:e.jsxs("span",{className:`inline-flex items-baseline gap-1.5 ${g.accent}`,children:[e.jsx(Yn.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(Yn.h1,{className:`text-3xl font-bold ${g.accent} mb-1`,initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.9},children:[f.title.join(" ")," ",f.emojis[4]]}),e.jsxs(Yn.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:`text-lg font-semibold ${g.text} mb-1`,children:n}),r&&e.jsxs("p",{className:`text-sm ${g.text} opacity-70 flex items-center justify-center gap-1 mb-5`,children:[e.jsx(ka,{className:"h-3 w-3"}),r]})]}),h&&e.jsx(Yn.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"})}),p&&e.jsx(Yn.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:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Yn.div,{className:"bg-gradient-to-br from-amber-50 to-orange-50 rounded-2xl p-5 mb-6 border border-amber-100 shadow-inner",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsxs("p",{className:`text-sm ${g.text} leading-relaxed italic`,children:['"',i||f.defaultMessage,'"']})}),e.jsxs(Yn.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(Yn.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-amber-200 shadow-md",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${g.header} flex items-center justify-center shadow-md`,children:e.jsx("span",{className:"text-sm font-bold text-white",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:`text-sm font-bold ${g.accent}`,children:l}),u&&e.jsx("p",{className:`text-xs ${g.text} opacity-60`,children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(Yn.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${g.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Ar,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Yn.a,{href:`mailto:${d}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${g.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Vs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Yn.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 LG({delay:s,x:t,y:n,size:r,color:a}){return e.jsx(Yn.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 WNe({delay:s,x:t,y:n,size:r}){return e.jsx(Yn.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 WXe={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 knn(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:p}=s,f=RR[t],g=WXe[t]||WXe.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(LG,{delay:0,x:"5%",y:"10%",size:300,color:g.mesh[0]}),e.jsx(LG,{delay:2,x:"60%",y:"50%",size:250,color:g.mesh[1]}),e.jsx(LG,{delay:4,x:"30%",y:"70%",size:200,color:g.mesh[2]}),e.jsx(LG,{delay:1,x:"80%",y:"15%",size:180,color:g.mesh[0]}),e.jsx(WNe,{delay:0,x:"15%",y:"20%",size:100}),e.jsx(WNe,{delay:3,x:"70%",y:"60%",size:140}),e.jsx(WNe,{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(Yn.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(Yn.div,{className:`relative rounded-[28px] overflow-hidden backdrop-blur-2xl bg-white/[0.06] border border-white/[0.12] shadow-2xl ${g.glow}`,initial:{scale:.92},animate:{scale:1},transition:{duration:.6,delay:.2,type:"spring",stiffness:120},children:[e.jsx("div",{className:"relative h-[2px] bg-gradient-to-r from-transparent via-white/20 to-transparent overflow-hidden",children:e.jsx(Yn.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(Yn.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(Yn.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(Yn.span,{className:"text-5xl",animate:{scale:[1,1.08,1]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:f.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Yn.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(Yn.span,{className:"text-3xl font-black text-white",initial:{opacity:0},animate:{opacity:1},transition:{delay:.8},children:a}),e.jsx("span",{className:`text-[10px] font-bold uppercase tracking-[0.2em] ${g.accent}`,children:a===1?"Year":"Years"})]}),e.jsx(Yn.h1,{className:"text-4xl font-extralight text-white/90 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.7},children:f.title[0]}),f.title[1]&&e.jsx(Yn.h2,{className:"text-4xl font-bold text-white mb-6 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.85},children:f.title[1]}),e.jsxs(Yn.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(ka,{className:"h-3 w-3"})," ",r]})]}),e.jsx(Yn.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(Yn.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"})}),p&&e.jsx(Yn.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:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Yn.div,{className:"bg-white/[0.04] rounded-2xl p-5 border border-white/[0.08] mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsxs("p",{className:"text-sm text-white/60 leading-relaxed italic",children:['"',i||f.defaultMessage,'"']})}),e.jsxs(Yn.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(Yn.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(Yn.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(Ar,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Yn.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(Vs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Yn.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 KNe({delay:s,x:t,angle:n,color:r}){return e.jsx(Yn.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 DG({delay:s,x:t}){return e.jsx(Yn.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 KXe={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 Snn(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:p}=s,f=RR[t],g=KXe[t]||KXe.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${g.gradient} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,rgba(255,255,255,0.04)_0%,transparent_60%)]"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_bottom,rgba(0,0,0,0.6)_0%,transparent_60%)]"}),e.jsx(KNe,{delay:0,x:"20%",angle:15,color:g.stripe}),e.jsx(KNe,{delay:2,x:"75%",angle:-12,color:g.stripe}),e.jsx(KNe,{delay:4,x:"50%",angle:5,color:g.stripe}),e.jsx(DG,{delay:0,x:"30%"}),e.jsx(DG,{delay:1.5,x:"60%"}),e.jsx(DG,{delay:3,x:"45%"}),e.jsx(DG,{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(Yn.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2},children:[e.jsx(Yn.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(Yn.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(Yn.div,{className:`h-20 w-20 mx-auto rounded-2xl bg-gradient-to-br ${g.accent} flex items-center justify-center shadow-2xl`,animate:{boxShadow:["0 0 40px rgba(255,255,255,0.05)","0 0 80px rgba(255,255,255,0.1)","0 0 40px rgba(255,255,255,0.05)"]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-4xl",children:f.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Yn.div,{className:"mb-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:.7},children:[e.jsx(Yn.span,{className:`text-6xl font-black bg-gradient-to-r ${g.accent} bg-clip-text text-transparent`,initial:{scale:.5,opacity:0},animate:{scale:1,opacity:1},transition:{delay:.9,type:"spring"},children:a}),e.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-white/30 mt-1",children:a===1?"Year":"Years"})]}),e.jsx("div",{className:"overflow-hidden mb-2",children:e.jsx(Yn.h1,{className:"text-5xl font-thin text-white/90 tracking-wide",initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.8,ease:[.16,1,.3,1]},children:f.title[0]})}),f.title[1]&&e.jsx("div",{className:"overflow-hidden mb-8",children:e.jsx(Yn.h2,{className:`text-5xl font-black bg-gradient-to-r ${g.accent} bg-clip-text text-transparent`,initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.95,ease:[.16,1,.3,1]},children:f.title[1]})}),e.jsxs(Yn.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(ka,{className:"h-3 w-3"})," ",r]})]}),e.jsxs(Yn.div,{className:"flex items-center justify-center gap-3 my-8",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2},children:[e.jsx(Yn.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(Yn.span,{className:"text-white/10 text-xs",animate:{rotate:[0,360]},transition:{duration:20,repeat:1/0,ease:"linear"},children:"✦"}),e.jsx(Yn.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(Yn.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"})]}),p&&e.jsx(Yn.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:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Yn.p,{className:"text-sm text-white/40 leading-relaxed max-w-xs mx-auto mb-10 font-light",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.4,duration:.8},children:i||f.defaultMessage}),e.jsxs(Yn.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(Yn.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/10 shadow-xl",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${g.accent} flex items-center justify-center shadow-xl`,children:e.jsx("span",{className:"text-sm font-bold text-slate-900",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-medium text-white/70",children:l}),u&&e.jsx("p",{className:"text-[11px] text-white/25",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[c&&e.jsxs(Yn.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${g.accent} text-xs font-semibold text-slate-900 shadow-lg`,whileHover:{scale:1.05,boxShadow:"0 10px 40px rgba(255,255,255,0.15)"},whileTap:{scale:.95},children:[e.jsx(Ar,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Yn.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(Vs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})}),e.jsx(Yn.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 ANt(){const{shareToken:s}=bi(),{data:t,isLoading:n,error:r}=ct({queryKey:["public-sendable-card",s],queryFn:async()=>{const{data:l,error:o}=await q.from("sendable_cards").select("*").eq("share_token",s).single();if(o)throw o;return l},enabled:!!s});if(N.useEffect(()=>{s&&q.rpc("log_sendable_card_view",{p_share_token:s}).then(({error:l})=>{l&&console.error("Error tracking view:",l)})},[s]),n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"animate-pulse space-y-4 text-center",children:[e.jsx("div",{className:"h-8 w-48 bg-muted rounded mx-auto"}),e.jsx("div",{className:"h-4 w-32 bg-muted rounded mx-auto"})]})});if(r||!t)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Card not found"}),e.jsx("p",{className:"text-muted-foreground",children:"This card may have been removed or the link is invalid."})]})});const a=t.home_anniversary_date?Math.floor((Date.now()-Cl(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(wnn,{...i});case"warm":return e.jsx(Nnn,{...i});case"glass":return e.jsx(knn,{...i});case"cinematic":return e.jsx(Snn,{...i});case"elegant":default:return e.jsx(_nn,{...i})}}function Cnn(){const s=ma();return ct({queryKey:["drip-settings",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("drip_settings").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function Tnn(){const s=ma(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r}=await q.from("drip_settings").select("id").eq("user_id",s).maybeSingle();if(r){const{data:a,error:i}=await q.from("drip_settings").update(n).eq("user_id",s).select().single();if(i)throw i;return a}else{const{data:a,error:i}=await q.from("drip_settings").insert({user_id:s,is_globally_enabled:n.is_globally_enabled??!1,append_signature:n.append_signature??!0}).select().single();if(i)throw i;return a}},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-settings"]})}})}function Enn(){const s=Mn(),{isGmailConnected:t,gmailEmail:n}=Oh(),{data:r,isLoading:a}=Cnn(),i=Tnn(),[l,o]=N.useState(!1),[c,d]=N.useState(!0),[u,h]=N.useState(!1);N.useEffect(()=>{r&&(o(r.is_globally_enabled),d(r.append_signature))},[r]);const p=async g=>{if(g&&!t){ae.error("Connect your Gmail account first before enabling Smart Drips");return}o(g);try{await i.mutateAsync({is_globally_enabled:g}),ae.success(g?"Smart Drips enabled globally":"Smart Drips paused globally")}catch{o(!g),ae.error("Failed to update settings")}},f=async g=>{d(g);try{await i.mutateAsync({append_signature:g}),ae.success(g?"Signature will be appended to drip emails":"Signature disabled for drip emails")}catch{d(!g),ae.error("Failed to update settings")}};return e.jsxs(bs,{open:u,onOpenChange:h,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(Xo,{className:"h-3.5 w-3.5"}),"Settings"]})}),e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Xo,{className:"h-5 w-5 text-primary"}),"Smart Drip Settings"]}),e.jsx(Qn,{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(Vs,{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(ze,{variant:"outline",className:"gap-1 text-emerald-600 border-emerald-200 bg-emerald-500/10 text-[10px]",children:[e.jsx(xr,{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(ll,{}),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(b9,{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(bn,{checked:l,onCheckedChange:p,disabled:a||i.isPending})]}),e.jsx(ll,{}),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(wv,{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(bn,{checked:c,onCheckedChange:f,disabled:a||i.isPending})]}),c&&e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>{h(!1),s("/profile")},children:[e.jsx(wv,{className:"h-3 w-3 mr-1"}),"Edit your email signature in Profile settings"]})]})]})]})}function Ann(){const s=ma();return ct({queryKey:["drip-templates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_templates").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Mnn(){const s=ma();return ct({queryKey:["drip-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Inn(){const s=ma(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("drip_templates").insert({owner_user_id:s,stage_id:n.stage_id,title:n.title||"",subject:n.subject||"",body:n.body||"",video_url:n.video_url||null,channel:n.channel||"email",delay_type:n.delay_type||"instant",delay_minutes:n.delay_minutes||0,is_enabled:!1,deal_type:n.deal_type||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}function Pnn(){const s=Ht();return gt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("drip_templates").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function Lnn(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("drip_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function Dnn(){const s=ma(),t=Ht();return gt({mutationFn:async({templateId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("drip_templates").select("*").eq("id",n).single();if(i)throw i;const{data:l,error:o}=await q.from("drip_templates").insert({owner_user_id:s,stage_id:r,title:a.title,subject:a.subject,body:a.body,video_url:a.video_url,channel:a.channel,delay_type:a.delay_type,delay_minutes:a.delay_minutes,is_enabled:!1,is_starter:!1,deal_type:a.deal_type}).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}const Rnn=[{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 Onn({open:s,onOpenChange:t,campaignId:n,campaignName:r}){const{data:a,isLoading:i}=bGs(n||void 0),l=wGs(),o=R_t(),c=async(h,p)=>{try{await l.mutateAsync({id:h,status:p}),ae.success(`Enrollment ${p}`)}catch{ae.error("Failed to update")}},d=async h=>{if(n)try{const p=await o.mutateAsync({campaignId:n,contactIds:[h]});p.enrolled>0?ae.success("Contact re-enrolled — first email queued"):p.skipped>0?ae.message("Already active in this campaign"):ae.error("Could not re-enroll")}catch{ae.error("Failed to re-enroll")}},u=h=>{const p={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(ze,{variant:"outline",className:`text-[10px] capitalize ${p[h]||""}`,children:h})};return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsxs("div",{className:"p-5 border-b shrink-0",children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"}),"Enrollments — ",r||"Campaign"]}),e.jsx(Qn,{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(Ws,{className:"h-14"},h))}):!a||a.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Nn,{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 p,f,g,_;return e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg bg-card",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(p=h.contact)==null?void 0:p.first_name," ",(f=h.contact)==null?void 0:f.last_name]}),u(h.status)]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[((g=h.contact)==null?void 0:g.email)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vs,{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: ",Ss(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(bf,{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(Al,{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(Bn,{className:"h-3.5 w-3.5 text-destructive"})}),(h.status==="exited"||h.status==="completed")&&((_=h.contact)==null?void 0:_.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(cm,{className:"h-3 w-3"}),"Re-enroll"]})]},h.id)})})})})]})})}function Fnn(){var S;const{data:s,isLoading:t}=P1e(),{hasLeadSite:n}=Ip(),r=L_t(),a=xGs(),i=P_t(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(null),[p,f]=N.useState(null),g=(s||[]).filter(A=>!A.is_starter),_=(s||[]).filter(A=>A.is_starter).filter(A=>!A.requires_lead_site||n),v=async A=>{try{await r.mutateAsync(A),ae.success("Campaign added to your library — customize and activate it!"),o(null)}catch(T){ae.error(T.message||"Failed to copy campaign")}},j=async A=>{try{await i.mutateAsync({id:A.id,is_active:!A.is_active}),ae.success(A.is_active?"Campaign paused":"Campaign activated")}catch{ae.error("Failed to update")}},b=async A=>{if(confirm("Delete this campaign? Active enrollments will be removed."))try{await a.mutateAsync(A),ae.success("Campaign deleted")}catch{ae.error("Failed to delete")}};return t?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(A=>e.jsx(Ws,{className:"h-44 rounded-xl"},A))}):e.jsxs("div",{className:"space-y-8",children:[e.jsx("div",{className:"rounded-xl border bg-gradient-to-br from-primary/5 via-background to-background p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(yw,{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(Oc,{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(cr,{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(Nn,{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(Is,{className:"h-3.5 w-3.5 mr-1.5"})," New Campaign"]})]}),g.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl bg-muted/20",children:[e.jsx(un,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold mb-1",children:"No custom campaigns yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Build one from scratch or clone a starter from the library below."}),e.jsxs(B,{size:"sm",onClick:()=>{h(null),d(!0)},children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"})," Create your first campaign"]})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:g.map(A=>e.jsx(znn,{campaign:A,onPreview:()=>o(A.id),onToggleActive:()=>j(A),onDelete:()=>b(A.id),onEdit:()=>{h(A.id),d(!0)},onViewEnrollments:()=>f(A.id)},A.id))})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-amber-500"}),"Starter Library"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Premium, ready-to-go campaigns crafted for real estate. One-click copy."})]}),e.jsxs(ze,{variant:"outline",className:"text-[10px]",children:[_.length," templates"]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:_.map(A=>e.jsx(Bnn,{campaign:A,onPreview:()=>o(A.id)},A.id))})]}),e.jsx($nn,{campaignId:l,open:!!l,onOpenChange:A=>!A&&o(null),onClone:v,isCloning:r.isPending,onEdit:A=>{o(null),h(A),d(!0)}}),e.jsx(z_t,{open:c,onOpenChange:d,campaignId:u}),e.jsx(Onn,{open:!!p,onOpenChange:A=>!A&&f(null),campaignId:p,campaignName:(S=g.find(A=>A.id===p))==null?void 0:S.name})]})}function znn({campaign:s,onPreview:t,onToggleActive:n,onDelete:r,onEdit:a,onViewEnrollments:i}){const o=_Gs(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(ze,{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(ze,{variant:"outline",className:"text-[9px] mt-2",children:L1e[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($l,{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(_a,{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 Bnn({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(ze,{className:"absolute top-2 right-2 bg-white/90 text-foreground hover:bg-white text-[10px]",children:[e.jsx(un,{className:"h-2.5 w-2.5 mr-0.5"})," Starter"]})]}),e.jsxs("div",{className:"p-3.5",children:[e.jsx("h3",{className:"font-semibold text-sm",children:s.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1 min-h-[2rem]",children:s.description}),e.jsx(ze,{variant:"outline",className:"text-[9px] mt-2",children:L1e[s.category]})]})]})}function $nn({campaignId:s,open:t,onOpenChange:n,onClone:r,isCloning:a,onEdit:i}){const{data:l}=P1e(),{data:o}=D_t(s||void 0),[c,d]=N.useState(new Set),u=l==null?void 0:l.find(f=>f.id===s);if(!u)return null;const h=f=>{d(g=>{const _=new Set(g);return _.has(f)?_.delete(f):_.add(f),_})},p=(f,g)=>{if(f.delay_type==="calendar_anchor"){const v=f.anchor_field==="birthday"?"birthday":"home anniversary",j=f.anchor_offset_days||0;return j===0?`On their ${v}`:j<0?`${Math.abs(j)} days before ${v}`:`${j} days after ${v}`}if(g===0&&f.delay_days===0&&f.delay_hours===0)return"Sends immediately";const _=[];return f.delay_days&&_.push(`${f.delay_days}d`),f.delay_hours&&_.push(`${f.delay_hours}h`),g===0?`After ${_.join(" ")}`:`+${_.join(" ")}`};return e.jsx(bs,{open:t,onOpenChange:n,children:e.jsxs(vs,{className:"max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${u.cover_color} p-6 text-white shrink-0`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("span",{className:"text-5xl drop-shadow-sm",children:u.icon}),e.jsxs("div",{className:"flex-1",children:[e.jsx(_s,{className:"text-xl font-bold text-white",children:u.name}),e.jsx(Qn,{className:"text-white/90 mt-1",children:u.description}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx(ze,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:L1e[u.category]}),e.jsxs(ze,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:[(o==null?void 0:o.length)||0," step",(o==null?void 0:o.length)!==1?"s":""]})]})]})]})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsxs("div",{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"The sequence"}),u.is_starter?e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Copy to your library to edit"}):e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Tap a step to expand · Edit to customize"})]}),o==null?void 0:o.map((f,g)=>{const _=c.has(f.id);return e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"shrink-0 flex flex-col items-center",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:g+1}),gh(f.id),className:"flex-1 pb-4 text-left",children:e.jsxs("div",{className:"border rounded-lg p-3 bg-muted/20 hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5 text-xs text-muted-foreground",children:[f.delay_type==="calendar_anchor"?e.jsx(yr,{className:"h-3 w-3"}):e.jsx(gr,{className:"h-3 w-3"}),e.jsx("span",{children:p(f,g)}),e.jsx("span",{children:"·"}),e.jsx(Vs,{className:"h-3 w-3"}),e.jsx("span",{className:"capitalize",children:f.channel})]}),e.jsx("p",{className:"font-medium text-sm",children:f.subject}),(()=>{const v=f.body||"",j=/<\/?[a-z][\s\S]*>/i.test(v),b=j?v.replace(//gi,"").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+/g," ").trim():v;return _?j?e.jsx("div",{className:"text-xs text-foreground mt-2 prose prose-sm max-w-none [&_a]:text-primary",dangerouslySetInnerHTML:{__html:v}}):e.jsx("p",{className:"text-xs text-muted-foreground mt-2 whitespace-pre-line",children:v}):e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:b})})(),f.body&&f.body.length>160&&e.jsx("span",{className:"text-[10px] text-primary mt-1.5 inline-block",children:_?"Show less":"Show full email"})]})})]},f.id)})]})}),e.jsxs(Xn,{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(_a,{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(ts,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy to my campaigns"]})]})]})})}const lpe=[{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 Unn(){const s=ma();return ct({queryKey:["drip-auto-rules",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_auto_enroll_rules").select("*, campaign:drip_campaigns(id, name, category, cover_color)").eq("owner_user_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function qnn(){const s=ma(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={owner_user_id:s,campaign_id:n.campaign_id,trigger_type:n.trigger_type,lead_days:n.lead_days??14,filter_tags:n.filter_tags??[],filter_relationship_types:n.filter_relationship_types??[],require_email:n.require_email??!0,is_active:n.is_active??!0};n.id&&(r.id=n.id);const{data:a,error:i}=await q.from("drip_auto_enroll_rules").upsert(r).select().single();if(i)throw i;return a},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-auto-rules"]})}})}function Vnn(){const s=Ht();return gt({mutationFn:async({id:t,is_active:n})=>{const{error:r}=await q.from("drip_auto_enroll_rules").update({is_active:n}).eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["drip-auto-rules"]})})}function Hnn(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("drip_auto_enroll_rules").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-auto-rules"]})})}function Gnn(s=25){const t=ma();return ct({queryKey:["drip-auto-log",t,s],queryFn:async()=>{if(!t)return[];const{data:n,error:r}=await q.from("drip_auto_enroll_log").select("*, contact:innercircle_contacts(id, first_name, last_name, email)").eq("owner_user_id",t).order("created_at",{ascending:!1}).limit(s);if(r)throw r;return n||[]},enabled:!!t})}function Wnn(){const s=ma();return ct({queryKey:["life-event-coverage",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("innercircle_contacts").select("birthday, home_anniversary, spouse_birthday, wedding_anniversary, email").eq("owner_user_id",s).limit(1e4);if(n)throw n;const r=t||[],a=(l,o)=>{if(!l)return!1;const[,c,d]=String(l).split("-").map(Number),u=new Date;let h=new Date(u.getFullYear(),c-1,d);return h{const o=r.filter(c=>!!c[l.column]);i[l.value]={total:o.length,upcoming30:o.filter(c=>a(c[l.column],30)).length}}),{totalContacts:r.length,counts:i}},enabled:!!s})}function Knn(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("process-life-event-drips",{body:t?{rule_id:t}:{}});if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-auto-rules"]}),s.invalidateQueries({queryKey:["drip-auto-log"]}),s.invalidateQueries({queryKey:["drip-campaign-enrollments"]})}})}const Ynn={birthday:cu,home_anniversary:hb,spouse_birthday:Oi,wedding_anniversary:gi};function Znn(){var A;const{data:s,isLoading:t}=Unn(),{data:n}=P1e(),{data:r}=Wnn(),{data:a}=Gnn(10),i=qnn(),l=Vnn(),o=Hnn(),c=Knn(),d=L_t(),[u,h]=N.useState(null),p=N.useMemo(()=>(n||[]).filter(T=>!T.is_starter),[n]),f={birthday:"Birthday",home_anniversary:"Home Anniversary",spouse_birthday:"Spouse Birthday",wedding_anniversary:"Wedding Anniversary"},g=N.useMemo(()=>{if(!(u!=null&&u.trigger_type))return null;const T=f[u.trigger_type];return!T||p.some(D=>String(D.name||"").toLowerCase().includes(T.toLowerCase()))?null:(n||[]).find(D=>D.is_starter&&String(D.name||"").toLowerCase()===T.toLowerCase())??null},[n,p,u==null?void 0:u.trigger_type]),_=async()=>{if(g)try{const T=await d.mutateAsync(g.id);h(L=>({...L,campaign_id:T.id})),ae.success(`“${g.name}” template added to your campaigns`)}catch(T){ae.error((T==null?void 0:T.message)||"Could not copy the template")}},v=T=>(s||[]).find(L=>L.trigger_type===T),j=async()=>{if(!(u!=null&&u.campaign_id)||!(u!=null&&u.trigger_type)){ae.error("Pick a campaign first");return}try{await i.mutateAsync(u),ae.success("Autopilot rule saved"),h(null)}catch(T){ae.error((T==null?void 0:T.message)||"Could not save rule")}},b=async()=>{try{const T=await c.mutateAsync(void 0);ae.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){ae.error((T==null?void 0:T.message)||"Autopilot run failed")}},S=(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(un,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold leading-tight",children:"Life Event Autopilot"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-xl",children:"Every morning we scan your database for upcoming birthdays and anniversaries and quietly enroll those contacts in the campaign you choose. You never miss a moment again."})]})]}),e.jsxs(B,{variant:"outline",onClick:b,disabled:c.isPending||S===0,className:"gap-2 shrink-0",children:[c.isPending?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(Ti,{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:lpe.map(T=>{const L=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:(L==null?void 0:L.total)??0}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[(L==null?void 0:L.upcoming30)??0," in next 30 days"]})]},T.value)})})]}),t?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(ts,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:lpe.map(T=>{var F;const L=v(T.value),D=Ynn[T.value]||cu,M=r==null?void 0:r.counts[T.value];return e.jsxs("div",{className:Et("rounded-xl border bg-card p-4 transition-colors",(L==null?void 0:L.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",L!=null&&L.is_active?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(D,{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}),(L==null?void 0:L.is_active)&&e.jsx(ze,{className:"text-[10px] bg-primary/10 text-primary hover:bg-primary/10",children:"On"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:L?`${((F=L.campaign)==null?void 0:F.name)??"Campaign"} · starts ${L.lead_days} days before`:T.description}),L&&L.total_enrolled>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:[L.total_enrolled," contact",L.total_enrolled===1?"":"s"," enrolled so far"]}),!L&&((M==null?void 0:M.total)??0)===0&&e.jsx("p",{className:"text-[11px] text-amber-600 dark:text-amber-400 mt-1",children:"No contacts have this date on file yet."})]}),L?e.jsx(bn,{checked:L.is_active,onCheckedChange:z=>l.mutate({id:L.id,is_active:z})}):null]}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(B,{size:"sm",variant:L?"outline":"default",className:"flex-1 gap-1.5",onClick:()=>h(L??{trigger_type:T.value,lead_days:T.value==="birthday"?7:14,require_email:!0,is_active:!0,filter_tags:[],filter_relationship_types:[]}),children:[L?e.jsx(hh,{className:"h-3.5 w-3.5"}):e.jsx(Is,{className:"h-3.5 w-3.5"}),L?"Edit rule":"Turn on autopilot"]}),L&&e.jsx(B,{size:"sm",variant:"ghost",className:"text-muted-foreground hover:text-destructive",onClick:()=>o.mutate(L.id),children:e.jsx(_n,{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 L,D;return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5",children:[e.jsx(Ir,{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:[(L=T.contact)==null?void 0:L.first_name," ",(D=T.contact)==null?void 0:D.last_name]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[String(T.trigger_type).replace(/_/g," ")," · ",T.note]})]}),e.jsx("span",{className:"text-[11px] text-muted-foreground shrink-0",children:new Date(T.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})})]},T.id)})})]}),e.jsx(bs,{open:!!u,onOpenChange:T=>!T&&h(null),children:e.jsxs(vs,{className:"sm:max-w-md",children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:[(A=lpe.find(T=>T.value===(u==null?void 0:u.trigger_type)))==null?void 0:A.label," autopilot"]}),e.jsx(Qn,{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(ds,{value:(u==null?void 0:u.campaign_id)??"",onValueChange:T=>h(L=>({...L,campaign_id:T})),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select one of your campaigns"})}),e.jsx(cs,{children:p.map(T=>e.jsx(Qe,{value:T.id,children:T.name},T.id))})]}),g&&e.jsx("div",{className:"rounded-lg border border-primary/25 bg-primary/5 p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(un,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium leading-tight",children:["Use the LevelUp “",g.name,"” template"]}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Beautifully designed, personalized emails written for this moment. We'll copy it into your campaigns so you can edit anything you like."}),e.jsxs(B,{size:"sm",variant:"outline",className:"mt-2 gap-1.5",disabled:d.isPending,onClick:_,children:[d.isPending?e.jsx(ts,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Is,{className:"h-3.5 w-3.5"}),"Use this template"]})]})]})}),p.length===0&&!g&&e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:"You need one of your own campaigns first — clone a starter from the Campaigns tab."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(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(Bm,{min:0,max:45,step:1,value:[(u==null?void 0:u.lead_days)??14],onValueChange:([T])=>h(L=>({...L,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(bn,{checked:(u==null?void 0:u.require_email)??!0,onCheckedChange:T=>h(L=>({...L,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(bn,{checked:(u==null?void 0:u.is_active)??!0,onCheckedChange:T=>h(L=>({...L,is_active:T}))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>h(null),children:"Cancel"}),e.jsxs(B,{onClick:j,disabled:i.isPending||!(u!=null&&u.campaign_id),children:[i.isPending&&e.jsx(ts,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save rule"]})]})]})})]})}function Qnn(){const s=ma(),t=Mn(),{isGmailConnected:n,gmailEmail:r,isLoading:a}=Oh(),{data:i,isLoading:l}=Ann(),{data:o,isLoading:c}=Mnn(),d=Inn(),u=Pnn(),h=Lnn(),p=Dnn(),[f,g]=N.useState(null),[_,v]=N.useState(null),j=(i==null?void 0:i.filter(F=>!F.is_starter&&F.owner_user_id===s))||[],b=(i==null?void 0:i.filter(F=>F.is_starter))||[],S=F=>j.filter(z=>z.stage_id===F),A=async F=>{try{await u.mutateAsync({id:F.id,is_enabled:!F.is_enabled}),ae.success(F.is_enabled?"Drip disabled":"Drip enabled")}catch{ae.error("Failed to update")}},T=async F=>{try{const z=o==null?void 0:o.find(V=>V.id===F);await d.mutateAsync({stage_id:F,title:`${(z==null?void 0:z.name)||"Stage"} follow-up`,subject:"",body:"",channel:"email",delay_type:"instant",delay_minutes:0}),g(F),ae.success("Drip template created")}catch{ae.error("Failed to create template")}},L=async F=>{try{await h.mutateAsync(F),ae.success("Template deleted")}catch{ae.error("Failed to delete")}},D=async F=>{if(!o||o.length===0){ae.error("No pipeline stages found");return}const z=o[0].id;try{await p.mutateAsync({templateId:F,stageId:z}),ae.success("Template copied to your drips!")}catch{ae.error("Failed to copy template")}},M=l||c;return e.jsx(Ts,{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(hh,{className:"h-5 w-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"Smart Drips"}),e.jsx(ze,{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(Enn,{})]}),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(yw,{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(Vs,{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(yw,{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(Vs,{className:"h-3 w-3 mr-1.5"}),"Connect Gmail"]})]})]})),e.jsxs(Br,{defaultValue:"my-drips",children:[e.jsxs(Fr,{className:"grid grid-cols-4 w-full max-w-2xl mb-6",children:[e.jsx(Kt,{value:"my-drips",children:"Stage Drips"}),e.jsxs(Kt,{value:"campaigns",children:["Campaigns",e.jsx(ze,{variant:"outline",className:"ml-1.5 text-[9px] bg-amber-500/10 text-amber-600 border-amber-200 px-1 py-0",children:"New"})]}),e.jsxs(Kt,{value:"autopilot",children:["Life Events",e.jsx(ze,{variant:"outline",className:"ml-1.5 text-[9px] bg-primary/10 text-primary border-primary/20 px-1 py-0",children:"Auto"})]}),e.jsxs(Kt,{value:"starters",children:["Stage Starters",b.length>0&&e.jsx(ze,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0",children:b.length})]})]}),e.jsx(is,{value:"campaigns",children:e.jsx(Fnn,{})}),e.jsx(is,{value:"autopilot",children:e.jsx(Znn,{})}),e.jsx(is,{value:"my-drips",children:M?e.jsx("div",{className:"space-y-3",children:[1,2,3,4].map(F=>e.jsx(Ws,{className:"h-16 w-full rounded-xl"},F))}):!o||o.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(hh,{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(F=>!F.is_won_stage&&!F.is_lost_stage).map(F=>{const z=S(F.id),V=f===F.id,W=z.some(Y=>Y.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>g(V?null:F.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:F.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:F.name}),z.length>0&&e.jsxs(ze,{variant:"outline",className:`text-[10px] ${W?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[z.length," drip",z.length!==1?"s":"",W&&" · Active"]}),V?e.jsx(io,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(xa,{className:"h-4 w-4 text-muted-foreground"})]}),V&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:z.length===0?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No drip set for this stage"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>T(F.id),disabled:d.isPending,children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"}),"Create Drip"]})]}):e.jsxs(e.Fragment,{children:[z.map(Y=>e.jsx(YXe,{template:Y,isEditing:_===Y.id,onToggleEdit:()=>v(_===Y.id?null:Y.id),onToggleEnabled:()=>A(Y),onUpdate:K=>u.mutateAsync({id:Y.id,...K}),onDelete:()=>L(Y.id),userId:s||""},Y.id)),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>T(F.id),children:[e.jsx(Is,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},F.id)}),o.filter(F=>F.is_won_stage||F.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(F=>F.is_won_stage||F.is_lost_stage).map(F=>{const z=S(F.id),V=f===F.id,W=z.some(Y=>Y.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden mb-2",children:[e.jsxs("button",{onClick:()=>g(V?null:F.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:F.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:F.name}),z.length>0&&e.jsxs(ze,{variant:"outline",className:`text-[10px] ${W?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[z.length," drip",z.length!==1?"s":"",W&&" · Active"]}),V?e.jsx(io,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(xa,{className:"h-4 w-4 text-muted-foreground"})]}),V&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:z.length===0?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No drip set for this stage"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>T(F.id),disabled:d.isPending,children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"})," Create Drip"]})]}):e.jsxs(e.Fragment,{children:[z.map(Y=>e.jsx(YXe,{template:Y,isEditing:_===Y.id,onToggleEdit:()=>v(_===Y.id?null:Y.id),onToggleEnabled:()=>A(Y),onUpdate:K=>u.mutateAsync({id:Y.id,...K}),onDelete:()=>L(Y.id),userId:s||""},Y.id)),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>T(F.id),children:[e.jsx(Is,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},F.id)})]})]})}),e.jsx(is,{value:"starters",children:b.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(un,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No Starter Templates Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"Admin-created starter templates will appear here. You'll be able to copy them into your own drips."})]}):e.jsx("div",{className:"space-y-3",children:b.map(F=>e.jsx(Xnn,{template:F,onCopy:()=>D(F.id),isCopying:p.isPending},F.id))})})]})]})})}function YXe({template:s,isEditing:t,onToggleEdit:n,onToggleEnabled:r,onUpdate:a,onDelete:i,userId:l}){const[o,c]=N.useState(s.title),[d,u]=N.useState(s.subject),[h,p]=N.useState(s.body),[f,g]=N.useState(s.video_url||""),[_,v]=N.useState(s.channel),[j,b]=N.useState(s.delay_type),[S,A]=N.useState(s.delay_minutes),[T,L]=N.useState(!1),D=async()=>{L(!0);try{await a({title:o,subject:d,body:h,video_url:f||null,channel:_,delay_type:j,delay_minutes:S}),ae.success("Drip saved"),n()}catch{ae.error("Failed to save")}finally{L(!1)}},M=F=>{p(z=>z+F)};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(Ei,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Vs,{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(br,{className:"h-3 w-3 text-primary"})]})]}),e.jsx(bn,{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:F=>c(F.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(F=>e.jsxs("button",{onClick:()=>v(F),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 ${_===F?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[F==="sms"?e.jsx(Ei,{className:"h-3 w-3"}):e.jsx(Vs,{className:"h-3 w-3"}),F==="sms"?"SMS":"Email"]},F))})]}),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:()=>b("instant"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${j==="instant"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:"Instant"}),e.jsxs("button",{onClick:()=>b("scheduled"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${j==="scheduled"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[e.jsx(gr,{className:"h-3 w-3 mr-1 inline"}),"Delay"]})]})]})]}),j==="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:S>=60?Math.round(S/60):S,onChange:F=>{const z=parseInt(F.target.value)||0;A(S>=60?z*60:z)},className:"h-8 w-20 text-sm"}),e.jsx("div",{className:"flex gap-1",children:[{label:"Minutes",mins:S<60?S:30},{label:"Hours",mins:S>=60?S:60},{label:"Days",mins:S>=1440?S:1440}].map(F=>e.jsx("button",{className:`px-2 py-1 rounded text-xs border transition-colors ${F.label==="Minutes"&&S<60||F.label==="Hours"&&S>=60&&S<1440||F.label==="Days"&&S>=1440?"bg-primary/10 text-primary border-primary/30":"text-muted-foreground border-input"}`,onClick:()=>{F.label==="Minutes"?A(30):F.label==="Hours"?A(60):A(1440)},children:F.label},F.label))})]})]}),_==="email"&&e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium",children:"Subject Line"}),e.jsx(ye,{value:d,onChange:F=>u(F.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:_==="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:F=>{F.target.value&&M(F.target.value),F.target.value=""},children:[e.jsx("option",{value:"",children:"Merge variable..."}),Rnn.map(F=>e.jsx("option",{value:F.key,children:F.label},F.key))]})]})]}),e.jsx("textarea",{value:h,onChange:F=>p(F.target.value),placeholder:_==="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"}),f?e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsxs("div",{className:"flex-1 text-xs text-muted-foreground truncate bg-muted/50 rounded px-2 py-1.5 border border-input",children:[e.jsx(br,{className:"h-3 w-3 inline mr-1 text-primary"}),f.length>50?f.slice(0,50)+"...":f]}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>g(""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(b8e,{onVideoReady:F=>g(F)}),e.jsx(a6,{userId:l,onSelect:F=>g(F),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 F=prompt("Paste a YouTube or Loom URL:");F&&g(F)},children:[e.jsx(Jo,{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(_n,{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:D,disabled:T,children:T?"Saving...":"Save Drip"})]})]})]})]})}function Xnn({template:s,onCopy:t,isCopying:n}){const[r,a]=N.useState(!1),i=s.body.replace(/<[^>]+>/g,""),l=s.deal_type==="buyer"?"Buyer":s.deal_type==="seller"?"Seller":null,o=s.delay_type==="instant"?"Sends instantly":s.delay_minutes>=1440?`Sends after ${Math.round(s.delay_minutes/1440)} day${Math.round(s.delay_minutes/1440)!==1?"s":""}`:s.delay_minutes>=60?`Sends after ${Math.round(s.delay_minutes/60)} hour${Math.round(s.delay_minutes/60)!==1?"s":""}`:`Sends after ${s.delay_minutes} min`;return e.jsxs("div",{className:"border rounded-xl overflow-hidden transition-all hover:shadow-sm",children:[e.jsxs("button",{onClick:()=>a(!r),className:"w-full flex items-start gap-3 p-4 text-left hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium text-sm",children:s.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:s.subject}),!r&&e.jsx("p",{className:"text-xs text-muted-foreground/70 line-clamp-1 mt-1",children:i})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",children:[l&&e.jsx(ze,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:l}),e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1",children:[s.channel==="sms"?e.jsx(Ei,{className:"h-3 w-3"}):e.jsx(Vs,{className:"h-3 w-3"}),s.channel==="sms"?"SMS":"Email"]}),e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(gr,{className:"h-3 w-3"}),s.delay_type==="instant"?"Instant":o.replace("Sends ","")]}),r?e.jsx(io,{className:"h-4 w-4 text-muted-foreground ml-1"}):e.jsx(xa,{className:"h-4 w-4 text-muted-foreground ml-1"})]})]}),r&&e.jsxs("div",{className:"border-t bg-muted/10 p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase font-semibold text-muted-foreground tracking-wider mb-1",children:"Subject Line"}),e.jsx("p",{className:"text-sm font-medium",children:s.subject})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase font-semibold text-muted-foreground tracking-wider mb-1",children:"Email Body"}),e.jsx("div",{className:"text-sm text-foreground/80 bg-background rounded-lg border p-4 prose prose-sm max-w-none [&_ul]:list-disc [&_ul]:pl-5 [&_ol]:list-decimal [&_ol]:pl-5 [&_li]:my-0.5 [&_p]:my-2 [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:s.body}})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(gr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:o})]}),e.jsxs(B,{onClick:c=>{c.stopPropagation(),t()},size:"sm",className:"w-full gap-1.5",disabled:n,children:[e.jsx(Xr,{className:"h-3.5 w-3.5"}),"Use This Template"]})]})]})}const MNt=()=>{const s=Jl();return N.useEffect(()=>{console.error("404 Error: User attempted to access non-existent route:",s.pathname)},[s.pathname]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-100",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"mb-4 text-4xl font-bold",children:"404"}),e.jsx("p",{className:"mb-4 text-xl text-gray-600",children:"Oops! Page not found"}),e.jsx("a",{href:"/",className:"text-blue-500 underline hover:text-blue-700",children:"Return to Home"})]})})};function Jnn(){return N.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),e.jsxs(efe,{children:[e.jsx(as,{path:"/c/:shareToken",element:e.jsx(ANt,{})}),e.jsx(as,{path:"*",element:e.jsx(MNt,{})})]})}const YNe={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function INt({slugOverride:s}){const t=bi(),n=s||t.slug,[r,a]=N.useState("types"),[i,l]=N.useState(null),[o,c]=N.useState(null),[d,u]=N.useState(null),[h,p]=N.useState(new Date),[f,g]=N.useState({name:"",email:"",phone:"",message:""}),[_,v]=N.useState(!1),{data:j,isLoading:b}=ct({queryKey:["public-booking-settings",n],queryFn:async()=>{const{data:K,error:J}=await q.from("agent_booking_settings").select("*").eq("slug",n).eq("is_active",!0).single();if(J)throw J;return K},enabled:!!n}),{data:S}=ct({queryKey:["public-booking-profile",j==null?void 0:j.user_id],queryFn:async()=>{const{data:K,error:J}=await q.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",j.user_id).single();if(J)throw J;return K},enabled:!!(j!=null&&j.user_id)}),{data:A=[]}=ct({queryKey:["public-booking-types",j==null?void 0:j.user_id],queryFn:async()=>{const{data:K,error:J}=await q.from("agent_booking_types").select("id, name, description, duration_minutes, color, icon, qualification_enabled").eq("user_id",j.user_id).eq("is_active",!0).order("sort_order");if(J)throw J;return K},enabled:!!(j!=null&&j.user_id)}),{data:T=[]}=ct({queryKey:["public-availability",j==null?void 0:j.user_id],queryFn:async()=>{const{data:K,error:J}=await q.from("agent_availability_slots").select("day_of_week, start_time, end_time").eq("user_id",j.user_id).eq("is_active",!0);if(J)throw J;return K},enabled:!!(j!=null&&j.user_id)}),{data:L=[]}=ct({queryKey:["public-blocked-dates",j==null?void 0:j.user_id],queryFn:async()=>{const{data:K,error:J}=await q.from("agent_blocked_dates").select("blocked_date").eq("user_id",j.user_id);if(J)throw J;return K.map(ne=>ne.blocked_date)},enabled:!!(j!=null&&j.user_id)}),{data:D=[]}=ct({queryKey:["public-existing-bookings",j==null?void 0:j.user_id,o],queryFn:async()=>{if(!o)return[];const K=Ss(o,"yyyy-MM-dd"),{data:J,error:ne}=await q.from("bookings").select("start_time, end_time").eq("agent_user_id",j.user_id).eq("booking_date",K).eq("status","confirmed");if(ne)throw ne;return J},enabled:!!(j!=null&&j.user_id)&&!!o}),M=N.useMemo(()=>[...new Set(T.map(K=>K.day_of_week))],[T]),F=K=>{const J=kf(new Date),ne=Bl(J,(j==null?void 0:j.max_advance_days)||30),ie=Bl(J,0);return wb(K,ie)||Bv(K,ne)||L.includes(Ss(K,"yyyy-MM-dd"))?!1:M.includes(K.getDay())},z=N.useMemo(()=>{if(!o||!i||!j)return[];const K=T.filter(pe=>pe.day_of_week===o.getDay()),J=i.duration_minutes,ne=j.buffer_minutes||0,ie=[],he=new Date,ce=(j.min_notice_hours||2)*60*60*1e3;for(const pe of K){const[le,ve]=pe.start_time.split(":").map(Number),[ge,Te]=pe.end_time.split(":").map(Number);let Me=K9(W9(o,le),ve);const Ce=K9(W9(o,ge),Te);for(;kP(Me,J)<=Ce;){const Ae=Ss(Me,"HH:mm"),De=Ss(kP(Me,J),"HH:mm");Me.getTime()-he.getTime()>=ce&&(D.some(Fe=>{const qe=Fe.start_time.slice(0,5),be=Fe.end_time.slice(0,5);return Aeqe})||ie.push(Ae)),Me=kP(Me,J+ne)}}return ie},[o,i,T,j,D]),V=N.useMemo(()=>{const K=h.getFullYear(),J=h.getMonth(),ne=new Date(K,J,1),ie=new Date(K,J+1,0),he=ne.getDay(),ce=[];for(let pe=0;pe{if(!(!i||!o||!d||!f.name||!j)){v(!0);try{const K=Ss(kP(K9(W9(new Date,parseInt(d.split(":")[0])),parseInt(d.split(":")[1])),i.duration_minutes),"HH:mm"),{error:J}=await q.from("bookings").insert({agent_user_id:j.user_id,booking_type_id:i.id,booking_date:Ss(o,"yyyy-MM-dd"),start_time:d,end_time:K,guest_name:f.name,guest_email:f.email||null,guest_phone:f.phone||null,guest_message:f.message||null});if(J)throw J;q.functions.invoke("booking-notify",{body:{agentUserId:j.user_id,guestName:f.name,guestEmail:f.email||null,guestPhone:f.phone||null,guestMessage:f.message||null,bookingTypeName:i.name,bookingDate:Ss(o,"yyyy-MM-dd"),startTime:d,endTime:K,durationMinutes:i.duration_minutes,meetingLink:j.meeting_link||null}}).catch(ne=>console.error("Booking notify error:",ne)),a("confirmed")}catch(K){ae.error("Failed to book: "+K.message)}finally{v(!1)}}},Y=K=>{const[J,ne]=K.split(":").map(Number),ie=J>=12?"PM":"AM";return`${J%12||12}:${ne.toString().padStart(2,"0")} ${ie}`};return b?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[#406E71] border-t-transparent"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading booking page..."})]})}):j?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:[S!=null&&S.avatar_url?e.jsx("img",{src:S.avatar_url,alt:(S==null?void 0:S.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(Xi,{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:(S==null?void 0:S.name)||"Agent"}),(S==null?void 0:S.title)&&e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:S.title})]})]})}),e.jsxs("div",{className:"px-6 py-4 flex flex-wrap gap-2",children:[(S==null?void 0:S.phone)&&e.jsxs("a",{href:`tel:${S.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(Ar,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:S.phone}),e.jsx("span",{className:"sm:hidden",children:"Call"})]}),(S==null?void 0:S.email)&&e.jsxs("a",{href:`mailto:${S.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(Vs,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:S.email}),e.jsx("span",{className:"sm:hidden",children:"Email"})]})]})]}),e.jsx("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden",children:e.jsxs("div",{className:"p-5 sm:p-6",children:[r==="types"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Select a meeting type"}),e.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:"Choose the type of meeting you'd like to schedule"})]}),e.jsx("div",{className:"space-y-2.5",children:A.map(K=>e.jsx("button",{onClick:()=>{l(K),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:K.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:YNe[K.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:K.name}),K.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:K.description})]})]}),e.jsxs("div",{className:"shrink-0 flex items-center gap-1 px-2.5 py-1 rounded-full bg-slate-100 text-slate-600 text-xs font-medium",children:[e.jsx(gr,{className:"h-3 w-3"}),K.duration_minutes,"m"]})]})})},K.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(Hr,{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:YNe[i.icon]||"📅"}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("p",{className:"font-semibold text-sm text-slate-800",children:i.name})}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-slate-500 font-medium",children:[e.jsx(gr,{className:"h-3 w-3"}),i.duration_minutes," min"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Ss(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:()=>p(new Date(h.getFullYear(),h.getMonth()-1)),children:e.jsx(pl,{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:()=>p(new Date(h.getFullYear(),h.getMonth()+1)),children:e.jsx(xa,{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(K=>e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400 font-semibold py-2",children:K},K)),V.map((K,J)=>{if(!K)return e.jsx("div",{},`pad-${J}`);const ne=F(K),ie=o&&Vl(K,o),he=Vl(K,new Date);return e.jsx("button",{disabled:!ne,onClick:()=>{c(K),u(null)},className:`h-10 w-10 mx-auto rounded-xl text-sm font-medium transition-all duration-150 ${ie?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-105":ne?"hover:bg-[#406E71]/10 text-slate-700 hover:text-[#406E71]":"text-slate-200 cursor-not-allowed"} ${he&&!ie?"ring-1 ring-[#406E71]/40":""}`,children:K.getDate()},K.toISOString())})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tl,{className:"h-4 w-4 text-[#406E71]"}),e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Ss(o,"EEEE, MMMM d")})]}),z.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(gr,{className:"h-8 w-8 text-slate-300 mx-auto"}),e.jsx("p",{className:"text-sm text-slate-400",children:"No available times on this day"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Try selecting a different date"})]}):e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2 max-h-52 overflow-y-auto pr-1 custom-scrollbar",children:z.map(K=>{const J=d===K;return e.jsx("button",{onClick:()=>u(K),className:`px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150 ${J?"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:Y(K)},K)})}),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(Hr,{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:YNe[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(Tl,{className:"h-3.5 w-3.5 text-[#406E71]"}),Ss(o,"EEE, MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3.5 w-3.5 text-[#406E71]"}),Y(d)," · ",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:f.name,onChange:K=>g({...f,name:K.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(Vs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{type:"email",value:f.email,onChange:K=>g({...f,email:K.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(Ar,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{type:"tel",value:f.phone,onChange:K=>g({...f,phone:K.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(Es,{value:f.message,onChange:K=>g({...f,message:K.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:W,disabled:!f.name||_,children:_?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(xr,{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 ",(S==null?void 0:S.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&&Ss(o,"EEEE, MMMM d, yyyy")}),e.jsxs("p",{className:"text-slate-500",children:[d&&Y(d)," · ",i==null?void 0:i.duration_minutes," min"]})]})}),e.jsx("p",{className:"text-sm text-slate-400 max-w-xs mx-auto",children:"A confirmation with meeting details will be sent to you shortly."}),((S==null?void 0:S.phone)||(S==null?void 0:S.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:[(S==null?void 0:S.phone)&&e.jsxs("a",{href:`tel:${S.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(Ar,{className:"h-3.5 w-3.5"})," Call"]}),(S==null?void 0:S.email)&&e.jsxs("a",{href:`mailto:${S.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(Vs,{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(Tl,{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 ern(){const t=Jl().pathname.slice(1).split("/")[0];return N.useEffect(()=>{document.body.classList.add("booking-page");const n=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("booking-page"),r.forEach(clearTimeout)}},[]),t?e.jsx(INt,{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 trn(){const t=Jl().pathname.slice(1);return N.useEffect(()=>{document.body.classList.add("connect-page");const n=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("connect-page"),r.forEach(clearTimeout)}},[]),!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Connect"}),e.jsx("p",{className:"text-slate-500",children:"Stay connected with your real estate professional."}),e.jsx("p",{className:"text-slate-400 text-sm mt-2",children:"Visit a specific agent link to get started."})]})}):e.jsx(Ymt,{slugOverride:t})}function srn(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 nrn={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function rrn({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=nrn[s.heading_font||"playfair"],u=s.eyebrow||null,h=s.headline_accent||null,p=Array.isArray(s.trust_pills)?s.trust_pills:[],f=t.slice(0,5);return e.jsxs("section",{className:"relative w-full min-h-screen md:min-h-[760px] overflow-hidden",style:{backgroundColor:c},children:[s.hero_image_url?e.jsx("img",{src:s.hero_image_url,alt:"",className:"absolute inset-0 w-full h-full object-cover",loading:"eager"}):e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(135deg, ${c}, #000)`}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/85 via-black/55 to-black/25"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-black/20"}),e.jsx("div",{className:"relative z-10 mx-auto w-full max-w-7xl px-6 md:px-10 py-16 md:py-24 min-h-screen md:min-h-[760px] flex items-center",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-10 lg:gap-12 w-full items-center",children:[e.jsxs("div",{className:"lg:col-span-3 text-white",children:[s.logo_url&&e.jsx(arn,{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(Ar,{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(Vs,{className:"h-3 w-3"})," ",s.agent_email]})]})]})]})]}),e.jsx("div",{className:"lg:col-span-2",children:e.jsxs("div",{className:"rounded-2xl border border-white/15 bg-white/10 backdrop-blur-xl shadow-2xl p-5 md:p-6",children:[e.jsxs("form",{className:"space-y-3",onSubmit:a,children:[f.map(g=>e.jsxs("div",{children:[e.jsxs(se,{className:"block text-[11px] font-semibold tracking-wider uppercase text-white/85 mb-1.5",children:[g.label,g.is_required&&e.jsx("span",{className:"ml-1",style:{color:o},children:"*"})]}),e.jsx("div",{className:"[&_input]:bg-white/95 [&_input]:border-0 [&_input]:text-neutral-900 [&_input]:placeholder:text-neutral-400 [&_textarea]:bg-white/95 [&_textarea]:border-0 [&_textarea]:text-neutral-900 [&_textarea]:placeholder:text-neutral-400 [&_button[role=combobox]]:bg-white/95 [&_button[role=combobox]]:border-0 [&_button[role=combobox]]:text-neutral-900",children:l(g,n,r,c)})]},g.id)),e.jsx("button",{type:"submit",disabled:i,className:"w-full px-6 py-3.5 rounded-lg font-bold text-neutral-900 text-base md:text-lg shadow-lg hover:brightness-110 active:brightness-95 transition-all disabled:opacity-60 mt-2",style:{backgroundColor:o},children:i?"Submitting...":s.cta_text||"Get Started"})]}),p.length>0&&e.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 mt-4",children:p.map((g,_)=>e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] md:text-xs text-white/80 font-medium",children:[e.jsx("span",{className:"h-1 w-1 rounded-full",style:{backgroundColor:o}}),g]},_))})]})})]})})]})}function arn({src:s}){const[t,n]=N.useState(null),r=e.jsx("img",{src:s,alt:"Logo",crossOrigin:"anonymous",className:"h-10 md:h-12 w-auto object-contain",onLoad:a=>n(srn(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 irn(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 orn(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 lrn(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 crn({startsAt:s,locationName:t,address:n,title:r,accent:a}){const[i,l]=N.useState(Date.now());N.useEffect(()=>{const f=setInterval(()=>l(Date.now()),1e3);return()=>clearInterval(f)},[]);const o=new Date(s).getTime();if(!Number.isFinite(o))return null;const c=irn(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(" · "),p=n?`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(n)}`:null;return e.jsx("section",{className:"max-w-5xl mx-auto px-4 py-10",children:e.jsx("div",{className:"rounded-2xl border bg-white/80 backdrop-blur p-6 md:p-8 shadow-sm",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider font-medium",style:{color:a},children:d?"Just happened":"Event starts in"}),d?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Missed this one? Submit the form and we'll let you know about the next one."}):e.jsx("div",{className:"flex items-baseline gap-3",children:[{v:c.d,l:"days"},{v:c.h,l:"hrs"},{v:c.m,l:"min"},{v:c.s,l:"sec"}].map(f=>e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-3xl md:text-4xl font-bold tabular-nums",style:{color:a},children:String(f.v).padStart(2,"0")}),e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:f.l})]},f.l))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 pt-2 text-sm text-neutral-700",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(gr,{className:"h-3.5 w-3.5"})," ",u]}),h&&e.jsxs("a",{href:p||"#",target:p?"_blank":void 0,rel:"noreferrer",className:"inline-flex items-center gap-1.5 hover:underline",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," ",h]})]})]}),!d&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("a",{href:orn(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(yr,{className:"h-4 w-4"})," Add to Google"]}),e.jsxs("a",{href:lrn(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(yr,{className:"h-4 w-4"})," Apple / Outlook"]})]})]})})})}function drn(){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 PNt({slugOverride:s}){var V;const{slug:t}=bi(),n=s||t,[r,a]=N.useState(!1),[i,l]=N.useState({}),[o,c]=N.useState(0),[d,u]=N.useState(!1),[h,p]=N.useState(""),[f]=N.useState(()=>Date.now()),g=N.useState(()=>drn())[0],{data:_,isLoading:v}=ct({queryKey:["public-landing-page",n],queryFn:async()=>{const{data:W,error:Y}=await q.from("landing_pages").select("*").eq("slug",n).eq("is_published",!0).single();if(Y)throw Y;return W},enabled:!!n}),{data:j=[]}=ct({queryKey:["public-landing-page-fields",_==null?void 0:_.id],queryFn:async()=>{const{data:W,error:Y}=await q.from("landing_page_fields").select("*").eq("page_id",_.id).order("sort_order");if(Y)throw Y;return W},enabled:!!(_!=null&&_.id)});N.useEffect(()=>{_!=null&&_.id&&q.from("landing_pages").update({view_count:(_.view_count||0)+1}).eq("id",_.id).then(()=>{})},[_==null?void 0:_.id]),N.useEffect(()=>{if(!(_!=null&&_.id))return;const W=new URLSearchParams(window.location.search);q.functions.invoke("landing-page-track",{body:{page_id:_.id,event_type:"view",session_id:g,utm_source:W.get("utm_source"),utm_medium:W.get("utm_medium"),utm_campaign:W.get("utm_campaign"),referrer:document.referrer||null,device:window.matchMedia("(max-width: 768px)").matches?"mobile":"desktop"}}).catch(()=>{})},[_==null?void 0:_.id,g]);const b=gt({mutationFn:async()=>{const W=j.find(le=>le.field_type==="text"&&le.label.toLowerCase().includes("name")),Y=j.find(le=>le.field_type==="email"),K=j.find(le=>le.field_type==="phone"),J=W?String(i[W.label]||""):null,ne=Y?String(i[Y.label]||""):null,ie=K?String(i[K.label]||""):null,he=new URLSearchParams(window.location.search),{data:ce,error:pe}=await q.functions.invoke("landing-page-submit",{body:{page_id:_.id,answers:JSON.parse(JSON.stringify(i)),contact_name:J,contact_email:ne,contact_phone:ie,session_id:g,honeypot:h,rendered_at:f,utm_source:he.get("utm_source"),utm_medium:he.get("utm_medium"),utm_campaign:he.get("utm_campaign"),referrer:document.referrer||null}});if(pe)throw pe;return ce},onSuccess:W=>{a(!0),W!=null&&W.redirect_url&&setTimeout(()=>{window.location.href=W.redirect_url},1500)}}),S=W=>{W.preventDefault(),!(j.filter(K=>K.is_required&&!i[K.label]).length>0)&&b.mutate()};if(v)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(!_)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-700",children:"Page Not Found"}),e.jsx("p",{className:"text-gray-500 mt-2",children:"This page doesn't exist or is no longer available."})]})});const A=_.primary_color||"#406E71",T=_.accent_color||"#2a4c64",L=_,D=_.page_type==="lead_magnet",M=_.page_type==="just_listed"||_.page_type==="just_sold",F=Array.isArray(L.property_photos)?L.property_photos:[],z=L.lead_magnet_file_url||L.lead_magnet_external_url;if(r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:`linear-gradient(135deg, ${A}, ${T})`},children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4 text-center",children:[e.jsx(xr,{className:"h-16 w-16 mx-auto mb-4",style:{color:A}}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:D?"Your download is ready!":"Submitted!"}),e.jsx("p",{className:"text-gray-600",children:_.success_message}),D&&z&&e.jsxs("a",{href:z,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 mt-6 px-6 py-3 rounded-lg text-white font-semibold transition-transform hover:scale-105",style:{backgroundColor:A},children:[e.jsx(Pa,{className:"h-5 w-5"}),"Download ",L.lead_magnet_file_name||"Your File"]}),_.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:_.agent_name}),_.agent_phone&&e.jsxs("a",{href:`tel:${_.agent_phone}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:A},children:[e.jsx(Ar,{className:"h-3 w-3"})," ",_.agent_phone]}),_.agent_email&&e.jsxs("a",{href:`mailto:${_.agent_email}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:A},children:[e.jsx(Vs,{className:"h-3 w-3"})," ",_.agent_email]})]})]})});if(M){const W=Y=>{const K=parseFloat(Y.replace(/[^0-9.]/g,""));return isNaN(K)?Y:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(K)};return e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[d&&F.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(Bn,{className:"h-8 w-8"})}),e.jsx("button",{onClick:Y=>{Y.stopPropagation(),c(K=>K===0?F.length-1:K-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(pl,{className:"h-6 w-6"})}),e.jsx("img",{src:F[o],alt:`Property photo ${o+1}`,className:"max-h-[90vh] max-w-[90vw] object-contain rounded-lg",onClick:Y=>Y.stopPropagation()}),e.jsx("button",{onClick:Y=>{Y.stopPropagation(),c(K=>K===F.length-1?0:K+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(xa,{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," / ",F.length]})]}),F.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:L.property_status==="just_sold"?"#e74c3c":A},children:L.property_status==="just_sold"?"🎉 Just Sold":"🏡 Just Listed"}),F.length===1?e.jsxs("div",{className:"rounded-2xl overflow-hidden cursor-pointer group",onClick:()=>{c(0),u(!0)},children:[e.jsx("img",{src:F[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(u4,{className:"h-4 w-4"})," View"]})]}):F.length===2?e.jsx("div",{className:"grid grid-cols-2 gap-2 rounded-2xl overflow-hidden",children:F.slice(0,2).map((Y,K)=>e.jsx("div",{className:"cursor-pointer group relative",onClick:()=>{c(K),u(!0)},children:e.jsx("img",{src:Y,alt:`Property ${K+1}`,className:"w-full h-[45vh] object-cover group-hover:scale-105 transition-transform duration-500"})},K))}):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:F[0],alt:"Property main",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})}),F.slice(1,5).map((Y,K)=>e.jsxs("div",{className:"cursor-pointer group relative",onClick:()=>{c(K+1),u(!0)},children:[e.jsx("img",{src:Y,alt:`Property ${K+2}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}),K===3&&F.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center text-white font-bold text-lg",children:["+",F.length-5," more"]})]},K))]}),F.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(u4,{className:"h-4 w-4"})," View all ",F.length," photos"]})]}),F.length===0&&e.jsx("div",{className:"relative py-16 px-4",style:{background:_.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${_.hero_image_url}) center/cover`:`linear-gradient(135deg, ${A}, ${T})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[_.logo_url&&e.jsx("img",{src:_.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:_.hero_headline}),_.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:_.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:[L.property_price&&e.jsx("p",{className:"text-3xl md:text-4xl font-bold mb-2",style:{color:A},children:W(L.property_price)}),L.property_address&&e.jsxs("p",{className:"text-gray-600 flex items-center gap-1.5 mb-5 text-lg",children:[e.jsx(ka,{className:"h-5 w-5 shrink-0"})," ",L.property_address]}),e.jsxs("div",{className:"flex gap-6 mb-5 py-4 border-y border-gray-100",children:[L.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(sy,{className:"h-5 w-5",style:{color:A}})," ",L.property_beds]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bedrooms"})]}),L.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(Cp,{className:"h-5 w-5",style:{color:A}})," ",L.property_baths]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bathrooms"})]}),L.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(J2,{className:"h-5 w-5",style:{color:A}})," ",Number(L.property_sqft).toLocaleString()]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Sq Ft"})]})]}),L.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:L.property_description})]})]})}),e.jsx("div",{className:"md:col-span-2",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 sticky top-6",children:[e.jsx("h2",{className:"text-lg font-bold mb-1",style:{color:A},children:L.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!"}),_.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-5 pb-4 border-b",children:[_.agent_photo_url&&e.jsx("img",{src:_.agent_photo_url,alt:_.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:_.agent_name}),e.jsxs("div",{className:"flex flex-col gap-0.5 text-xs text-gray-500",children:[_.agent_phone&&e.jsxs("a",{href:`tel:${_.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Ar,{className:"h-3 w-3"})," ",_.agent_phone]}),_.agent_email&&e.jsxs("a",{href:`mailto:${_.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Vs,{className:"h-3 w-3"})," ",_.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:S,className:"space-y-3",children:[j.map(Y=>e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs font-medium",children:[Y.label,Y.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),ZNe(Y,i,l)]},Y.id)),e.jsx(B,{type:"submit",className:"w-full text-white",style:{backgroundColor:A},disabled:b.isPending,children:b.isPending?"Submitting...":"Submit"}),b.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})})]})}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}return _.theme_style!=="classic"&&!D?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:W=>p(W.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),e.jsx(rrn,{page:_,fields:j,answers:i,setAnswers:l,onSubmit:S,isSubmitting:b.isPending,renderField:ZNe}),_.page_type==="event_registration"&&((V=_.settings)==null?void 0:V.event_starts_at)&&e.jsx(crn,{startsAt:_.settings.event_starts_at,locationName:_.settings.event_location_name,address:_.settings.event_address,title:_.hero_headline||_.title,accent:_.accent_color||_.primary_color||"#406E71"}),b.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center py-4",children:"Something went wrong. Please try again."}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]}):e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[e.jsx("div",{className:"relative py-16 px-4",style:{background:_.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${_.hero_image_url}) center/cover`:`linear-gradient(135deg, ${A}, ${T})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[_.logo_url&&e.jsx("img",{src:_.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:_.hero_headline}),_.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:_.hero_subtext}),D&&L.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(Pa,{className:"h-4 w-4"}),"Free Download: ",L.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:[D&&e.jsx("p",{className:"text-sm text-gray-500 mb-4 text-center",children:"Fill out the form below to get your free download!"}),_.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-6 pb-4 border-b",children:[_.agent_photo_url&&e.jsx("img",{src:_.agent_photo_url,alt:_.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:_.agent_name}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-500",children:[_.agent_phone&&e.jsxs("a",{href:`tel:${_.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Ar,{className:"h-3 w-3"})," ",_.agent_phone]}),_.agent_email&&e.jsxs("a",{href:`mailto:${_.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Vs,{className:"h-3 w-3"})," ",_.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:S,className:"space-y-4",children:[j.map(W=>e.jsxs("div",{children:[e.jsxs(se,{className:"text-sm font-medium",children:[W.label,W.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),ZNe(W,i,l)]},W.id)),e.jsx(B,{type:"submit",className:"w-full text-white",style:{backgroundColor:A},disabled:b.isPending,children:b.isPending?"Submitting...":D?"Get My Free Download":"Submit"}),b.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}function ZNe(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(Es,{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(ds,{value:String(a),onValueChange:l=>n(o=>({...o,[s.label]:l})),children:[e.jsx(ls,{className:"mt-1",children:e.jsx(us,{placeholder:"Select..."})}),e.jsx(cs,{children:i.map(l=>e.jsx(Qe,{value:l,children:l},l))})]});case"multiselect":return e.jsx("div",{className:"mt-1 space-y-2",children:i.map(l=>{const o=Array.isArray(a)?a:[];return e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(ui,{checked:o.includes(l),onCheckedChange:c=>{const d=c?[...o,l]:o.filter(u=>u!==l);n(u=>({...u,[s.label]:d}))}}),e.jsx("span",{className:"text-sm",children:l})]},l)})});case"toggle":return e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[e.jsx(bn,{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 urn(){const t=Jl().pathname.slice(1).split("/")[0];return N.useEffect(()=>{document.body.classList.add("landing-page-public");const n=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("landing-page-public"),r.forEach(clearTimeout)}},[]),t?e.jsx(PNt,{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 hrn=[{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}],vgn={hero:"Hero Section",featured_listings:"Featured Listings",featured_areas:"Featured Areas",about:"About Me",testimonials:"Testimonials",cta_banner:"Call To Action",new_listings:"New Listings Carousel",open_houses:"Open Houses Carousel",my_listings:"My Listings Carousel",city_pages:"City Pages Grid",property_types:"Property Types Gallery",advantages:"Advantages / Why Choose Us",rate_my_agent:"RateMyAgent Reviews",lifestyle_gallery:"Lifestyle Gallery",market_pulse:"Market Pulse",concierge_services:"Concierge Services",land_use_guide:"Land Use Guide",land_valuation_cta:"Land Valuation CTA",acreage_showcase:"Acreage Showcase",featured_video:"Featured Video",schedule_cta:"Schedule a Consultation"},bgn={hero:"Full-screen background image with headline, subtitle, and search bar",featured_listings:"Grid of highlighted properties from the MLS",featured_areas:"Spotlight regions or neighborhoods that link to property search",about:"Agent photo, bio, and credentials section",testimonials:"Client reviews carousel with quotes",cta_banner:"Call-to-action block to drive contact and search engagement",new_listings:"Horizontal carousel of newest listings, filterable by city",open_houses:"Horizontal carousel of open house listings, filterable by city",my_listings:"Showcase the agent's own active listings in a carousel",city_pages:"Grid of your city landing pages with photos and links",property_types:"Visual gallery of property categories (Ranch, Farm, Land, etc.)",advantages:"Feature cards highlighting your expertise and unique value",rate_my_agent:"Verified client reviews carousel powered by RateMyAgent",lifestyle_gallery:"Cinematic photo grid showcasing luxury living — pools, views, interiors",market_pulse:"Sleek market stats dashboard with avg price, days on market, inventory",concierge_services:"White-glove services showcase — staging, design, moving coordination",land_use_guide:"Interactive land use cards — Agriculture, Hunting, Equestrian, Recreational",land_valuation_cta:`"What's Your Land Worth?" — bold call-to-action for landowners`,acreage_showcase:"Large visual cards emphasizing lot size with aerial imagery",featured_video:"Embedded YouTube or Bunny video section for cinematic storytelling",schedule_cta:"Prominent booking section that sends visitors to your online scheduling calendar"},ZXe={basic:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","rate_my_agent","featured_video","schedule_cta","cta_banner"],luxury:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","rate_my_agent","cta_banner","lifestyle_gallery","market_pulse","concierge_services","featured_video","schedule_cta"],"land-ranch":["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","rate_my_agent","cta_banner","property_types","advantages","land_use_guide","land_valuation_cta","acreage_showcase","featured_video","schedule_cta"]};function _gn(s){return ZXe[s]||ZXe.basic}function mrn(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}):hrn,testimonials:Array.isArray(s.testimonials)?s.testimonials:[],featuredListingIds:s.featured_listing_ids||[],searchCities:Array.isArray(t.searchCities)?t.searchCities:[],searchZipCodes:Array.isArray(t.searchZipCodes)?t.searchZipCodes:[],searchCounties:Array.isArray(t.searchCounties)?t.searchCounties:[],searchSubdivisions:Array.isArray(t.searchSubdivisions)?t.searchSubdivisions:[],referralMode:t.referralMode===!0,referralPrimaryLabel:t.referralPrimaryLabel||void 0,referralPrimaryUrl:t.referralPrimaryUrl||void 0,referralSecondaryLabel:t.referralSecondaryLabel||void 0,referralSecondaryUrl:t.referralSecondaryUrl||void 0}}function prn(){const t=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return t?t[1]:null}function frn(){const s=prn(),{data:t,isLoading:n,error:r}=ct({queryKey:["lead-site",s],queryFn:async()=>{var u;if(!s)return null;const{data:a,error:i}=await q.from("lead_sites").select("*").eq("subdomain_slug",s).eq("is_active",!0).maybeSingle();if(i)throw i;if(!a)return null;const{data:l}=await q.from("profiles").select("id, name, avatar_url, email, phone, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("id",a.agent_id).single();let o=null;if(a.show_team_logo)if(a.team_logo_url)o=a.team_logo_url;else{const{data:h}=await q.from("team_members").select("team_id, teams(avatar_url, name)").eq("user_id",a.agent_id).limit(1).maybeSingle();h&&((u=h.teams)!=null&&u.avatar_url)&&(o=h.teams.avatar_url)}const c={id:a.id,agentId:a.agent_id,subdomainSlug:a.subdomain_slug,mlsProviderId:a.mls_provider_id,siteTitle:a.site_title,siteTagline:a.site_tagline,leadRegistrationMode:a.lead_registration_mode||"disabled",registrationTriggerCount:a.registration_trigger_count??1,themeConfig:a.theme_config||{},isActive:a.is_active,brokerageLegalName:a.brokerage_legal_name||null,brokerageLicenseNumber:a.brokerage_license_number||null,agentLicenseNumber:a.agent_license_number||null,licenseState:a.license_state||null,mlsDisclaimerText:a.mls_disclaimer_text||null,mlsLogoUrl:a.mls_logo_url||null,equalHousingEnabled:a.equal_housing_enabled??!0,faviconUrl:a.favicon_url||null,ogImageUrl:a.og_image_url||null,showTeamLogo:a.show_team_logo??!1,teamLogoUrl:o,noMlsMode:a.no_mls_mode===!0,bookingUrl:a.booking_url||null,pageSubtitles:a.page_subtitles||{},agent:l?{id:l.id,full_name:l.name||"",avatar_url:l.avatar_url,email:l.email,phone:l.phone,title:l.title,bio:l.bio,areas_served:l.areas_served||null,years_experience:l.years_experience??null,instagram_url:l.instagram_url||null,facebook_url:l.facebook_url||null,linkedin_url:l.linkedin_url||null}:void 0,testimonials:Array.isArray(a.testimonials)?a.testimonials.filter(h=>h&&typeof h=="object"&&h.text).map(h=>({name:String(h.name||"Client"),text:String(h.text),rating:typeof h.rating=="number"?h.rating:5,location:h.location?String(h.location):void 0})):[],seoMetaTitle:a.seo_meta_title||null,seoMetaDescription:a.seo_meta_description||null},d=mrn(a);return{siteConfig:c,themeConfig:d}},enabled:!!s,staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1});return{siteConfig:(t==null?void 0:t.siteConfig)??null,themeConfig:(t==null?void 0:t.themeConfig)??null,isLoading:n,error:r,slug:s}}async function xrn(s,t){try{await q.functions.invoke("lead-site-notify",{body:{lead:t,lead_site_id:s}})}catch(n){console.warn("Lead notification failed:",n)}}const LNt=N.createContext(null);function lbe(){const s=N.useContext(LNt);if(!s)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return s}function grn({siteConfig:s,children:t}){const[n,r]=N.useState(null),[a,i]=N.useState(null),[l,o]=N.useState(!0);N.useEffect(()=>{const{data:{subscription:h}}=q.auth.onAuthStateChange(async(p,f)=>{const g=(f==null?void 0:f.user)??null;if(r(g),g){const{data:_}=await q.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",g.id).eq("lead_site_id",s.id).maybeSingle();_&&i({..._,email:g.email||""})}else i(null);o(!1)});return q.auth.getSession().then(({data:{session:p}})=>{r((p==null?void 0:p.user)??null),p!=null&&p.user?q.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",p.user.id).eq("lead_site_id",s.id).maybeSingle().then(({data:f})=>{f&&i({...f,email:p.user.email||""}),o(!1)}):o(!1)}),()=>h.unsubscribe()},[s.id]);const c=N.useCallback(async h=>{const p=h.email.toLowerCase().trim(),f=h.phone.replace(/\D/g,""),{data:g,error:_}=await q.auth.signUp({email:p,password:f,options:{data:{full_name:h.name,consumer_site_id:s.id},emailRedirectTo:window.location.origin}});if(_){if(_.message.includes("already registered")){await d(p,f);return}throw _}if(g.user){const{error:v}=await q.from("lead_site_consumer_profiles").insert({user_id:g.user.id,lead_site_id:s.id,name:h.name.trim(),phone:h.phone.trim()});v&&console.warn("Consumer profile insert error:",v);const{error:j}=await q.from("lead_site_leads").insert({lead_site_id:s.id,name:h.name.trim(),email:p,phone:h.phone.trim(),message:"Created account on website",source_page:window.location.pathname,lead_type:"website_registration",metadata:{registered:!0,has_account:!0}});j&&console.error("Lead insert error (CRM sync may not trigger):",j),xrn(s.id,{name:h.name.trim(),email:p,phone:h.phone.trim(),lead_type:"website_registration",message:"Created account on website",source_page:window.location.pathname})}},[s.id]),d=N.useCallback(async(h,p)=>{const f=p.replace(/\D/g,""),{error:g}=await q.auth.signInWithPassword({email:h.toLowerCase().trim(),password:f});if(g)throw g},[]),u=N.useCallback(async()=>{await q.auth.signOut(),r(null),i(null)},[]);return e.jsx(LNt.Provider,{value:{user:n,profile:a,isLoading:l,signUp:c,signIn:d,signOut:u},children:t})}const yrn=new Set(["7605cc2e-ce21-4f4f-8bb1-4c0f217b1109"]),vrn=new Set(["tomlois"]);function DNt(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||yrn.has(s.id||"")||vrn.has((s.subdomainSlug||"").toLowerCase())||!s.mlsProviderId:!1}function wgn(s){return`Contact ${s.split(" ")[0]||"Me"}`}const OR="#c9a96e",brn="Schedule a Free Consultation",_rn={sm:"px-5 py-2.5 text-[11px]",md:"px-7 py-3.5 text-xs",lg:"px-9 py-4 text-xs"};function aN({bookingUrl:s,label:t=brn,className:n="",variant:r="solid",color:a=OR,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 ${_rn[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(ZS,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:t})]})}function jgn({bookingUrl:s,agentName:t,accentColor:n=OR,config:r={},luxury:a=!0}){const i=r.bookingUrl||s;if(!i)return null;const l=r.eyebrow||"No Cost. No Obligation.",o=r.sectionTitle||"Schedule a Free Consultation",c=r.subtitle||`Pick a time that works for you and ${t.split(" ")[0]} will personally call you for a free 30-minute real estate consultation.`,d=r.buttonLabel||"Book My Free Consultation",u=[{icon:gr,title:r.point1Title||"30 Minutes",text:r.point1Text||"A focused conversation about your goals, timeline, and options."},{icon:g9,title:r.point2Title||"A Personal Call",text:r.point2Text||`${t.split(" ")[0]} calls you at the time you choose — no phone tag.`},{icon:xr,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(Yn.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((p,f)=>e.jsxs("div",{className:"border border-white/10 bg-white/[0.03] p-6",children:[e.jsx(p.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:p.title}),e.jsx("p",{className:"text-white/45 text-sm leading-relaxed",children:p.text})]},f))}),e.jsxs("div",{className:"mt-12 flex flex-col items-center gap-4",children:[e.jsx(aN,{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 Ngn({bookingUrl:s,accentColor:t=OR,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(aN,{bookingUrl:s,label:"Schedule Now",color:t,size:"sm",className:"flex-shrink-0",source:l})]}):null}function wrn({bookingUrl:s,accentColor:t=OR}){const[n,r]=N.useState(!1),[a,i]=N.useState(!1);if(N.useEffect(()=>{sessionStorage.getItem("schedule-cta-dismissed")==="1"&&i(!0);const o=()=>r(window.scrollY>260);return o(),window.addEventListener("scroll",o,{passive:!0}),()=>window.removeEventListener("scroll",o)},[]),!s||a)return null;const l=()=>{sessionStorage.setItem("schedule-cta-dismissed","1"),i(!0)};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`md:hidden fixed inset-x-0 bottom-0 z-[60] transition-transform duration-300 ${n?"translate-y-0":"translate-y-full"}`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:e.jsxs("div",{className:"bg-[#0d0b0a]/95 backdrop-blur-lg border-t border-white/10 px-4 py-3 flex items-center gap-3",children:[e.jsxs("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:"flex-1 inline-flex items-center justify-center gap-2 rounded-full py-3 text-[11px] font-semibold tracking-[0.18em] uppercase",style:{backgroundColor:t,color:"#0d0b0a"},children:[e.jsx(ZS,{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(Bn,{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(aN,{bookingUrl:s,label:"Schedule a Free Consultation",size:"sm",color:t,source:"sticky"})})]})}function jrn({bookingUrl:s,agentName:t}){return N.useEffect(()=>{if(s){const n=setTimeout(()=>window.location.replace(s),400);return()=>clearTimeout(n)}},[s]),e.jsx("div",{className:"min-h-[70vh] flex items-center justify-center bg-[#0d0b0a] px-6 text-center",children:e.jsxs("div",{children:[e.jsx(ZS,{className:"h-8 w-8 mx-auto mb-6",style:{color:OR}}),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(aN,{bookingUrl:s,label:"Open Booking Calendar",size:"lg",source:"schedule_page"})})]})})}function E8e({open:s,mode:t,siteConfig:n,onComplete:r,onSkip:a,theme:i="default",accentColor:l}){var Y;const{signUp:o,signIn:c}=lbe(),[d,u]=N.useState(!1),[h,p]=N.useState(""),[f,g]=N.useState(""),[_,v]=N.useState(""),[j,b]=N.useState(!1),[S,A]=N.useState(""),T=t==="required",L=i==="luxury",D=l||(L?"#c9a96e":"#2563eb"),M=((Y=n.agent)==null?void 0:Y.full_name)||"the agent",F={borderColor:`${D}66`,"--tw-ring-color":`${D}66`},z=async K=>{var ne;if(K.preventDefault(),A(""),!f.trim()||!_.trim()){A("Email and phone number are required.");return}if(!d&&!h.trim()){A("Name is required.");return}if(_.replace(/\D/g,"").length<7){A("Please enter a valid phone number.");return}b(!0);try{d?await c(f,_):await o({name:h,email:f,phone:_}),r()}catch(ie){(ne=ie==null?void 0:ie.message)!=null&&ne.includes("Invalid login")?A("Invalid email or phone number. Please try again."):A((ie==null?void 0:ie.message)||"Something went wrong. Please try again.")}finally{b(!1)}},V=L?"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",W=L?F:void 0;return e.jsx(bs,{open:s,onOpenChange:T?void 0:K=>{K||a()},children:e.jsxs(vs,{className:`sm:max-w-md ${L?"border-white/10 bg-[#f7f1e7] text-[#201915]":""}`,onPointerDownOutside:T?K=>K.preventDefault():void 0,onEscapeKeyDown:T?K=>K.preventDefault():void 0,children:[e.jsxs(ws,{children:[e.jsx(_s,{className:"text-xl",style:L?{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(Qn,{className:L?"text-[#5f5145]":void 0,children:d?"Sign in with your email and phone number.":`Create a free account to save favorites, get alerts, and connect with ${M}.`})]}),e.jsxs("form",{onSubmit:z,className:"space-y-3 mt-2",children:[!d&&e.jsx("input",{type:"text",required:!0,placeholder:"Your name",value:h,onChange:K=>p(K.target.value),className:V,style:W}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:f,onChange:K=>g(K.target.value),className:V,style:W}),e.jsxs("div",{children:[e.jsx("input",{type:"tel",required:!0,placeholder:"Phone number",value:_,onChange:K=>v(K.target.value),className:V,style:W}),e.jsx("p",{className:`text-xs mt-1 ${L?"text-[#8a7869]":"text-gray-400"}`,children:d?"Your phone number is your password":"Your phone number will be used as your password"})]}),S&&e.jsx("p",{className:"text-red-600 text-sm",children:S}),e.jsx("button",{type:"submit",disabled:j,className:`w-full py-2.5 font-medium rounded-lg disabled:opacity-50 transition-colors ${L?"text-black hover:opacity-90 tracking-wider uppercase text-sm":"bg-blue-600 text-white hover:bg-blue-700"}`,style:L?{backgroundColor:D}:void 0,children:j?d?"Signing in...":"Creating account...":d?"Sign In":"Create Account"}),e.jsx("button",{type:"button",onClick:()=>{u(!d),A("")},className:"w-full text-center text-sm hover:opacity-80 transition-opacity",style:{color:D},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 ${L?"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 ${L?"text-[#8a7869]":"text-gray-400"}`,children:"By registering you agree to receive property updates. You can unsubscribe anytime."})]})})}function A8e({siteConfig:s,pagePath:t}){const n=s.agent;if(!n)return null;const r=`https://${s.subdomainSlug}.thelocalmove.com`,i=(n.areas_served||"").split(/,|;|\|/).map(S=>S.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(S=>S.toUpperCase()))],h=s.testimonials||[],p=h.length?{"@type":"AggregateRating",ratingValue:(h.reduce((S,A)=>S+(A.rating||5),0)/h.length).toFixed(1),reviewCount:h.length,bestRating:5,worstRating:1}:void 0,f=[n.facebook_url,n.instagram_url,n.linkedin_url].filter(Boolean),g={"@context":"https://schema.org","@type":["RealEstateAgent","LocalBusiness"],"@id":`${r}/#agent`,name:n.full_name,url:r,image:n.avatar_url||s.ogImageUrl||void 0,logo:s.ogImageUrl||n.avatar_url||void 0,email:n.email,telephone:n.phone||void 0,jobTitle:n.title||"Real Estate Agent",description:n.bio||`${n.full_name} is a trusted local real estate professional${l?` serving ${l}`:""}.`,priceRange:"$$",...f.length&&{sameAs:f},...s.brokerageLegalName&&{worksFor:{"@type":"RealEstateAgent",name:s.brokerageLegalName,...s.brokerageLicenseNumber&&{identifier:s.brokerageLicenseNumber}}},...s.agentLicenseNumber&&{identifier:s.agentLicenseNumber},...o&&{address:{"@type":"PostalAddress",addressLocality:o,...c&&{addressRegion:c},addressCountry:"US"}},...i.length&&{areaServed:i.map(S=>{const[A,T]=S.split(/,\s*/);return{"@type":"City",name:A,...T&&{containedInPlace:{"@type":"State",name:T}}}})},...p&&{aggregateRating:p},...h.length&&{review:h.slice(0,10).map(S=>({"@type":"Review",author:{"@type":"Person",name:S.name},reviewBody:S.text,reviewRating:{"@type":"Rating",ratingValue:S.rating||5,bestRating:5,worstRating:1},...S.location&&{locationCreated:{"@type":"Place",name:S.location}}}))}},_={"@context":"https://schema.org","@type":"Person","@id":`${r}/#person`,name:n.full_name,jobTitle:n.title||"Real Estate Agent",description:n.bio||void 0,image:n.avatar_url||void 0,url:r,email:n.email,telephone:n.phone||void 0,...f.length&&{sameAs:f},...n.years_experience&&{knowsAbout:["Residential Real Estate","Home Buying","Home Selling",l?`${l} Real Estate`:"Local Real Estate"].filter(Boolean)},...u.length&&{hasCredential:u.map(S=>({"@type":"EducationalOccupationalCredential",credentialCategory:"designation",name:S}))},...s.brokerageLegalName&&{worksFor:{"@type":"Organization",name:s.brokerageLegalName}}},v={"@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"}},j=[{name:"Search Homes",description:`Browse all current MLS listings${l?` in ${l}`:""}.`,path:"/search"},{name:"Featured Areas",description:"Explore featured neighborhoods, cities, and communities.",path:"/areas"},{name:"Sold Properties",description:"See recently sold homes and local market activity.",path:"/sold"},{name:"Home Valuation",description:"Get a free, no-obligation estimate of what your home is worth.",path:"/sell"},{name:"About",description:`Learn more about ${n.full_name}${s.brokerageLegalName?` and ${s.brokerageLegalName}`:""}.`,path:"/about"},{name:"Contact",description:`Get in touch with ${n.full_name} for buying, selling, or relocation help.`,path:"/contact"}],b={"@context":"https://schema.org","@type":"ItemList","@id":`${r}/#nav`,name:"Main Navigation",itemListElement:j.map((S,A)=>({"@type":"SiteNavigationElement",position:A+1,name:S.name,description:S.description,url:`${r}${S.path}`}))};return e.jsxs(Go,{children:[e.jsx("script",{type:"application/ld+json",children:JSON.stringify(g)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(_)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(v)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(b)})]})}function kgn({items:s,siteConfig:t}){const n=`https://${t.subdomainSlug}.thelocalmove.com`,r={"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:s.map((a,i)=>({"@type":"ListItem",position:i+1,name:a.name,item:`${n}${a.path}`}))};return e.jsx(Go,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})})}function Sgn({listing:s,siteConfig:t}){var a;const n=`https://${t.subdomainSlug}.thelocalmove.com`,r={"@context":"https://schema.org","@type":"SingleFamilyResidence",name:`${s.address}, ${s.city}, ${s.state} ${s.zip}`,url:`${n}/listing/${s.mlsNumber}`,image:((a=s.photos)==null?void 0:a[0])||void 0,numberOfRooms:s.bedrooms,numberOfBathroomsTotal:s.bathrooms,floorSize:s.sqft?{"@type":"QuantitativeValue",value:s.sqft,unitCode:"FTK"}:void 0,address:{"@type":"PostalAddress",streetAddress:s.address,addressLocality:s.city,addressRegion:s.state,postalCode:s.zip},...s.latitude&&s.longitude&&{geo:{"@type":"GeoCoordinates",latitude:s.latitude,longitude:s.longitude}},offers:{"@type":"Offer",price:s.price,priceCurrency:"USD",availability:s.status==="Active"?"https://schema.org/InStock":"https://schema.org/SoldOut"},...s.yearBuilt&&{yearBuilt:s.yearBuilt}};return e.jsx(Go,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})})}function Nrn({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(Go,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(t)})})}function Cgn({title:s,description:t,publishedAt:n,imageUrl:r,slug:a,siteConfig:i}){const l=`https://${i.subdomainSlug}.thelocalmove.com`,o=i.agent,c={"@context":"https://schema.org","@type":"Article",headline:s,description:t,url:`${l}/blog/${a}`,datePublished:n,...r&&{image:r},author:o?{"@type":"Person",name:o.full_name,url:l}:void 0,publisher:{"@type":"Organization",name:i.siteTitle||(o==null?void 0:o.full_name)||"Agent",url:l}};return e.jsx(Go,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(c)})})}function M8e({siteConfig:s}){var f;const t=s.agent;if(!t)return null;const n=t.full_name,r=s.brokerageLegalName||"their brokerage",a=t.areas_served||"the local market",i=((f=a.split(/,|;|\|/)[0])==null?void 0:f.trim())||"the local area",l=t.years_experience,o=t.phone||"",c=t.email,d=s.agentLicenseNumber,u=(t.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],h=[...new Set(u.map(g=>g.toUpperCase()))],p=[{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(Nrn,{faqs:p})}const QXe="ls_visitor_geo",krn=1e3*60*60,QNe="lu_lc_attrib_v1",Srn=1e3*60*60*24*90;function Crn(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 Trn(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 Ern(){try{const s=localStorage.getItem(QXe);if(s){const t=JSON.parse(s);if(Date.now()-t.ts{i.current||(i.current=!0,Ern().then(l=>{a.current=l}))},[]),N.useEffect(()=>{if(!(s!=null&&s.id))return;const l=n.pathname;if(l===r.current)return;r.current=l;const o=Crn(l),c=Trn(l,o),d=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,u=a.current;(async()=>{const p=new URLSearchParams(n.search),f=p.get("luc");if(f&&/^[0-9a-f-]{36}$/i.test(f)){try{localStorage.setItem(QNe,JSON.stringify({contact_id:f,ts:Date.now()}))}catch{}return f}const g=p.get("lc");if(g&&/^[0-9a-f-]{36}$/i.test(g)){const{data:_}=await q.from("listing_email_recipients").select("contact_id").eq("id",g).maybeSingle(),v=_==null?void 0:_.contact_id;if(v){try{localStorage.setItem(QNe,JSON.stringify({contact_id:v,ts:Date.now()}))}catch{}return v}}try{const _=localStorage.getItem(QNe);if(_){const v=JSON.parse(_);if(v!=null&&v.contact_id&&Date.now()-(v.ts||0){q.from("lead_site_page_views").insert({lead_site_id:s.id,page_type:o,page_path:l,page_title:c,visitor_fingerprint:d,auth_user_id:t||null,contact_id:p,visitor_city:(u==null?void 0:u.city)||null,visitor_region:(u==null?void 0:u.region)||null,visitor_country:(u==null?void 0:u.country)||null,visitor_lat:(u==null?void 0:u.lat)||null,visitor_lng:(u==null?void 0:u.lng)||null}).then(({error:f})=>{f&&console.error("[PageTracking] insert failed:",f.message)})})},[n.pathname,n.search,s==null?void 0:s.id,t])}const Arn=3e4;function P8e(s,t){const n=Jl(),r=N.useRef(null),a=N.useRef(null),i=N.useRef(0),l=n.pathname,o=Mrn(l),c=Irn(l,o),d=o==="listing"&&l.split("/listing/")[1]||null;N.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;o==="listing"&&(i.current+=1);const u=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,h=async()=>{const{data:p,error:f}=await q.from("lead_site_active_visitors").upsert({lead_site_id:s.id,auth_user_id:t,visitor_fingerprint:u,current_page_path:l,current_page_title:c,current_mls_number:d,last_seen_at:new Date().toISOString(),listing_views_count:i.current},{onConflict:"lead_site_id,coalesce(auth_user_id::text,visitor_fingerprint,'')"}).select("id, notified_agent").single();!f&&p&&(r.current=p.id,i.current>=2&&!p.notified_agent&&q.functions.invoke("lead-site-presence-notify",{body:{visitor_id:p.id,lead_site_id:s.id}}).catch(()=>{}))};return h(),a.current&&clearInterval(a.current),a.current=setInterval(h,Arn),()=>{a.current&&clearInterval(a.current)}},[s==null?void 0:s.id,t,l]),N.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;const u=()=>{r.current&&q.from("lead_site_active_visitors").delete().eq("id",r.current).then(()=>{})};return window.addEventListener("beforeunload",u),()=>window.removeEventListener("beforeunload",u)},[s==null?void 0:s.id,t])}function Mrn(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 Irn(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 Ra=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},Prn=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=Lrn},Lrn=Number.MAX_SAFE_INTEGER||9007199254740991;let mi=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}({}),Pn=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}({}),wt=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 ol={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Ya={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class qI{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 Drn{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 qI(t),this.fast_=new qI(n),this.defaultTTFB_=a,this.ttfb_=new qI(t)}update(t,n){const{slow_:r,fast_:a,ttfb_:i}=this;r.halfLife!==t&&(this.slow_=new qI(t,r.getEstimate(),r.getTotalWeight())),a.halfLife!==n&&(this.fast_=new qI(n,a.getEstimate(),a.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new qI(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 Rrn(s,t,n){return(t=Frn(t))in s?Object.defineProperty(s,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[t]=n,s}function Yc(){return Yc=Object.assign?Object.assign.bind():function(s){for(var t=1;t`):iS}function JXe(s,t,n){return t[s]?t[s].bind(t):Brn(s,n)}const ITe=MTe();function $rn(s,t,n){const r=MTe();if(typeof console=="object"&&s===!0||typeof s=="object"){const a=["debug","log","info","warn","error"];a.forEach(i=>{r[i]=JXe(i,s,n)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return MTe()}a.forEach(i=>{ITe[i]=JXe(i,s)})}else Yc(ITe,r);return r}const Pc=ITe;function B4(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Urn(s){return typeof self<"u"&&s===self.ManagedMediaSource}function RNt(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 yy(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 nf(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(!Ra(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return Th(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 Hrn extends FNt{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 zNt(s,t){const n=Object.getPrototypeOf(s);if(n){const r=Object.getOwnPropertyDescriptor(n,t);return r||zNt(n,t)}}function Grn(s,t){const n=zNt(s,t);n&&(n.enumerable=!0,Object.defineProperty(s,t,n))}const tJe=Math.pow(2,32)-1,Wrn=[].push,BNt={video:1,audio:2,id3:3,text:4};function Mm(s){return String.fromCharCode.apply(null,s)}function $Nt(s,t){const n=s[t]<<8|s[t+1];return n<0?65536+n:n}function uo(s,t){const n=UNt(s,t);return n<0?4294967296+n:n}function sJe(s,t){let n=uo(s,t);return n*=Math.pow(2,32),n+=uo(s,t+4),n}function UNt(s,t){return s[t]<<24|s[t+1]<<16|s[t+2]<<8|s[t+3]}function Krn(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 sl(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=sl(s.subarray(a+8,o),t.slice(1));c.length&&Wrn.apply(n,c)}a=o}return n}function Yrn(s){const t=[],n=s[0];let r=8;const a=uo(s,r);r+=4;let i=0,l=0;n===0?(i=uo(s,r),l=uo(s,r+4),r+=8):(i=sJe(s,r),l=sJe(s,r+8),r+=16),r+=2;let o=s.length+l;const c=$Nt(s,r);r+=2;for(let d=0;d>>31===1)return Pc.warn("SIDX has hierarchical references (not supported)"),null;const g=uo(s,u);u+=4,t.push({referenceSize:p,subsegmentDuration:g,info:{duration:g/a,start:o,end:o+p-1}}),o+=p,u+=4,r=u}return{earliestPresentationTime:i,timescale:a,version:n,referencesCount:c,references:t}}function qNt(s){const t=[],n=sl(s,["moov","trak"]);for(let a=0;a{const i=uo(a,4),l=t[i];l&&(l.default={duration:uo(a,12),flags:uo(a,20)})}),t}function Zrn(s){const t=s.subarray(8),n=t.subarray(86),r=Mm(t.subarray(4,8));let a=r,i;const l=r==="enca"||r==="encv";if(l){const d=sl(t,[r])[0].subarray(r==="enca"?28:78);sl(d,["sinf"]).forEach(h=>{const p=sl(h,["schm"])[0];if(p){const f=Mm(p.subarray(4,8));if(f==="cbcs"||f==="cenc"){const g=sl(h,["frma"])[0];g&&(a=Mm(g))}}})}const o=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{const c=sl(n,["avcC"])[0];c&&c.length>3&&(a+="."+OG(c[1])+OG(c[2])+OG(c[3]),i=RG(o==="avc1"?"dva1":"dvav",n));break}case"mp4a":{const c=sl(t,[r])[0],d=sl(c.subarray(28),["esds"])[0];if(d&&d.length>7){let u=4;if(d[u++]!==3)break;u=eke(d,u),u+=2;const h=d[u++];if(h&128&&(u+=2),h&64&&(u+=d[u++]),d[u++]!==4)break;u=eke(d,u);const p=d[u++];if(p===64)a+="."+OG(p);else break;if(u+=12,d[u++]!==5)break;u=eke(d,u);const f=d[u++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((d[u]&224)>>5)),a+="."+g}break}case"hvc1":case"hev1":{const c=sl(n,["hvcC"])[0];if(c&&c.length>12){const d=c[1],u=["","A","B","C"][d>>6],h=d&31,p=uo(c,2),f=(d&32)>>5?"H":"L",g=c[12],_=c.subarray(6,12);a+="."+u+h,a+="."+Qrn(p).toString(16).toUpperCase(),a+="."+f+g;let v="";for(let j=_.length;j--;){const b=_[j];(b||v)&&(v="."+b.toString(16).toUpperCase()+v)}a+=v}i=RG(o=="hev1"?"dvhe":"dvh1",n);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{a=RG(a,n)||a;break}case"vp09":{const c=sl(n,["vpcC"])[0];if(c&&c.length>6){const d=c[4],u=c[5],h=c[6]>>4&15;a+="."+V_(d)+"."+V_(u)+"."+V_(h)}break}case"av01":{const c=sl(n,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,u=c[1]&31,h=c[2]>>>7?"H":"M",p=(c[2]&64)>>6,f=(c[2]&32)>>5,g=d===2&&p?f?12:10:p?10:8,_=(c[2]&16)>>4,v=(c[2]&8)>>3,j=(c[2]&4)>>2,b=c[2]&3;a+="."+d+"."+V_(u)+h+"."+V_(g)+"."+_+"."+v+j+b+"."+V_(1)+"."+V_(1)+"."+V_(1)+"."+0,i=RG("dav1",n)}break}}return{codec:a,encrypted:l,supplemental:i}}function RG(s,t){const n=sl(t,["dvvC"]),r=n.length?n[0]:sl(t,["dvcC"])[0];if(r){const a=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return s+"."+V_(a)+"."+V_(i)}}function Qrn(s){let t=0;for(let n=0;n<32;n++)t|=(s>>n&1)<<31-n;return t>>>0}function eke(s,t){const n=t+5;for(;s[t++]&128&&t{const i=r.subarray(8,24);i.some(l=>l!==0)||(Pc.log(`[eme] Patching keyId in 'enc${a?"a":"v"}>sinf>>tenc' box: ${nf(i)} -> ${nf(n)}`),r.set(n,8))})}function Jrn(s){const t=[];return VNt(s,n=>t.push(n.subarray(8,24))),t}function VNt(s,t){sl(s,["moov","trak"]).forEach(r=>{const a=sl(r,["mdia","minf","stbl","stsd"])[0];if(!a)return;const i=a.subarray(8);let l=sl(i,["enca"]);const o=l.length>0;o||(l=sl(i,["encv"])),l.forEach(c=>{const d=o?c.subarray(28):c.subarray(78);sl(d,["sinf"]).forEach(h=>{const p=HNt(h);p&&t(p,o)})})})}function HNt(s){const t=sl(s,["schm"])[0];if(t){const n=Mm(t.subarray(4,8));if(n==="cbcs"||n==="cenc"){const r=sl(s,["schi","tenc"])[0];if(r)return r}}}function ean(s,t,n){const r={},a=sl(s,["moof","traf"]);for(let i=0;ir[i].duration)){let i=1/0,l=0;const o=sl(s,["sidx"]);for(let c=0;ch+p.info.duration||0,0);l=Math.max(l,u+d.earliestPresentationTime/d.timescale)}}l&&Ra(l)&&Object.keys(r).forEach(c=>{r[c].duration||(r[c].duration=l*r[c].timescale-r[c].start)})}return r}function tan(s){const t={valid:null,remainder:null},n=sl(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 Yv(s,t){const n=new Uint8Array(s.length+t.length);return n.set(s),n.set(t,s.length),n}function nJe(s,t){const n=[],r=t.samples,a=t.timescale,i=t.id;let l=!1;return sl(r,["moof"]).map(c=>{const d=c.byteOffset-8;sl(c,["traf"]).map(h=>{const p=sl(h,["tfdt"]).map(f=>{const g=f[0];let _=uo(f,4);return g===1&&(_*=Math.pow(2,32),_+=uo(f,8)),_/a})[0];return p!==void 0&&(s=p),sl(h,["tfhd"]).map(f=>{const g=uo(f,4),_=uo(f,0)&16777215,v=(_&1)!==0,j=(_&2)!==0,b=(_&8)!==0;let S=0;const A=(_&16)!==0;let T=0;const L=(_&32)!==0;let D=8;g===i&&(v&&(D+=8),j&&(D+=4),b&&(S=uo(f,D),D+=4),A&&(T=uo(f,D),D+=4),L&&(D+=4),t.type==="video"&&(l=cbe(t.codec)),sl(h,["trun"]).map(M=>{const F=M[0],z=uo(M,0)&16777215,V=(z&1)!==0;let W=0;const Y=(z&4)!==0,K=(z&256)!==0;let J=0;const ne=(z&512)!==0;let ie=0;const he=(z&1024)!==0,ce=(z&2048)!==0;let pe=0;const le=uo(M,4);let ve=8;V&&(W=uo(M,ve),ve+=4),Y&&(ve+=4);let ge=W+d;for(let Te=0;Te>1&63;return n===39||n===40}else return(t&31)===6}function R8e(s,t,n,r){const a=GNt(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){Pc.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(l===4){if(a[u++]===181){const p=$Nt(a,u);if(u+=2,p===49){const f=uo(a,u);if(u+=4,f===1195456820){const g=a[u++];if(g===3){const _=a[u++],v=31&_,j=64&_,b=j?2+v*3:0,S=new Uint8Array(b);if(j){S[0]=_;for(let A=1;A16){const h=[];for(let g=0;g<16;g++){const _=a[u++].toString(16);h.push(_.length==1?"0"+_:_),(g===3||g===5||g===7||g===9)&&h.push("-")}const p=o-16,f=new Uint8Array(p);for(let g=0;g>24&255,i[1]=r>>16&255,i[2]=r>>8&255,i[3]=r&255,i.set(s,4),a=0,r=8;a0?(i=new Uint8Array(4),t.length>0&&new DataView(i.buffer).setUint32(0,t.length,!1)):i=new Uint8Array;const l=new Uint8Array(4);return n.byteLength>0&&new DataView(l.buffer).setUint32(0,n.byteLength,!1),ran([112,115,115,104],new Uint8Array([r,0,0,0]),s,i,a,l,n)}function ian(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=nf(new Uint8Array(l,n+12,16));let c=null,d=null,u=0;if(i===0)u=28;else{const p=s.getUint32(28);if(!p||r<32+p*16)return{offset:n,size:t};c=[];for(let f=0;f/\(Windows.+Firefox\//i.test(navigator.userAgent),vD={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 O8e(s,t){const n=vD[t];return!!n&&!!n[s.slice(0,4)]}function _$(s,t,n=!0){return!s.split(",").some(r=>!F8e(r,t,n))}function F8e(s,t,n=!0){var r;const a=B4(n);return(r=a==null?void 0:a.isTypeSupported(w$(s,t)))!=null?r:!1}function w$(s,t){return`${t}/mp4;codecs=${s}`}function rJe(s){if(s){const t=s.substring(0,4);return vD.video[t]}return 2}function Zge(s){const t=WNt();return s.split(",").reduce((n,r)=>{const i=t&&cbe(r)?9:vD.video[r];return i?(i*2+n)/(n?3:2):(vD.audio[r]+n)/(n?2:1)},0)}const tke={};function lan(s,t=!0){if(tke[s])return tke[s];const n={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let a=0;alan(n.toLowerCase(),t))}function dan(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)&&(aJe(s,"audio")||aJe(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 aJe(s,t){return O8e(s,t)&&F8e(s,t)}function uan(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 han(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 iJe(s){const t=B4(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 PTe(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const man={supported:!0,powerEfficient:!0,smooth:!0},pan={supported:!1,smooth:!1,powerEfficient:!1},KNt={supported:!0,configurations:[],decodingInfoResults:[man]};function YNt(s,t){return{supported:!1,configurations:t,decodingInfoResults:[pan],error:s}}function fan(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((p,f)=>{if(f){const g=t.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(_=>{p[_]=(p[_]||0)+g.channels[_]})}return p},{2:0})}catch{return!0}return l!==void 0&&(l.split(",").some(p=>cbe(p))||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&&Ra(u)&&Object.keys(h).some(p=>parseInt(p)>u)}function ZNt(s,t,n,r={}){const a=s.videoCodec;if(!a&&!s.audioCodec||!n)return Promise.resolve(KNt);const i=[],l=xan(s),o=l.length,c=gan(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 p=h.audio.bitrate;h.video&&p&&(h.video.bitrate-=p)}i.push(h)}if(a){const u=navigator.userAgent;if(a.split(",").some(h=>cbe(h))&&WNt())return Promise.resolve(YNt(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),i))}return Promise.all(i.map(u=>{const h=van(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 xan(s){var t;const n=(t=s.videoCodec)==null?void 0:t.split(","),r=QNt(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:w$(han(c),"video"),width:a,height:i,bitrate:r,framerate:l};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function gan(s,t,n){var r;const a=(r=s.audioCodec)==null?void 0:r.split(","),i=QNt(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 p=parseFloat(h.channels||"");a.forEach(f=>{const g={contentType:w$(f,"audio"),bitrate:n?yan(f,i):i};p&&(g.channels=""+p),u.push(g)})}return u},l):l},[]):[]}function yan(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 QNt(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function van(s){let t="";const{audio:n,video:r}=s;if(r){const a=PTe(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=PTe(n.contentType);t+=`${r?"_":""}${a}_c${n.channels}`}return t}const LTe=["NONE","TYPE-0","TYPE-1",null];function ban(s){return LTe.indexOf(s)>-1}const Xge=["SDR","PQ","HLG"];function _an(s){return!!s&&Xge.indexOf(s)>-1}var dpe={No:"",Yes:"YES",v2:"v2"};function oJe(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 cJe(this._audioGroups,t)}hasSubtitleGroup(t){return cJe(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 cJe(s,t){return!t||!s?!1:s.indexOf(t)!==-1}function wan(){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 jan(s,t){let n=!1,r=[];if(s&&(n=s!=="SDR",r=[s]),t){r=t.allowedVideoRanges||Xge.slice(0);const a=r.join("")!=="SDR"&&!t.videoCodec;n=t.preferHDR!==void 0?t.preferHDR:a&&wan(),n||(r=["SDR"])}return{preferHDR:n,allowedVideoRanges:r}}const Nan=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}},id=(s,t)=>JSON.stringify(s,Nan(t));function kan(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,p=1/0,f=1/0,g=1/0,_=1/0,v=0,j=[];const{preferHDR:b,allowedVideoRanges:S}=jan(t,a);for(let M=i.length;M--;){const F=s[i[M]];u||(u=F.channels[2]>0),p=Math.min(p,F.minHeight),f=Math.min(f,F.minFramerate),g=Math.min(g,F.minBitrate),S.filter(V=>F.videoRanges[V]>0).length>0&&(h=!0)}p=Ra(p)?p:0,f=Ra(f)?f:0;const A=Math.max(1080,p),T=Math.max(30,f);g=Ra(g)?g:n,n=Math.max(g,n),h||(t=void 0);const L=i.length>1;return{codecSet:i.reduce((M,F)=>{const z=s[F];if(F===M)return M;if(j=h?S.filter(V=>z.videoRanges[V]>0):[],L){if(z.minBitrate>n)return M_(F,`min bitrate of ${z.minBitrate} > current estimate of ${n}`),M;if(!z.hasDefaultAudio)return M_(F,"no renditions with default or auto-select sound found"),M;if(o&&F.indexOf(o.substring(0,4))%5!==0)return M_(F,`audio codec preference "${o}" not found`),M;if(l&&!d){if(!z.channels[l])return M_(F,`no renditions with ${l} channel sound found (channels options: ${Object.keys(z.channels)})`),M}else if((!o||d)&&u&&z.channels[2]===0)return M_(F,"no renditions with stereo sound found"),M;if(z.minHeight>A)return M_(F,`min resolution of ${z.minHeight} > maximum of ${A}`),M;if(z.minFramerate>T)return M_(F,`min framerate of ${z.minFramerate} > maximum of ${T}`),M;if(!j.some(V=>z.videoRanges[V]>0))return M_(F,`no variants with VIDEO-RANGE of ${id(j)} found`),M;if(c&&F.indexOf(c.substring(0,4))%5!==0)return M_(F,`video codec preference "${c}" not found`),M;if(z.maxScore=Zge(M)||z.fragmentError>s[M].fragmentError)?M:(_=z.minIndex,v=z.maxScore,F)},void 0),videoRanges:j,preferHDR:b,minFramerate:f,minBitrate:g,minIndex:_}}function M_(s,t){Pc.log(`[abr] start candidates with "${s}" ignored because ${t}`)}function XNt(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 San(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(p=>{c.channels[p]=(c.channels[p]||0)+h.channels[p]}))}),a},{})}function dJe(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 cw(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 RE(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 Ean(s,t,n,r,a){const i=t[r],o=t.reduce((p,f,g)=>{const _=f.uri;return(p[_]||(p[_]=[])).push(g),p},{})[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=uJe(t,r,p=>{if(p.videoRange!==c||p.frameRate!==d||p.codecSet.substring(0,4)!==u)return!1;const f=p.audioGroups,g=n.filter(_=>!f||f.indexOf(_.groupId)!==-1);return cw(s,g,a)>-1});return h>-1?h:uJe(t,r,p=>{const f=p.audioGroups,g=n.filter(_=>!f||f.indexOf(_.groupId)!==-1);return cw(s,g,a)>-1})}function uJe(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,p=d-u.loading.start,f=l.minAutoLevel,g=a.level,_=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const v=_>-1&&_!==g,j=!!n||v;if(!j&&(c.paused||!c.playbackRate||!c.readyState))return;const b=l.mainForwardBufferInfo;if(!j&&b===null)return;const S=this.bwEstimator.getEstimateTTFB(),A=Math.abs(c.playbackRate);if(p<=Math.max(S,1e3*(h/(A*2))))return;const T=b?b.len/A:0,L=u.loading.first?u.loading.first-u.loading.start:-1,D=u.loaded&&L>-1,M=this.getBwEstimate(),F=l.levels,z=F[g],V=Math.max(u.loaded,Math.round(h*(a.bitrate||z.averageBitrate)/8));let W=D?p-L:p;W<1&&D&&(W=Math.min(p,u.loaded*8/M));const Y=D?u.loaded*1e3/W:0,K=S/1e3,J=Y?(V-u.loaded)/Y:V*8/M+K;if(J<=T)return;const ne=Y?Y*8:M,ie=((r=(n==null?void 0:n.details)||this.hls.latestLevelDetails)==null?void 0:r.live)===!0,he=this.hls.config.abrBandWidthUpFactor;let ce=Number.POSITIVE_INFINITY,pe;for(pe=g-1;pe>f;pe--){const Te=F[pe].maxBitrate,Me=!F[pe].details||ie;if(ce=this.getTimeToLoadFrag(K,ne,h*Te,Me),ce=J||ce>h*10)return;D?this.bwEstimator.sample(p-Math.min(S,L),u.loaded):this.bwEstimator.sampleTTFB(p);const le=F[pe].maxBitrate;this.getBwEstimate()*he>le&&this.resetEstimator(le);const ve=this.findBestLevel(le,f,pe,0,T,1,1);ve>-1&&(pe=ve),this.warn(`Fragment ${a.sn}${i?" part "+i.index:""} of level ${g} is loading too slowly; Fragment duration: ${a.duration.toFixed(3)} Time to underbuffer: ${T.toFixed(3)} s Estimated load time for current fragment: ${J.toFixed(3)} s Estimated load time for down switch fragment: ${ce.toFixed(3)} s TTFB estimate: ${L|0} ms Current BW estimate: ${Ra(M)?M|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${pe} @ ${le|0} bps`),l.nextLoadLevel=l.nextAutoLevel=pe,this.clearTimer();const ge=()=>{if(this.clearTimer(),this.fragCurrent===a&&this.hls.loadLevel===pe&&pe>0){const Te=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${pe>0?"and switching down":""} Fragment duration: ${a.duration.toFixed(3)} s Time to underbuffer: ${Te.toFixed(3)} s`),a.abortRequests(),this.fragCurrent=this.partCurrent=null,pe>f){let Me=this.findBestLevel(this.hls.levels[f].bitrate,f,pe,0,Te,1,1);Me===-1&&(Me=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=Me,this.resetEstimator(this.hls.levels[Me].bitrate)}}};v||J>ce*2?ge():this.timer=self.setInterval(ge,ce*1e3),l.trigger(wt.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 Drn(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(wt.FRAG_LOADING,this.onFragLoading,this),t.on(wt.FRAG_LOADED,this.onFragLoaded,this),t.on(wt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(wt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(wt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(wt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(wt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(wt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(wt.FRAG_LOADING,this.onFragLoading,this),t.off(wt.FRAG_LOADED,this.onFragLoaded,this),t.off(wt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(wt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(wt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(wt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(wt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(wt.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 Pn.BUFFER_ADD_CODEC_ERROR:case Pn.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Pn.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;Ra(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===Ya.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(wt.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!==Ya.MAIN||t.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:n}=this.hls,r=this.getBwEstimate(),a=this.hls.config.maxStarvationDelay,i=this.findBestLevel(r,n,t,0,a,1,1);if(i>-1)return i;const l=this.hls.firstLevel,o=Math.min(Math.max(l,n),t);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,r=this.bwEstimator.canEstimate(),a=this.lastLoadedFragLevel>-1;if(t!==-1&&(!r||!a||this.nextAutoLevelKey===this.getAutoLevelKey()))return t;const i=r&&a?this.getNextABRAutoLevel():this.firstAutoLevel;if(t!==-1){const l=this.hls.levels;if(l.length>Math.max(t,i)&&l[t].loadError<=l[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:n,hls:r}=this;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:a,config:i,minAutoLevel:l}=r,o=n?n.duration:t?t.duration:0,c=this.getBwEstimate(),d=this.getStarvationDelay();let u=i.abrBandWidthFactor,h=i.abrBandWidthUpFactor;if(d){const v=this.findBestLevel(c,l,a,d,0,u,h);if(v>=0)return this.rebufferNotice=-1,v}let p=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!d){const v=this.bitrateTestDelay;v&&(p=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-v,this.info(`bitrate test took ${Math.round(1e3*v)}ms, set first fragment max fetchDuration to ${Math.round(1e3*p)} ms`),u=h=1)}const f=this.findBestLevel(c,l,a,d,p,u,h);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const g=r.levels[l],_=r.loadLevelObj;return _&&(g==null?void 0:g.bitrate)<_.bitrate?l:r.loadLevel}getStarvationDelay(){const t=this.hls,n=t.media;if(!n)return 1/0;const r=n&&n.playbackRate!==0?Math.abs(n.playbackRate):1,a=t.mainForwardBufferInfo;return(a?a.len:0)/r}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,n,r,a,i,l,o){var c;const d=a+i,u=this.lastLoadedFragLevel,h=u===-1?this.hls.firstLevel:u,{fragCurrent:p,partCurrent:f}=this,{levels:g,allAudioTracks:_,loadLevel:v,config:j}=this.hls;if(g.length===1)return 0;const b=g[h],S=!!((c=this.hls.latestLevelDetails)!=null&&c.live),A=v===-1||u===-1;let T,L="SDR",D=(b==null?void 0:b.frameRate)||0;const{audioPreference:M,videoPreference:F}=j,z=this.audioTracksByGroup||(this.audioTracksByGroup=XNt(_));let V=-1;if(A){if(this.firstSelection!==-1)return this.firstSelection;const ne=this.codecTiers||(this.codecTiers=San(g,z,n,r)),ie=kan(ne,L,t,M,F),{codecSet:he,videoRanges:ce,minFramerate:pe,minBitrate:le,minIndex:ve,preferHDR:ge}=ie;V=ve,T=he,L=ge?ce[ce.length-1]:ce[0],D=pe,t=Math.max(t,le),this.log(`picked start tier ${id(ie)}`)}else T=b==null?void 0:b.codecSet,L=b==null?void 0:b.videoRange;const W=f?f.duration:p?p.duration:0,Y=this.bwEstimator.getEstimateTTFB()/1e3,K=[];for(let ne=r;ne>=n;ne--){var J;const ie=g[ne],he=ne>h;if(!ie)continue;if(j.useMediaCapabilities&&!ie.supportedResult&&!ie.supportedPromise){const Me=navigator.mediaCapabilities;typeof(Me==null?void 0:Me.decodingInfo)=="function"&&fan(ie,z,L,D,t,M)?(ie.supportedPromise=ZNt(ie,z,Me,this.supportedCache),ie.supportedPromise.then(Ce=>{if(!this.hls)return;ie.supportedResult=Ce;const Ae=this.hls.levels,De=Ae.indexOf(ie);Ce.error?this.warn(`MediaCapabilities decodingInfo error: "${Ce.error}" for level ${De} ${id(Ce)}`):Ce.supported?Ce.decodingInfoResults.some(Ie=>Ie.smooth===!1||Ie.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${De} not smooth or powerEfficient: ${id(Ce)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${De} ${id(Ce)}`),De>-1&&Ae.length>1&&(this.log(`Removing unsupported level ${De}`),this.hls.removeLevel(De),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Ce=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Ce}`)})):ie.supportedResult=KNt}if((T&&ie.codecSet!==T||L&&ie.videoRange!==L||he&&D>ie.frameRate||!he&&D>0&&DMe.smooth===!1))&&(!A||ne!==V)){K.push(ne);continue}const ce=ie.details,pe=(f?ce==null?void 0:ce.partTarget:ce==null?void 0:ce.averagetargetduration)||W;let le;he?le=o*t:le=l*t;const ve=W&&a>=W*2&&i===0?ie.averageBitrate:ie.maxBitrate,ge=this.getTimeToLoadFrag(Y,le,ve*pe,ce===void 0);if(le>=ve&&(ne===u||ie.loadError===0&&ie.fragmentError===0)&&(ge<=Y||!Ra(ge)||S&&!this.bitrateTestDelay||ge${ne} adjustedbw(${Math.round(le)})-bitrate=${Math.round(le-ve)} ttfb:${Y.toFixed(1)} avgDuration:${pe.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${ge.toFixed(1)} firstSelection:${A} codecSet:${ie.codecSet} videoRange:${ie.videoRange} hls.loadLevel:${v}`)),A&&(this.firstSelection=ne),ne}}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 JNt={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 Man(s,t,n){if(t===null||!Array.isArray(s)||!s.length||!Ra(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)&&hJe(n,r,i)===0||Ian(i,s,Math.min(a,r))))return i;const l=JNt.search(t,hJe.bind(null,n,r));return l&&(l!==s||!i)?l:i}function Ian(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 hJe(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 Pan(s,t,n){const r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0))*1e3;return(n.endProgramDateTime||0)-r>s}function ekt(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 JNt.search(r,l=>l.cct?-1:(i=l,l.end<=n?1:l.start>n?-1:0)),i||null}return null}function e0e(s){switch(s.details){case Pn.FRAG_LOAD_TIMEOUT:case Pn.KEY_LOAD_TIMEOUT:case Pn.LEVEL_LOAD_TIMEOUT:case Pn.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function tkt(s){return s.details.startsWith("key")}function skt(s){return tkt(s)&&!!s.frag&&!s.frag.decryptdata}function mJe(s,t){const n=e0e(t);return s.default[`${n?"timeout":"error"}Retry`]}function z8e(s,t){const n=s.backoff==="linear"?1:Math.pow(2,t);return Math.min(n*s.retryDelayMs,s.maxRetryDelayMs)}function pJe(s){return Tc(Tc({},s),{errorRetry:null,timeoutRetry:null})}function t0e(s,t,n,r){if(!s)return!1;const a=r==null?void 0:r.code,i=t499)}function DTe(s){return s===0&&navigator.onLine===!1}var sf={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},B0={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class Dan extends r1{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(wt.ERROR,this.onError,this),t.on(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(wt.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(wt.ERROR,this.onError,this),t.off(wt.ERROR,this.onErrorOut,this),t.off(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(wt.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)===Ya.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 Pn.FRAG_LOAD_ERROR:case Pn.FRAG_LOAD_TIMEOUT:case Pn.KEY_LOAD_ERROR:case Pn.KEY_LOAD_TIMEOUT:n.errorAction=this.getFragRetryOrSwitchAction(n);return;case Pn.FRAG_PARSING_ERROR:if((r=n.frag)!=null&&r.gap){n.errorAction=GL();return}case Pn.FRAG_GAP:case Pn.FRAG_DECRYPT_ERROR:{n.errorAction=this.getFragRetryOrSwitchAction(n),n.errorAction.action=sf.SendAlternateToPenaltyBox;return}case Pn.LEVEL_EMPTY_ERROR:case Pn.LEVEL_PARSING_ERROR:{var l;const c=n.parent===Ya.MAIN?n.level:a.loadLevel;n.details===Pn.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 Pn.LEVEL_LOAD_ERROR:case Pn.LEVEL_LOAD_TIMEOUT:typeof(i==null?void 0:i.level)=="number"&&(n.errorAction=this.getPlaylistRetryOrSwitchAction(n,i.level));return;case Pn.AUDIO_TRACK_LOAD_ERROR:case Pn.AUDIO_TRACK_LOAD_TIMEOUT:case Pn.SUBTITLE_LOAD_ERROR:case Pn.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const c=a.loadLevelObj;if(c&&(i.type===ol.AUDIO_TRACK&&c.hasAudioGroup(i.groupId)||i.type===ol.SUBTITLE_TRACK&&c.hasSubtitleGroup(i.groupId))){n.errorAction=this.getPlaylistRetryOrSwitchAction(n,a.loadLevel),n.errorAction.action=sf.SendAlternateToPenaltyBox,n.errorAction.flags=B0.MoveAllAlternatesMatchingHost;return}}return;case Pn.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:n.errorAction={action:sf.SendAlternateToPenaltyBox,flags:B0.MoveAllAlternatesMatchingHDCP};return;case Pn.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Pn.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Pn.KEY_SYSTEM_NO_SESSION:n.errorAction={action:sf.SendAlternateToPenaltyBox,flags:B0.MoveAllAlternatesMatchingKey};return;case Pn.BUFFER_ADD_CODEC_ERROR:case Pn.REMUX_ALLOC_ERROR:case Pn.BUFFER_APPEND_ERROR:if(!n.errorAction){var o;n.errorAction=this.getLevelSwitchAction(n,(o=n.level)!=null?o:a.loadLevel)}return;case Pn.INTERNAL_EXCEPTION:case Pn.BUFFER_APPENDING_ERROR:case Pn.BUFFER_FULL_ERROR:case Pn.LEVEL_SWITCH_ERROR:case Pn.BUFFER_STALLED_ERROR:case Pn.BUFFER_SEEK_OVER_HOLE:case Pn.BUFFER_NUDGE_ON_STALL:n.errorAction=GL();return}n.type===mi.KEY_SYSTEM_ERROR&&(n.levelRetry=!1,n.errorAction=GL())}getPlaylistRetryOrSwitchAction(t,n){const r=this.hls,a=mJe(r.config.playlistLoadPolicy,t),i=this.playlistError++;if(t0e(a,i,e0e(t),t.response))return{action:sf.RetryRequest,flags:B0.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=mJe(tkt(t)?l:i,t),c=n.levels.reduce((u,h)=>u+h.fragmentError,0);if(a&&(t.details!==Pn.FRAG_GAP&&a.fragmentError++,!skt(t)&&t0e(o,c,e0e(t),t.response)))return{action:sf.RetryRequest,flags:B0.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===Pn.BUFFER_APPEND_ERROR&&a.fragmentError++;let u=-1;const{levels:h,loadLevel:p,minAutoLevel:f,maxAutoLevel:g}=r;!r.autoLevelEnabled&&!r.config.preserveManualLevelOnError&&(r.loadLevel=-1);const _=(i=t.frag)==null?void 0:i.type,j=(_===Ya.AUDIO&&d===Pn.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(d===Pn.BUFFER_ADD_CODEC_ERROR||d===Pn.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:L})=>a.audioCodec!==L),S=t.sourceBufferName==="video"&&(d===Pn.BUFFER_ADD_CODEC_ERROR||d===Pn.BUFFER_APPEND_ERROR)&&h.some(({codecSet:L,audioCodec:D})=>a.codecSet!==L&&a.audioCodec===D),{type:A,groupId:T}=(l=t.context)!=null?l:{};for(let L=h.length;L--;){const D=(L+p)%h.length;if(D!==p&&D>=f&&D<=g&&h[D].loadError===0){var o,c;const M=h[D];if(d===Pn.FRAG_GAP&&_===Ya.MAIN&&t.frag){const F=h[D].details;if(F){const z=zM(t.frag,F.fragments,t.frag.start);if(z!=null&&z.gap)continue}}else{if(A===ol.AUDIO_TRACK&&M.hasAudioGroup(T)||A===ol.SUBTITLE_TRACK&&M.hasSubtitleGroup(T))continue;if(_===Ya.AUDIO&&(o=a.audioGroups)!=null&&o.some(F=>M.hasAudioGroup(F))||_===Ya.SUBTITLE&&(c=a.subtitleGroups)!=null&&c.some(F=>M.hasSubtitleGroup(F))||j&&a.audioCodec===M.audioCodec||S&&a.codecSet===M.codecSet||!j&&a.codecSet!==M.codecSet)continue}u=D;break}}if(u>-1&&r.loadLevel!==u)return t.levelRetry=!0,this.playlistError=0,{action:sf.SendAlternateToPenaltyBox,flags:B0.None,nextAutoLevel:u}}return{action:sf.SendAlternateToPenaltyBox,flags:B0.MoveAllAlternatesMatchingHost}}onErrorOut(t,n){var r;switch((r=n.errorAction)==null?void 0:r.action){case sf.DoNothing:break;case sf.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(n),!n.errorAction.resolved&&n.details!==Pn.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 B0.None:this.switchLevel(t,i);break;case B0.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=LTe[LTe.indexOf(u)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${n.maxHdcpLevel}" or lower`);break}}case B0.MoveAllAlternatesMatchingKey:{const c=t.decryptdata;if(c){const d=this.hls.levels,u=d.length;for(let p=u;p--;)if(this.variantHasKey(d[p],c)){var l,o;this.log(`Banned key found in level ${p} (${d[p].bitrate}bps) or audio group "${(l=d[p].audioGroups)==null?void 0:l.join(",")}" (${(o=t.frag)==null?void 0:o.type} fragment) ${nf(c.keyId||[])}`),d[p].fragmentError++,d[p].loadError++,this.log(`Removing level ${p} with key error (${t.error})`),this.hls.removeLevel(p)}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=VI(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),FG(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]=fJe(r,a=>a.fragment.sn>=t))}fragBuffered(t,n){const r=VI(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<=p){i.time.push({startPTS:Math.max(l,a.start(u)),endPTS:Math.min(o,a.end(u))});break}else if(lh){const f=Math.max(l,a.start(u)),g=Math.min(o,a.end(u));g>f&&(i.partial=!0,i.time.push({startPTS:f,endPTS:g}))}else if(o<=h)break}return i}getPartialFragment(t){let n=null,r,a,i,l=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(d=>{const u=c[d];u&&FG(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||FG(n))}getState(t){const n=VI(t),r=this.fragments[n];return r?r.buffered?FG(r)?Lm.PARTIAL:Lm.OK:Lm.APPENDING:Lm.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=VI(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=VI(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=VI(t);t.clearElementaryStreamInfo();const r=this.activePartLists[t.type];if(r){const a=t.sn;this.activePartLists[t.type]=fJe(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 FG(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 VI(s){return`${s.type}_${s.level}_${s.sn}`}function fJe(s,t){return s.filter(n=>{const r=t(n);return r||n.clearElementaryStreamInfo(),r})}var $4={cbc:0,ctr:1};class Oan{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 $4.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},n,t);case $4.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 Fan(s){const t=s.byteLength,n=t&&new DataView(s.buffer).getUint8(t-1);return n?s.slice(0,t-n):s}class zan{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],p=c[3],f=new Uint32Array(256);let g=0,_=0,v=0;for(v=0;v<256;v++)v<128?f[v]=v<<1:f[v]=v<<1^283;for(v=0;v<256;v++){let j=_^_<<1^_<<2^_<<3^_<<4;j=j>>>8^j&255^99,t[g]=j,n[j]=g;const b=f[g],S=f[b],A=f[S];let T=f[j]*257^j*16843008;a[g]=T<<24|T>>>8,i[g]=T<<16|T>>>16,l[g]=T<<8|T>>>24,o[g]=T,T=A*16843009^S*65537^b*257^g*16843008,d[j]=T<<24|T>>>8,u[j]=T<<16|T>>>16,h[j]=T<<8|T>>>24,p[j]=T,g?(g=b^f[f[f[A^b]]],_^=f[f[_]]):g=_=1}}expandKey(t){const n=this.uint8ArrayToUint32Array_(t);let r=!0,a=0;for(;a{const o=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(o,n,r,a);const c=this.flush();c?i(c.buffer):l(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),n,r,a)}softwareDecrypt(t,n,r,a){const{currentIV:i,currentResult:l,remainderData:o}=this;if(a!==$4.cbc||n.byteLength!==16)return Pc.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=Yv(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 zan),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 Ban(this.subtle,n,a)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Oan(this.subtle,new Uint8Array(r),a).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(Pc.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%Uan;return r!==t.length&&(n=t.slice(0,r),this.remainderData=t.slice(r)),n}logOnce(t){this.logEnabled&&(Pc.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const xJe=Math.pow(2,17);class qan{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 N2({type:mi.NETWORK_ERROR,details:Pn.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(g=>g[0]==="GAP")){c(yJe(t));return}else t.gap=!1;const d=this.loader=i?new i(a):new l(a),u=gJe(t);t.loader=d;const h=pJe(a.fragLoadPolicy.default),p={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:xJe};t.stats=d.stats;const f={onSuccess:(g,_,v,j)=>{this.resetLoader(t,d);let b=g.data;v.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(b.slice(0,16)),b=b.slice(16)),o({frag:t,part:null,payload:b,networkDetails:j})},onError:(g,_,v,j)=>{this.resetLoader(t,d),c(new N2({type:mi.NETWORK_ERROR,details:Pn.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:Tc({url:r,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:v,stats:j}))},onAbort:(g,_,v)=>{this.resetLoader(t,d),c(new N2({type:mi.NETWORK_ERROR,details:Pn.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:v,stats:g}))},onTimeout:(g,_,v)=>{this.resetLoader(t,d),c(new N2({type:mi.NETWORK_ERROR,details:Pn.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${p.timeout}ms`),networkDetails:v,stats:g}))}};n&&(f.onProgress=(g,_,v,j)=>n({frag:t,part:null,payload:v,networkDetails:j})),d.load(u,p,f)})}loadPart(t,n,r){this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap||n.gap){c(yJe(t,n));return}const d=this.loader=i?new i(a):new l(a),u=gJe(t,n);t.loader=d;const h=pJe(a.fragLoadPolicy.default),p={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:xJe};n.stats=d.stats,d.load(u,p,{onSuccess:(f,g,_,v)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,n);const j={frag:t,part:n,payload:f.data,networkDetails:v};r(j),o(j)},onError:(f,g,_,v)=>{this.resetLoader(t,d),c(new N2({type:mi.NETWORK_ERROR,details:Pn.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:n,response:Tc({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:_,stats:v}))},onAbort:(f,g,_)=>{t.stats.aborted=n.stats.aborted,this.resetLoader(t,d),c(new N2({type:mi.NETWORK_ERROR,details:Pn.INTERNAL_ABORTED,fatal:!1,frag:t,part:n,error:new Error("Aborted"),networkDetails:_,stats:f}))},onTimeout:(f,g,_)=>{this.resetLoader(t,d),c(new N2({type:mi.NETWORK_ERROR,details:Pn.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:n,error:new Error(`Timeout after ${p.timeout}ms`),networkDetails:_,stats:f}))}})})}updateStatsFromPart(t,n){const r=t.stats,a=n.stats,i=a.total;if(r.loaded+=a.loaded,i){const c=Math.round(t.duration/n.duration),d=Math.min(Math.round(r.loaded/i),c),h=(c-d)*Math.round(r.loaded/d);r.total=r.loaded+h}else r.total=Math.max(r.loaded,r.total);const l=r.loading,o=a.loading;l.start?l.first+=o.first-o.start:(l.start=o.start,l.first=o.first),l.end=o.end}resetLoader(t,n){t.loader=null,this.loader===n&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),n.destroy()}}function gJe(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(Ra(a)&&Ra(i)){var l;let o=a,c=i;if(s.sn==="initSegment"&&Van((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 yJe(s,t){const n=new Error(`GAP ${s.gap?"tag":"attribute"} found`),r={type:mi.MEDIA_ERROR,details:Pn.FRAG_GAP,fatal:!1,frag:s,error:n,networkDetails:null};return t&&(r.part=t),(t||s).stats.aborted=!0,new N2(r)}function Van(s){return s==="AES-128"||s==="AES-256"}class N2 extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class nkt extends r1{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 $8e{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=zG(),this.buffering={audio:zG(),video:zG(),audiovideo:zG()},this.level=t,this.sn=n,this.id=r,this.size=a,this.part=i,this.partial=l}}function zG(){return{start:0,executeStart:0,executeEnd:0,end:0}}const vJe={length:0,start:()=>0,end:()=>0};class wo{static isBuffered(t,n){if(t){const r=wo.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=wo.getBuffered(t);return wo.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 p=i[h-1].end;t[u].start-pp&&(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<=p&&(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 _Je(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 Han(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 Gan=/^(\d+)x(\d+)$/,wJe=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ju{constructor(t,n){typeof t=="string"&&(t=ju.parseAttrList(t,n)),Yc(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=Gan.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(wJe.lastIndex=0;(r=wJe.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=RTe(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":Pc.warn(`${t}: attribute ${l} is missing quotes`)}a[l]=o}return a}}const Wan="com.apple.hls.interstitial";function Kan(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function Yan(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class akt{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]){Pc.warn(`DATERANGE tag attribute: "${l}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=l;break}t=Yc(new ju({}),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"]);Ra(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?(Pc.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(Ra(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===Wan}get isValid(){return!!this.id&&!this._badValueForSameId&&Ra(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 Zan=10;class Qan{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?Ra(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Zan}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 s0e(s,t){return s.length===t.length?!s.some((n,r)=>n!==t[r]):!1}function jJe(s,t){return!s&&!t?!0:!s||!t?!1:s0e(s,t)}function WL(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function U8e(s){switch(s){case"AES-128":case"AES-256":return $4.cbc;case"AES-256-CTR":return $4.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function q8e(s){return Uint8Array.from(atob(s),t=>t.charCodeAt(0))}function OTe(s){return Uint8Array.from(unescape(encodeURIComponent(s)),t=>t.charCodeAt(0))}function Xan(s){const t=OTe(s).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}function ikt(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 okt(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=q8e(l)):n=Xan(l)}}return n}const n0e=typeof self<"u"?self:void 0;var Mu={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},of={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function upe(s){switch(s){case of.FAIRPLAY:return Mu.FAIRPLAY;case of.PLAYREADY:return Mu.PLAYREADY;case of.WIDEVINE:return Mu.WIDEVINE;case of.CLEARKEY:return Mu.CLEARKEY}}function ske(s){switch(s){case Mu.FAIRPLAY:return of.FAIRPLAY;case Mu.PLAYREADY:return of.PLAYREADY;case Mu.WIDEVINE:return of.WIDEVINE;case Mu.CLEARKEY:return of.CLEARKEY}}function M7(s){const{drmSystems:t,widevineLicenseUrl:n}=s,r=t?[Mu.FAIRPLAY,Mu.WIDEVINE,Mu.PLAYREADY,Mu.CLEARKEY].filter(a=>!!t[a]):[];return!r[Mu.WIDEVINE]&&n&&r.push(Mu.WIDEVINE),r}const lkt=function(s){return n0e!=null&&(s=n0e.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Jan(s,t,n,r){let a;switch(s){case Mu.FAIRPLAY:a=["cenc","sinf"];break;case Mu.WIDEVINE:case Mu.PLAYREADY:a=["cenc"];break;case Mu.CLEARKEY:a=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return ein(a,t,n,r)}function ein(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 tin(s){var t;return!!s&&(s.sessionType==="persistent-license"||!!((t=s.sessionTypes)!=null&&t.some(n=>n==="persistent-license")))}function ckt(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=q8e(o).subarray(0,16);return ikt(c),c}}return null}let HI={};class j4{static clearKeyUriToKeyIdMap(){HI={}}static setKeyIdForUri(t,n){HI[t]=n}static addKeyIdForUri(t){const n=Object.keys(HI).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,n),HI[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&&!WL(t),l!=null&&l.startsWith("0x")&&(this.keyId=new Uint8Array(ONt(l)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&s0e(t.keyFormatVersions,this.keyFormatVersions)&&jJe(t.iv,this.iv)&&jJe(t.keyId,this.keyId)}isSupported(){if(this.method){if(WL(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case of.FAIRPLAY:case of.WIDEVINE:case of.PLAYREADY:case of.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(WL(this.method)){let i=this.iv;return i||(typeof t!="number"&&(Pc.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),i=nin(t)),new j4(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){const i=HI[this.uri];if(i&&!s0e(this.keyId,i)&&j4.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const r=okt(this.uri);if(r)switch(this.keyFormat){case of.WIDEVINE:if(this.pssh=r,!this.keyId){const i=ian(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=NJe(n));break;case of.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=aan(i,null,r),this.keyId=ckt(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=sin(n),i||(i=NJe(n),i||(i=HI[this.uri])),i&&(this.keyId=i,j4.setKeyIdForUri(this.uri,i))}return this}}function sin(s){const t=s==null?void 0:s[of.WIDEVINE];return t?t.keyId:null}function NJe(s){const t=s==null?void 0:s[of.PLAYREADY];if(t){const n=okt(t.uri);if(n)return ckt(n)}return null}function nin(s){const t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=s>>8*(15-n)&255;return t}const kJe=/#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,SJe=/#EXT-X-MEDIA:(.*)/g,rin=/^#EXT(?:INF|-X-TARGETDURATION):/m,nke=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),ain=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 dw{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(SJe.lastIndex=0;(a=SJe.exec(t))!==null;){const d=new ju(a[1],r),u=d.TYPE;if(u){const h=o[u],p=i[u]||[];i[u]=p;const f=d.LANGUAGE,g=d["ASSOC-LANGUAGE"],_=d.CHANNELS,v=d.CHARACTERISTICS,j=d["INSTREAM-ID"],b={attrs:d,bitrate:0,id:c++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:u,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?dw.resolve(d.URI,n):""};if(g&&(b.assocLang=g),_&&(b.channels=_),v&&(b.characteristics=v),j&&(b.instreamId=j),h!=null&&h.length){const S=dw.findGroup(h,b.groupId)||h[0];AJe(b,S,"audioCodec"),AJe(b,S,"textCodec")}p.push(b)}}return i}static parseLevelPlaylist(t,n,r,a,i,l){var o;const c={url:n},d=new Qan(n),u=d.fragments,h=[];let p=null,f=0,g=0,_=0,v=0,j=0,b=null,S=new JNe(a,c),A,T,L,D=-1,M=!1,F=null,z;if(nke.lastIndex=0,d.m3u8=t,d.hasVariableRefs=bJe(t),((o=nke.exec(t))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(A=nke.exec(t))!==null;){M&&(M=!1,S=new JNe(a,c),S.playlistOffset=_,S.setStart(_),S.sn=f,S.cc=v,j&&(S.bitrate=j),S.level=r,p&&(S.initSegment=p,p.rawProgramDateTime&&(S.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),F&&(S.setByteRange(F),F=null)));const K=A[1];if(K){S.duration=parseFloat(K);const J=(" "+A[2]).slice(1);S.title=J||null,S.tagList.push(J?["INF",K,J]:["INF",K])}else if(A[3]){if(Ra(S.duration)){S.playlistOffset=_,S.setStart(_),L&&IJe(S,L,d),S.sn=f,S.level=r,S.cc=v,u.push(S);const J=(" "+A[3]).slice(1);S.relurl=RTe(d,J),FTe(S,b,h),b=S,_+=S.duration,f++,g=0,M=!0}}else{if(A=A[0].match(ain),!A){Pc.warn("No matches on slow regex match for level playlist!");continue}for(T=1;T0&&PJe(d,J,A),f=d.startSN=parseInt(ne);break;case"SKIP":{d.skippedSegments&&h2(d,J,A);const he=new ju(ne,d),ce=he.decimalInteger("SKIPPED-SEGMENTS");if(Ra(ce)){d.skippedSegments+=ce;for(let le=ce;le--;)u.push(null);f+=ce}const pe=he.enumeratedString("RECENTLY-REMOVED-DATERANGES");pe&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(pe.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&h2(d,J,A),d.targetduration=Math.max(parseInt(ne),1);break;case"VERSION":d.version!==null&&h2(d,J,A),d.version=parseInt(ne);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||h2(d,J,A),d.live=!1;break;case"#":(ne||ie)&&S.tagList.push(ie?[ne,ie]:[ne]);break;case"DISCONTINUITY":v++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([J]);break;case"BITRATE":S.tagList.push([J,ne]),j=parseInt(ne)*1e3,Ra(j)?S.bitrate=j:j=0;break;case"DATERANGE":{const he=new ju(ne,d),ce=new akt(he,d.dateRanges[he.ID],d.dateRangeTagCount);d.dateRangeTagCount++,ce.isValid||d.skippedSegments?d.dateRanges[ce.id]=ce:Pc.warn(`Ignoring invalid DATERANGE tag: "${ne}"`),S.tagList.push(["EXT-X-DATERANGE",ne]);break}case"DEFINE":{{const he=new ju(ne,d);"IMPORT"in he?Han(d,he,l):_Je(d,he,n)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?h2(d,J,A):u.length>0&&PJe(d,J,A),d.startCC=v=parseInt(ne);break;case"KEY":{const he=CJe(ne,n,d);if(he.isSupported()){if(he.method==="NONE"){L=void 0;break}L||(L={});const ce=L[he.keyFormat];ce!=null&&ce.matches(he)||(ce&&(L=Yc({},L)),L[he.keyFormat]=he)}else Pc.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${ne}"`);break}case"START":d.startTimeOffset=TJe(ne);break;case"MAP":{const he=new ju(ne,d);if(S.duration){const ce=new JNe(a,c);MJe(ce,he,r,L),p=ce,S.initSegment=p,p.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=p.rawProgramDateTime)}else{const ce=S.byteRangeEndOffset;if(ce){const pe=S.byteRangeStartOffset;F=`${ce-pe}@${pe}`}else F=null;MJe(S,he,r,L),p=S,M=!0}p.cc=v;break}case"SERVER-CONTROL":{z&&h2(d,J,A),z=new ju(ne),d.canBlockReload=z.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=z.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&z.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=z.optionalFloat("PART-HOLD-BACK",0),d.holdBack=z.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&h2(d,J,A);const he=new ju(ne);d.partTarget=he.decimalFloatingPoint("PART-TARGET");break}case"PART":{let he=d.partList;he||(he=d.partList=[]);const ce=g>0?he[he.length-1]:void 0,pe=g++,le=new ju(ne,d),ve=new Hrn(le,S,c,pe,ce);he.push(ve),S.duration+=ve.duration;break}case"PRELOAD-HINT":{const he=new ju(ne,d);d.preloadHint=he;break}case"RENDITION-REPORT":{const he=new ju(ne,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(he);break}default:Pc.warn(`line parsed but not handled: ${A}`);break}}}b&&!b.relurl?(u.pop(),_-=b.duration,d.partList&&(d.fragmentHint=b)):d.partList&&(FTe(S,b,h),S.cc=v,d.fragmentHint=S,L&&IJe(S,L,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const V=u.length,W=u[0],Y=u[V-1];if(_+=d.skippedSegments*d.targetduration,_>0&&V&&Y){d.averagetargetduration=_/V;const K=Y.sn;d.endSN=K!=="initSegment"?K:0,d.live||(Y.endList=!0),D>0&&(oin(u,D),W&&h.unshift(W))}return d.fragmentHint&&(_+=d.fragmentHint.duration),d.totalduration=_,h.length&&d.dateRangeTagCount&&W&&dkt(h,d),d.endCC=v,d}}function dkt(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 p=(n[r+1]||u[u.length-1]).sn-s.startSN;for(let f=p;f>d;f--){const g=u[f].programDateTime;if(t>=g&&tr);["video","audio","text"].forEach(r=>{const a=n.filter(i=>O8e(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 AJe(s,t,n){const r=t[n];r&&(s[n]=r)}function oin(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 FTe(s,t,n){s.rawProgramDateTime?n.push(s):t!=null&&t.programDateTime&&(s.programDateTime=t.endProgramDateTime)}function MJe(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 IJe(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 h2(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${n[0]})`)}function PJe(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${n[0]})`)}function rke(s,t){const n=t.startPTS;if(Ra(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 ukt(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(Ra(u)){const j=Math.abs(u-n);s&&j>s.totalduration?l.warn(`media timestamps and playlist times differ by ${j}s for level ${t.level} ${s.url}`):Ra(t.deltaPTS)?t.deltaPTS=Math.max(j,t.deltaPTS):t.deltaPTS=j,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 p=n-t.start;t.start!==0&&t.setStart(n),t.setDuration(r-t.start),t.startPTS=n,t.maxStartPTS=c,t.startDTS=a,t.endPTS=r,t.minEndPTS=d,t.endDTS=i;const f=t.sn;if(!s||fs.endSN)return 0;let g;const _=f-s.startSN,v=s.fragments;for(v[_]=t,g=_;g>0;g--)rke(v[g],v[g-1]);for(g=_;g=0;u--){const h=a[u].initSegment;if(h){r=h;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let i;uin(s,t,(u,h,p,f)=>{if((!t.startCC||t.skippedSegments)&&h.cc!==u.cc){const g=u.cc-h.cc;for(let _=p;_{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=cin(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?ukt(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,n):hkt(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 cin(s,t,n){const{dateRanges:r,recentlyRemovedDateranges:a}=t,i=Yc({},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 akt(r[c].attr,d);u.isValid?(i[c]=u,d||(u.tagOrder+=o)):n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${id(r[c].attr)}"`)}),i):r}function din(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 uin(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 p=u.relurl,f=h.relurl;if(p&&hin(p,f)){t.playlistParsingError=LJe(`media sequence mismatch ${h.sn}:`,s,t,u,h);return}else if(u.cc!==h.cc){t.playlistParsingError=LJe(`discontinuity sequence mismatch (${u.cc}!=${h.cc})`,s,t,u,h);return}}}}function LJe(s,t,n,r,a){return new Error(`${s} ${a.url} Playlist starting @${t.startSN} ${t.m3u8} Playlist starting @${n.startSN} ${n.m3u8}`)}function hkt(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 hin(s,t){return s!==t&&t?RJe(s)!==RJe(t):!1}function RJe(s){return s.replace(/\?[^?]*$/,"")}function Mz(s,t){for(let r=0,a=s.length;rs.startCC)}function OJe(s,t){const n=s.start+t;s.startPTS=n,s.setStart(n),s.endPTS=n+s.duration}function gkt(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,p=wo.bufferInfo(d||c,h,l.maxBufferHole),f=!p.len;if(this.log(`Media seeking to ${Ra(h)?h.toFixed(3):h}, state: ${u}, ${f?"out of":"in"} buffer`),this.state===dr.ENDED)this.resetLoadingState();else if(o){const g=l.maxFragLookUpTolerance,_=o.start-g,v=o.start+o.duration+g;if(f||vp.end){const j=h>v;(h<_||j)&&(j&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(h,1/0,this.playlistType,!0);const g=this.lastCurrentTime;if(h>g&&(this.lastCurrentTime=h),!this.loadingParts){const _=Math.max(p.end,h),v=this.shouldLoadParts(this.getLevelDetails(),_);v&&(this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${_.toFixed(2)}`),this.loadingParts=v)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,f&&(this.startPosition=h)),f&&this.state===dr.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 qan(t.config),this.keyLoader=r,this.fragmentTracker=n,this.config=t.config,this.decrypter=new B8e(t.config)}registerListeners(){const{hls:t}=this;t.on(wt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(wt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(wt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(wt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(wt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(wt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(wt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(wt.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===dr.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=dr.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=wo.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===dr.FRAG_LOADING||!this.fragCurrent&&l===dr.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=dr.IDLE);return}"payload"in i&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(wt.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===dr.STOPPED||this.state===dr.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)===Lm.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)===Lm.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(wt.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&&WL(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(l),o.key.buffer,o.iv.buffer,U8e(o.method)).catch(d=>{throw a.trigger(wt.ERROR,{type:mi.MEDIA_ERROR,details:Pn.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:i}),d}).then(d=>{const u=self.performance.now();return a.trigger(wt.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===dr.STOPPED||this.state===dr.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!==dr.STOPPED&&(this.state=dr.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(wt.ERROR,{type:mi.KEY_SYSTEM_ERROR,details:Pn.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?fin.toString(wo.getBuffered(r)):"(detached)"})`),Th(t)){var a;if(t.type!==Ya.SUBTITLE){const l=t.elementaryStreams;if(!Object.keys(l).some(o=>!!l[o])){this.state=dr.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=dr.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 $8e(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=dr.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(p=>{if(!this.fragContextChanged(p.frag))return this.hls.trigger(wt.KEY_LOADED,p),this.state===dr.KEY_LOADING&&(this.state=dr.IDLE),p}),this.hls.trigger(wt.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(Th(t)&&(!c||t.sn!==c.sn)){const p=this.shouldLoadParts(n.details,t.end);p!==this.loadingParts&&(this.log(`LL-Part loading ${p?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${t.sn}`),this.loadingParts=p)}if(r=Math.max(t.start,r||0),this.loadingParts&&Th(t)){const p=l.partList;if(p&&a){r>l.fragmentEnd&&l.fragmentHint&&(t=l.fragmentHint);const f=this.getNextPart(p,t,r);if(f>-1){const g=p[f];t=this.fragCurrent=g.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${g.index} (${f}/${p.length-1}) of ${this.fragInfo(t,!1,g)}) cc: ${t.cc} [${l.startSN}-${l.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=g.start+g.duration,this.state=dr.FRAG_LOADING;let _;return o?_=o.then(v=>!v||this.fragContextChanged(v.frag)?null:this.doFragPartsLoad(t,g,n,a)).catch(v=>this.handleFragLoadError(v)):_=this.doFragPartsLoad(t,g,n,a).catch(v=>this.handleFragLoadError(v)),this.hls.trigger(wt.FRAG_LOADING,{frag:t,part:g,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):_}else if(!t.url||this.loadedEndOfParts(p,r))return Promise.resolve(null)}}if(Th(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(p=>p.loaded).map(p=>`[${p.start}-${p.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))}`),Ra(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=dr.FRAG_LOADING;const u=this.config.progressive&&t.type!==Ya.SUBTITLE;let h;return u&&o?h=o.then(p=>!p||this.fragContextChanged(p.frag)?null:this.fragmentLoader.load(t,a)).catch(p=>this.handleFragLoadError(p)):h=Promise.all([this.fragmentLoader.load(t,u?a:void 0),o]).then(([p])=>(!u&&a&&a(p),p)).catch(p=>this.handleFragLoadError(p)),this.hls.trigger(wt.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(p=>{c[h.index]=p;const f=p.part;this.hls.trigger(wt.FRAG_LOADED,p);const g=DJe(r.details,t.sn,h.index+1)||fkt(d,t.sn,h.index+1);if(g)u(g);else return i({frag:t,part:f,partsLoaded:c})}).catch(l)};u(n)})}handleFragLoadError(t){if("data"in t){const n=t.data;n.frag&&n.details===Pn.INTERNAL_ABORTED?this.handleFragLoadAborted(n.frag,n.part):n.frag&&n.type===mi.KEY_SYSTEM_ERROR?(n.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(n.frag)):this.hls.trigger(wt.ERROR,n)}else this.hls.trigger(wt.ERROR,{type:mi.OTHER_ERROR,details:Pn.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const n=this.getCurrentContext(t);if(!n||this.state!==dr.PARSING){!this.fragCurrent&&this.state!==dr.STOPPED&&this.state!==dr.ERROR&&(this.state=dr.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===Ya.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?DJe(c,i,l):null,u=d?d.fragment:pkt(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!==dr.PARSING)return;const{data1:l,data2:o}=t;let c=l;if(o&&(c=Yv(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(wt.BUFFER_APPENDING,h),t.dropped&&t.independent&&!r){if(i)return;this.flushBufferGap(n)}}flushBufferGap(t){const n=this.media;if(!n)return;if(!wo.isBuffered(n,n.currentTime)){this.flushMainBuffer(0,t.start);return}const r=n.currentTime,a=wo.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(!Ra(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=wo.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 wo.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=Ya.MAIN){const r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,n):null;return r&&"fragment"in r?r.fragment:r}getNextFragment(t,n){const r=n.fragments,a=r.length;if(!a)return null;const{config:i}=this,l=n.fragmentStart,o=i.lowLatencyMode&&!!n.partList;let c=null;if(n.live){const h=i.initialLiveManifestSize;if(a=l?(v=f,j=f===p?"config":"next load start"):g!==null?(v=g,j="live edge"):(v=t,j="buffer pos"),v<_&&(v=_,j="live frag start"),v=i){const c=l.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${a}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,l}get primaryPrefetch(){if(FJe(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(FJe(this.config)&&t.type!==Ya.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=Man(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=ekt(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 p;if(tn-d||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:d;p=zM(i,l,t,_)}else p=l[l.length-1];if(p){const g=p.sn-r.startSN,_=this.fragmentTracker.getState(p);if((_===Lm.OK||_===Lm.PARTIAL&&p.gap)&&(i=p),i&&p.sn===i.sn&&(!h||u[0].fragment.sn>p.sn||!r.live)&&p.level===i.level){const j=l[g+1];p.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&&Th(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!==dr.FRAG_LOADING_WAITING_RETRY)&&(this.state=dr.IDLE)}onFragmentOrKeyLoadError(t,n){var r;if(n.chunkMeta&&!n.frag){const j=this.getCurrentContext(n.chunkMeta);j&&(n.frag=j.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===Pn.FRAG_GAP;l&&this.fragmentTracker.fragBuffered(a,!0);const o=n.errorAction;if(!o){this.state=dr.ERROR;return}const{action:c,flags:d,retryCount:u=0,retryConfig:h}=o,p=!!h,f=p&&c===sf.RetryRequest,g=p&&!o.resolved&&d===B0.MoveAllAlternatesMatchingHost,_=(r=this.hls.latestLevelDetails)==null?void 0:r.live;if(!f&&g&&Th(a)&&!a.endList&&_&&!skt(n))this.resetFragmentErrors(t),this.treatAsGap(a),o.resolved=!0;else if((f||g)&&u=n||r&&!DTe(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=dr.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===dr.PARSING||this.state===dr.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===Ya.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==dr.STOPPED&&(this.state=dr.IDLE)}afterBufferFlushed(t,n,r){if(!t)return;const a=wo.getBuffered(t);this.fragmentTracker.detectEvictedFragments(n,a,r),this.state===dr.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==dr.STOPPED&&(this.state=dr.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 p=a?0:ukt(i,t,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(wt.LEVEL_PTS_UPDATED,{details:i,level:r,drift:p,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(wt.ERROR,{type:mi.MEDIA_ERROR,details:Pn.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=dr.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${n?" part: "+n.index:""} of ${this.fragInfo(t,!1,n)})`),this.hls.trigger(wt.FRAG_PARSED,{frag:t,part:n})}playlistLabel(){return this.playlistType===Ya.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 FJe(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class vkt{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=xin(t,n);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}}function xin(s,t){const n=new Uint8Array(t);let r=0;for(let a=0;a0)return s.subarray(n,n+r)}function jin(s,t,n,r){const a=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],i=t[n+2],l=i>>2&15;if(l>12){const f=new Error(`invalid ADTS sampling index:${l}`);s.emit(wt.ERROR,wt.ERROR,{type:mi.MEDIA_ERROR,details:Pn.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(i>>6&3)+1,c=t[n+3]>>6&3|(i&1)<<2,d="mp4a.40."+o,u=a[l];let h=l;(o===5||o===29)&&(h-=3);const p=[o<<3|(h&14)>>1,(h&1)<<7|c<<3];return Pc.log(`manifest codec:${r}, parsed codec:${d}, channels:${c}, rate:${u} (ADTS object type:${o} sampling index:${l})`),{config:p,samplerate:u,channelCount:c,codec:d,parsedCodec:d,manifestCodec:r}}function _kt(s,t){return s[t]===255&&(s[t+1]&246)===240}function wkt(s,t){return s[t+1]&1?7:9}function W8e(s,t){return(s[t+3]&3)<<11|s[t+4]<<3|(s[t+5]&224)>>>5}function Nin(s,t){return t+5=s.length)return!1;const r=W8e(s,t);if(r<=n)return!1;const a=t+r;return a===s.length||a0e(s,a)}return!1}function jkt(s,t,n,r,a){if(!s.samplerate){const i=jin(t,n,r,a);if(!i)return;Yc(s,i)}}function Nkt(s){return 1024*9e4/s}function Cin(s,t){const n=wkt(s,t);if(t+n<=s.length){const r=W8e(s,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}function kkt(s,t,n,r,a){const i=Nkt(s.samplerate),l=r+a*i,o=Cin(t,n);let c;if(o){const{frameLength:h,headerLength:p}=o,f=p+h,g=Math.max(0,n+f-t.length);g?(c=new Uint8Array(f-p),c.set(t.subarray(n+p,t.length),0)):c=t.subarray(n+p,n+f);const _={unit:c,pts:l};return g||s.samples.push(_),{sample:_,length:f,missing:g}}const d=t.length-n;return c=new Uint8Array(d),c.set(t.subarray(n,t.length),0),{sample:{unit:c,pts:l},length:d,missing:-1}}function Tin(s,t){return G8e(s,t)&&dbe(s,t+6)+10<=s.length-t}function Ein(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function ike(s,t=0,n=1/0){return Ain(s,t,n,Uint8Array)}function Ain(s,t,n,r){const a=Min(s);let i=1;"BYTES_PER_ELEMENT"in r&&(i=r.BYTES_PER_ELEMENT);const l=Iin(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 Min(s){return s instanceof ArrayBuffer?s:s.buffer}function Iin(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function Pin(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=yy(ike(s.data,1,r)),i=s.data[2+r],l=s.data.subarray(3+r).indexOf(0);if(l===-1)return;const o=yy(ike(s.data,3+r,l));let c;return a==="-->"?c=yy(ike(s.data,4+r+l)):c=Ein(s.data.subarray(4+r+l)),t.mimeType=a,t.pictureType=i,t.description=o,t.data=c,t}function Lin(s){if(s.size<2)return;const t=yy(s.data,!0),n=new Uint8Array(s.data.subarray(t.length+1));return{key:s.type,info:t,data:n.buffer}}function Din(s){if(s.size<2)return;if(s.type==="TXXX"){let n=1;const r=yy(s.data.subarray(n),!0);n+=r.length+1;const a=yy(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=yy(s.data.subarray(1));return{key:s.type,info:"",data:t}}function Rin(s){if(s.type==="WXXX"){if(s.size<2)return;let n=1;const r=yy(s.data.subarray(n),!0);n+=r.length+1;const a=yy(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=yy(s.data);return{key:s.type,info:"",data:t}}function Oin(s){return s.type==="PRIV"?Lin(s):s.type[0]==="W"?Rin(s):s.type==="APIC"?Pin(s):Din(s)}function Fin(s){const t=String.fromCharCode(s[0],s[1],s[2],s[3]),n=dbe(s,4),r=10;return{type:t,size:n,data:s.subarray(r,r+n)}}const BG=10,zin=10;function Skt(s){let t=0;const n=[];for(;G8e(s,t);){const r=dbe(s,t+6);s[t+5]>>6&1&&(t+=BG),t+=BG;const a=t+r;for(;t+zin0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Y0.audioId3,duration:Number.POSITIVE_INFINITY});a{if(Ra(s))return s*90;const r=n?n.baseTime*9e4/n.timescale:0;return t*9e4+r};let $G=null;const Uin=[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],qin=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Vin=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Hin=[0,1,1,4];function Tkt(s,t,n,r,a){if(n+24>t.length)return;const i=Ekt(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 Ekt(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=Uin[c*14+a-1]*1e3,h=qin[(n===3?0:n===2?1:2)*3+i],p=o===3?1:2,f=Vin[n][r],g=Hin[r],_=f*8*g,v=Math.floor(f*d/h+l)*g;if($G===null){const S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);$G=S?parseInt(S[1]):0}return!!$G&&$G<=87&&r===2&&d>=224e3&&o===0&&(s[t+3]=s[t+3]|128),{sampleRate:h,channelCount:p,frameLength:v,samplesPerFrame:_}}}function Z8e(s,t){return s[t]===255&&(s[t+1]&224)===224&&(s[t+1]&6)!==0}function Akt(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 p=0;h===2?p+=2:(h&1&&h!==1&&(p+=2),h&4&&(p+=2));const f=(t[n+6]<<8|t[n+7])>>12-p&1,_=[2,1,2,3,3,4,4,5][h]+f,v=t[n+5]>>3,j=t[n+5]&7,b=new Uint8Array([i<<6|v<<1|j>>2,(j&3)<<6|h<<3|f<<2|c>>4,c<<4&224]),S=1536/o*9e4,A=r+a*S,T=t.subarray(n,n+u);return s.config=b,s.channelCount=_,s.samplerate=o,s.samples.push({unit:T,pts:A}),u}class Yin extends Y8e{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=k$(t,0);let r=(n==null?void 0:n.length)||0;if(n&&t[r]===11&&t[r+1]===119&&K8e(n)!==void 0&&Ikt(t,r)<=16)return!1;for(let a=t.length;r{const l=nan(i);if(Zin.test(l.schemeIdUri)){const o=BJe(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:Y0.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&l.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=BJe(l,n);r.samples.push({data:l.payload,len:l.payload.byteLength,dts:o,pts:o,type:Y0.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 BJe(s,t){return Ra(s.presentationTime)?s.presentationTime/s.timeScale:t+s.presentationTimeDelta/s.timeScale}class Xin{constructor(t,n,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new B8e(n,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,$4.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 Lkt{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,p=-1,f=0;for(i===-1&&(p=0,f=this.getNALuType(n,0),i=0,c=1);c=0){const g={data:n.subarray(p,u),type:f};o.push(g)}else{const g=this.getLastNalUnit(t.samples);g&&(l&&c<=4-l&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-l)),u>0&&(g.data=Yv(g.data,n.subarray(0,u)),g.state=0))}c=0&&i>=0){const g={data:n.subarray(p,a),type:f,state:i};o.push(g)}if(o.length===0){const g=this.getLastNalUnit(t.samples);g&&(g.data=Yv(g.data,n))}return t.naluState=i,o}}class Iz{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&&Pc.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 Jin extends Lkt{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 _=!1;o=!0;const v=d.data;if(c&&v.length>4){const j=this.readSliceType(v);(j===2||j===4||j===7||j===9)&&(_=!0)}if(_){var p;(p=l)!=null&&p.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=_;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,R8e(d.data,1,r.pts,n.samples);break}case 7:{var f,g;o=!0,c=!0;const _=d.data,v=this.readSPS(_);if(!t.sps||t.width!==v.width||t.height!==v.height||((f=t.pixelRatio)==null?void 0:f[0])!==v.pixelRatio[0]||((g=t.pixelRatio)==null?void 0:g[1])!==v.pixelRatio[1]){t.width=v.width,t.height=v.height,t.pixelRatio=v.pixelRatio,t.sps=[_];const j=_.subarray(1,4);let b="avc1.";for(let S=0;S<3;S++){let A=j[S].toString(16);A.length<2&&(A="0"+A),b+=A}t.codec=b}break}case 8:o=!0,t.pps=[d.data];break;case 9:o=!0,t.audFound=!0,(h=l)!=null&&h.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:o=!0;break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,n){return t[n]&31}readSliceType(t){const n=new Iz(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 p;(p=l)!=null&&p.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,R8e(d.data,2,r.pts,n.samples);break;case 32:o=!0,t.vps||(typeof t.params!="object"&&(t.params={}),t.params=Yc(t.params,this.readVPS(d.data)),this.initVPS=d.data),t.vps=[d.data];break;case 33:if(o=!0,c=!0,t.vps!==void 0&&t.vps[0]!==this.initVPS&&t.sps!==void 0&&!this.matchSPS(t.sps[0],d.data)&&(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const f=this.readSPS(d.data);t.width=f.width,t.height=f.height,t.pixelRatio=f.pixelRatio,t.codec=f.codecString,t.sps=[],typeof t.params!="object"&&(t.params={});for(const g in f.params)t.params[g]=f.params[g]}this.pushParameterSet(t.sps,d.data,t.vps),l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.key=!0;break;case 34:if(o=!0,typeof t.params=="object"){if(!t.pps){t.pps=[];const f=this.readPPS(d.data);for(const g in f)t.params[g]=f[g]}this.pushParameterSet(t.pps,d.data,t.vps)}break;case 35:o=!0,t.audFound=!0,(h=l)!=null&&h.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}pushParameterSet(t,n,r){(r&&r[0]===this.initVPS||!r&&!t.length)&&t.push(n)}getNALuType(t,n){return(t[n]&126)>>>1}ebsp2rbsp(t){const n=new Uint8Array(t.byteLength);let r=0;for(let a=0;a=2&&t[a]===3&&t[a-1]===0&&t[a-2]===0||(n[r]=t[a],r++);return new Uint8Array(n.buffer,0,r)}pushAccessUnit(t,n){super.pushAccessUnit(t,n),this.initVPS&&(this.initVPS=null)}readVPS(t){const n=new Iz(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 Iz(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(),p=n.readUByte(),f=n.readUByte(),g=n.readUByte(),_=n.readUByte(),v=n.readUByte(),j=n.readUByte(),b=[],S=[];for(let je=0;je0)for(let je=r;je<8;je++)n.readBits(2);for(let je=0;je1&&n.readEG();for(let rt=0;rt0&&tt<16?(ve=at[tt-1],ge=He[tt-1]):tt===255&&(ve=n.readBits(16),ge=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(),Ae=n.readBoolean(),Ae&&(n.skipUEG(),n.skipUEG(),n.skipUEG(),n.skipUEG()),n.readBoolean()&&(Me=n.readBits(32),Ce=n.readBits(32),n.readBoolean()&&n.readUEG(),n.readBoolean())){const He=n.readBoolean(),dt=n.readBoolean();let bt=!1;(He||dt)&&(bt=n.readBoolean(),bt&&(n.readUByte(),n.readBits(5),n.readBoolean(),n.readBits(5)),n.readBits(4),n.readBits(4),bt&&n.readBits(4),n.readBits(5),n.readBits(5),n.readBits(5));for(let vt=0;vt<=r;vt++){Te=n.readBoolean();const Bt=Te||n.readBoolean();let Zt=!1;Bt?n.readEG():Zt=n.readBoolean();const Fs=Zt?1:n.readUEG()+1;if(He)for(let Rs=0;Rs>je&1)<<31-je)>>>0;let Ne=Ze.toString(16);return l===1&&Ne==="2"&&(Ne="6"),{codecString:`hvc1.${qe}${l}.${Ne}.${i?"H":"L"}${j}.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,p,f,g,_,v],general_level_idc:j,bit_depth:W+8,bit_depth_luma_minus8:W,bit_depth_chroma_minus8:Y,min_spatial_segmentation_idc:le,chroma_format_idc:A,frame_rate:{fixed:Te,fps:Ce/Me}},width:Ie,height:Fe,pixelRatio:[ve,ge]}}readPPS(t){const n=new Iz(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 fp=188;class oS{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=oS.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(fp*5,n-fp)+1,a=0;for(;a1&&(l===0&&o>2||c+fp>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:BNt[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=oS.createTrack("video"),this._videoTrack.duration=a,this._audioTrack=oS.createTrack("audio",a),this._id3Track=oS.createTrack("id3"),this._txtTrack=oS.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,p=o.pid,f=c.pid,g=o.pesData,_=c.pesData,v=null,j=this.pmtParsed,b=this._pmtId,S=t.length;if(this.remainderData&&(t=Yv(this.remainderData,t),S=t.length,this.remainderData=null),S>4;let V;if(z>1){if(V=D+5+t[D+4],V===D+fp)continue}else V=D+4;switch(F){case u:M&&(h&&(i=GI(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(V,D+fp)),h.size+=D+fp-V);break;case p:if(M){if(g&&(i=GI(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,i);break;case"mp3":this.parseMPEGPES(o,i);break;case"ac3":this.parseAC3PES(o,i);break}g={data:[],size:0}}g&&(g.data.push(t.subarray(V,D+fp)),g.size+=D+fp-V);break;case f:M&&(_&&(i=GI(_,this.logger))&&this.parseID3PES(c,i),_={data:[],size:0}),_&&(_.data.push(t.subarray(V,D+fp)),_.size+=D+fp-V);break;case 0:M&&(V+=t[V]+1),b=this._pmtId=ton(t,V);break;case b:{M&&(V+=t[V]+1);const W=son(t,V,this.typeSupported,r,this.observer,this.logger);u=W.videoPid,u>0&&(l.pid=u,l.segmentCodec=W.segmentVideoCodec),p=W.audioPid,p>0&&(o.pid=p,o.segmentCodec=W.segmentAudioCodec),f=W.id3Pid,f>0&&(c.pid=f),v!==null&&!j&&(this.logger.warn(`MPEG-TS PMT found at ${D} after unknown PID '${v}'. Backtracking to sync byte @${A} to parse all TS packets.`),v=null,D=A-188),j=this.pmtParsed=!0;break}case 17:case 8191:break;default:v=F;break}}else T++;T>0&&$Te(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),l.pesData=h,o.pesData=g,c.pesData=_;const L={audioTrack:o,videoTrack:l,id3Track:c,textTrack:d};return a&&this.extractRemainingSamples(L),L}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=GI(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=GI(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=GI(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 Xin(this.observer,this.config,n);return this.decrypt(a,i)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new Jin:t==="hevc"&&(this.videoParser=new eon))}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,p=a.sample.unit.byteLength;if(h===-1)i=Yv(a.sample.unit,i);else{const f=p-h;a.sample.unit.set(i.subarray(0,h),f),t.samples.push(a.sample),r=a.missing}}let l,o;for(l=r,o=i.length;l0;)o+=c}}parseID3PES(t,n){if(n.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const r=Yc({},n,{type:this._videoTrack?Y0.emsg:Y0.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(r)}}function BTe(s,t){return((s[t+1]&31)<<8)+s[t+2]}function ton(s,t){return(s[t+10]&31)<<8|s[t+11]}function son(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 p=t+5,f=h;for(;f>2;){switch(s[p]){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 _=s[p+1]+2;p+=_,f-=_}}break;case 194:case 135:return $Te(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 $Te(s,t,n,r){r.warn(`parsing error: ${t.message}`),s.emit(wt.ERROR,wt.ERROR,{type:mi.MEDIA_ERROR,details:Pn.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,error:t,reason:t.message})}function oke(s,t){t.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function GI(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]=Yv(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 p=new Uint8Array(s.size);for(let f=0,g=c.length;f_){h-=_;continue}else r=r.subarray(h),_-=h,h=0;p.set(r,n),n+=_}return a&&(a-=i+3),{data:p,pts:l,dts:o,len:a}}return null}class non{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 Ik=Math.pow(2,32)-1;class An{static init(){An.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 An.types)An.types.hasOwnProperty(t)&&(An.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]);An.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]);An.STTS=An.STSC=An.STCO=i,An.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),An.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),An.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),An.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]);An.FTYP=An.box(An.types.ftyp,l,c,l,o),An.DINF=An.box(An.types.dinf,An.box(An.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 An.box(An.types.mdia,An.mdhd(t.timescale||0,t.duration||0),An.hdlr(t.type),An.minf(t))}static mfhd(t){return An.box(An.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"?An.box(An.types.minf,An.box(An.types.smhd,An.SMHD),An.DINF,An.stbl(t)):An.box(An.types.minf,An.box(An.types.vmhd,An.VMHD),An.DINF,An.stbl(t))}static moof(t,n,r){return An.box(An.types.moof,An.mfhd(t),An.traf(r,n))}static moov(t){let n=t.length;const r=[];for(;n--;)r[n]=An.trak(t[n]);return An.box.apply(null,[An.types.moov,An.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(An.mvex(t)))}static mvex(t){let n=t.length;const r=[];for(;n--;)r[n]=An.trex(t[n]);return An.box.apply(null,[An.types.mvex,...r])}static mvhd(t,n){n*=t;const r=Math.floor(n/(Ik+1)),a=Math.floor(n%(Ik+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 An.box(An.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=An.box(An.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 An.box(An.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,An.box(An.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),An.box(An.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 An.box(An.types.mp4a,An.audioStsd(t),An.box(An.types.esds,An.esds(t)))}static mp3(t){return An.box(An.types[".mp3"],An.audioStsd(t))}static ac3(t){return An.box(An.types["ac-3"],An.audioStsd(t),An.box(An.types.dac3,t.config))}static stsd(t){const{segmentCodec:n}=t;if(t.type==="audio"){if(n==="aac")return An.box(An.types.stsd,An.STSD,An.mp4a(t));if(n==="ac3"&&t.config)return An.box(An.types.stsd,An.STSD,An.ac3(t));if(n==="mp3"&&t.codec==="mp3")return An.box(An.types.stsd,An.STSD,An.mp3(t))}else if(t.pps&&t.sps){if(n==="avc")return An.box(An.types.stsd,An.STSD,An.avc1(t));if(n==="hevc"&&t.vps)return An.box(An.types.stsd,An.STSD,An.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/(Ik+1)),o=Math.floor(r%(Ik+1));return An.box(An.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=An.sdtp(t),a=t.id,i=Math.floor(n/(Ik+1)),l=Math.floor(n%(Ik+1));return An.box(An.types.traf,An.box(An.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255])),An.box(An.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])),An.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,An.box(An.types.trak,An.tkhd(t),An.mdia(t))}static trex(t){const n=t.id;return An.box(An.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,p;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,p>>>24&255,p>>>16&255,p>>>8&255,p&255],12+16*o);return An.box(An.types.trun,l)}static initSegment(t){An.types||An.init();const n=An.moov(t);return Yv(An.FTYP,n)}static hvc1(t){const n=t.params,r=[t.vps,t.sps,t.pps],a=4,i=new Uint8Array([1,n.general_profile_space<<6|(n.general_tier_flag?32:0)|n.general_profile_idc,n.general_profile_compatibility_flags[0],n.general_profile_compatibility_flags[1],n.general_profile_compatibility_flags[2],n.general_profile_compatibility_flags[3],n.general_constraint_indicator_flags[0],n.general_constraint_indicator_flags[1],n.general_constraint_indicator_flags[2],n.general_constraint_indicator_flags[3],n.general_constraint_indicator_flags[4],n.general_constraint_indicator_flags[5],n.general_level_idc,240|n.min_spatial_segmentation_idc>>8,255&n.min_spatial_segmentation_idc,252|n.parallelismType,252|n.chroma_format_idc,248|n.bit_depth_luma_minus8,248|n.bit_depth_chroma_minus8,0,parseInt(n.frame_rate.fps),a-1|n.temporal_id_nested<<2|n.num_temporal_layers<<3|(n.frame_rate.fixed?64:0),r.length]);let l=i.length;for(let g=0;g>8,r[g][_].length&255]),l),l+=2,o.set(r[g][_],l),l+=r[g][_].length}const d=An.box(An.types.hvcC,o),u=t.width,h=t.height,p=t.pixelRatio[0],f=t.pixelRatio[1];return An.box(An.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,An.box(An.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),An.box(An.types.pasp,new Uint8Array([p>>24,p>>16&255,p>>8&255,p&255,f>>24,f>>16&255,f>>8&255,f&255])))}}An.types=void 0;An.HDLR_TYPES=void 0;An.STTS=void 0;An.STSC=void 0;An.STCO=void 0;An.STSZ=void 0;An.VMHD=void 0;An.SMHD=void 0;An.STSD=void 0;An.FTYP=void 0;An.DINF=void 0;const Dkt=9e4;function Q8e(s,t,n=1,r=!1){const a=s*t*n;return r?Math.round(a):a}function ron(s,t,n=1,r=!1){return Q8e(s,t,1/n,r)}function UF(s,t=!1){return Q8e(s,1e3,1/Dkt,t)}function aon(s,t=1){return Q8e(s,Dkt,1/t)}function $Je(s){const{baseTime:t,timescale:n,trackId:r}=s;return`${t/n} (${t}/${n}) trackId: ${r}`}const ion=10*1e3,oon=1024,lon=1152,con=1536;let WI=null,lke=null;function UJe(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 hpe extends r1{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,WI===null){const l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);WI=l?parseInt(l[1]):0}if(lke===null){const i=navigator.userAgent.match(/Safari\/(\d+)/i);lke=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&&$Je(n)} > ${t&&$Je(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=$0(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,p,f,g,_=i,v=i;const j=t.pid>-1,b=n.pid>-1,S=n.samples.length,A=t.samples.length>0,T=o&&S>0||S>1;if((!j||A)&&(!b||T)||this.ISGenerated||o){if(this.ISGenerated){var D,M,F,z;const K=this.videoTrackConfig;(K&&(n.width!==K.width||n.height!==K.height||((D=n.pixelRatio)==null?void 0:D[0])!==((M=K.pixelRatio)==null?void 0:M[0])||((F=n.pixelRatio)==null?void 0:F[1])!==((z=K.pixelRatio)==null?void 0:z[1]))||!K&&T||this.nextAudioTs===null&&A)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,n,i,l));const V=this.isVideoContiguous;let W=-1,Y;if(T&&(W=don(n.samples),!V&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,W>0){this.warn(`Dropped ${W} out of ${S} video samples due to a missing keyframe`);const K=this.getVideoStartPts(n.samples);n.samples=n.samples.slice(W),n.dropped+=W,v+=(n.samples[0].pts-K)/n.inputTimeScale,Y=v}else W===-1&&(this.warn(`No keyframe found out of ${S} video samples`),g=!1);if(this.ISGenerated){if(A&&T){const K=this.getVideoStartPts(n.samples),ne=($0(t.samples[0].pts,K)-K)/n.inputTimeScale;_+=Math.max(0,ne),v+=Math.max(0,-ne)}if(A){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(t,n,i,l)),u=this.remuxAudio(t,_,this.isAudioContiguous,l,b||T||c===Ya.AUDIO?v:void 0),T){const K=u?u.endPTS-u.startPTS:0;n.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(t,n,i,l)),d=this.remuxVideo(n,v,V,K)}}else T&&(d=this.remuxVideo(n,v,V,0));d&&(d.firstKeyFrame=W,d.independent=W!==-1,d.firstKeyFramePTS=Y)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(f=Rkt(r,i,this._initPTS,this._initDTS)),a.samples.length&&(p=Okt(a,i,this._initPTS))),{audio:u,video:d,initSegment:h,independent:g,text:p,id3:f}}computeInitPts(t,n,r,a){const i=Math.round(r*n);let l=$0(t,i);if(l0?le-1:le].dts&&(b=!0)}b&&l.sort(function(le,ve){const ge=le.dts-ve.dts,Te=le.pts-ve.pts;return ge||Te}),g=l[0].dts,_=l[l.length-1].dts;const A=_-g,T=A?Math.round(A/(c-1)):f||t.inputTimeScale/30;if(r){const le=g-S,ve=le>T,ge=le<-1;if((ve||ge)&&(ve?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${UF(le,!0)} ms (${le}dts) hole between fragments detected at ${n.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${UF(-le,!0)} ms (${le}dts) overlapping between fragments detected at ${n.toFixed(3)}`),!ge||S>=l[0].pts||WI)){g=S;const Te=l[0].pts-le;if(ve)l[0].dts=g,l[0].pts=Te;else{let Me=!0;for(let Ce=0;CeTe&&Me);Ce++){const Ae=l[Ce].pts;if(l[Ce].dts-=le,l[Ce].pts-=le,Ce0?ve.dts-l[le-1].dts:T;if(Me=le>0?ve.pts-l[le-1].pts:T,Ae.stretchShortVideoTrack&&this.nextAudioTs!==null){const Ie=Math.floor(Ae.maxBufferHole*i),Fe=(a?v+a*i:this.nextAudioTs+u)-ve.pts;Fe>Ie?(f=Fe-De,f<0?f=De:W=!0,this.log(`It is approximately ${Fe/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=De}else f=De}const Ce=Math.round(ve.pts-ve.dts);Y=Math.min(Y,f),J=Math.max(J,f),K=Math.min(K,Me),ne=Math.max(ne,Me),o.push(UJe(ve.key,f,Te,Ce))}if(o.length){if(WI){if(WI<70){const le=o[0].flags;le.dependsOn=2,le.isNonSync=0}}else if(lke&&ne-K0&&(a&&Math.abs(S-(j+b))<9e3||Math.abs($0(_[0].pts,S)-(j+b))<20*u),_.forEach(function(ne){ne.pts=$0(ne.pts,S)}),!r||j<0){const ne=_.length;if(_=_.filter(ie=>ie.pts>=0),ne!==_.length&&this.warn(`Removed ${_.length-ne} of ${ne} samples (initPTS ${b} / ${l})`),!_.length)return;i===0?j=0:a&&!g?j=Math.max(0,S-b):j=_[0].pts-b}if(t.segmentCodec==="aac"){const ne=this.config.maxAudioFramesDrift;for(let ie=0,he=j+b;ie<_.length;ie++){const ce=_[ie],pe=ce.pts,le=pe-he,ve=Math.abs(1e3*le/l);if(le<=-ne*u&&g)ie===0&&(this.warn(`Audio frame @ ${(pe/l).toFixed(3)}s overlaps marker by ${Math.round(1e3*le/l)} ms.`),this.nextAudioTs=j=pe-b,he=pe);else if(le>=ne*u&&ve0){D+=v;try{L=new Uint8Array(D)}catch(ve){this.observer.emit(wt.ERROR,wt.ERROR,{type:mi.MUX_ERROR,details:Pn.REMUX_ALLOC_ERROR,fatal:!1,error:ve,bytes:D,reason:`fail allocating audio mdat ${D}`});return}p||(new DataView(L.buffer).setUint32(0,D),L.set(An.types.mdat,4))}else return;L.set(ce,v);const le=ce.byteLength;v+=le,f.push(UJe(!0,d,le,0)),T=pe}const F=f.length;if(!F)return;const z=f[f.length-1];j=T-b,this.nextAudioTs=j+c*z.duration;const V=p?new Uint8Array(0):An.moof(t.sequenceNumber++,A/c,Yc({},t,{samples:f}));t.samples=[];const W=(A-b)/l,Y=this.nextAudioTs/l,J={data1:V,data2:L,startPTS:W,endPTS:Y,startDTS:W,endDTS:Y,type:"audio",hasAudio:!0,hasVideo:!1,nb:F};return this.isAudioContiguous=!0,J}}function $0(s,t){let n;if(t===null)return s;for(t4294967296;)s+=n;return s}function don(s){for(let t=0;tl.pts-o.pts);const i=s.samples;return s.samples=[],{samples:i}}class uon extends r1{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=qNt(t);if(n)Xrn(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=qJe(i,td.AUDIO,this)),l&&(a=qJe(l,td.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};Ra(u)||(u=this.lastEndTime=i||0);const p=n.samples;if(!p.length)return h;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(p),g=this.initData),!((c=g)!=null&&c.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const _=ean(p,g,this),v=g.audio?_[g.audio.id]:null,j=g.video?_[g.video.id]:null,b=UG(j,1/0),S=UG(v,1/0),A=UG(j,0,!0),T=UG(v,0,!0);let L=i,D=0;const M=v&&(!j||!d&&S0?this.lastEndTime=V:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const W=!!g.audio,Y=!!g.video;let K="";W&&(K+="audio"),Y&&(K+="video");const J=(g.audio?g.audio.encrypted:!1)||(g.video?g.video.encrypted:!1),ne={data1:p,startPTS:z,startDTS:z,endPTS:V,endDTS:V,type:K,hasAudio:W,hasVideo:Y,nb:1,dropped:0,encrypted:J};h.audio=W&&!Y?ne:void 0,h.video=Y?ne:void 0;const ie=j==null?void 0:j.sampleCount;if(ie){const he=j.keyFrameIndex,ce=he!==-1;ne.nb=ie,ne.dropped=he===0||this.isVideoContiguous?0:ce?he:ie,ne.independent=ce,ne.firstKeyFrame=he,ce&&j.keyFrameStart&&(ne.firstKeyFramePTS=(j.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(h.independent=ce),this.isVideoContiguous||(this.isVideoContiguous=ce),ne.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${he}/${ie} dropped: ${ne.dropped} start: ${ne.firstKeyFramePTS||"NA"}`)}return h.initSegment=f,h.id3=Rkt(r,i,d,d),a.samples.length&&(h.text=Okt(a,i,d)),h}}function UG(s,t,n=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(n?s.duration:0))/s.timescale:t}function hon(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 qJe(s,t,n){const r=s.codec;return r&&r.length>4?r:t===td.AUDIO?r==="ec-3"||r==="ac-3"||r==="alac"?r:r==="fLaC"||r==="Opus"?Qge(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 k2;try{k2=self.performance.now.bind(self.performance)}catch{k2=Date.now}const mpe=[{demux:Qin,remux:uon},{demux:oS,remux:hpe},{demux:Win,remux:hpe},{demux:Yin,remux:hpe}];mpe.splice(2,0,{demux:Kin,remux:hpe});class VJe{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=k2();let l=new Uint8Array(t);const{currentTransmuxState:o,transmuxConfig:c}=this;a&&(this.currentTransmuxState=a);const{contiguous:d,discontinuity:u,trackSwitch:h,accurateTimeOffset:p,timeOffset:f,initSegmentChange:g}=a||o,{audioCodec:_,videoCodec:v,defaultInitPts:j,duration:b,initSegmentData:S}=c,A=mon(l,n);if(A&&WL(A.method)){const M=this.getDecrypter(),F=U8e(A.method);if(M.isSync()){let z=M.softwareDecrypt(l,A.key.buffer,A.iv.buffer,F);if(r.part>-1){const W=M.flush();z=W&&W.buffer}if(!z)return i.executeEnd=k2(),cke(r);l=new Uint8Array(z)}else return this.asyncResult=!0,this.decryptionPromise=M.webCryptoDecrypt(l,A.key.buffer,A.iv.buffer,F).then(z=>{const V=this.push(z,null,r);return this.decryptionPromise=null,V}),this.decryptionPromise}const T=this.needsProbing(u,h);if(T){const M=this.configureTransmuxer(l);if(M)return this.logger.warn(`[transmuxer] ${M.message}`),this.observer.emit(wt.ERROR,wt.ERROR,{type:mi.MEDIA_ERROR,details:Pn.FRAG_PARSING_ERROR,fatal:!1,error:M,reason:M.message}),i.executeEnd=k2(),cke(r)}(u||h||g||T)&&this.resetInitSegment(S,_,v,b,n),(u||g||T)&&this.resetInitialTimestamp(j),d||this.resetContiguity();const L=this.transmux(l,A,f,p,r);this.asyncResult=S$(L);const D=this.currentTransmuxState;return D.contiguous=!0,D.discontinuity=!1,D.trackSwitch=!1,i.executeEnd=k2(),L}flush(t){const n=t.transmuxing;n.executeStart=k2();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=k2();const h=[cke(t)];return this.asyncResult?Promise.resolve(h):h}const u=c.flush(o);return S$(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===Ya.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=k2()}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,p=mpe.length;h0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null&&(n=t),n}const cke=s=>({remuxResult:{},chunkMeta:s});function S$(s){return"then"in s&&s.then instanceof Function}class pon{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 fon{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 HJe=0;class Fkt{constructor(t,n,r,a){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=HJe++,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 p=(h=this.workerContext)==null?void 0:h.objectURL;p&&self.URL.revokeObjectURL(p);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(wt.ERROR,{type:mi.OTHER_ERROR,details:Pn.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===wt.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new H8e,this.observer.on(wt.FRAG_DECRYPTED,l),this.observer.on(wt.ERROR,l);const o=iJe(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(i.workerPath||vin()){try{i.workerPath?(c.log(`loading Web Worker ${i.workerPath} for "${n}"`),this.workerContext=_in(i.workerPath)):(c.log(`injecting Web Worker for "${n}"`),this.workerContext=bin());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:id(i)})}catch(u){c.warn(`Error setting up "${n}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new VJe(this.observer,o,i,"",n,t.logger)}return}}this.transmuxer=new VJe(this.observer,o,i,"",n,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=HJe++;const n=this.hls.config,r=iJe(n.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:r,id:this.id,config:id(n)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),win(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,p;d.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,_=l?l.start:i.start,v=i.decryptdata,j=this.frag,b=!(j&&i.cc===j.cc),S=!(j&&d.level===j.level),A=j?d.sn-j.sn:-1,T=this.part?d.part-this.part.index:-1,L=A===0&&d.id>1&&d.id===(j==null?void 0:j.stats.chunkCount),D=!S&&(A===1||A===0&&(T===1||L&&T<=0)),M=self.performance.now();(S||A||i.stats.parsing.start===0)&&(i.stats.parsing.start=M),l&&(T||!D)&&(l.stats.parsing.start=M);const F=!(j&&((h=i.initSegment)==null?void 0:h.url)===((p=j.initSegment)==null?void 0:p.url)),z=new fon(b,D,c,S,_,F);if(!D||b||F){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===Ya.MAIN?"level":"track"}: ${d.level} id: ${d.id} discontinuity: ${b} trackSwitch: ${S} contiguous: ${D} accurateTimeOffset: ${c} timeOffset: ${_} initSegmentChange: ${F}`);const V=new pon(r,a,n,o,u);this.configureTransmuxer(V)}if(this.frag=i,this.part=l,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:t,decryptdata:v,chunkMeta:d,state:z},t instanceof ArrayBuffer?[t]:[]);else if(g){const V=g.push(t,v,d,z);S$(V)?V.then(W=>{this.handleTransmuxComplete(W)}).catch(W=>{this.transmuxerError(W,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(V)}}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);S$(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(wt.ERROR,{type:mi.MEDIA_ERROR,details:Pn.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 GJe=100;class xon extends V8e{constructor(t,n,r){super(t,n,r,"audio-stream-controller",Ya.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(wt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(wt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(wt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(wt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(wt.BUFFER_RESET,this.onBufferReset,this),t.on(wt.BUFFER_CREATED,this.onBufferCreated,this),t.on(wt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(wt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(wt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(wt.FRAG_LOADING,this.onFragLoading,this),t.on(wt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(wt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(wt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(wt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(wt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(wt.BUFFER_RESET,this.onBufferReset,this),t.off(wt.BUFFER_CREATED,this.onBufferCreated,this),t.off(wt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(wt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(wt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(wt.FRAG_LOADING,this.onFragLoading,this),t.off(wt.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:n,id:r,initPTS:a,timescale:i,trackId:l}){if(r===Ya.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===dr.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===dr.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=ekt(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===dr.IDLE&&this.doTickIdle())}startLoad(t,n){if(!this.levels){this.startPosition=t,this.state=dr.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(GJe),r>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),t=r,this.state=dr.IDLE):this.state=dr.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}doTick(){switch(this.state){case dr.IDLE:this.doTickIdle();break;case dr.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=dr.WAITING_INIT_PTS}break}case dr.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case dr.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=dr.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=dr.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=dr.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,td.AUDIO,Ya.AUDIO));const u=this.getFwdBufferInfo(d,Ya.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,c)){n.trigger(wt.BUFFER_EOS,{type:"audio"}),this.state=dr.ENDED;return}const h=u.len,p=n.maxBufferLength,f=c.fragments,g=f[0].start,_=this.getLoadPosition(),v=this.flushing?_:u.end;if(this.switchingTrack&&a){const S=_;c.PTSKnown&&Sg||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),a.currentTime=g+.05)}if(h>=p&&!this.switchingTrack&&vb.end){const A=this.fragmentTracker.getFragAtPos(v,Ya.MAIN);A&&A.end>b.end&&(b=A,this.mainFragLoading={frag:A,targetBufferTime:null})}if(j.start>b.end)return}this.loadFragment(j,o,v)}onMediaDetaching(t,n){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,n)}onAudioTracksUpdated(t,{audioTracks:n}){this.resetTransmuxer(),this.levels=n.map(r=>new j$(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!==dr.STOPPED&&(this.setInterval(GJe),this.state=dr.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(wt.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!==dr.STOPPED&&(this.state=dr.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 p;h=this.alignPlaylists(i,u.details,(p=this.levelLastLoaded)==null?void 0:p.details)}i.alignedSliding||(ykt(i,d),i.alignedSliding||r0e(i,d),h=i.fragmentStart)}u.details=i,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,h),this.hls.trigger(wt.AUDIO_TRACK_UPDATED,{details:i,id:l,groupId:n.groupId}),this.state===dr.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=dr.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 p=this.transmuxer;p||(p=this.transmuxer=new Fkt(this.hls,Ya.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[r.cc],g=(n=r.initSegment)==null?void 0:n.data;if(f!==void 0){const v=a?a.index:-1,j=v!==-1,b=new $8e(r.level,r.sn,r.stats.chunkCount,i.byteLength,v,j);p.push(i,g,h,"",r,a,u.totalduration,!1,b,f)}else{this.log(`Unknown video PTS for cc ${r.cc}, waiting for video PTS before demuxing audio frag ${r.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:_}=this.waitingData=this.waitingData||{frag:r,part:a,cache:new vkt,complete:!1};_.push(new Uint8Array(i)),this.state!==dr.STOPPED&&(this.state=dr.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===Ya.MAIN&&Th(n.frag)&&(this.mainFragLoading=n,this.state===dr.IDLE&&this.tick())}onFragBuffered(t,n){const{frag:r,part:a}=n;if(r.type!==Ya.AUDIO){!this.audioOnly&&r.type===Ya.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(Th(r)){this.fragPrevious=r;const i=this.switchingTrack;i&&(this.bufferedTrack=i,this.switchingTrack=null,this.hls.trigger(wt.AUDIO_TRACK_SWITCHED,Tc({},i)))}this.fragBufferedComplete(r,a),this.media&&this.tick()}onError(t,n){var r;if(n.fatal){this.state=dr.ERROR;return}switch(n.details){case Pn.FRAG_GAP:case Pn.FRAG_PARSING_ERROR:case Pn.FRAG_DECRYPT_ERROR:case Pn.FRAG_LOAD_ERROR:case Pn.FRAG_LOAD_TIMEOUT:case Pn.KEY_LOAD_ERROR:case Pn.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ya.AUDIO,n);break;case Pn.AUDIO_TRACK_LOAD_ERROR:case Pn.AUDIO_TRACK_LOAD_TIMEOUT:case Pn.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===dr.WAITING_TRACK&&((r=n.context)==null?void 0:r.type)===ol.AUDIO_TRACK&&(this.state=dr.IDLE);break;case Pn.BUFFER_ADD_CODEC_ERROR:case Pn.BUFFER_APPEND_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)||this.resetLoadingState();break;case Pn.BUFFER_FULL_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Pn.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onBufferFlushing(t,{type:n}){n!==td.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:n}){if(n!==td.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===dr.ENDED&&(this.state=dr.IDLE);const r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,n,Ya.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:p,text:f,id3:g,initSegment:_}=i;if(this.fragContextChanged(c)||!h){this.fragmentTracker.removeFragment(c);return}if(this.state=dr.PARSING,this.switchingTrack&&p&&this.completeAudioSwitch(this.switchingTrack),_!=null&&_.tracks){const v=c.initSegment||c;if(this.unhandledEncryptionError(_,c))return;this._bufferInitSegment(u,_.tracks,v,l),a.trigger(wt.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:r,tracks:_.tracks})}if(p){const{startPTS:v,endPTS:j,startDTS:b,endDTS:S}=p;d&&(d.elementaryStreams[td.AUDIO]={startPTS:v,endPTS:j,startDTS:b,endDTS:S}),c.setElementaryStreamInfo(td.AUDIO,v,j,b,S),this.bufferFragmentData(p,c,d,l)}if(g!=null&&(n=g.samples)!=null&&n.length){const v=Yc({id:r,frag:c,details:h},g);a.trigger(wt.FRAG_PARSING_METADATA,v)}if(f){const v=Yc({id:r,frag:c,details:h},f);a.trigger(wt.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(t,n,r,a){if(this.state!==dr.PARSING||(n.video&&delete n.video,n.audiovideo&&delete n.audiovideo,!n.audio))return;const i=n.audio;i.id=Ya.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(wt.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(wt.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===Lm.NOT_LOADED||a===Lm.PARTIAL){var i;if(!Th(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=dr.WAITING_INIT_PTS;const l=this.mainDetails;l&&l.fragmentStart!==n.details.fragmentStart&&r0e(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;iM({name:n,lang:r,assocLang:a,characteristics:i,audioCodec:l,channels:o},t,RE)||(Jge(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(wt.AUDIO_TRACK_SWITCHED,Tc({},t))}}class X8e extends r1{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&&oJe(r);return new lJe(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){lin(r,a,this);const b=a.playlistParsingError;if(b){this.warn(b);const S=this.hls;if(!S.config.ignorePlaylistParsingErrors){var d;const{networkDetails:A}=n;S.trigger(wt.ERROR,{type:mi.NETWORK_ERROR,details:Pn.LEVEL_PARSING_ERROR,fatal:!1,url:a.url,error:b,reason:b.message,level:n.level||void 0,parent:(d=a.fragments[0])==null?void 0:d.type,networkDetails:A,stats:i});return}a.playlistParsingError=null}}a.requestScheduled===-1&&(a.requestScheduled=i.loading.start);const h=this.hls.mainForwardBufferInfo,p=h?h.end-h.len:0,f=(a.edge-p)*1e3,g=mkt(a,f);if(a.requestScheduled+g0){if(F>a.targetduration*3)this.log(`Playlist last advanced ${M.toFixed(2)}s ago. Omitting segment and part directives.`),v=void 0,j=void 0;else if(r!=null&&r.tuneInGoal&&F-a.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${z} with playlist age: ${a.age}`),z=0;else{const V=Math.floor(z/a.targetduration);if(v+=V,j!==void 0){const W=Math.round(z%a.targetduration/a.partTarget);j+=W}this.log(`CDN Tune-in age: ${a.ageHeader}s last advanced ${M.toFixed(2)}s goal: ${z} skip sn ${V} to part ${j}`)}a.tuneInGoal=z}if(_=this.getDeliveryDirectives(a,n.deliveryDirectives,v,j),b||!D){a.requestScheduled=l,this.loadingPlaylist(u,_);return}}else(a.canBlockReload||a.canSkipUntil)&&(_=this.getDeliveryDirectives(a,n.deliveryDirectives,v,j));_&&v!==void 0&&a.canBlockReload&&(a.requestScheduled=i.loading.first+Math.max(g-o*2,g/2)),this.scheduleLoading(u,_,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=oJe(t);return n!=null&&n.skip&&t.deltaUpdateFailed&&(r=n.msn,a=n.part,i=dpe.No),new lJe(r,a,i)}checkRetry(t){const n=t.details,r=e0e(t),a=t.errorAction,{action:i,retryCount:l=0,retryConfig:o}=a||{},c=!!a&&!!o&&(i===sf.RetryRequest||!a.resolved&&i===sf.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=z8e(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 zkt(s,t){if(s.length!==t.length)return!1;for(let n=0;ns[a]!==t[a])}function UTe(s,t){return t.label.toLowerCase()===s.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(s.lang||"").toLowerCase())}class gon extends X8e{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(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(wt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(wt.LEVEL_LOADING,this.onLevelLoading,this),t.on(wt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(wt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(wt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(wt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(wt.LEVEL_LOADING,this.onLevelLoading,this),t.off(wt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(wt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(wt.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(p=>!r||r.indexOf(p.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(p=>p.default)&&(this.selectDefaultTrack=!1),o.forEach((p,f)=>{p.id=f});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!i&&c){const p=cw(c,o,RE);if(p>-1)i=o[p];else{const f=cw(c,this.tracks);i=this.tracks[f]}}let d=this.findTrackId(i);d===-1&&i&&(d=this.findTrackId(null));const u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${r==null?void 0:r.join(",")}`),this.hls.trigger(wt.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 p=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(p.message),this.hls.trigger(wt.ERROR,{type:mi.MEDIA_ERROR,details:Pn.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:p})}}}onError(t,n){n.fatal||!n.context||n.context.type===ol.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&&iM(t,a,RE))return a;const i=cw(t,this.tracksInGroup,RE);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=Ean(t,n.levels,r,l,RE);if(o===-1)return null;n.nextLoadLevel=o}if(t.channels||t.audioCodec){const l=cw(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(wt.AUDIO_TRACK_SWITCHING,Tc({},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 WJe=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Bkt="HlsJsTrackRemovedError";class von extends Error{constructor(t){super(t),this.name=Bkt}}class bon extends r1{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(wt.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=Urn(B4(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(wt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(wt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(wt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(wt.BUFFER_RESET,this.onBufferReset,this),t.on(wt.BUFFER_APPENDING,this.onBufferAppending,this),t.on(wt.BUFFER_CODECS,this.onBufferCodecs,this),t.on(wt.BUFFER_EOS,this.onBufferEos,this),t.on(wt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(wt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(wt.FRAG_PARSED,this.onFragParsed,this),t.on(wt.FRAG_CHANGED,this.onFragChanged,this),t.on(wt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(wt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(wt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(wt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(wt.BUFFER_RESET,this.onBufferReset,this),t.off(wt.BUFFER_APPENDING,this.onBufferAppending,this),t.off(wt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(wt.BUFFER_EOS,this.onBufferEos,this),t.off(wt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(wt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(wt.FRAG_PARSED,this.onFragParsed,this),t.off(wt.FRAG_CHANGED,this.onFragChanged,this),t.off(wt.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?Yc(r,a.tracks):this.sourceBuffers.forEach(i=>{const[l]=i;l&&(r[l]=Yc({},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=B4(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,KJe(r),_on(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: ${id(r,(c,d)=>c==="initSegment"?void 0:d)}; transfer tracks: ${id(a,(c,d)=>c==="initSegment"?void 0:d)}}`),!RNt(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(wt.MEDIA_DETACHING,{}),this.onMediaAttaching(wt.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 p=this.fragmentTracker,f=u.id;if(p.hasFragments(f)||p.hasParts(f)){const v=wo.getBuffered(h);p.detectEvictedFragments(d,v,f,null,!0)}const g=dke(d),_=[d,h];this.sourceBuffers[g]=_,h.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,u)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const n=(t=this.mediaSource)==null?void 0:t.readyState;return n==="open"||n==="ended"}onMediaDetaching(t,n){const r=!!n.transferMedia;this.transferData=this.overrides=void 0;const{media:a,mediaSource:i,_objectUrl:l}=this;if(i){if(this.log(`media source ${r?"transferring":"detaching"}`),r)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=i.readyState==="open";try{const c=i.sourceBuffers;for(let d=c.length;d--;)o&&c[d].abort(),i.removeSourceBuffer(c[d]);o&&i.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}i.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("sourceended",this._onMediaSourceEnded),i.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(i.removeEventListener("startstreaming",this._onStartStreaming),i.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}a&&(a.removeEventListener("emptied",this._onMediaEmptied),r||(l&&self.URL.revokeObjectURL(l),this.mediaSrc===l?(a.removeAttribute("src"),this.appendSource&&KJe(a),a.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(wt.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[dke(t)]=[null,null];const n=this.tracks[t];n&&(n.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new yon(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:p,codec:f,levelCodec:g,container:_,metadata:v,supplemental:j}=h;let b=a[c];const S=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],A=S!=null&&S.buffer?S:b,T=(A==null?void 0:A.pendingCodec)||(A==null?void 0:A.codec),L=A==null?void 0:A.levelCodec;b||(b=a[c]={buffer:void 0,listeners:[],codec:f,supplemental:j,container:_,levelCodec:g,metadata:v,id:p});const D=cpe(T,L),M=D==null?void 0:D.replace(WJe,"$1");let F=cpe(f,g);const z=(u=F)==null?void 0:u.replace(WJe,"$1");F&&D&&M!==z&&(c.slice(0,5)==="audio"&&(F=Qge(F,this.appendSource)),this.log(`switching codec ${T} to ${F}`),F!==(b.pendingCodec||b.codec)&&(b.pendingCodec=F),b.container=_,this.appendChangeType(c,_,F))}),(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,Ya.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&&wo.isBuffered(c.buffer,a)||((o=this.fragmentTracker.getAppendedFrag(a,Ya.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:p,cc:f}=o,g=self.performance.now();h.start=g;const _=o.stats.buffering,v=c?c.stats.buffering:null;_.start===0&&(_.start=g),v&&v.start===0&&(v.start=g);const j=r.audio;let b=!1;i==="audio"&&(j==null?void 0:j.container)==="audio/mpeg"&&(b=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const S=r.video,A=S==null?void 0:S.buffer;if(A&&p!=="initSegment"){const D=c||o,M=this.blockedAudioAppend;if(i==="audio"&&l!=="main"&&!this.blockedAudioAppend&&!(S.ending||S.ended)){const z=D.start+D.duration*.05,V=A.buffered,W=this.currentOp("video");!V.length&&!W?this.blockAudio(D):!W&&!wo.isBuffered(A,z)&&this.lastVideoAppendEndz||F{var D;h.executeStart=self.performance.now();const M=(D=this.tracks[i])==null?void 0:D.buffer;M&&(b?this.updateTimestampOffset(M,T,.1,i,p,f):u!==void 0&&Ra(u)&&this.updateTimestampOffset(M,u,1e-6,i,p,f)),this.appendExecutor(a,i)},onStart:()=>{},onComplete:()=>{const D=self.performance.now();h.executeEnd=h.end=D,_.first===0&&(_.first=D),v&&v.first===0&&(v.first=D);const M={};this.sourceBuffers.forEach(([F,z])=>{F&&(M[F]=wo.getBuffered(z))}),this.appendErrors[i]=0,i==="audio"||i==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(wt.BUFFER_APPENDED,{type:i,frag:o,part:c,chunkMeta:d,parent:o.type,timeRanges:M})},onError:D=>{var M;const F={type:mi.MEDIA_ERROR,parent:o.type,details:Pn.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:c,chunkMeta:d,error:D,err:D,fatal:!1},z=(M=this.media)==null?void 0:M.error;if(D.code===DOMException.QUOTA_EXCEEDED_ERR||D.name=="QuotaExceededError"||"quota"in D)F.details=Pn.BUFFER_FULL_ERROR;else if(D.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!z)F.errorAction=GL(!0);else if(D.name===Bkt&&this.sourceBufferCount===0)F.errorAction=GL(!0);else{const V=++this.appendErrors[i];this.warn(`Failed ${V}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${z||"no media error"})`),(V>=this.hls.config.appendErrorMaxRetry||z)&&(F.fatal=!0)}this.hls.trigger(wt.ERROR,F)}};this.log(`queuing "${i}" append sn: ${p}${c?" p: "+c.index:""} of ${o.type===Ya.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(L,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(wt.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[td.AUDIOVIDEO]?i.push("audiovideo"):(l[td.AUDIO]&&i.push("audio"),l[td.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(wt.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(wt.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(wt.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===Pn.BUFFER_APPEND_ERROR&&n.frag){var r;const a=(r=n.errorAction)==null?void 0:r.nextAutoLevel;Ra(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(Ra(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(Ra(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=wo.getBuffered(i);if(o.length>0&&r>o.start(0)){var l;this.hls.trigger(wt.BACK_BUFFER_REACHED,{bufferEnd:r});const c=this.tracks[a];if((l=this.details)!=null&&l.live)this.hls.trigger(wt.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(wt.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:a})}}})}flushFrontBuffer(t,n,r){this.sourceBuffers.forEach(([a,i])=>{if(i){const l=wo.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(wt.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 Ra(i)?{duration:i}:null;const l=this.media.duration,o=Ra(r.duration)?r.duration:0;return a>o&&a>l||!Ra(l)?{duration:a}:null}updateMediaSource({duration:t,start:n,end:r}){const a=this.mediaSource;!this.media||!a||a.readyState!=="open"||(a.duration!==t&&(Ra(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}) ${id(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(wt.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(wt.ERROR,{type:mi.MEDIA_ERROR,details:Pn.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":""} ${id(o)}`);try{const u=r.addSourceBuffer(d),h=dke(l),p=[l,u];n[h]=p,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(wt.ERROR,{type:mi.MEDIA_ERROR,details:Pn.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")&&_$(r,"video")&&(a=dan(a,r));const i=cpe(a,t.levelCodec);return i?n.slice(0,5)==="audio"?Qge(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(wt.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(wt.ERROR,{type:mi.MEDIA_ERROR,details:Pn.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=Ra(a.duration)?a.duration:1/0,d=Ra(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 von(`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 KJe(s){const t=s.querySelectorAll("source");[].slice.call(t).forEach(n=>{s.removeChild(n)})}function _on(s,t){const n=self.document.createElement("source");n.type="video/mp4",n.src=t,s.appendChild(n)}function dke(s){return s==="audio"?1:0}class J8e{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(wt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(wt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(wt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(wt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(wt.BUFFER_CODECS,this.onBufferCodecs,this),t.on(wt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(wt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(wt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(wt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(wt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(wt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(wt.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&&Ra(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,J8e.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 won={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},kg=won,jon={HLS:"h"},Non=jon;class qw{constructor(t,n){Array.isArray(t)&&(t=t.map(r=>r instanceof qw?r:new qw(r))),this.value=t,this.params=n}}const kon="Dict";function Son(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 Con(s,t,n,r){return new Error(`failed to ${s} "${Son(t)}" as ${n}`,{cause:r})}function Vw(s,t,n){return Con("serialize",s,t,n)}class $kt{constructor(t){this.description=t}}const YJe="Bare Item",Ton="Boolean";function Eon(s){if(typeof s!="boolean")throw Vw(s,Ton);return s?"?1":"?0"}function Aon(s){return btoa(String.fromCharCode(...s))}const Mon="Byte Sequence";function Ion(s){if(ArrayBuffer.isView(s)===!1)throw Vw(s,Mon);return`:${Aon(s)}:`}const Pon="Integer";function Lon(s){return s<-999999999999999||99999999999999912)throw Vw(s,Ron);const n=t.toString();return n.includes(".")?n:`${n}.0`}const Fon="String",zon=/[\x00-\x1f\x7f]+/;function Bon(s){if(zon.test(s))throw Vw(s,Fon);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function $on(s){return s.description||s.toString().slice(7,-1)}const Uon="Token";function ZJe(s){const t=$on(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw Vw(t,Uon);return t}function qTe(s){switch(typeof s){case"number":if(!Ra(s))throw Vw(s,YJe);return Number.isInteger(s)?Ukt(s):Oon(s);case"string":return Bon(s);case"symbol":return ZJe(s);case"boolean":return Eon(s);case"object":if(s instanceof Date)return Don(s);if(s instanceof Uint8Array)return Ion(s);if(s instanceof $kt)return ZJe(s);default:throw Vw(s,YJe)}}const qon="Key";function VTe(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Vw(s,qon);return s}function eDe(s){return s==null?"":Object.entries(s).map(([t,n])=>n===!0?`;${VTe(t)}`:`;${VTe(t)}=${qTe(n)}`).join("")}function Vkt(s){return s instanceof qw?`${qTe(s.value)}${eDe(s.params)}`:qTe(s)}function Von(s){return`(${s.value.map(Vkt).join(" ")})${eDe(s.params)}`}function Hon(s,t={whitespace:!0}){if(typeof s!="object"||s==null)throw Vw(s,kon);const n=s instanceof Map?s.entries():Object.entries(s),r=t!=null&&t.whitespace?" ":"";return Array.from(n).map(([a,i])=>{i instanceof qw||(i=new qw(i));let l=VTe(a);return i.value===!0?l+=eDe(i.params):(l+="=",Array.isArray(i.value)?l+=Von(i):l+=Vkt(i)),l}).join(`,${r}`)}function Hkt(s,t){return Hon(s,t)}const I_="CMCD-Object",th="CMCD-Request",y3="CMCD-Session",Pk="CMCD-Status",Gon={br:I_,ab:I_,d:I_,ot:I_,tb:I_,tpb:I_,lb:I_,tab:I_,lab:I_,url:I_,pb:th,bl:th,tbl:th,dl:th,ltc:th,mtp:th,nor:th,nrr:th,rc:th,sn:th,sta:th,su:th,ttfb:th,ttfbb:th,ttlb:th,cmsdd:th,cmsds:th,smrt:th,df:th,cs:th,ts:th,cid:y3,pr:y3,sf:y3,sid:y3,st:y3,v:y3,msd:y3,bs:Pk,bsd:Pk,cdn:Pk,rtp:Pk,bg:Pk,pt:Pk,ec:Pk,e:Pk},Won={REQUEST:th};function Kon(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 Yon(s,t){const n={};if(!s)return n;const r=Object.keys(s),a=t?Kon(t):{};return r.reduce((i,l)=>{var o;const c=Gon[l]||a[l]||Won.REQUEST,d=(o=i[c])!==null&&o!==void 0?o:i[c]={};return d[l]=s[l],i},n)}function Zon(s){return["ot","sf","st","e","sta"].includes(s)}function Qon(s){return typeof s=="number"?Ra(s):s!=null&&s!==""&&s!==!1}const Gkt="event";function Xon(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 ppe=s=>Math.round(s),HTe=(s,t)=>Array.isArray(s)?s.map(n=>HTe(n,t)):s instanceof qw&&typeof s.value=="string"?new qw(HTe(s.value,t),s.params):(t.baseUrl&&(s=Xon(s,t.baseUrl)),t.version===1?encodeURIComponent(s):s),qG=s=>ppe(s/100)*100,Jon=(s,t)=>{let n=s;return t.version>=2&&(s instanceof qw&&typeof s.value=="string"?n=new qw([s]):typeof s=="string"&&(n=[s])),HTe(n,t)},eln={br:ppe,d:ppe,bl:qG,dl:qG,mtp:qG,nor:Jon,rtp:qG,tb:ppe},Wkt="request",Kkt="response",tDe=["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"],tln=["e"],sln=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function ube(s){return sln.test(s)}function nln(s){return tDe.includes(s)||tln.includes(s)||ube(s)}const Ykt=["d","dl","nor","ot","rtp","su"];function rln(s){return tDe.includes(s)||Ykt.includes(s)||ube(s)}const aln=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function iln(s){return tDe.includes(s)||Ykt.includes(s)||aln.includes(s)||ube(s)}const oln=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function lln(s){return oln.includes(s)||ube(s)}const cln={[Kkt]:iln,[Gkt]:nln,[Wkt]:rln};function Zkt(s,t={}){const n={};if(s==null||typeof s!="object")return n;const r=t.version||s.v||1,a=t.reportingMode||Wkt,i=r===1?lln:cln[a];let l=Object.keys(s).filter(i);const o=t.filter;typeof o=="function"&&(l=l.filter(o));const c=a===Kkt||a===Gkt;c&&!l.includes("ts")&&l.push("ts"),r>1&&!l.includes("v")&&l.push("v");const d=Yc({},eln,t.formatters),u={version:r,reportingMode:a,baseUrl:t.baseUrl};return l.sort().forEach(h=>{let p=s[h];const f=d[h];if(typeof f=="function"&&(p=f(p,u)),h==="v"){if(r===1)return;p=r}h=="pr"&&p===1||(c&&h==="ts"&&!Ra(p)&&(p=Date.now()),Qon(p)&&(Zon(h)&&typeof p=="string"&&(p=new $kt(p)),n[h]=p))}),n}function dln(s,t={}){const n={};if(!s)return n;const r=Zkt(s,t),a=Yon(r,t==null?void 0:t.customHeaderMap);return Object.entries(a).reduce((i,[l,o])=>{const c=Hkt(o,{whitespace:!1});return c&&(i[l]=c),i},n)}function uln(s,t,n){return Yc(s,dln(t,n))}const hln="CMCD";function mln(s,t={}){return s?Hkt(Zkt(s,t),{whitespace:!1}):""}function pln(s,t={}){if(!s)return"";const n=mln(s,t);return encodeURIComponent(n)}function fln(s,t={}){if(!s)return"";const n=pln(s,t);return`${hln}=${n}`}const QJe=/CMCD=[^&#]+/;function xln(s,t,n){const r=fln(t,n);if(!r)return s;if(QJe.test(s))return s.replace(QJe,r);const a=s.includes("?")?"&":"?";return`${s}${a}${r}`}class gln{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:kg.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===kg.VIDEO||c===kg.AUDIO||c==kg.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(wt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(wt.MEDIA_DETACHED,this.onMediaDetached,this),t.on(wt.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(wt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(wt.MEDIA_DETACHED,this.onMediaDetached,this),t.off(wt.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:Non.HLS,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,n={}){Yc(n,this.createData());const r=n.ot===kg.INIT||n.ot===kg.VIDEO||n.ot===kg.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={}),uln(t.headers,n,i)):t.url=xln(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 kg.TIMED_TEXT;if(t.sn==="initSegment")return kg.INIT;if(n==="audio")return kg.AUDIO;if(n==="main")return this.hls.audioTracks.length?kg.VIDEO:kg.MUXED}getTopBandwidth(t){let n=0,r;const a=this.hls;if(t===kg.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===kg.AUDIO?this.audioBuffer:this.videoBuffer;return!r||!n?NaN:wo.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 yln=3e5;class vln extends r1{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(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(wt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(wt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(wt.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(wt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(wt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(wt.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)===sf.SendAlternateToPenaltyBox&&r.flags===B0.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===Pn.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: ${id(i)} penalized: ${id(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]>yln&&delete r[i]});for(let i=0;i0){this.log(`Setting Pathway to "${l}"`),this.pathwayId=l,xkt(n),this.hls.trigger(wt.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 ju(u.attrs);h["PATHWAY-ID"]=l;const p=h.AUDIO&&`${h.AUDIO}_clone_${l}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${l}`;p&&(r[h.AUDIO]=p,h.AUDIO=p),f&&(a[h.SUBTITLES]=f,h.SUBTITLES=f);const g=Qkt(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),_=new j$({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:g,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let v=1;v{this.log(`Loaded steering manifest: "${a}"`);const g=u.data;if((g==null?void 0:g.VERSION)!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":_,"PATHWAY-CLONES":v,"PATHWAY-PRIORITY":j}=g;if(_)try{this.uri=new self.URL(_,a).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${_}`);return}this.scheduleRefresh(this.uri||p.url),v&&this.clonePathways(v);const b={steeringManifest:g,url:a.toString()};this.hls.trigger(wt.STEERING_MANIFEST_LOADED,b),j&&this.updatePathwayPriority(j)},onError:(u,h,p,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${h.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let g=this.timeToLoad*1e3;if(u.code===429){const _=this.loader;if(typeof(_==null?void 0:_.getResponseHeader)=="function"){const v=_.getResponseHeader("Retry-After");v&&(g=parseFloat(v)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},onTimeout:(u,h,p)=>{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 XJe(s,t,n,r){s&&Object.keys(t).forEach(a=>{const i=s.filter(l=>l.groupId===a).map(l=>{const o=Yc({},l);return o.details=void 0,o.attrs=new ju(o.attrs),o.url=o.attrs.URI=Qkt(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 Qkt(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 KL extends r1{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=KL.CDMCleanupPromise?[KL.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=M7(this.config));const o=l.map(ske).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(l=>{const o=upe(l);if(r!=="sinf"||o!==Mu.FAIRPLAY){this.log(`Ignoring "${n.type}" event with init data type: "${r}" for selected key-system ${o}`);return}let c;try{const f=Mm(new Uint8Array(a)),g=q8e(JSON.parse(f).sinf),_=HNt(g);if(!_)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(_.subarray(8,24))}catch(f){this.warn(`${i} Failed to parse sinf: ${f}`);return}const d=nf(c),{keyIdToKeySessionPromise:u,mediaKeySessions:h}=this;let p=u[d];for(let f=0;fthis.generateRequestWithPreferredKeySession(g,r,a,"encrypted-event-key-match")),p.catch(j=>this.handleError(j));break}}p||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(wt.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(wt.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(wt.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(wt.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(wt.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(wt.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(wt.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(wt.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(wt.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(wt.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===Mu.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 O0?o(h):o(new O0({type:mi.KEY_SYSTEM_ERROR,details:Pn.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 lkt===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=Jan(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: ${id(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(p=>(this.log(`Media-keys created for "${t}"`),c.hasMediaKeys=!0,u.then(f=>f?this.setMediaKeysServerCertificate(p,t,f):p)));return h.catch(p=>{this.error(`Failed to create media-keys for "${t}"}: ${p}`)}),h})}return o.then(()=>l.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:n,mediaKeys:r}){this.log(`Creating key-system session "${n}" keyId: ${nf(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=VG(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 ${nf(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})=>ske(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=ske(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=M7(this.config),r=t.map(upe).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 O0){const c=Tc({},o.data);this.getKeyStatus(n)==="internal-error"&&(c.decryptdata=n);const d=new O0(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 O0){n&&(t.data.frag=n);const r=t.data.decryptdata;this.error(`${t.message}${r?` (${nf(r.keyId||[])})`:""}`),this.hls.trigger(wt.ERROR,t.data)}else this.error(t.message),this.hls.trigger(wt.ERROR,{type:mi.KEY_SYSTEM_ERROR,details:Pn.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const n=VG(t),r=this.keyIdToKeySessionPromise[n];if(!r){const a=upe(t.keyFormat),i=a?[a]:M7(this.config);return this.attemptKeySystemAccess(i)}return r}getKeySystemSelectionPromise(t){if(t.length||(t=M7(this.config)),t.length===0)throw new O0({type:mi.KEY_SYSTEM_ERROR,details:Pn.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${id({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,n){if(this.mediaResolved=void 0,this.mediaKeys===n)return Promise.resolve();const r=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const a=Promise.all(r).then(()=>this.media?this.media.setMediaKeys(n):new Promise((i,l)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return l(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=n,this.media.setMediaKeys(n).then(i).catch(l)}}));return this.mediaKeys=n,this.setMediaKeysQueue.push(a),a.then(()=>{this.log(`Media-keys set for "${t}"`),r.push(a),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(i=>r.indexOf(i)===-1)})}generateRequestWithPreferredKeySession(t,n,r,a){var i;const l=(i=this.config.drmSystems)==null||(i=i[t.keySystem])==null?void 0:i.generateRequest;if(l)try{const g=l.call(this.hls,n,r,t);if(!g)throw new Error("Invalid response from configured generateRequest filter");n=g.initDataType,r=g.initData?g.initData:null,t.decryptdata.pssh=r?new Uint8Array(r):null}catch(g){if(this.warn(g.message),this.hls&&this.hls.config.debug)throw g}if(r===null)return this.log(`Skipping key-session request for "${a}" (no initData)`),Promise.resolve(t);const o=VG(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 H8e,u=t._onmessage=g=>{const _=t.mediaKeysSession;if(!_){d.emit("error",new Error("invalid state"));return}const{messageType:v,message:j}=g;this.log(`"${v}" message event for session "${_.sessionId}" message size: ${j.byteLength}`),v==="license-request"||v==="license-renewal"?this.renewLicense(t,j).catch(b=>{d.eventNames().length?d.emit("error",b):this.handleError(b)}):v==="license-release"?t.keySystem===Mu.FAIRPLAY&&this.updateKeySession(t,OTe("acknowledged")).then(()=>this.removeSession(t)).catch(b=>this.handleError(b)):this.warn(`unhandled media key message type "${v}"`)},h=(g,_)=>{_.keyStatus=g;let v;g.startsWith("usable")?d.emit("resolved"):g==="internal-error"||g==="output-restricted"||g==="output-downscaled"?v=JJe(g,_.decryptdata):g==="expired"?v=new Error(`key expired (keyId: ${o})`):g==="released"?v=new Error("key released"):g==="status-pending"||this.warn(`unhandled key status change "${g}" (keyId: ${o})`),v&&(d.eventNames().length?d.emit("error",v):this.handleError(v))},p=t._onkeystatuseschange=g=>{if(!t.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const v=this.getKeyStatuses(t);if(!Object.keys(v).some(A=>v[A]!=="status-pending"))return;if(v[o]==="expired"){this.log(`Expired key ${id(v)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let b=v[o];if(b)h(b,t);else{var S;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(S=t.keyStatusTimeouts)[o]||(S[o]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const T=this.getKeyStatus(t.decryptdata);if(T&&T!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${T} from other session.`),h(T,t);this.log(`key status for ${o} in key-session "${t.mediaKeysSession.sessionId}" timed out after 1000ms`),b="internal-error",h(b,t)},1e3)),this.log(`No status for keyId ${o} (${id(v)}).`)}};eg(t.mediaKeysSession,"message",u),eg(t.mediaKeysSession,"keystatuseschange",p);const f=new Promise((g,_)=>{d.on("error",_),d.on("resolved",g)});return t.mediaKeysSession.generateRequest(n,r).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(g=>{throw new O0({type:mi.KEY_SYSTEM_ERROR,details:Pn.KEY_SYSTEM_NO_SESSION,error:g,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>(d.removeAllListeners(),this.removeSession(t).then(()=>{throw g}))).then(()=>(d.removeAllListeners(),t))}getKeyStatuses(t){const n={};return t.mediaKeysSession.keyStatuses.forEach((r,a)=>{if(typeof a=="string"&&typeof r=="object"){const o=a;a=r,r=o}const i="buffer"in a?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);if(t.keySystem===Mu.PLAYREADY&&i.length===16){const o=nf(i);n[o]=r,ikt(i)}const l=nf(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:(p,f,g,_)=>{l(p.data)},onError:(p,f,g,_)=>{o(new O0({type:mi.KEY_SYSTEM_ERROR,details:Pn.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:Tc({url:c.url,data:void 0},p)},`"${t}" certificate request failed (${i}). Status: ${p.code} (${p.text})`))},onTimeout:(p,f,g)=>{o(new O0({type:mi.KEY_SYSTEM_ERROR,details:Pn.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:c.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(p,f,g)=>{o(new Error("aborted"))}};a.load(c,u,h)})):Promise.resolve()}setMediaKeysServerCertificate(t,n,r){return new Promise((a,i)=>{t.setServerCertificate(r).then(l=>{this.log(`setServerCertificate ${l?"success":"not supported by CDM"} (${r.byteLength}) on "${n}"`),a(t)}).catch(l=>{i(new O0({type:mi.KEY_SYSTEM_ERROR,details:Pn.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 O0({type:mi.KEY_SYSTEM_ERROR,details:Pn.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,p=i.length;h in key message");return OTe(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 O0({type:mi.KEY_SYSTEM_ERROR,details:Pn.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==Mu.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,eg(r,"encrypted",this.onMediaEncrypted),eg(r,"waitingforkey",this.onWaitingForKey);const a=this.mediaResolved;a?a():this.mediaKeys=r.mediaKeys}onMediaDetached(){const t=this.media;t&&(zg(t,"encrypted",this.onMediaEncrypted),zg(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,j4.clearKeyUriToKeyIdMap();const i=a.length;KL.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(wt.ERROR,{type:mi.OTHER_ERROR,details:Pn.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(wt.ERROR,{type:mi.OTHER_ERROR,details:Pn.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: ${nf((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(tin(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(wt.ERROR,{type:mi.OTHER_ERROR,details:Pn.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(wt.ERROR,{type:mi.OTHER_ERROR,details:Pn.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}KL.CDMCleanupPromise=void 0;function VG(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return nf(s.keyId)}function bln(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 O0 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 JJe(s,t){const n=s==="output-restricted",r=n?Pn.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Pn.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new O0({type:mi.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},n?"HDCP level output restricted":`key status changed to "${s}"`)}class _ln{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(wt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(wt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(wt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(wt.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(wt.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(wt.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 Xkt(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 Jkt(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){Pc.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){Pc.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${a}`)}}n==="disabled"&&(s.mode=n)}function $P(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 GTe(s,t,n,r){const a=s.mode;if(a==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const i=jln(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 fpe(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=fpe(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(wt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(wt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(wt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(wt.LEVEL_LOADING,this.onLevelLoading,this),t.on(wt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(wt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(wt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(wt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(wt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(wt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(wt.LEVEL_LOADING,this.onLevelLoading,this),t.off(wt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(wt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(wt.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;fpe(r.textTracks).forEach(l=>{$P(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=cw(o,l);if(u>-1)i=l[u];else{const h=cw(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(wt.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=cw(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(wt.SUBTITLE_TRACK_LOADING,{url:i,id:r,groupId:a,deliveryDirectives:n||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const n=fpe(t.textTracks),r=this.currentTrack;let a;if(r&&(a=n.filter(i=>UTe(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||!Ra(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(wt.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(wt.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 kln(){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 Pz(s){let t=5381,n=s.length;for(;n;)t=t*33^s.charCodeAt(--n);return(t>>>0).toString()}const YL=.025;let i0e=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function Sln(s,t,n){return`${s.identifier}-${n+1}-${Pz(t)}`}class Cln{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 uke(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=uke(n,t);return n-r<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,n=Ra(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 uke(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 Tln(this)}}function uke(s,t){return s-t.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function uP(s){const t=s.timelineStart,n=s.duration||0;return`["${s.identifier}" ${t.toFixed(2)}-${(t+n).toFixed(2)}]`}class Eln{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(wt.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new t(n);this.interstitial=r,this.assetItem=a;const l=()=>{this.hasDetails=!0};i.once(wt.LEVEL_LOADED,l),i.once(wt.AUDIO_TRACK_LOADED,l),i.once(wt.SUBTITLE_TRACK_LOADED,l),i.on(wt.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(wt.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,i.trigger(wt.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=eSt(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=wo.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=wo.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: ${uP(this.assetItem)} ${(t=this.hls)==null?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const eet=.033;class Aln extends r1{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,p=d.cue.post,f=u.cue.pre,g=u.cue.post;if(h&&!f)return-1;if(f&&!h||p&&!g)return 1;if(g&&!p)return-1;if(!h&&!f&&!p&&!g){const _=d.startTime,v=u.startTime;if(_!==v)return _-v}return d.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=l,c.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(t,c)}updateSchedule(t,n=[],r=!1){const a=this.events||[];if(a.length||n.length||this.length<2){const i=this.items,l=this.parseSchedule(a,t);(r||n.length||(i==null?void 0:i.length)!==l.length||l.some((c,d)=>Math.abs(c.playout.start-i[d].playout.start)>.005||Math.abs(c.playout.end-i[d].playout.end)>.005))&&(this.items=l,this.onScheduleUpdate(n,i))}}parseDateRanges(t,n,r){const a=[],i=Object.keys(t);for(let l=0;l!c.error&&!(c.cue.once&&c.hasPlayed)),t.length){this.resolveOffsets(t,n);let c=0,d=0;if(t.forEach((u,h)=>{const p=u.cue.pre,f=u.cue.post,g=t[h-1]||null,_=u.appendInPlace,v=f?i:u.startOffset,j=u.duration,b=u.timelineOccupancy===i0e.Range?j:0,S=u.resumptionOffset,A=(g==null?void 0:g.startTime)===v,T=v+u.cumulativeDuration;let L=_?T+j:v+S;if(p||!f&&v<=0){const M=d;d+=b,u.timelineStart=T;const F=l;l+=j,r.push({event:u,start:T,end:L,playout:{start:F,end:l},integrated:{start:M,end:d}})}else if(v<=i){if(!A){const z=v-c;if(z>eet){const V=c,W=d;d+=z;const Y=l;l+=z;const K={previousEvent:t[h-1]||null,nextEvent:u,start:V,end:V+z,playout:{start:Y,end:l},integrated:{start:W,end:d}};r.push(K)}else z>0&&g&&(g.cumulativeDuration+=z,r[r.length-1].end=v)}f&&(L=T),u.timelineStart=T;const M=d;d+=b;const F=l;l+=j,r.push({event:u,start:T,end:L,playout:{start:F,end:l},integrated:{start:M,end:d}})}else return;const D=u.resumeTime;f||D>i?c=i:c=D}),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=zM(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+1YL?(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=zM(null,o.fragments,r);if(!d)return this.log(`"${t.identifier}" resumption ${r} does not align with any fragments in ${l} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const u=l==="audio"?.175:0;return Math.abs(d.start-r){const v=p.data,j=v==null?void 0:v.ASSETS;if(!Array.isArray(j)){const b=this.assignAssetListError(t,Pn.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,_);this.hls.trigger(wt.ERROR,b);return}t.assetListResponse=v,this.hls.trigger(wt.ASSET_LIST_LOADED,{event:t,assetListResponse:v,networkDetails:_})},onError:(p,f,g,_)=>{const v=this.assignAssetListError(t,Pn.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${p.code} ${p.text} (${f.url})`),f.url,_,g);this.hls.trigger(wt.ERROR,v)},onTimeout:(p,f,g)=>{const _=this.assignAssetListError(t,Pn.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,p,g);this.hls.trigger(wt.ERROR,_)}};return o.load(c,u,h),this.hls.trigger(wt.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,n,r,a,i,l){return t.error=r,{type:mi.NETWORK_ERROR,details:n,fatal:!1,interstitial:t,url:a,error:r,networkDetails:l,stats:i}}}function tet(s){var t;s==null||(t=s.play())==null||t.catch(()=>{})}function KI(s,t){return`[${s}] Advancing timeline position to ${t}`}class Iln extends r1{constructor(t,n){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled||!this.schedule)return;const a=r-this.timelinePos;if(Math.abs(a)<1/7056e5)return;const l=a<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=r,this.bufferedPos=r;const o=this.playingItem;if(!o){this.checkBuffer();return}if(l&&this.schedule.resetErrorsInRange(r,r-a)&&this.updateSchedule(!0),this.checkBuffer(),l&&r=o.end){var c;const f=this.findItemIndex(o);let g=this.schedule.findItemIndexAtTime(r);if(g===-1&&(g=f+(l?-1:1),this.log(`seeked ${l?"back ":""}to position not covered by schedule ${r} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!l&&g>f){const _=this.schedule.findJumpRestrictedIndex(f+1,g);if(_>f){this.setSchedulePosition(_);return}}this.setSchedulePosition(g);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(r,f))}return}const u=d.timelineStart,h=d.duration||0;if(l&&r=u+h){var p;(p=o.event)!=null&&p.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(_=>_.identifier),h=!!(o.length||u.length);(h||a)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} Schedule: ${c.map(_=>B1(_))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let p=null,f=null;l&&(p=this.updateItem(l,this.timelinePos),this.itemsMatch(l,p)?this.playingItem=p:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const g=this.bufferingItem;if(g&&(f=this.updateItem(g,this.bufferedPos),this.itemsMatch(g,f)?this.bufferingItem=f:g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.event,null))),r.forEach(_=>{_.assetList.forEach(v=>{this.clearAssetPlayer(v.identifier,null)})}),this.playerQueue.forEach(_=>{if(_.interstitial.appendInPlace){const v=_.assetItem.timelineStart,j=_.timelineOffset-v;if(j)try{_.timelineOffset=v}catch(b){Math.abs(j)>YL&&this.warn(`${b} ("${_.assetId}" ${_.timelineOffset}->${v})`)}}}),h||a){if(this.hls.trigger(wt.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(p,l),g&&f!==p&&this.trimInPlace(f,g),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=n,this.assetListLoader=new Mln(t),this.schedule=new Aln(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(wt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(wt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(wt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(wt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(wt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(wt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(wt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(wt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(wt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(wt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(wt.BUFFER_APPENDED,this.onBufferAppended,this),t.on(wt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(wt.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(wt.MEDIA_ENDED,this.onMediaEnded,this),t.on(wt.ERROR,this.onError,this),t.on(wt.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(wt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(wt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(wt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(wt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(wt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(wt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(wt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(wt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(wt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(wt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(wt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(wt.BUFFER_APPENDED,this.onBufferAppended,this),t.off(wt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(wt.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(wt.MEDIA_ENDED,this.onMediaEnded,this),t.off(wt.ERROR,this.onError,this),t.off(wt.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){zg(t,"play",this.onPlay),zg(t,"pause",this.onPause),zg(t,"seeking",this.onSeeking),zg(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,n){const r=this.media=n.media;eg(r,"seeking",this.onSeeking),eg(r,"timeupdate",this.onTimeupdate),eg(r,"play",this.onPlay),eg(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,p,f,g,_)=>{if(h){let v=h[p].start;const j=h.event;if(j){if(p==="playout"||j.timelineOccupancy!==i0e.Point){const b=r(f);(b==null?void 0:b.interstitial)===j&&(v+=b.assetItem.startOffset+b[_])}}else{const b=g==="bufferedPos"?l():t[g];v+=b-h.start}return v}return 0},i=(h,p)=>{var f;if(h!==0&&p!=="primary"&&(f=t.schedule)!=null&&f.length){var g;const _=t.schedule.findItemIndexAtTime(h),v=(g=t.schedule.items)==null?void 0:g[_];if(v){const j=v[p].start-v.start;return h+j}}return h},l=()=>{const h=t.bufferedPos;return h===Number.MAX_VALUE?o("primary"):Math.max(h,0)},o=h=>{var p,f;return(p=t.primaryDetails)!=null&&p.live?t.primaryDetails.edge:((f=t.schedule)==null?void 0:f.durations[h])||0},c=(h,p)=>{var f,g;const _=t.effectivePlayingItem;if(_!=null&&(f=_.event)!=null&&f.restrictions.skip||!t.schedule)return;t.log(`seek to ${h} "${p}"`);const v=t.effectivePlayingItem,j=t.schedule.findItemIndexAtTime(h,p),b=(g=t.schedule.items)==null?void 0:g[j],S=t.getBufferingPlayer(),A=S==null?void 0:S.interstitial,T=A==null?void 0:A.appendInPlace,L=v&&t.itemsMatch(v,b);if(v&&(T||L)){const D=r(t.playingAsset),M=(D==null?void 0:D.media)||t.primaryMedia;if(M){const F=p==="primary"?M.currentTime:a(v,p,t.playingAsset,"timelinePos","currentTime"),z=h-F,V=(T?F:M.currentTime)+z;if(V>=0&&(!D||T||V<=D.duration)){M.currentTime=V;return}}}if(b){let D=h;if(p!=="primary"){const F=b[p].start,z=h-F;D=b.start+z}const M=!t.isInterstitial(b);if((!t.isInterstitial(v)||v.event.appendInPlace)&&(M||b.event.appendInPlace)){const F=t.media||(T?S==null?void 0:S.media:null);F&&(F.currentTime=D)}else if(v){const F=t.findItemIndex(v);if(j>F){const V=t.schedule.findJumpRestrictedIndex(F+1,j);if(V>F){t.setSchedulePosition(V);return}}let z=0;if(M)t.timelinePos=D,t.checkBuffer();else{const V=b.event.assetList,W=h-(b[p]||b).start;for(let Y=V.length;Y--;){const K=V[Y];if(K.duration&&W>=K.startOffset&&W{const h=t.effectivePlayingItem;if(t.isInterstitial(h))return h;const p=n();return t.isInterstitial(p)?p:null},u={get bufferedEnd(){const h=n(),p=t.bufferingItem;if(p&&p===h){var f;return a(p,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-p.playout.start||((f=t.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const h=d(),p=t.effectivePlayingItem;return p&&p===h?a(p,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-p.playout.start:0},set currentTime(h){const p=d(),f=t.effectivePlayingItem;f&&f===p&&c(h+f.playout.start,"playout")},get duration(){const h=d();return h?h.playout.end-h.playout.start:0},get assetPlayers(){var h;const p=(h=d())==null?void 0:h.event.assetList;return p?p.map(f=>t.getAssetPlayer(f.identifier)):[]},get playingIndex(){var h;const p=(h=d())==null?void 0:h.event;return p&&t.effectivePlayingAsset?p.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,p=h==null?void 0:h.event;if(p&&!p.restrictions.skip){const f=t.findItemIndex(h);if(p.appendInPlace){const g=h.playout.start+h.event.duration;c(g+.001,"playout")}else t.advanceAfterAssetEnded(p,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const n=this.playingItem,r=(t=this.schedule)==null?void 0:t.items;return!this.playbackStarted||!n||!r?!1:this.findItemIndex(n)===r.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var t,n;if(this.mediaSelection===null)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let a=this.media;!a&&(t=this.bufferingItem)!=null&&(t=t.event)!=null&&t.appendInPlace&&(a=this.primaryMedia);const i=(n=a)==null?void 0:n.currentTime;if(!(i===void 0||!Ra(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} ${id(i)}`),this.detachedData=i}else n&&a&&(this.shouldPlay||(this.shouldPlay=!a.paused))}transferMediaTo(t,n){var r,a;if(t.media===n)return;let i=null;const l=this.hls,o=t!==l,c=o&&t.interstitial.appendInPlace,d=(r=this.detachedData)==null?void 0:r.mediaSource;let u;if(l.media)c&&(i=l.transferMedia(),this.detachedData=i),u="Primary";else if(d){const g=this.getBufferingPlayer();g?(i=g.transferMedia(),u=`${g}`):u="detached MediaSource"}else u="detached media";if(!i){if(d)i=this.detachedData,this.log(`using detachedData: MediaSource ${id(i)}`);else if(!this.detachedData||l.media===n){const g=this.playerQueue;g.length>1&&g.forEach(_=>{if(o&&_.interstitial.appendInPlace!==c){const v=_.interstitial;this.clearInterstitial(_.interstitial,null),v.appendInPlace=!1,v.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${v}`)}}),this.hls.detachMedia(),this.detachedData={media:n}}}const h=i&&"mediaSource"in i&&((a=i.mediaSource)==null?void 0:a.readyState)!=="closed",p=h&&i?i:n;this.log(`${h?"transfering MediaSource":"attaching media"} to ${o?t:"Primary"} from ${u} (media.currentTime: ${n.currentTime})`);const f=this.schedule;if(p===i&&f){const g=o&&t.assetId===f.assetIdAtEnd;p.overrides={duration:f.duration,endOfStream:!o||g,cueRemoval:!o}}t.attachMedia(p)}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(KI("checkStart (preroll)",i));const l=t.findEventIndex(n[0].identifier);this.setSchedulePosition(l)}else if(i>=0||!this.primaryLive){this.log(KI("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(KI("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=hke(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=hke(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&&B1(i)}) pos: ${this.timelinePos}`);const l=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(l)){const u=l.event,h=this.playingAsset,p=h==null?void 0:h.identifier,f=p?this.getAssetPlayer(p):null;if(f&&p&&(!this.eventItemsMatch(l,i)||n!==void 0&&p!==u.assetList[n].identifier)){var c;const g=u.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${g+1}/${u.assetList.length} ${uP(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(wt.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:g,event:u,schedule:a.slice(0),scheduleIndex:t,player:f}),l!==this.playingItem){this.itemsMatch(l,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),g);return}this.retreiveMediaSource(p,i),f.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(l,i)&&(this.endedItem=l,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${B1(l)}`),u.hasPlayed=!0,this.hls.trigger(wt.INTERSTITIAL_ENDED,{event:u,schedule:a.slice(0),scheduleIndex:t}),u.cue.once)){var d;this.updateSchedule();const g=(d=this.schedule)==null?void 0:d.items;if(i&&g){const _=this.findItemIndex(i);this.advanceSchedule(_,g,n,l,o)}return}}this.advanceSchedule(t,a,n,l,o)}advanceSchedule(t,n,r,a,i){const l=this.schedule;if(!l)return;const o=n[t]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(u=>{const h=u.interstitial,p=l.findEventIndex(h.identifier);(pt+1)&&this.clearInterstitial(h,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const u=o.event;if(r===void 0){r=l.findAssetIndex(u,this.timelinePos);const g=hke(u,r-1);if(u.isAssetPastPlayoutLimit(g)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,t,r);return}r=g}const h=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let p=this.preloadAssets(u,r);if(this.eventItemsMatch(o,h||a)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${B1(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(wt.INTERSTITIAL_STARTED,{event:u,schedule:n.slice(0),scheduleIndex:t})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const f=u.assetList[r];if(!f){this.advanceAfterAssetEnded(u,t,r||0);return}if(p||(p=this.getAssetPlayer(f.identifier)),p===null||p.destroyed){const g=u.assetList.length;this.warn(`asset ${r+1}/${g} player destroyed ${u}`),p=this.createAssetPlayer(u,f,r),p.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(p,r,n,t,c),this.shouldPlay&&tet(p.media)}else o?(this.resumePrimary(o,t,a),this.shouldPlay&&tet(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 ${B1(t)}`),!((a=this.detachedData)!=null&&a.mediaSource)){let o=this.timelinePos;(o=t.end)&&(o=this.getPrimaryResumption(t,n),this.log(KI("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 ${B1(t)}`),this.hls.trigger(wt.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:wo.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(KI("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(wt.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(wt.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=Tc(Tc({},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=Tc(Tc({},this.altSelection),{},{audio:r});return}const i=Tc(Tc({},a),{},{audio:r});this.mediaSelection=i}onSubtitleTrackUpdated(t,n){const r=this.hls.subtitleTracks[n.id],a=this.mediaSelection;if(!a){this.altSelection=Tc(Tc({},this.altSelection),{},{subtitles:r});return}const i=Tc(Tc({},a),{},{subtitles:r});this.mediaSelection=i}onAudioTrackSwitching(t,n){const r=dJe(n);this.playerQueue.forEach(({hls:a})=>a&&(a.setAudioOption(n)||a.setAudioOption(r)))}onSubtitleTrackSwitch(t,n){const r=dJe(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=wo.bufferInfo(this.primaryMedia,r,0);(a.end>r||(a.nextStart||0)>r)&&(this.log(`trim buffered interstitial ${B1(t)} (was ${B1(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=wo.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=p.event)!=null&&d.appendInPlace&&t+.01>=p.start)&&(c=h),this.isInterstitial(i)){const f=i.event;if(h-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=t,c>u&&c>o)this.bufferedToItem(p);else{const f=this.primaryDetails;this.primaryLive&&f&&t>f.edge-f.targetduration&&p.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 ${B1(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 p=this.getAssetPlayer(u.identifier);p&&(h===d&&p.loadSource(),p.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(wt.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 p=this.playingItem;!this.isInterstitial(p)&&(p==null||(o=p.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 p=u-c;p>0&&(d=Math.round(p*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(wt.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:a})})}getAssetPlayerQueueIndex(t){const n=this.playerQueue;for(let r=0;r1){const T=n.duration;T&&A{if(A.live){var T;const M=new Error(`Interstitials MUST be VOD assets ${t}`),F={fatal:!0,type:mi.OTHER_ERROR,details:Pn.INTERSTITIAL_ASSET_ITEM_ERROR,error:M},z=((T=this.schedule)==null?void 0:T.findEventIndex(t.identifier))||-1;this.handleAssetItemError(F,t,z,r,M.message);return}const L=A.edge-A.fragmentStart,D=n.duration;(_||D===null||L>D)&&(_=!1,this.log(`Interstitial asset "${h}" duration change ${D} > ${L}`),n.duration=L,this.updateSchedule())};g.on(wt.LEVEL_UPDATED,(A,{details:T})=>v(T)),g.on(wt.LEVEL_PTS_UPDATED,(A,{details:T})=>v(T)),g.on(wt.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const j=(A,T)=>{const L=this.getAssetPlayer(h);if(L&&T.tracks){L.off(wt.BUFFER_CODECS,j),L.tracks=T.tracks;const D=this.primaryMedia;this.bufferingAsset===L.assetItem&&D&&!L.media&&this.bufferAssetPlayer(L,D)}};g.on(wt.BUFFER_CODECS,j);const b=()=>{var A;const T=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${T}`),!T||!this.schedule)return;const L=this.schedule.findEventIndex(t.identifier),D=(A=this.schedule.items)==null?void 0:A[L];this.isInterstitial(D)&&this.advanceAssetBuffering(D,n)};g.on(wt.BUFFERED_TO_END,b);const S=A=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const L=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,L,A)};return g.once(wt.MEDIA_ENDED,S(r)),g.once(wt.PLAYOUT_LIMIT_REACHED,S(1/0)),g.on(wt.ERROR,(A,T)=>{if(!this.schedule)return;const L=this.getAssetPlayer(h);if(T.details===Pn.BUFFER_STALLED_ERROR){if(L!=null&&L.appendInPlace){this.handleInPlaceStall(t);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(T,t,this.schedule.findEventIndex(t.identifier),r,`Asset player error ${T.error} ${t}`)}),g.on(wt.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const T=new Error(`Asset player destroyed unexpectedly ${h}`),L={fatal:!0,type:mi.OTHER_ERROR,details:Pn.INTERSTITIAL_ASSET_ITEM_ERROR,error:T};this.handleAssetItemError(L,t,this.schedule.findEventIndex(t.identifier),r,T.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${uP(n)}`),this.hls.trigger(wt.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:n,assetListIndex:r,event:t,player:g}),g}clearInterstitial(t,n){this.clearAssetPlayers(t,n),t.reset()}clearAssetPlayers(t,n){t.assetList.forEach(r=>{this.clearAssetPlayer(r.identifier,n)})}resetAssetPlayer(t){const n=this.getAssetPlayerQueueIndex(t);if(n!==-1){this.log(`reset asset player "${t}" after error`);const r=this.playerQueue[n];this.transferMediaFromPlayer(r,null),r.resetDetails()}}clearAssetPlayer(t,n){const r=this.getAssetPlayerQueueIndex(t);if(r!==-1){const a=this.playerQueue[r];this.log(`clear ${a} toSegment: ${n&&B1(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} ${uP(o)}`),this.hls.trigger(wt.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&&!RNt(h,t.tracks)){const p=new Error(`Asset ${uP(l)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),f={fatal:!0,type:mi.OTHER_ERROR,details:Pn.INTERSTITIAL_ASSET_ITEM_ERROR,error:p},g=i.findAssetIndex(l);this.handleAssetItemError(f,i,o,g,p.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!_.error))n.error=g;else for(let _=a;_{const j=parseFloat(_.DURATION);this.createAsset(i,v,u,c+u,j,_.URI),u+=j}),i.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${d}) ${i}`);const h=this.waitingItem,p=(h==null?void 0:h.event.identifier)===l;this.updateSchedule();const f=(a=this.bufferingItem)==null?void 0:a.event;if(p){var g;const _=this.schedule.findEventIndex(l),v=(g=this.schedule.items)==null?void 0:g[_];if(v){if(!this.playingItem&&this.timelinePos>v.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==_){i.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${i}`),this.log(i.error.message),this.updateSchedule(!0),this.primaryFallback(i);return}this.setBufferingItem(v)}this.setSchedulePosition(_)}else if((f==null?void 0:f.identifier)===l){const _=i.assetList[0];if(_){const v=this.getAssetPlayer(_.identifier);if(f.appendInPlace){const j=this.primaryMedia;v&&j&&this.bufferAssetPlayer(v,j)}else v&&v.loadSource()}}}onError(t,n){if(this.schedule)switch(n.details){case Pn.ASSET_LIST_PARSING_ERROR:case Pn.ASSET_LIST_LOAD_ERROR:case Pn.ASSET_LIST_LOAD_TIMEOUT:{const r=n.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break}case Pn.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 set=500;class Pln extends V8e{constructor(t,n,r){super(t,n,r,"subtitle-stream-controller",Ya.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(wt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(wt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(wt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(wt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(wt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(wt.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(wt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(wt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(wt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(wt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(wt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(wt.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,n){this.stopLoad(),this.state=dr.IDLE,this.setInterval(set),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)||(Th(r)&&(this.fragPrevious=r),this.state=dr.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 j$(r));return}this.tracksBuffered=[],this.levels=n.map(r=>{const a=new j$(r);return this.tracksBuffered[a.id]=[],a}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Ya.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!==dr.STOPPED&&this.setInterval(set)}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 p=h.fragments[0];if(!c.details)l.hasProgramDateTime&&h.hasProgramDateTime?(r0e(l,h),d=l.fragmentStart):p&&(d=p.start,zTe(l,d));else{var u;d=this.alignPlaylists(l,c.details,(u=this.levelLastLoaded)==null?void 0:u.details),d===0&&p&&(d=p.start,zTe(l,d))}h&&!this.startFragRequested&&this.setStartPosition(h,d)}c.details=l,this.levelLastLoaded=c,o===a&&(this.hls.trigger(wt.SUBTITLE_TRACK_UPDATED,{details:l,id:o,groupId:n.groupId}),this.tick(),l.live&&!this.fragCurrent&&this.media&&this.state===dr.IDLE&&(zM(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&&WL(a.method)){const l=performance.now();this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer,U8e(a.method)).catch(o=>{throw i.trigger(wt.ERROR,{type:mi.MEDIA_ERROR,details:Pn.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:n}),o}).then(o=>{const c=performance.now();i.trigger(wt.FRAG_DECRYPTED,{frag:n,payload:o,stats:{tstart:l,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=dr.IDLE})}}doTick(){if(!this.media){this.state=dr.IDLE;return}if(this.state===dr.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=wo.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,p=h.length,f=d.edge;let g=null;const _=this.fragPrevious;if(of-b?0:b;g=zM(_,h,Math.max(h[0].start,o),S),!g&&_&&_.start{if(a=a>>>0,a>i-1)throw new DOMException(`Failed to execute '${r}' on 'TimeRanges': The index provided (${a}) is greater than the maximum bound (${i})`);return t[a][r]};this.buffered={get length(){return t.length},end(r){return n("end",r,t.length)},start(r){return n("start",r,t.length)}}}}const Dln={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},tSt=s=>String.fromCharCode(Dln[s]||s),V1=15,m2=100,Rln={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Oln={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Fln={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},zln={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Bln=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class $ln{constructor(){this.time=null,this.verboseLevel=0}log(t,n){if(this.verboseLevel>=t){const r=typeof n=="function"?n():n;Pc.log(`${this.time} [${t}] ${r}`)}}}const v3=function(t){const n=[];for(let r=0;rm2&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=m2)}moveCursor(t){const n=this.pos+t;if(t>1)for(let r=this.pos+1;r=144&&this.backSpace();const n=tSt(t);if(this.pos>=m2){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 = "+id(t));let n=t.row-1;if(this.nrRollUpRows&&n"bkgData = "+id(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 net{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 mke(r),this.nonDisplayedMemory=new mke(r),this.lastOutputScreen=new mke(r),this.currRollUpRow=this.displayedMemory.rows[V1-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[V1-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: "+id(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 ret{constructor(t,n,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Hln(),this.logger=void 0;const a=this.logger=new $ln;this.channels=[null,new net(t,n,a),new net(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"["+v3([n[r],n[r+1]])+"] -> ("+v3([a,i])+")");const c=this.cmdHistory;if(a>=16&&a<=31){if(Vln(a,i,c)){HG(null,null,c),this.logger.log(3,()=>"Repeated command ("+v3([a,i])+") is dropped");continue}HG(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 HG(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 "+v3([a,i])+" orig: "+v3([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 ("+v3([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?Rln[t]:Fln[t]:r=l===1?Oln[t]:zln[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 '"+tSt(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 = "+v3(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=Bln[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.");L=z,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",i({},h,{get:function(){return D},set:function(z){const V=a(z);if(!V)throw new SyntaxError("An invalid or illegal string was specified.");D=V,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",i({},h,{get:function(){return M},set:function(z){if(z<0||z>100)throw new Error("Size must be between 0 and 100.");M=z,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",i({},h,{get:function(){return F},set:function(z){const V=a(z);if(!V)throw new SyntaxError("An invalid or illegal string was specified.");F=V,this.hasBeenReset=!0}})),u.displayState=void 0}return l.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},l}();class Gln{decode(t,n){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function nSt(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 Wln{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 rSt(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 WTe=new sDe(0,0,""),GG=WTe.align==="middle"?"middle":"center";function Kln(s,t,n){const r=s;function a(){const o=nSt(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 Wln;rSt(o,function(p,f){let g;switch(p){case"region":for(let _=n.length-1;_>=0;_--)if(n[_].id===f){d.set(p,n[_].region);break}break;case"vertical":d.alt(p,f,["rl","lr"]);break;case"line":g=f.split(","),d.integer(p,g[0]),d.percent(p,g[0])&&d.set("snapToLines",!1),d.alt(p,g[0],["auto"]),g.length===2&&d.alt("lineAlign",g[1],["start",GG,"end"]);break;case"position":g=f.split(","),d.percent(p,g[0]),g.length===2&&d.alt("positionAlign",g[1],["start",GG,"end","line-left","line-right","auto"]);break;case"size":d.percent(p,f);break;case"align":d.alt(p,f,["start",GG,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let u=d.get("line","auto");u==="auto"&&WTe.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",GG);let h=d.get("position","auto");h==="auto"&&WTe.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 aSt(s){return s.replace(//gi,` `)}class Yln{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Gln,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=aSt(i);l")===-1){n.cue.id=i;continue}case"CUE":if(!n.cue){n.state="BADCUE";continue}try{Kln(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 Zln=/\r\n|\n\r|\n|\r/g,pke=function(t,n,r=0){return t.slice(r,r+n.length)===n},Qln=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(!Ra(n)||!Ra(r)||!Ra(a)||!Ra(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return n+=1e3*r,n+=60*1e3*a,n+=60*60*1e3*i,n};function nDe(s,t,n){return Pz(s.toString())+Pz(t.toString())+Pz(n)}const Xln=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 Jln(s,t,n,r,a,i,l){const o=new Yln,c=yy(new Uint8Array(s)).trim().replace(Zln,` `).split(` `),d=[],u=t?aon(t.baseTime,t.timescale):0;let h="00:00.000",p=0,f=0,g,_=!0;o.oncue=function(v){const j=n[r];let b=n.ccOffset;const S=(p-u)/9e4;if(j!=null&&j.new&&(f!==void 0?b=n.ccOffset=j.start:Xln(n,r,S)),S){if(!t){g=new Error("Missing initPTS for VTT MPEGTS");return}b=S-n.presentationOffset}const A=v.endTime-v.startTime,T=$0((v.startTime+b-f)*9e4,a*9e4)/9e4;v.startTime=Math.max(T,0),v.endTime=Math.max(T+A,0);const L=v.text.trim();v.text=decodeURIComponent(encodeURIComponent(L)),v.id||(v.id=nDe(v.startTime,v.endTime,L)),v.endTime>0&&d.push(v)},o.onparsingerror=function(v){g=v},o.onflush=function(){if(g){l(g);return}i(d)},c.forEach(v=>{if(_)if(pke(v,"X-TIMESTAMP-MAP=")){_=!1,v.slice(16).split(",").forEach(j=>{pke(j,"LOCAL:")?h=j.slice(6):pke(j,"MPEGTS:")&&(p=parseInt(j.slice(7)))});try{f=Qln(h)/1e3}catch(j){g=j}return}else v===""&&(_=!1);o.parse(v+` `)}),o.flush()}const fke="stpp.ttml.im1t",iSt=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,oSt=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ecn={left:"start",center:"center",right:"end",start:"start",end:"end"};function aet(s,t,n,r){const a=sl(new Uint8Array(s),["mdat"]);if(a.length===0){r(new Error("Could not parse IMSC1 mdat"));return}const i=a.map(o=>yy(o)),l=ron(t.baseTime,1,t.timescale);try{i.forEach(o=>n(tcn(o,l)))}catch(o){r(o)}}function tcn(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,p)=>(h[p]=a.getAttribute(`ttp:${p}`)||i[p],h),{}),o=a.getAttribute("xml:space")!=="preserve",c=iet(xke(a,"styling","style")),d=iet(xke(a,"layout","region")),u=xke(a,"body","[begin]");return[].map.call(u,h=>{const p=lSt(h,o);if(!p||!h.hasAttribute("begin"))return null;const f=yke(h.getAttribute("begin"),l),g=yke(h.getAttribute("dur"),l);let _=yke(h.getAttribute("end"),l);if(f===null)throw oet(h);if(_===null){if(g===null)throw oet(h);_=f+g}const v=new sDe(f-t,_-t,p);v.id=nDe(v.startTime,v.endTime,v.text);const j=d[h.getAttribute("region")],b=c[h.getAttribute("style")],S=scn(j,b,c),{textAlign:A}=S;if(A){const T=ecn[A];T&&(v.lineAlign=T),v.align=A}return Yc(v,S),v}).filter(h=>h!==null)}function xke(s,t,n){const r=s.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function iet(s){return s.reduce((t,n)=>{const r=n.getAttribute("xml:id");return r&&(t[r]=n),t},{})}function lSt(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?lSt(r,t):t?n+r.textContent.trim().replace(/\s+/g," "):n+r.textContent},"")}function scn(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=gke(t,r,c)||gke(s,r,c)||gke(a,r,c);return d&&(o[c]=d),o},{})}function gke(s,t,n){return s&&s.hasAttributeNS(t,n)?s.getAttributeNS(t,n):null}function oet(s){return new Error(`Could not parse ttml timestamp ${s}`)}function yke(s,t){if(!s)return null;let n=nSt(s);return n===null&&(iSt.test(s)?n=ncn(s,t):oSt.test(s)&&(n=rcn(s,t))),n}function ncn(s,t){const n=iSt.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 rcn(s,t){const n=oSt.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 WG{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 acn{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=det(),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(wt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(wt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(wt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(wt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(wt.FRAG_LOADING,this.onFragLoading,this),t.on(wt.FRAG_LOADED,this.onFragLoaded,this),t.on(wt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(wt.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(wt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(wt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(wt.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(wt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(wt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(wt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(wt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(wt.FRAG_LOADING,this.onFragLoading,this),t.off(wt.FRAG_LOADED,this.onFragLoaded,this),t.off(wt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(wt.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(wt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(wt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(wt.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new WG(this,"textTrack1"),n=new WG(this,"textTrack2"),r=new WG(this,"textTrack3"),a=new WG(this,"textTrack4");this.cea608Parser1=new ret(1,t,n),this.cea608Parser2=new ret(3,r,a)}addCues(t,n,r,a,i){let l=!1;for(let o=i.length;o--;){const c=i[o],d=icn(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(wt.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===Ya.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(wt.FRAG_LOADED,c):this.hls.trigger(wt.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{$P(a[i]),delete a[i]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=det(),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===fke);if(this.config.enableWebVTT||a&&this.config.enableIMSC1){if(zkt(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const l=this.media,o=l?fpe(l.textTracks):null;if(this.tracks.forEach((c,d)=>{let u;if(o){let h=null;for(let p=0;pd!==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(wt.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===Ya.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===Ya.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===fke?this._parseIMSC1(r,a):this._parseVTTs(n)}}else this.hls.trigger(wt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,n){const r=this.hls;aet(n,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),r.trigger(wt.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},a=>{r.logger.log(`Failed to parse IMSC1: ${a}`),r.trigger(wt.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?Yv(r.initSegment.data,new Uint8Array(a)).buffer:a;Jln(d,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,u=>{this._appendCues(u,r.level),c.trigger(wt.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(wt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:u})})}_fallbackToIMSC1(t,n){const r=this.tracks[t.level];r.textCodec||aet(n,this.initPTS[t.cc],()=>{r.textCodec=fke,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=>Jkt(a,i))}else{const a=this.tracks[n];if(!a)return;const i=a.default?"default":"subtitles"+n;r.trigger(wt.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,n){const{frag:r}=n;r.type===Ya.SUBTITLE&&this.onFragLoaded(wt.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===Ya.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let i=0;iGTe(o[c],n,r))}if(this.config.renderTextTracksNatively&&n===0&&a!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>GTe(o[c],n,a))}}}extractCea608Data(t){const n=[[],[]],r=t[0]&31;let a=2;for(let i=0;i=16?c--:c++;const f=aSt(d.trim()),g=nDe(t,n,f);s!=null&&(h=s.cues)!=null&&h.getCueById(g)||(l=new u(t,n,f),l.id=g,l.line=p+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((p,f)=>p.line==="auto"||f.line==="auto"?0:p.line>8&&f.line>8?f.line-p.line:p.line-f.line),a.forEach(p=>Jkt(s,p))),a}};function ccn(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const dcn=/(\d+)-(\d+)\/(\d+)/;class uet{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||pcn,this.controller=new self.AbortController,this.stats=new D8e}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=ucn(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&&Ra(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},n.timeout),(S$(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var p;this.response=this.loader=h;const f=Math.max(self.performance.now(),a.loading.start);if(self.clearTimeout(this.requestTimeout),n.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},d-(f-a.loading.start)),!h.ok){const{status:_,statusText:v}=h;throw new fcn(v||"fetch, bad network response",_,h)}a.loading.first=f,a.total=mcn(h.headers)||a.total;const g=(p=this.callbacks)==null?void 0:p.onProgress;return g&&Ra(n.highWaterMark)?this.loadProgressively(h,a,t,n.highWaterMark,g):l?h.arrayBuffer():t.responseType==="json"?h.json():h.text()}).then(h=>{var p,f;const g=this.response;if(!g)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),a.loading.end=Math.max(self.performance.now(),a.loading.first);const _=h[o];_&&(a.loaded=a.total=_);const v={url:g.url,data:h,code:g.status},j=(p=this.callbacks)==null?void 0:p.onProgress;j&&!Ra(n.highWaterMark)&&j(a,t,h,g),(f=this.callbacks)==null||f.onSuccess(v,a,t,g)}).catch(h=>{var p;if(self.clearTimeout(this.requestTimeout),a.aborted)return;const f=h&&h.code||0,g=h?h.message:null;(p=this.callbacks)==null||p.onError({code:f,text:g},t,h?h.details:null,a)})}getCacheAge(){let t=null;if(this.response){const n=this.response.headers.get("age");t=n?parseFloat(n):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,n,r,a=0,i){const l=new vkt,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 ucn(s,t){const n={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Yc({},s.headers))};return s.rangeEnd&&n.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),n}function hcn(s){const t=dcn.exec(s);if(t)return parseInt(t[2])-parseInt(t[1])+1}function mcn(s){const t=s.get("Content-Range");if(t){const r=hcn(t);if(Ra(r))return r}const n=s.get("Content-Length");if(n)return parseInt(n)}function pcn(s,t){return new self.Request(s.url,t)}class fcn extends Error{constructor(t,n,r){super(t),this.code=void 0,this.details=void 0,this.code=n,this.details=r}}const xcn=/^age:\s*[\d.]+\s*$/im;class dSt{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 D8e,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&&Ra(i)?i:l,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),t.send()}readystatechange(){const{context:t,loader:n,stats:r}=this;if(!t||!n)return;const a=n.readyState,i=this.config;if(!r.aborted&&a>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),a===4)){self.clearTimeout(this.requestTimeout),n.onreadystatechange=null,n.onprogress=null;const d=n.status,u=n.responseType==="text"?n.responseText:null;if(d>=200&&d<300){const g=u??n.response;if(g!=null){var l,o;r.loading.end=Math.max(self.performance.now(),r.loading.first);const _=n.responseType==="arraybuffer"?g.byteLength:g.length;r.loaded=r.total=_,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const v=(l=this.callbacks)==null?void 0:l.onProgress;v&&v(r,t,g,n);const j={url:n.responseURL,data:g,code:d};(o=this.callbacks)==null||o.onSuccess(j,r,t,n);return}}const h=i.loadPolicy.errorRetry,p=r.retry,f={url:t.url,data:void 0,code:d};if(t0e(h,p,!1,f))this.retry(h);else{var c;Pc.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(t0e(t,n,!0))this.retry(t);else{var r;Pc.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=z8e(t,r.retry),r.retry++,Pc.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&&xcn.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 gcn={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},ycn=Tc(Tc({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:dSt,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Aan,bufferController:bon,capLevelController:J8e,errorController:Dan,fpsController:_ln,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:lkt,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:gcn},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},vcn()),{},{subtitleStreamController:Pln,subtitleTrackController:Nln,timelineController:acn,audioStreamController:xon,audioTrackController:gon,emeController:KL,cmcdController:gln,contentSteeringController:vln,interstitialsController:Iln});function vcn(){return{cueHandler:lcn,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 bcn(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=KTe(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}`,p=t[h];if(p!==void 0&&c){d.push(h);const f=r[o].default;switch(t[o]={default:f},u){case"TimeOut":f.maxLoadTimeMs=p,f.maxTimeToFirstByteMs=p;break;case"MaxRetry":f.errorRetry.maxNumRetry=p,f.timeoutRetry.maxNumRetry=p;break;case"RetryDelay":f.errorRetry.retryDelayMs=p,f.timeoutRetry.retryDelayMs=p;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=p,f.timeoutRetry.maxRetryDelayMs=p;break}}}),d.length&&n.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${id(t[o])}`)}),Tc(Tc({},r),t)}function KTe(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(KTe):Object.keys(s).reduce((t,n)=>(t[n]=KTe(s[n]),t),{}):s}function _cn(s,t){const n=s.loader;n!==uet&&n!==dSt?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):ccn()&&(s.loader=uet,s.progressive=!0,s.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}const xpe=2,wcn=.1,jcn=.05,Ncn=100;class kcn extends nkt{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(wt.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=n,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(wt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(wt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(wt.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(wt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(wt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(wt.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(Ncn),this.mediaSource=n.mediaSource;const r=this.media=n.media;eg(r,"playing",this.onMediaPlaying),eg(r,"waiting",this.onMediaWaiting),eg(r,"ended",this.onMediaEnded)}onMediaDetaching(t,n){this.clearInterval();const{media:r}=this;r&&(zg(r,"playing",this.onMediaPlaying),zg(r,"waiting",this.onMediaWaiting),zg(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(wt.MEDIA_ENDED,{stalled:!1}));return}if(!wo.getBuffered(l).length){this.nudgeRetry=0;return}const h=wo.bufferInfo(l,t,0),p=h.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const L=het(this.hls.inFlightFragments,t),D=h.len>xpe,M=!p||L||p-t>xpe&&!f.getPartialFragment(t);if(D||M)return;this.moved=!1}const g=(a=this.hls)==null?void 0:a.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(h.len>0)&&!p)return;const D=Math.max(p,h.start||0)-t,F=!!(g!=null&&g.live)?g.targetduration*2:xpe,z=KG(t,f);if(D>0&&(D<=F||z)){l.paused||this._trySkipBufferHole(z);return}}const _=i.detectStallWithCurrentTimeMs,v=self.performance.now(),j=this.waiting;let b=this.stalled;if(b===null)if(j>0&&v-j<_)b=this.stalled=j;else{this.stalled=v;return}const S=v-b;if(!o&&(S>=_||j)&&this.hls){var A;if(((A=this.mediaSource)==null?void 0:A.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(t-((g==null?void 0:g.edge)||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(wt.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}const T=wo.bufferInfo(l,t,i.maxBufferHole);this._tryFixBufferStall(T,S,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(wt.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=wo.bufferedInfo(wo.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&n>=i.start){const l=wo.timeRangesToArray(a),o=wo.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 p=KG(t,this.fragmentTracker);p&&"fragment"in p?p=p.fragment:p||(p=void 0);const f=wo.bufferInfo(this.media,t,0);this.hls.trigger(wt.ERROR,{type:mi.MEDIA_ERROR,details:Pn.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:p,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(t,n,r){var a,i;const{fragmentTracker:l,media:o}=this,c=(a=this.hls)==null?void 0:a.config;if(!o||!l||!c)return;const d=(i=this.hls)==null?void 0:i.latestLevelDetails,u=KG(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,Ya.MAIN),l=r.getFragAtPos(a,Ya.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 (${id(t)})`);this.warn(l.message),n.trigger(wt.ERROR,{type:mi.MEDIA_ERROR,details:Pn.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=wo.bufferInfo(a,l,0),c=l0&&o.len<1&&a.readyState<3,p=c-l;if(p>0&&(u||h)){if(p>i.maxBufferHole){let g=!1;if(l===0){const _=r.getAppendedFrag(0,Ya.MAIN);_&&c<_.end&&(g=!0)}if(!g&&t){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||het(this.hls.inFlightFragments,c))return 0;let v=!1,j=t.end;for(;j"u"))return self.VTTCue||self.TextTrackCue}function vke(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,id(a?Tc({type:a},r):r))}return i}const YG=(()=>{const s=YTe();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Ccn{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(wt.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(wt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(wt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(wt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(wt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(wt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(wt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(wt.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(wt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(wt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(wt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(wt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(wt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(wt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(wt.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&&$P(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;nYG&&(h=YG),h-u<=0&&(h=u+Scn);for(let f=0;fu.type===Y0.audioId3&&c:a==="video"?d=u=>u.type===Y0.emsg&&o:d=u=>u.type===Y0.audioId3&&c||u.type===Y0.emsg&&o,GTe(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=YTe();if(r&&a&&!l){const{fragmentStart:_,fragmentEnd:v}=t;let j=this.assetCue;j?(j.startTime=_,j.endTime=v):o&&(j=this.assetCue=vke(o,_,v,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),j&&(j.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(j),j.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 p;if((p=c.cues)!=null&&p.length){const _=Object.keys(h).filter(v=>!u.includes(v));for(let v=_.length;v--;){var f;const j=_[v],b=(f=h[j])==null?void 0:f.cues;delete h[j],b&&Object.keys(b).forEach(S=>{const A=b[S];if(A){A.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(A)}catch{}}})}}else h=this.dateRangeCuesAppended={}}const g=t.fragments[t.fragments.length-1];if(!(u.length===0||!Ra(g==null?void 0:g.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let _=0;_{if(W!==j.id){const Y=d[W];if(Y.class===j.class&&Y.startDate>j.startDate&&(!V||j.startDate.01&&(W.startTime=b,W.endTime=L);else if(o){let Y=j.attr[V];Yan(V)&&(Y=ONt(Y));const J=vke(o,b,L,{key:V,data:Y},Y0.dateRange);J&&(J.id=v,this.id3Track.addCue(J),A[V]=J,l&&(V==="X-ASSET-LIST"||V==="X-ASSET-URL")&&J.addEventListener("enter",this.onEventCueEnter))}}h[v]={cues:A,dateRange:j,durationKnown:T}}}}}class Tcn{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)),p=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,f=Math.min(h,Math.max(1,p));this.changeMediaPlaybackRate(n,f)}else n.playbackRate!==1&&n.playbackRate!==0&&this.changeMediaPlaybackRate(n,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return((t=this.hls)==null?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;const n=this.levelDetails;return n?t.liveMaxLatencyDurationCount*n.targetduration:0}get targetLatency(){const t=this.levelDetails;if(t===null||this.hls===null)return null;const{holdBack:n,partHoldBack:r,targetduration:a}=t,{liveSyncDuration:i,liveSyncDurationCount:l,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let d=o&&r||n;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||d===0)&&(d=i!==void 0?i:l*a);const u=a;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),n=this.targetLatency;if(t===null||n===null)return null;const r=this.levelDetails;if(r===null)return null;const a=r.edge,i=t-n-this.edgeStalled,l=a-r.totalduration,o=a-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(l,i),o)}get drift(){const t=this.levelDetails;return t===null?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(t===null)return 0;const n=(this.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;return Math.max(t.age-n,0)}get forwardBufferLength(){const{media:t}=this,n=this.levelDetails;if(!t||!n)return 0;const r=t.buffered.length;return(r?t.buffered.end(r-1):n.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(wt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(wt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(wt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(wt.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(wt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(wt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(wt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(wt.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===Pn.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 Ecn extends X8e{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(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(wt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(wt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(wt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(wt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(wt.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(wt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(wt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(wt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(wt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(wt.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:p,videoCodec:f}=u;p&&(u.audioCodec=p=Qge(p,r)||void 0),f&&(f=u.videoCodec=uan(f));const{width:g,height:_,unknownCodecs:v}=u,j=(v==null?void 0:v.length)||0;if(o||(o=!!(g&&_)),c||(c=!!f),d||(d=!!p),j||p&&!this.isAudioSupported(p)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:b,"FRAME-RATE":S,"HDCP-LEVEL":A,"PATHWAY-ID":T,RESOLUTION:L,"VIDEO-RANGE":D}=h,F=`${`${T||"."}-`}${u.bitrate}-${L}-${S}-${b}-${D}-${A}`;if(i[F])if(i[F].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const z=l[F]+=1;u.attrs["PATHWAY-ID"]=new Array(z+1).join(".");const V=this.createLevel(u);i[F]=V,a.push(V)}else i[F].addGroupId("audio",h.AUDIO),i[F].addGroupId("text",h.SUBTITLES);else{const z=this.createLevel(u);i[F]=z,l[F]=1,a.push(z)}}),this.filterAndSortMediaOptions(a,n,o,c,d)}createLevel(t){const n=new j$(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=YNt(a,[])}return n}isAudioSupported(t){return _$(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return _$(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,n,r,a,i){var l;let o=[],c=[],d=t;const u=((l=n.stats)==null?void 0:l.parsing)||{};if((r||a)&&i&&(d=d.filter(({videoCodec:b,videoRange:S,width:A,height:T})=>(!!b||!!(A&&T))&&_an(S))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let b="no level with compatible codecs found in manifest",S=b;n.levels.length&&(S=`one or more CODECS in variant not supported: ${id(n.levels.map(T=>T.attrs.CODECS).filter((T,L,D)=>D.indexOf(T)===L))}`,this.warn(S),b+=` (${S})`);const A=new Error(b);this.hls.trigger(wt.ERROR,{type:mi.MEDIA_ERROR,details:Pn.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:n.url,error:A,reason:S})}}),u.end=performance.now();return}n.audioTracks&&(o=n.audioTracks.filter(b=>!b.audioCodec||this.isAudioSupported(b.audioCodec)),pet(o)),n.subtitles&&(c=n.subtitles,pet(c));const h=d.slice(0);d.sort((b,S)=>{if(b.attrs["HDCP-LEVEL"]!==S.attrs["HDCP-LEVEL"])return(b.attrs["HDCP-LEVEL"]||"")>(S.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&b.height!==S.height)return b.height-S.height;if(b.frameRate!==S.frameRate)return b.frameRate-S.frameRate;if(b.videoRange!==S.videoRange)return Xge.indexOf(b.videoRange)-Xge.indexOf(S.videoRange);if(b.videoCodec!==S.videoCodec){const A=rJe(b.videoCodec),T=rJe(S.videoCodec);if(A!==T)return T-A}if(b.uri===S.uri&&b.codecSet!==S.codecSet){const A=Zge(b.codecSet),T=Zge(S.codecSet);if(A!==T)return T-A}return b.averageBitrate!==S.averageBitrate?b.averageBitrate-S.averageBitrate:0});let p=h[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==h.length)){for(let b=0;bA&&A===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=T)}break}const g=i&&!a,_=this.hls.config,v=!!(_.audioStreamController&&_.audioTrackController),j={levels:d,audioTracks:o,subtitleTracks:c,sessionData:n.sessionData,sessionKeys:n.sessionKeys,firstLevel:this._firstLevel,stats:n.stats,audio:i,video:a,altAudio:v&&!g&&o.some(b=>!!b.url)};u.end=performance.now(),this.hls.trigger(wt.MANIFEST_PARSED,j)}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(wt.ERROR,{type:mi.OTHER_ERROR,details:Pn.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(wt.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===ol.LEVEL&&n.context.level===this.level&&this.checkRetry(n)}onFragBuffered(t,{frag:n}){if(n!==void 0&&n.type===Ya.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(wt.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));xkt(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(wt.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(wt.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:n,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function pet(s){const t={};s.forEach(n=>{const r=n.groupId||"";n.id=t[r]=t[r]||0,t[r]++})}function uSt(){return self.SourceBuffer||self.WebKitSourceBuffer}function hSt(){if(!B4())return!1;const t=uSt();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function Acn(){if(!hSt())return!1;const s=B4();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(w$(t,"video")))||["mp4a.40.2","fLaC"].some(t=>s.isTypeSupported(w$(t,"audio"))))}function Mcn(){var s;const t=uSt();return typeof(t==null||(s=t.prototype)==null?void 0:s.changeType)=="function"}const Icn=100;class Pcn extends V8e{constructor(t,n,r){super(t,n,r,"stream-controller",Ya.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||!Ra(i)||(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i)))return;const l=this.getFwdBufferInfoAtPos(a,i,Ya.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(wt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(wt.LEVEL_LOADING,this.onLevelLoading,this),t.on(wt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(wt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(wt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(wt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(wt.BUFFER_CREATED,this.onBufferCreated,this),t.on(wt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(wt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(wt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(wt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(wt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(wt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(wt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(wt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(wt.BUFFER_CREATED,this.onBufferCreated,this),t.off(wt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(wt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(wt.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(Icn),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=dr.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=dr.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case dr.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=dr.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=dr.IDLE;break}break}case dr.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===dr.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 _={};this.altAudio===2&&(_.type="video"),this.hls.trigger(wt.BUFFER_EOS,_),this.state=dr.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===dr.WAITING_LEVEL||this.waitForLive(l)){this.level=i,this.state=dr.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 p=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(p,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&Th(f)&&this.fragmentTracker.getState(f)!==Lm.OK){var g;const v=((g=this.backtrackFragment)!=null?g:f).sn-d.startSN,j=d.fragments[v-1];j&&f.cc===j.cc&&(f=j,this.fragmentTracker.removeFragment(j))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,p)){if(!f.gap){const v=this.audioOnly&&!this.altAudio?td.AUDIO:td.VIDEO,j=(v===td.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;j&&this.afterBufferFlushed(j,v,Ya.MAIN)}f=this.getNextFragmentLoopLoading(f,d,o,Ya.MAIN,h)}f&&(this.exceedsMaxBuffer(o,h,f)||(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,l,p)))}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);a===Lm.NOT_LOADED||a===Lm.PARTIAL?Th(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,Ya.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(wt.AUDIO_TRACK_SWITCHED,n)}),r.trigger(wt.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(wt.AUDIO_TRACK_SWITCHED,n)}}onAudioTrackSwitched(t,n){const r=Jge(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===Ya.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===dr.PARSED&&(this.state=dr.IDLE);return}const o=a?a.stats:r.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Th(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,a)}const l=this.media;l&&(!this._hasEnoughToStart&&wo.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=dr.ERROR;return}switch(n.details){case Pn.FRAG_GAP:case Pn.FRAG_PARSING_ERROR:case Pn.FRAG_DECRYPT_ERROR:case Pn.FRAG_LOAD_ERROR:case Pn.FRAG_LOAD_TIMEOUT:case Pn.KEY_LOAD_ERROR:case Pn.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ya.MAIN,n);break;case Pn.LEVEL_LOAD_ERROR:case Pn.LEVEL_LOAD_TIMEOUT:case Pn.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===dr.WAITING_LEVEL&&((r=n.context)==null?void 0:r.type)===ol.LEVEL&&(this.state=dr.IDLE);break;case Pn.BUFFER_ADD_CODEC_ERROR:case Pn.BUFFER_APPEND_ERROR:if(n.parent!=="main")return;this.reduceLengthAndFlushBuffer(n)&&this.resetLoadingState();break;case Pn.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 Pn.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onFragLoadEmergencyAborted(){this.state=dr.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:n}){if(n!==td.AUDIO||!this.altAudio){const r=(n===td.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,n,Ya.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=dr.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(wt.FRAG_LOADED,r),i.bitrateTest=!1}).catch(r=>{this.state===dr.STOPPED||this.state===dr.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:p,initSegment:f}=a,{details:g}=d,_=this.altAudio?void 0:a.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=dr.PARSING,f){const v=f.tracks;if(v){const A=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(d,v,A,i),r.trigger(wt.FRAG_PARSING_INIT_SEGMENT,{frag:A,id:n,tracks:v})}const j=f.initPTS,b=f.timescale,S=this.initPTS[o.cc];if(Ra(j)&&(!S||S.baseTime!==j||S.timescale!==b)){const A=f.trackId;this.initPTS[o.cc]={baseTime:j,timescale:b,trackId:A},r.trigger(wt.INIT_PTS_FOUND,{frag:o,id:n,initPTS:j,timescale:b,trackId:A})}}if(u&&g){_&&u.type==="audiovideo"&&this.logMuxedErr(o);const v=g.fragments[o.sn-1-g.startSN],j=o.sn===g.startSN,b=!v||o.cc>v.cc;if(a.independent!==!1){const{startPTS:S,endPTS:A,startDTS:T,endDTS:L}=u;if(c)c.elementaryStreams[u.type]={startPTS:S,endPTS:A,startDTS:T,endDTS:L};else if(u.firstKeyFrame&&u.independent&&i.id===1&&!b&&(this.couldBacktrack=!0),u.dropped&&u.independent){const D=this.getMainFwdBufferInfo(),M=(D?D.end:this.getLoadPosition())+this.config.maxBufferHole,F=u.firstKeyFramePTS?u.firstKeyFramePTS:S;if(!j&&Mxpe&&(o.gap=!0);o.setElementaryStreamInfo(u.type,S,A,T,L),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,c,i,j||b)}else if(j||b)o.gap=!0;else{this.backtrack(o);return}}if(_){const{startPTS:v,endPTS:j,startDTS:b,endDTS:S}=_;c&&(c.elementaryStreams[td.AUDIO]={startPTS:v,endPTS:j,startDTS:b,endDTS:S}),o.setElementaryStreamInfo(td.AUDIO,v,j,b,S),this.bufferFragmentData(_,o,c,i)}if(g&&p!=null&&p.samples.length){const v={id:n,frag:o,details:g,samples:p.samples};r.trigger(wt.FRAG_PARSING_METADATA,v)}if(g&&h){const v={id:n,frag:o,details:g,samples:h.samples};r.trigger(wt.FRAG_PARSING_USERDATA,v)}}logMuxedErr(t){this.warn(`${Th(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,n,r,a){if(this.state!==dr.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=cpe(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 p=i.metadata;p&&"channelCount"in p&&(p.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=Ya.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=Ya.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(wt.BUFFER_CODECS,n),!this.hls)return;c.forEach(d=>{const h=n[d].initSegment;h!=null&&h.byteLength&&this.hls.trigger(wt.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,Ya.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=dr.IDLE}checkFragmentChanged(){const t=this.media;let n=null;if(t&&t.readyState>1&&t.seeking===!1){const r=t.currentTime;if(wo.isBuffered(t,r)?n=this.getAppendedFrag(r):wo.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(wt.FRAG_CHANGED,{frag:n}),(!a||a.level!==i)&&this.hls.trigger(wt.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 Ra(n)?this.getAppendedFrag(n):null}get currentProgramDateTime(){var t;const n=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(Ra(n)){const r=this.getLevelDetails(),a=this.currentFrag||(r?zM(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 Lcn extends r1{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=Pn.KEY_LOAD_ERROR,r,a,i){return new N2({type:mi.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=upe(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const a=M7(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,Pn.KEY_LOAD_ERROR,d))}const l=i.uri;if(!l)return Promise.reject(this.createKeyLoadError(t,Pn.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${l}"`)));const o=bke(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: "+nf(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,Pn.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=Jrn(n.initSegment.data);if(l.length){let o=l[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${nf(o)}`),j4.setKeyIdForUri(t.decryptdata.uri,o)):(o=j4.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${nf(o)}`)),t.decryptdata.keyId=o}}if(!t.decryptdata.keyId&&!Th(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:(p,f,g,_)=>{const{frag:v,keyInfo:j}=g,b=bke(j.decryptdata);if(!v.decryptdata||j!==this.keyIdToKeyInfo[b])return o(this.createKeyLoadError(v,Pn.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),_));j.decryptdata.key=v.decryptdata.key=new Uint8Array(p.data),v.keyLoader=null,j.loader=null,l({frag:v,keyInfo:j})},onError:(p,f,g,_)=>{this.resetLoader(f),o(this.createKeyLoadError(n,Pn.KEY_LOAD_ERROR,new Error(`HTTP Error ${p.code} loading key ${p.text}`),g,Tc({url:c.url,data:void 0},p)))},onTimeout:(p,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(n,Pn.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(p,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(n,Pn.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};i.load(c,u,h)})}resetLoader(t){const{frag:n,keyInfo:r,url:a}=t,i=r.loader;n.keyLoader===i&&(n.keyLoader=null,r.loader=null);const l=bke(r.decryptdata)||a;delete this.keyIdToKeyInfo[l],i&&i.destroy()}}function bke(s){if(s.keyFormat!==of.FAIRPLAY){const t=s.keyId;if(t)return nf(t)}return s.uri}function fet(s){const{type:t}=s;switch(t){case ol.AUDIO_TRACK:return Ya.AUDIO;case ol.SUBTITLE_TRACK:return Ya.SUBTITLE;default:return Ya.MAIN}}function _ke(s,t){let n=s.url;return(n===void 0||n.indexOf("data:")===0)&&(n=t.url),n}class Dcn{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(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(wt.LEVEL_LOADING,this.onLevelLoading,this),t.on(wt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(wt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(wt.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(wt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(wt.LEVEL_LOADING,this.onLevelLoading,this),t.off(wt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(wt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(wt.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:ol.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:ol.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:ol.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:ol.SUBTITLE_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onLevelsUpdated(t,n){const r=this.loaders[ol.LEVEL];if(r){const a=r.context;a&&!n.levels.some(i=>i===a.levelOrTrack)&&(r.abort(),delete this.loaders[ol.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===ol.MANIFEST?i=r.manifestLoadPolicy.default:i=Yc({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(t),Ra((n=t.deliveryDirectives)==null?void 0:n.part)){let d;if(t.type===ol.LEVEL&&t.level!==null?d=this.hls.levels[t.level].details:t.type===ol.AUDIO_TRACK&&t.id!==null?d=this.hls.audioTracks[t.id].details:t.type===ol.SUBTITLE_TRACK&&t.id!==null&&(d=this.hls.subtitleTracks[t.id].details),d){const u=d.partTarget,h=d.targetduration;if(u&&h){const p=Math.max(u*3,h*.8)*1e3;i=Yc({},i,{maxTimeToFirstByteMs:Math.min(p,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(p,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,p)=>{const f=this.getInternalLoader(h);this.resetInternalLoader(h.type);const g=d.data;u.parsing.start=performance.now(),dw.isMediaPlaylist(g)||h.type!==ol.MANIFEST?this.handleTrackOrLevelPlaylist(d,u,h,p||null,f):this.handleMasterPlaylist(d,u,h,p)},onError:(d,u,h,p)=>{this.handleNetworkError(u,h,!1,d,p)},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=_ke(t,r),c=dw.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:p,startTimeOffset:f,variableList:g}=c;this.variableList=g,u.forEach(b=>{const{unknownCodecs:S}=b;if(S){const{preferManagedMediaSource:A}=this.hls.config;let{audioCodec:T,videoCodec:L}=b;for(let D=S.length;D--;){const M=S[D];_$(M,"audio",A)?(b.audioCodec=T=T?`${T},${M}`:M,vD.audio[T.substring(0,4)]=2,S.splice(D,1)):_$(M,"video",A)&&(b.videoCodec=L=L?`${L},${M}`:M,vD.video[L.substring(0,4)]=2,S.splice(D,1))}}});const{AUDIO:_=[],SUBTITLES:v,"CLOSED-CAPTIONS":j}=dw.parseMasterPlaylistMedia(l,o,c);_.length&&!_.some(S=>!S.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"),_.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ju({}),bitrate:0,url:""})),i.trigger(wt.MANIFEST_LOADED,{levels:u,audioTracks:_,subtitles:v,captions:j,contentSteering:d,url:o,stats:n,networkDetails:a,sessionData:h,sessionKeys:p,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(t,n,r,a,i){const l=this.hls,{id:o,level:c,type:d}=r,u=_ke(t,r),h=Ra(c)?c:Ra(o)?o:0,p=fet(r),f=dw.parseLevelPlaylist(t.data,u,h,p,0,this.variableList);if(d===ol.MANIFEST){const g={attrs:new ju({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=n.loading.start+mkt(f,0),l.trigger(wt.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:u,stats:n,networkDetails:a,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}n.parsing.end=performance.now(),r.levelDetails=f,this.handlePlaylistLoaded(f,t,n,r,a,i)}handleManifestParsingError(t,n,r,a,i){this.hls.trigger(wt.ERROR,{type:mi.NETWORK_ERROR,details:Pn.MANIFEST_PARSING_ERROR,fatal:n.type===ol.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===ol.LEVEL?l+=`: ${t.level} id: ${t.id}`:(t.type===ol.AUDIO_TRACK||t.type===ol.SUBTITLE_TRACK)&&(l+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let c=Pn.UNKNOWN,d=!1;const u=this.getInternalLoader(t);switch(t.type){case ol.MANIFEST:c=r?Pn.MANIFEST_LOAD_TIMEOUT:Pn.MANIFEST_LOAD_ERROR,d=!0;break;case ol.LEVEL:c=r?Pn.LEVEL_LOAD_TIMEOUT:Pn.LEVEL_LOAD_ERROR,d=!1;break;case ol.AUDIO_TRACK:c=r?Pn.AUDIO_TRACK_LOAD_TIMEOUT:Pn.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case ol.SUBTITLE_TRACK:c=r?Pn.SUBTITLE_TRACK_LOAD_TIMEOUT:Pn.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(t.type);const h={type:mi.NETWORK_ERROR,details:c,fatal:d,url:t.url,loader:u,context:t,error:o,networkDetails:n,stats:i};if(a){const p=(n==null?void 0:n.url)||t.url;h.response=Tc({url:p,data:void 0},a)}this.hls.trigger(wt.ERROR,h)}handlePlaylistLoaded(t,n,r,a,i,l){const o=this.hls,{type:c,level:d,levelOrTrack:u,id:h,groupId:p,deliveryDirectives:f}=a,g=_ke(n,a),_=fet(a);let v=typeof a.level=="number"&&_===Ya.MAIN?d:void 0;const j=t.playlistParsingError;if(j){if(this.hls.logger.warn(`${j} ${t.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(wt.ERROR,{type:mi.NETWORK_ERROR,details:Pn.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:j,reason:j.message,response:n,context:a,level:v,parent:_,networkDetails:i,stats:r});return}t.playlistParsingError=null}if(!t.fragments.length){const b=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(wt.ERROR,{type:mi.NETWORK_ERROR,details:Pn.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:b,reason:b.message,response:n,context:a,level:v,parent:_,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 ol.MANIFEST:case ol.LEVEL:if(v){if(!u)v=0;else if(u!==o.levels[v]){const b=o.levels.indexOf(u);b>-1&&(v=b)}}o.trigger(wt.LEVEL_LOADED,{details:t,levelInfo:u||o.levels[0],level:v||0,id:h||0,stats:r,networkDetails:i,deliveryDirectives:f,withoutMultiVariant:c===ol.MANIFEST});break;case ol.AUDIO_TRACK:o.trigger(wt.AUDIO_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:p||"",stats:r,networkDetails:i,deliveryDirectives:f});break;case ol.SUBTITLE_TRACK:o.trigger(wt.SUBTITLE_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:p||"",stats:r,networkDetails:i,deliveryDirectives:f});break}}}class sw{static get version(){return N$}static isMSESupported(){return hSt()}static isSupported(){return Acn()}static getMediaSource(){return B4()}static get Events(){return wt}static get MetadataSchema(){return Y0}static get ErrorTypes(){return mi}static get ErrorDetails(){return Pn}static get DefaultConfig(){return sw.defaultConfig?sw.defaultConfig:ycn}static set DefaultConfig(t){sw.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 H8e,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=$rn(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=bcn(sw.DefaultConfig,t,n);this.userConfig=t,r.progressive&&_cn(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 Ran(this),p=r.interstitialsController,f=p?this.interstitialsController=new p(this,sw):null,g=this.bufferController=new i(this,h),_=this.capLevelController=new l(this),v=new c(this),j=new Dcn(this),b=r.contentSteeringController,S=b?new b(this):null,A=this.levelController=new Ecn(this,S),T=new Ccn(this),L=new Lcn(this.config,this.logger),D=this.streamController=new Pcn(this,h,L),M=this.gapController=new kcn(this,h);_.setStreamController(D),v.setStreamController(D);const F=[j,A,D];f&&F.splice(1,0,f),S&&F.splice(1,0,S),this.networkControllers=F;const z=[u,g,M,_,v,T,h];this.audioTrackController=this.createController(r.audioTrackController,F);const V=r.audioStreamController;V&&F.push(this.audioStreamController=new V(this,h,L)),this.subtitleTrackController=this.createController(r.subtitleTrackController,F);const W=r.subtitleStreamController;W&&F.push(this.subtititleStreamController=new W(this,h,L)),this.createController(r.timelineController,z),L.emeController=this.emeController=this.createController(r.emeController,z),this.cmcdController=this.createController(r.cmcdController,z),this.latencyController=this.createController(Tcn,z),this.coreComponents=z,F.push(d);const Y=d.onErrorOut;typeof Y=="function"&&this.on(wt.ERROR,Y,d),this.on(wt.MANIFEST_LOADED,j.onManifestLoaded,j)}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===wt.ERROR;this.trigger(wt.ERROR,{type:mi.OTHER_ERROR,details:Pn.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(wt.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(wt.ERROR,{type:mi.OTHER_ERROR,details:Pn.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(wt.MEDIA_ATTACHING,a)}detachMedia(){this.logger.log("detachMedia"),this.trigger(wt.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(wt.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const n=this.media,r=this._url,a=this._url=L8e.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(wt.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={[Ya.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[Ya.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[Ya.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=kln()),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){ban(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=XNt(n);return ZNt(t,r,navigator.mediaCapabilities)}}sw.defaultConfig=void 0;const Rcn=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function UP(s){return!!s&&Rcn.test(s)&&!/\.mp4($|\?)/i.test(s)}function Ocn(s){const t=s.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return t?{libraryId:t[1],videoId:t[2]}:null}function Fcn(s,t){if(!s)return null;const n=Ocn(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 zcn(s){const t=s.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return t?t[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const ZTe=N.forwardRef(function({sourceUrl:t,thumbnailUrl:n,autoPlay:r,muted:a,loop:i,playsInline:l=!0,...o},c){const d=N.useRef(null),[u,h]=N.useState(null),p=N.useMemo(()=>Fcn(t,{autoplay:!!r,muted:!!a,loop:!!i}),[t,r,a,i]);N.useEffect(()=>{let g=!1;if(!t){h(null);return}if(!UP(t)){h(t);return}if(!p){h(null);return}return h(null),fetch(p).then(async _=>{if(!_.ok)throw new Error(`Failed to load Bunny embed (${_.status})`);const v=await _.text();return zcn(v)}).then(_=>{g||h(_)}).catch(()=>{g||h(null)}),()=>{g=!0}},[p,t]),N.useEffect(()=>{const g=d.current;if(!g||!u)return;let _=null;const v=()=>{if(!r)return;const b=g.play();b&&b.catch(()=>{})};if(g.muted=!!a,g.loop=!!i,u.endsWith(".m3u8")){if(g.canPlayType("application/vnd.apple.mpegurl")){g.src=u;const b=()=>v();return g.addEventListener("loadedmetadata",b),()=>{g.removeEventListener("loadedmetadata",b),g.removeAttribute("src"),g.load()}}return sw.isSupported()?(_=new sw({enableWorker:!0,lowLatencyMode:!0}),_.loadSource(u),_.attachMedia(g),_.on(sw.Events.MANIFEST_PARSED,v),()=>{_==null||_.destroy(),g.removeAttribute("src"),g.load()}):void 0}g.src=u;const j=()=>v();return g.addEventListener("loadedmetadata",j),()=>{g.removeEventListener("loadedmetadata",j),g.removeAttribute("src"),g.load()}},[r,i,a,u]),N.useEffect(()=>{const g=d.current;if(g){if(g.muted=!!a,g.loop=!!i,r&&u){const _=g.play();_&&_.catch(()=>{});return}g.pause()}},[r,i,a,u]);const f=g=>{if(d.current=g,typeof c=="function"){c(g);return}c&&(c.current=g)};return e.jsx("video",{ref:f,poster:n||void 0,autoPlay:r,muted:a,loop:i,playsInline:l,preload:"metadata",...o})}),Bcn={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 $cn(){try{let s=localStorage.getItem("vg_visitor_token");return s||(s=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",s)),s}catch{return null}}function xet(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 rDe({config:s,appSlug:t="video_greeter",preview:n=!1,embedded:r=!1}){const[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!0),[u,h]=N.useState(!1),[p,f]=N.useState("portrait"),[g,_]=N.useState(!1),[v,j]=N.useState(!1),[b,S]=N.useState({name:"",email:"",phone:""}),[A,T]=N.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),L=N.useRef(null),D=N.useRef(null),M=N.useRef(!1),F=async(je,Ge)=>{if(!n)try{await q.from("widget_events").insert({user_id:s.user_id,app_slug:t,event_type:je,visitor_token:$cn(),page_url:typeof window<"u"?window.location.href:null,metadata:Ge||{}})}catch{}};N.useEffect(()=>{if(u)return;const je=typeof window<"u"?window.location.pathname:"/",Ge=s.targeting||{mode:"all"};if(Ge.mode==="include"&&!xet(Ge.include,je)||Ge.mode==="exclude"&&xet(Ge.exclude,je))return;const Be=s.trigger||{type:"immediate"};if(Be.type==="immediate"||n){i(!0);return}if(Be.type==="delay"){const Ye=(Be.value||3)*1e3,We=setTimeout(()=>i(!0),Ye);return()=>clearTimeout(We)}if(Be.type==="scroll"){const Ye=(Be.value||25)/100,We=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=Ye&&(i(!0),window.removeEventListener("scroll",We))};return window.addEventListener("scroll",We,{passive:!0}),()=>window.removeEventListener("scroll",We)}if(Be.type==="exit_intent"){const Ye=We=>{We.clientY<=0&&i(!0)};return document.addEventListener("mouseleave",Ye),()=>document.removeEventListener("mouseleave",Ye)}},[u,s.targeting,s.trigger,n]),N.useEffect(()=>{a&&!M.current&&(M.current=!0,F("impression"))},[a]),N.useEffect(()=>{if(l&&D.current&&!UP(s.video_url)){D.current.currentTime=0,D.current.muted=!1,d(!1);const je=D.current.play();je&&je.catch(()=>{})}else l&&UP(s.video_url)&&d(!1)},[l,s.video_url]),N.useEffect(()=>{if(!s.thumbnail_url)return;let je=!1;const Ge=new Image;return Ge.onload=()=>{je||f(Ge.naturalWidth>Ge.naturalHeight?"landscape":"portrait")},Ge.src=s.thumbnail_url,()=>{je=!0}},[s.thumbnail_url]),N.useEffect(()=>{const je=()=>{T({width:window.innerWidth,height:window.innerHeight})};return je(),window.addEventListener("resize",je),()=>window.removeEventListener("resize",je)},[]);const z=()=>{o(!0),F("expand")},V=je=>{je.stopPropagation(),h(!0),o(!1)},W=je=>{F("cta_click",{cta_id:je.id,label:je.label,url:je.url})},Y=async je=>{if(je.preventDefault(),n){_(!0);return}if(!(!b.email||!b.name)){j(!0);try{const{error:Ge}=await q.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:t,name:b.name,email:b.email,phone:b.phone||void 0,page_url:window.location.href}});if(Ge)throw Ge;F("lead_capture",{email:b.email}),_(!0)}catch(Ge){console.error("lead submit failed",Ge)}finally{j(!1)}}};if(!a||u||!s.video_url&&!s.video_embed_url)return null;const K=Bcn[p][s.size||"md"],J=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",ne=s.shape==="circle"?"rounded-full":"rounded-2xl",ie=n?p==="landscape"?"w-[280px]":"w-[220px]":p==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",he=p==="landscape"?"aspect-video":"aspect-[9/16]",ce=s.agent||{},pe=s.lead_form_fields||["name","email","phone"],le=!!(s.show_socials&&(ce.instagram_url||ce.facebook_url||ce.linkedin_url)),ve=108+(s.ctas||[]).length*48+(s.lead_form_enabled&&!g?72+pe.length*42:0)+(g?40:0)+(le?34:0),ge=Math.max(300,A.height-32),Te=Math.max(220,A.width-32),Me=Math.max(150,ge-ve),Ce=Math.floor(p==="landscape"?Me*(16/9):Me*(9/16)),Ae=p==="landscape"?Math.max(220,Math.min(420,Te,Ce)):Math.max(180,Math.min(340,Te,Ce)),De=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":`${ie} 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`,Ie=r?{width:`${Ae}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,Fe=r?"p-3 space-y-2.5":"p-4 space-y-3",qe=r?"w-9 h-9 rounded-full object-cover":"w-10 h-10 rounded-full object-cover",be=r?"font-bold text-[15px] text-gray-900 leading-tight":"font-bold text-gray-900 leading-tight",Ze=r?"text-[11px] text-gray-500 mt-0.5":"text-xs text-gray-500 mt-0.5",Ne=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",it=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:`${J} z-[70]`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:l?e.jsxs("div",{className:De,style:Ie,children:[e.jsxs("div",{className:`relative bg-black ${he}`,children:[UP(s.video_url)?e.jsx(ZTe,{ref:D,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:c,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:je=>{const{videoWidth:Ge,videoHeight:Be}=je.currentTarget;Ge&&Be&&f(Ge>Be?"landscape":"portrait")},onEnded:()=>F("watch_complete")},`expanded-${s.video_url}-${s.thumbnail_url||"no-thumb"}-${l?"on":"off"}`):e.jsx("video",{ref:D,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:()=>F("watch_complete"),onLoadedMetadata:je=>{const{videoWidth:Ge,videoHeight:Be}=je.currentTarget;Ge&&Be&&f(Ge>Be?"landscape":"portrait")}}),e.jsx("button",{onClick:()=>{D.current&&(D.current.muted=!D.current.muted,d(D.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(B9,{className:"w-4 h-4"}):e.jsx(z9,{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(Bn,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:Fe,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[ce.avatar_url&&e.jsx("img",{src:ce.avatar_url,alt:ce.name||"",className:qe}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:be,children:s.greeting_title||"Glad you're here!"}),s.greeting_subtitle&&e.jsx("p",{className:Ze,children:s.greeting_subtitle})]})]}),(s.ctas||[]).length>0&&e.jsx("div",{className:"space-y-2",children:(s.ctas||[]).map(je=>{var Ge;return e.jsxs("a",{href:je.url,target:(Ge=je.url)!=null&&Ge.startsWith("http")?"_blank":void 0,rel:"noopener noreferrer",onClick:()=>W(je),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 ${je.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:je.label}),e.jsx(tr,{className:"w-3.5 h-3.5 opacity-60"})]},je.id)})}),s.lead_form_enabled&&!g&&e.jsxs("form",{onSubmit:Y,className:"space-y-2 pt-1",children:[pe.includes("name")&&e.jsx("input",{type:"text",placeholder:"Name",required:!0,value:b.name,onChange:je=>S({...b,name:je.target.value}),className:Ne}),pe.includes("email")&&e.jsx("input",{type:"email",placeholder:"Email",required:!0,value:b.email,onChange:je=>S({...b,email:je.target.value}),className:Ne}),pe.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:b.phone,onChange:je=>S({...b,phone:je.target.value}),className:Ne}),e.jsxs("button",{type:"submit",disabled:v,className:it,children:[e.jsx(cr,{className:"w-3.5 h-3.5"}),v?"Sending...":"Send"]})]}),g&&e.jsx("p",{className:"text-sm text-emerald-600 font-medium text-center py-2",children:"Thanks! I'll be in touch shortly."}),s.show_socials&&(ce.instagram_url||ce.facebook_url||ce.linkedin_url)&&e.jsxs("div",{className:"flex items-center justify-center gap-3 pt-2 border-t border-gray-100",children:[ce.instagram_url&&e.jsx("a",{href:ce.instagram_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>F("cta_click",{social:"instagram"}),children:e.jsx(du,{className:"w-4 h-4"})}),ce.facebook_url&&e.jsx("a",{href:ce.facebook_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>F("cta_click",{social:"facebook"}),children:e.jsx(Lh,{className:"w-4 h-4"})}),ce.linkedin_url&&e.jsx("a",{href:ce.linkedin_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>F("cta_click",{social:"linkedin"}),children:e.jsx(vf,{className:"w-4 h-4"})})]})]})]}):e.jsxs("div",{className:"relative animate-in fade-in slide-in-from-bottom-4 duration-500",children:[e.jsxs("button",{onClick:z,className:`relative ${ne} overflow-hidden shadow-2xl ring-2 ring-white/40 hover:ring-white/80 hover:scale-105 transition-all bg-black`,style:{width:K.w,height:K.h},"aria-label":"Play video greeting",children:[UP(s.video_url)?e.jsx(ZTe,{ref:L,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:je=>{const{videoWidth:Ge,videoHeight:Be}=je.currentTarget;Ge&&Be&&f(Ge>Be?"landscape":"portrait")}},`collapsed-${s.video_url}-${s.thumbnail_url||"no-thumb"}`):e.jsx("video",{ref:L,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:je=>{const{videoWidth:Ge,videoHeight:Be}=je.currentTarget;Ge&&Be&&f(Ge>Be?"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:V,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(Bn,{className:"w-3.5 h-3.5"})})]})})}function aDe({slug:s}){const[t,n]=N.useState(null);return N.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await q.rpc("get_public_video_greeter_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(rDe,{config:t}):null}const mSt="eip_last_shown",get="eip_visitor_token";function Ucn(){try{let s=localStorage.getItem(get);return s||(s=crypto.randomUUID(),localStorage.setItem(get,s)),s}catch{return}}function qcn(s){try{const t=Number(localStorage.getItem(mSt)||0);return t?Date.now()-t>s*24*60*60*1e3:!0}catch{return!0}}function Vcn(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 pSt({config:s,preview:t=!1,forceOpen:n=!1}){const[r,a]=N.useState(n),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState({name:"",email:"",phone:""}),h=N.useRef(!1),p=N.useRef(!1),f=async(L,D={})=>{if(!t)try{await q.from("widget_events").insert({user_id:s.user_id,app_slug:"exit_intent",event_type:L,visitor_token:Ucn(),page_url:window.location.href,metadata:D})}catch{}};N.useEffect(()=>{if(t||!Vcn(s.targeting)||!qcn(s.frequency_days))return;const L=/Mobi|Android/i.test(navigator.userAgent),D={low:5,medium:15,high:30}[s.trigger_sensitivity]||15,M=W=>{if(!h.current){h.current=!0,a(!0);try{localStorage.setItem(mSt,String(Date.now()))}catch{}f("impression",{reason:W})}},F=W=>{W.clientY<=D&&M("mouse_leave")},z=()=>{s.enable_mobile_back&&L&&M("back_button")};if(s.enable_mobile_back&&L){try{window.history.pushState({eip:!0},"")}catch{}window.addEventListener("popstate",z)}else document.addEventListener("mouseleave",F);let V;return s.enable_time_fallback&&(V=window.setTimeout(()=>M("time_fallback"),Math.max(5,s.time_fallback_seconds)*1e3)),()=>{document.removeEventListener("mouseleave",F),window.removeEventListener("popstate",z),V&&window.clearTimeout(V)}},[s,t]),N.useEffect(()=>{r&&!p.current&&!t&&!h.current&&(p.current=!0)},[r,t]);const g=()=>{a(!1),t||f("close")},_=async L=>{if(L.preventDefault(),t){l(!0);return}if(!(!d.email||!d.name)){c(!0);try{const{error:D}=await q.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"exit_intent",name:d.name,email:d.email,phone:d.phone||void 0,page_url:window.location.href}});if(D)throw D;f("lead_capture",{email:d.email}),l(!0),s.cta_url&&setTimeout(()=>{window.location.href=s.cta_url},1200)}catch(D){console.error("exit intent submit failed",D)}finally{c(!1)}}};if(!r)return null;const v=s.form_fields||["name","email"],j=s.agent||{},b=[j.first_name,j.last_name].filter(Boolean).join(" "),S=s.use_agent_photo&&j.avatar_url||s.image_url,A=s.theme_color||"#f97316",T=t?"absolute inset-0 flex items-center justify-center p-4 z-10":"fixed inset-0 z-[80] flex items-center justify-center p-4";return e.jsx("div",{className:T,style:{background:t?"transparent":"rgba(0,0,0,0.6)"},children:e.jsxs("div",{className:"relative w-full max-w-md bg-background rounded-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-300",onClick:L=>L.stopPropagation(),children:[e.jsx("div",{className:"h-2 w-full",style:{background:`linear-gradient(90deg, ${A}, ${wke(A,-25)})`}}),e.jsx("button",{onClick:g,className:"absolute top-3 right-3 z-10 w-8 h-8 rounded-full bg-background/80 backdrop-blur hover:bg-background flex items-center justify-center text-muted-foreground hover:text-foreground transition","aria-label":"Close",children:e.jsx(Bn,{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:[S&&e.jsx("img",{src:S,alt:b||"Agent",className:"w-14 h-14 rounded-full object-cover ring-2 shadow-md",style:{boxShadow:`0 0 0 2px ${A}33`,"--tw-ring-color":A}}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold",style:{background:`${A}1A`,color:A},children:[e.jsx(un,{className:"w-3 h-3"}),s.offer_label]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:s.headline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.subheadline})]}),i?e.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${A}10`,color:A},children:[e.jsx("div",{className:"text-3xl",children:"🎉"}),e.jsx("p",{className:"text-sm font-medium",style:{color:A},children:s.success_message})]}):s.form_enabled?e.jsxs("form",{onSubmit:_,className:"space-y-2.5",children:[v.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:d.name,onChange:L=>u({...d,name:L.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":A},required:!0}),v.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:d.email,onChange:L=>u({...d,email:L.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":A},required:!0}),v.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:d.phone,onChange:L=>u({...d,phone:L.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":A}}),e.jsx("button",{type:"submit",disabled:o,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60",style:{background:`linear-gradient(135deg, ${A}, ${wke(A,-20)})`},children:o?"Sending...":s.cta_label}),e.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We respect your inbox. Unsubscribe anytime."})]}):e.jsx("a",{href:s.cta_url||"#",onClick:()=>f("cta_click",{url:s.cta_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 transition",style:{background:`linear-gradient(135deg, ${A}, ${wke(A,-20)})`},children:s.cta_label}),b&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground pt-1",children:["Sent personally by ",b]})]})]})})}function wke(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 iDe({slug:s}){const[t,n]=N.useState(null);return N.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await q.rpc("get_public_exit_intent_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(pSt,{config:t}):null}const yet="lm_dismissed",vet="lm_visitor_token";function Hcn(){try{let s=localStorage.getItem(vet);return s||(s=crypto.randomUUID(),localStorage.setItem(vet,s)),s}catch{return}}function Gcn(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 oDe({config:s,preview:t=!1}){const[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState({name:"",email:"",phone:""}),p=N.useRef(!1),f=async(S,A={})=>{if(!t)try{await q.from("widget_events").insert({user_id:s.user_id,app_slug:"lead_magnet",event_type:S,visitor_token:Hcn(),page_url:window.location.href,metadata:A})}catch{}};N.useEffect(()=>{if(t){r(!0);return}if(!Gcn(s.targeting))return;try{if(sessionStorage.getItem(yet))return}catch{}const S=()=>{p.current||(p.current=!0,r(!0),f("impression"))};if(s.trigger_type==="immediate")S();else if(s.trigger_type==="delay"){const A=window.setTimeout(S,Math.max(0,s.trigger_value)*1e3);return()=>window.clearTimeout(A)}else if(s.trigger_type==="scroll"){const A=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight*100>=(s.trigger_value||30)&&S()};return window.addEventListener("scroll",A,{passive:!0}),()=>window.removeEventListener("scroll",A)}},[s,t]);const g=()=>{r(!1);try{sessionStorage.setItem(yet,"1")}catch{}t||f("close")},_=async S=>{if(S.preventDefault(),t){o(!0);return}if(!(!u.email||!u.name)){d(!0);try{const{error:A}=await q.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"lead_magnet",name:u.name,email:u.email,phone:u.phone||void 0,page_url:window.location.href}});if(A)throw A;f("lead_capture",{email:u.email}),o(!0),(s.delivery_method==="instant"||s.delivery_method==="both")&&s.download_url&&setTimeout(()=>{const T=document.createElement("a");T.href=s.download_url,T.target="_blank",T.rel="noopener",T.download="",document.body.appendChild(T),T.click(),T.remove()},600)}catch(A){console.error("lead magnet submit failed",A)}finally{d(!1)}}};if(!n)return null;const v=s.theme_color||"#2563eb",j=t?s.position==="bottom-left"?"absolute left-4 bottom-4":"absolute right-4 bottom-4":s.position==="bottom-left"?"fixed left-4 bottom-4 md:left-6 md:bottom-6":"fixed right-4 bottom-4 md:right-6 md:bottom-6";if(s.display_style==="bar")return e.jsxs("div",{className:t?"absolute left-0 right-0 bottom-0 z-10":"fixed left-0 right-0 bottom-0 z-[75]",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:[e.jsx("div",{className:"text-white shadow-2xl",style:{background:`linear-gradient(90deg, ${v}, ${qF(v,-20)})`},children:e.jsxs("div",{className:"max-w-6xl mx-auto px-4 py-3 flex items-center gap-3 flex-wrap",children:[e.jsx(Oi,{className:"w-5 h-5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold truncate",children:s.title}),e.jsx("p",{className:"text-xs text-white/80 truncate",children:s.description})]}),e.jsx("button",{onClick:()=>{i(!0),f("expand")},className:"px-4 py-2 rounded-lg text-sm font-semibold bg-white shrink-0 hover:bg-white/95 transition",style:{color:v},children:s.download_label}),e.jsx("button",{onClick:g,className:"text-white/80 hover:text-white","aria-label":"Close",children:e.jsx(Bn,{className:"w-4 h-4"})})]})}),a&&b()]});if(!a)return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>{i(!0),f("expand")},className:`${j} z-[75] group flex items-center gap-3 pl-3 pr-4 py-3 rounded-2xl shadow-2xl hover:shadow-3xl transition-all hover:scale-[1.03] animate-in fade-in slide-in-from-bottom-4 duration-500`,style:{background:`linear-gradient(135deg, ${v}, ${qF(v,-20)})`,paddingBottom:"env(safe-area-inset-bottom)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 backdrop-blur flex items-center justify-center text-white",children:e.jsx(Ou,{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:S=>{S.stopPropagation(),g()},className:"ml-1 w-6 h-6 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center text-white","aria-label":"Close",children:e.jsx(Bn,{className:"w-3 h-3"})})]}),a&&b()]});return b();function b(){const S=s.form_fields||["name","email"],A=s.agent||{},T=[A.first_name,A.last_name].filter(Boolean).join(" ");return e.jsx("div",{className:t?"absolute inset-0 flex items-center justify-center p-4 z-20":"fixed inset-0 z-[85] flex items-center justify-center p-4",style:{background:t?"transparent":"rgba(0,0,0,0.6)"},onClick:()=>i(!1),children:e.jsxs("div",{className:"relative w-full max-w-lg bg-background rounded-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-300",onClick:L=>L.stopPropagation(),children:[e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",style:{background:`linear-gradient(135deg, ${v}, ${qF(v,-25)})`},children:[s.cover_image_url?e.jsx("img",{src:s.cover_image_url,alt:s.title,className:"w-full h-full object-cover opacity-90"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Nr,{className:"w-20 h-20 text-white/40"})}),e.jsxs("div",{className:"absolute top-3 left-3 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-white shadow",style:{color:v},children:[e.jsx(Oi,{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(Bn,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:s.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.description})]}),l?e.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${v}10`},children:[e.jsx(Pa,{className:"w-8 h-8 mx-auto",style:{color:v}}),e.jsx("p",{className:"text-sm font-medium",style:{color:v},children:s.success_message}),s.download_url&&e.jsx("a",{href:s.download_url,target:"_blank",rel:"noopener",className:"inline-block mt-2 text-xs underline",style:{color:v},children:"Click here if download didn't start"})]}):s.form_enabled?e.jsxs("form",{onSubmit:_,className:"space-y-2.5",children:[S.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:u.name,onChange:L=>h({...u,name:L.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":v},required:!0}),S.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:u.email,onChange:L=>h({...u,email:L.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":v},required:!0}),S.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:u.phone,onChange:L=>h({...u,phone:L.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":v}}),e.jsxs("button",{type:"submit",disabled:c,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60 inline-flex items-center justify-center gap-2",style:{background:`linear-gradient(135deg, ${v}, ${qF(v,-20)})`},children:[e.jsx(Pa,{className:"w-4 h-4"}),c?"Sending...":s.download_label]}),e.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We'll email you a copy too. No spam — promise."})]}):e.jsx("a",{href:s.download_url||"#",target:"_blank",rel:"noopener",onClick:()=>f("cta_click",{url:s.download_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg",style:{background:`linear-gradient(135deg, ${v}, ${qF(v,-20)})`},children:s.download_label}),T&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",T]})]})]})})}}function qF(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 lDe({slug:s}){const[t,n]=N.useState(null);return N.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await q.rpc("get_public_lead_magnet_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(oDe,{config:t}):null}function Wcn({children:s,siteConfig:t}){var ge,Te,Me,Ce,Ae,De,Ie,Fe,qe;const n=Jl(),r=Mn(),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState([]),[p,f]=N.useState([]),[g,_]=N.useState(null),v=N.useRef(null),j=N.useRef(null),{user:b,profile:S,signOut:A}=lbe();I8e(t,b==null?void 0:b.id),P8e(t,b==null?void 0:b.id);const T=((ge=t.agent)==null?void 0:ge.full_name)||"Agent",L=t.siteTitle||`${T} Real Estate`,D=n.pathname==="/search",M=n.pathname==="/",F=t.leadRegistrationMode!=="disabled";N.useEffect(()=>{(async()=>{const{data:Ze}=await q.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});h(Ze||[])})()},[t.id]),N.useEffect(()=>{(async()=>{const{data:Ze}=await q.from("lead_site_menu_items").select("*").eq("site_id",t.id).eq("is_visible",!0).order("sort_order",{ascending:!0});f(Ze||[])})()},[t.id]),N.useEffect(()=>{const be=Ze=>{v.current&&!v.current.contains(Ze.target)&&d(!1),j.current&&!j.current.contains(Ze.target)&&_(null)};return document.addEventListener("mousedown",be),()=>document.removeEventListener("mousedown",be)},[]);const z=DNt(t),V=t==null?void 0:t.bookingUrl,W=z?p.filter(be=>{const Ze=String(be.target_url||"").toLowerCase(),Ne=String(be.label||"").toLowerCase();return Ze!=="/search"&&!Ze.startsWith("/search?")&&!Ne.includes("search")}):p,Y=W.length>0,K=[{to:"/",label:"Home"},...z?[]:[{to:"/search",label:"Search"}],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],J=Y?[]:K,ne=W.filter(be=>!be.parent_id),ie=be=>W.filter(Ze=>Ze.parent_id===be),he=M?"bg-transparent text-white":"bg-white/95 backdrop-blur text-gray-900 border-b border-gray-100 shadow-sm",ce=t.siteTitle||`${T} - Real Estate`,pe=t.siteTagline||`Browse homes and listings with ${T}`,le=t.ogImageUrl||((Te=t.agent)==null?void 0:Te.avatar_url)||"",ve=`https://${t.subdomainSlug||""}.thelocalmove.com`;return e.jsxs("div",{className:`flex flex-col ${D?"h-screen overflow-hidden":"min-h-screen"} bg-white`,children:[e.jsx(A8e,{siteConfig:t,pagePath:n.pathname}),e.jsx(M8e,{siteConfig:t}),e.jsxs(Go,{children:[e.jsx("title",{children:ce}),e.jsx("meta",{name:"description",content:pe}),e.jsx("meta",{property:"og:title",content:ce}),e.jsx("meta",{property:"og:description",content:pe}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:ve+n.pathname}),le&&e.jsx("meta",{property:"og:image",content:le}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:ce}),e.jsx("meta",{name:"twitter:description",content:pe}),le&&e.jsx("meta",{name:"twitter:image",content:le}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${ve}${n.pathname}`}),t.subdomainSlug==="matthogg"&&e.jsx("script",{src:"https://analytics.ahrefs.com/analytics.js","data-key":"kyFjzruyvE0yTdMokzgCBw",async:!0})]}),e.jsxs("header",{className:`${M?"absolute":"sticky"} top-0 left-0 right-0 z-50 transition-all ${he}`,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(Ln,{to:"/",className:"flex items-center gap-3",children:[((Me=t.agent)==null?void 0:Me.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:L})})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[t.bookingUrl&&e.jsx(aN,{bookingUrl:t.bookingUrl,label:"Schedule",size:"sm",className:"order-last ml-3",source:"nav"}),J.map(be=>e.jsx(Ln,{to:be.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${n.pathname===be.to?M?"bg-white/15 text-white":"bg-gray-100 text-gray-900":M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:be.label},be.to)),Y&&ne.map(be=>{if(be.item_type==="dropdown"){const Ze=ie(be.id);return e.jsxs("div",{ref:j,className:"relative",children:[e.jsxs("button",{onClick:()=>_(g===be.id?null:be.id),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[be.label," ",e.jsx(io,{className:`h-3.5 w-3.5 transition-transform ${g===be.id?"rotate-180":""}`})]}),g===be.id&&Ze.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:Ze.map(Ne=>e.jsx(ZG,{item:Ne,onClick:()=>_(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"},Ne.id))})]},be.id)}return e.jsx(ZG,{item:be,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`},be.id)}),u.length>0&&e.jsxs("div",{ref:v,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${n.pathname.startsWith("/homes-for-sale-in-")?M?"bg-white/15 text-white":"bg-gray-100 text-gray-900":M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:["Cities ",e.jsx(io,{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(be=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${be.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:be.city_name},be.city_slug))})]}),b?e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsxs(Ln,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(gi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),e.jsxs(Ln,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(Xi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:((Ce=S==null?void 0:S.name)==null?void 0:Ce.split(" ")[0])||"Account"})]})]}):F?e.jsx("button",{onClick:()=>o(!0),className:`ml-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${M?"bg-white/15 text-white hover:bg-white/25":"bg-blue-600 text-white hover:bg-blue-700"}`,children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>i(!a),className:`md:hidden p-2 rounded-lg ${M?"text-white hover:bg-white/10":"text-gray-600 hover:bg-gray-100"}`,children:a?e.jsx(Bn,{className:"h-5 w-5"}):e.jsx(s4,{className:"h-5 w-5"})})]})}),a&&e.jsx("div",{className:`md:hidden border-t ${M?"border-white/10 bg-black/95 backdrop-blur":"border-gray-100 bg-white"} max-h-[calc(100vh-5rem)] overflow-y-auto overscroll-contain`,children:e.jsxs("div",{className:"px-4 py-3 space-y-1 pb-8",children:[t.bookingUrl&&e.jsx(aN,{bookingUrl:t.bookingUrl,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),J.map(be=>e.jsx(Ln,{to:be.to,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===be.to?M?"bg-white/15 text-white":"bg-gray-100 text-gray-900":M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:be.label},be.to)),Y&&ne.map(be=>{if(be.item_type==="dropdown"){const Ze=ie(be.id);return e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${M?"text-white/40":"text-gray-400"}`,children:be.label}),Ze.map(Ne=>e.jsx(ZG,{item:Ne,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},Ne.id))]},be.id)}return e.jsx(ZG,{item:be,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},be.id)}),u.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${M?"text-white/40":"text-gray-400"}`,children:"Cities"}),u.map(be=>e.jsx(Ln,{to:`/homes-for-sale-in-${be.city_slug}`,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===`/homes-for-sale-in-${be.city_slug}`?M?"bg-white/15 text-white":"bg-gray-100 text-gray-900":M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:be.city_name},be.city_slug))]}),b?e.jsxs(e.Fragment,{children:[e.jsx(Ln,{to:"/account",onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"My Account"}),e.jsx("button",{onClick:async()=>{await A(),i(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"Sign Out"})]}):F?e.jsx("button",{onClick:()=>{o(!0),i(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-blue-600 hover:bg-blue-50"}`,children:"Sign In / Register"}):null]})})]}),e.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:s}),!D&&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:[((Ae=t.agent)==null?void 0:Ae.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:((De=t.agent)==null?void 0:De.title)||"Real Estate Professional"})]})]}),((Ie=t.agent)==null?void 0:Ie.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(Ar,{className:"h-3.5 w-3.5"})," ",t.agent.phone]})}),((Fe=t.agent)==null?void 0:Fe.email)&&e.jsx("p",{className:"text-sm mt-1",children:e.jsxs("a",{href:`mailto:${t.agent.email}`,className:"hover:text-white transition-colors flex items-center gap-2",children:[e.jsx(Vs,{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:[J.map(be=>e.jsx("li",{children:e.jsx(Ln,{to:be.to,className:"hover:text-white transition-colors",children:be.label})},be.to)),V&&e.jsx("li",{children:e.jsx("a",{href:V,target:"_blank",rel:"noopener noreferrer",className:"hover:text-white transition-colors",children:"Schedule a Call"})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Get In Touch"}),e.jsx("p",{className:"text-sm text-gray-500 leading-relaxed mb-4",children:z?"Have a real estate question or need a trusted connection? Get in touch today.":"Ready to find your dream home? Get in touch today for a personalized consultation."}),e.jsx(Ln,{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."]})]})]})]})}),!D&&((qe=t.agent)==null?void 0:qe.avatar_url)&&e.jsx(Kcn,{agent:t.agent,bookingUrl:V}),l&&e.jsx(E8e,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1)}),e.jsx(aDe,{slug:t.subdomainSlug}),e.jsx(iDe,{slug:t.subdomainSlug}),e.jsx(lDe,{slug:t.subdomainSlug})]})}function Kcn({agent:s,bookingUrl:t}){var i;const[n,r]=N.useState(!1),a=Mn();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(Ar,{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(Vs,{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(Bn,{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 ZG({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(Ln,{to:r,className:t,onClick:n,children:s.label})}const bet={california:"California DRE License",ca:"California DRE License"};function QTe(s){const t=(s||"").trim();if(!t)return"Real Estate License";const n=t.toLowerCase();return bet[n]?bet[n]:`${t.replace(/\b\w/g,a=>a.toUpperCase())} Real Estate License`}function _et(s){if(s)return s.replace(/^\s*DRE\s*#?\s*/i,"").replace(/^\s*#/,"").trim()||void 0}function Ycn({children:s,siteConfig:t}){var ve,ge,Te,Me,Ce,Ae,De;const n=Jl(),r=Mn(),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState([]),[p,f]=N.useState(!1),g=N.useRef(null),{user:_,profile:v,signOut:j}=lbe();I8e(t,_==null?void 0:_.id),P8e(t,_==null?void 0:_.id);const b=((ve=t.agent)==null?void 0:ve.full_name)||"Agent",S=_et(t.agentLicenseNumber),A=_et(t.brokerageLicenseNumber),T=t.siteTitle||`${b} Real Estate`,L=t.brokerageLegalName?`${b} | ${t.brokerageLegalName}`:b,D=Ie=>{if(!Ie)return Ie;const Fe=b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),qe=new RegExp(`^\\s*${Fe}\\s*[|\\-–—:]\\s*`,"i");return Ie.replace(qe,"").trim()},M=T&&T!==`${b} Real Estate`?T:null,F=M?D(M):null,z=F&&F.toLowerCase()!==b.toLowerCase()?F:null,V=n.pathname==="/search",W=n.pathname==="/",Y=t.leadRegistrationMode!=="disabled",K="#c9a96e",J=t.bookingUrl;N.useEffect(()=>{const Ie=()=>f(window.scrollY>80);return window.addEventListener("scroll",Ie,{passive:!0}),()=>window.removeEventListener("scroll",Ie)},[]),N.useEffect(()=>{(async()=>{const{data:Fe}=await q.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});h(Fe||[])})()},[t.id]),N.useEffect(()=>{const Ie=Fe=>{g.current&&!g.current.contains(Fe.target)&&d(!1)};return document.addEventListener("mousedown",Ie),()=>document.removeEventListener("mousedown",Ie)},[]);const ne=[{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"}],ie=t.siteTitle||`${b} - Real Estate`,he=t.siteTagline||`Browse homes and listings with ${b}`,ce=t.ogImageUrl||((ge=t.agent)==null?void 0:ge.avatar_url)||"",pe=`https://${t.subdomainSlug||""}.thelocalmove.com`,le=W?p?"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 ${V?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[e.jsx(A8e,{siteConfig:t,pagePath:n.pathname}),e.jsx(M8e,{siteConfig:t}),e.jsxs(Go,{children:[e.jsx("title",{children:ie}),e.jsx("meta",{name:"description",content:he}),e.jsx("meta",{property:"og:title",content:ie}),e.jsx("meta",{property:"og:description",content:he}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:pe+n.pathname}),ce&&e.jsx("meta",{property:"og:image",content:ce}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:ie}),e.jsx("meta",{name:"twitter:description",content:he}),ce&&e.jsx("meta",{name:"twitter:image",content:ce}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${pe}${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:`${W?"fixed":"sticky"} top-0 left-0 right-0 z-50 transition-all duration-500 ${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.jsx(Ln,{to:"/",className:"flex items-center gap-3 min-w-0",children:e.jsxs("span",{className:"flex flex-col leading-none max-w-[320px] xl:max-w-[420px]",children:[e.jsx("span",{className:"block whitespace-normal text-white text-xl tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:L}),z&&e.jsx("span",{className:"mt-1 text-[11px] tracking-[0.18em] uppercase text-white/70",children:z})]})}),e.jsxs("nav",{className:"hidden lg:flex items-center gap-1",children:[ne.map(Ie=>e.jsx(Ln,{to:Ie.to,className:`px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${n.pathname===Ie.to?"text-white":"text-white/40 hover:text-white"}`,children:Ie.label},Ie.to)),u.length>0&&e.jsxs("div",{ref:g,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${n.pathname.startsWith("/homes-for-sale-in-")?"text-white":"text-white/40 hover:text-white"}`,children:["Cities ",e.jsx(io,{className:`h-3 w-3 transition-transform ${c?"rotate-180":""}`})]}),c&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-[#1a1715] border border-white/10 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:u.map(Ie=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${Ie.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:Ie.city_name},Ie.city_slug))})]}),_?e.jsxs("div",{className:"flex items-center gap-1 ml-3",children:[e.jsxs(Ln,{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(gi,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:"Saved"})]}),e.jsxs(Ln,{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(Xi,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:((Te=v==null?void 0:v.name)==null?void 0:Te.split(" ")[0])||"Account"})]})]}):Y?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(aN,{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(Bn,{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(aN,{bookingUrl:J,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),ne.map(Ie=>e.jsx(Ln,{to:Ie.to,onClick:()=>i(!1),className:`block px-3 py-3 text-xs tracking-[0.2em] uppercase transition-colors ${n.pathname===Ie.to?"text-white":"text-white/40 hover:text-white"}`,children:Ie.label},Ie.to)),u.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:K},children:"Cities"}),u.map(Ie=>e.jsx(Ln,{to:`/homes-for-sale-in-${Ie.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:Ie.city_name},Ie.city_slug))]}),_?e.jsxs(e.Fragment,{children:[e.jsx(Ln,{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 j(),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"})]}):Y?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}),!V&&e.jsx("footer",{className:"bg-[#0a0908] text-white/70 border-t border-white/10",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-20",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-16",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-white text-xl tracking-tight mb-3",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:b}),e.jsx("p",{className:"text-white/70 text-xs tracking-[0.15em] uppercase mb-6",children:((Me=t.agent)==null?void 0:Me.title)||"Real Estate Professional"}),(S||A)&&e.jsxs("div",{className:"mb-6 p-4 border border-white/10 bg-white/5",children:[S&&e.jsxs("p",{className:"text-sm text-white font-medium tracking-wide",children:[QTe(t.licenseState)," #",S]}),A&&e.jsxs("p",{className:"text-xs text-white/70 tracking-wider uppercase mt-1",children:["Brokerage License #",A]})]}),((Ce=t.agent)==null?void 0:Ce.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(Ar,{className:"h-3.5 w-3.5"})," ",t.agent.phone]}),((Ae=t.agent)==null?void 0:Ae.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(Vs,{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:K},children:"Quick Links"}),e.jsxs("ul",{className:"space-y-3",children:[ne.map(Ie=>e.jsx("li",{children:e.jsx(Ln,{to:Ie.to,className:"text-xs tracking-wider uppercase text-white/70 hover:text-white transition-colors",children:Ie.label})},Ie.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:OR},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:K},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(aN,{bookingUrl:J,label:"Schedule a Free Consultation",size:"sm",source:"footer"}),e.jsx(Ln,{to:"/contact",className:"inline-block px-8 py-3 text-xs tracking-[0.3em] uppercase border border-white/20 text-white/90 hover:bg-white hover:text-black transition-all duration-500",children:"Contact Me"})]})]})]}),e.jsxs("div",{className:"mt-16 pt-8 border-t border-white/10",children:[t.showTeamLogo&&t.teamLogoUrl&&e.jsx("div",{className:"flex items-center justify-center mb-6",children:e.jsx("img",{src:t.teamLogoUrl,alt:"Team",className:"h-10 w-auto object-contain opacity-70"})}),t.brokerageLegalName&&e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-[11px] text-white/70 tracking-wider uppercase mb-3",children:[e.jsxs("span",{children:[b," · ",t.brokerageLegalName]}),S&&e.jsxs("span",{children:[QTe(t.licenseState)," #",S]}),A&&e.jsxs("span",{children:["Brokerage #",A]})]}),t.mlsDisclaimerText&&e.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[t.mlsLogoUrl&&e.jsx("img",{src:t.mlsLogoUrl,alt:"MLS",className:"h-6 w-auto flex-shrink-0 mt-0.5 opacity-70"}),e.jsx("p",{className:"text-[11px] text-white/70 leading-relaxed max-w-3xl text-center",children:t.mlsDisclaimerText})]}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-[11px] text-white/70 tracking-wider uppercase",children:[t.equalHousingEnabled&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-4 w-4",children:e.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),e.jsx("span",{children:"Equal Housing Opportunity"})]}),e.jsxs("span",{children:["© ",new Date().getFullYear()," ",b,". Powered by LevelUp."]})]})]})]})}),!V&&((De=t.agent)==null?void 0:De.avatar_url)&&e.jsx(Zcn,{agent:t.agent,agentLicense:S,siteConfig:t,accentColor:K}),l&&e.jsx(E8e,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1),theme:"luxury",accentColor:K}),e.jsx(aDe,{slug:t.subdomainSlug}),e.jsx(iDe,{slug:t.subdomainSlug}),e.jsx(lDe,{slug:t.subdomainSlug})]})}function Zcn({agent:s,agentLicense:t,siteConfig:n,accentColor:r}){var o;const[a,i]=N.useState(!1),l=Mn();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:QTe(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(Ar,{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(Vs,{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(Bn,{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 VF="#2c1810",P_="#b8860b";function Qcn({children:s,siteConfig:t}){var M,F,z;const n=Jl();Mn();const[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState([]),[h,p]=N.useState(!1),f=N.useRef(null),{user:g,profile:_,signOut:v}=lbe();I8e(t,g==null?void 0:g.id),P8e(t,g==null?void 0:g.id);const j=((M=t.agent)==null?void 0:M.full_name)||"Agent",b=t.siteTitle||`${j} Land & Ranch`,S=n.pathname==="/",A=t.leadRegistrationMode!=="disabled";N.useEffect(()=>{const V=()=>p(window.scrollY>80);return window.addEventListener("scroll",V,{passive:!0}),()=>window.removeEventListener("scroll",V)},[]),N.useEffect(()=>{(async()=>{const{data:W}=await q.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order");W&&u(W)})()},[t.id]),N.useEffect(()=>{const V=W=>{f.current&&!f.current.contains(W.target)&&c(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[]);const T=[{label:"Home",path:"/"},{label:"Search Properties",path:"/search"},{label:"About",path:"/about"},{label:"Blog",path:"/blog"},{label:"Contact",path:"/contact"}],L=h||!S?"bg-white/95 backdrop-blur-md shadow-sm":"bg-transparent",D=h||!S?VF:"#ffffff";return e.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[e.jsxs(Go,{children:[e.jsx("title",{children:b}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600;700;800&family=Lora:wght@400;500;600&display=swap",rel:"stylesheet"})]}),e.jsx(A8e,{siteConfig:t}),e.jsx(M8e,{siteConfig:t}),e.jsxs("header",{className:`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${L}`,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(Ln,{to:"/",className:"flex items-center gap-2.5",children:[e.jsx(eL,{className:"w-7 h-7",style:{color:P_}}),e.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:D,fontFamily:"'Playfair Display', Georgia, serif"},children:b})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[T.map(V=>e.jsx(Ln,{to:V.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:n.pathname===V.path?P_:D},children:V.label},V.path)),d.length>0&&e.jsxs("div",{ref:f,className:"relative",children:[e.jsxs("button",{onClick:()=>c(!o),className:"px-4 py-2 text-sm font-medium tracking-wide uppercase flex items-center gap-1 transition-colors hover:opacity-80",style:{color:D},children:["Areas ",e.jsx(io,{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(V=>e.jsx(Ln,{to:`/homes-for-sale-in-${V.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:VF},onClick:()=>c(!1),children:V.city_name},V.city_slug))})]}),g?e.jsx("div",{className:"flex items-center gap-2 ml-3",children:e.jsxs(Ln,{to:"/account",className:"px-4 py-2 text-sm font-medium rounded-full border-2 transition-all hover:scale-105",style:{borderColor:P_,color:D},children:[e.jsx(Xi,{className:"w-4 h-4 inline mr-1.5"}),(_==null?void 0:_.name)||"Account"]})}):A?e.jsx("button",{onClick:()=>l(!0),className:"ml-3 px-5 py-2.5 text-sm font-semibold text-white rounded-full hover:shadow-lg transition-all hover:scale-105",style:{backgroundColor:P_},children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>a(!r),className:"md:hidden p-2",style:{color:D},children:r?e.jsx(Bn,{className:"w-6 h-6"}):e.jsx(s4,{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(V=>e.jsx(Ln,{to:V.path,className:"block px-4 py-3 text-base font-medium rounded-lg hover:bg-gray-50 transition-colors",style:{color:n.pathname===V.path?P_:VF},onClick:()=>a(!1),children:V.label},V.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(V=>e.jsx(Ln,{to:`/homes-for-sale-in-${V.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:VF},onClick:()=>a(!1),children:V.city_name},V.city_slug))]}),!g&&A&&e.jsx("button",{onClick:()=>{l(!0),a(!1)},className:"w-full mt-3 px-5 py-3 text-white font-semibold rounded-full",style:{backgroundColor:P_},children:"Sign In"})]})})]}),e.jsx("main",{children:s}),e.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:VF},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(eL,{className:"w-6 h-6",style:{color:P_}}),e.jsx("span",{className:"text-lg font-bold text-white",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:b})]}),e.jsx("p",{className:"text-white/60 text-sm leading-relaxed",children:"Your trusted specialist in land, ranch, and rural properties. Expert guidance for every acre."})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),e.jsx("div",{className:"space-y-2",children:T.map(V=>e.jsx(Ln,{to:V.path,className:"block text-white/60 hover:text-white text-sm transition-colors",children:V.label},V.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:[((F=t.agent)==null?void 0:F.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(Ar,{className:"w-4 h-4",style:{color:P_}}),t.agent.phone]}),((z=t.agent)==null?void 0:z.email)&&e.jsxs("a",{href:`mailto:${t.agent.email}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[e.jsx(Vs,{className:"w-4 h-4",style:{color:P_}}),t.agent.email]})]})]})]}),e.jsxs("div",{className:"mt-12 pt-8 border-t border-white/10 flex items-center justify-between",children:[e.jsxs("p",{className:"text-white/40 text-xs",children:["© ",new Date().getFullYear()," ",b,". All rights reserved."]}),e.jsx("div",{className:"h-px w-16",style:{backgroundColor:P_}})]})]})}),i&&e.jsx(E8e,{open:i,mode:t.leadRegistrationMode==="required"?"required":"optional",siteConfig:t,onSkip:()=>l(!1),onComplete:()=>l(!1)}),e.jsx(aDe,{slug:t.subdomainSlug}),e.jsx(iDe,{slug:t.subdomainSlug}),e.jsx(lDe,{slug:t.subdomainSlug})]})}function Xcn(){const{pathname:s}=Jl();return N.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[s]),null}const Jcn=N.lazy(()=>yi(()=>import("./LeadSiteHome-B44w5nol.js"),__vite__mapDeps([0,1,2,3]))),edn=N.lazy(()=>yi(()=>import("./LeadSiteLuxuryHome-Ccm5ywM1.js"),__vite__mapDeps([4,2,3]))),tdn=N.lazy(()=>yi(()=>import("./LeadSiteLandRanchHome-CdftC7sf.js"),__vite__mapDeps([5,1,2,3]))),sdn=N.lazy(()=>yi(()=>import("./LeadSiteSearch-B7yGozJa.js"),__vite__mapDeps([6,1,7,3,8]))),ndn=N.lazy(()=>yi(()=>import("./LeadSiteLuxurySearch-ARli2576.js"),__vite__mapDeps([9,1,7,3,8]))),rdn=N.lazy(()=>yi(()=>import("./LeadSiteListingDetail-vlQ28mlB.js"),__vite__mapDeps([10,11,3,12]))),adn=N.lazy(()=>yi(()=>import("./LeadSiteLuxuryListingDetail-DmnNYjtm.js"),__vite__mapDeps([13,11,3,12]))),idn=N.lazy(()=>yi(()=>import("./LeadSiteAbout-l8HTWLJX.js"),[])),odn=N.lazy(()=>yi(()=>import("./LeadSiteLuxuryAbout-B_oATOIb.js"),[])),ldn=N.lazy(()=>yi(()=>import("./LeadSiteContact-CXmVw7Ye.js"),[])),cdn=N.lazy(()=>yi(()=>import("./LeadSiteLuxuryContact-Cr3DM9rc.js"),[])),ddn=N.lazy(()=>yi(()=>import("./LeadSiteConsumerDashboard-GnQUJVKW.js"),[])),wet=N.lazy(()=>yi(()=>import("./LeadSiteBlog-O59aR-iR.js"),[])),udn=N.lazy(()=>yi(()=>import("./LeadSiteCommunity-BJGdSxr9.js"),[])),hdn=N.lazy(()=>yi(()=>import("./LeadSiteSellers-OeDp6QQv.js"),[])),mdn=N.lazy(()=>yi(()=>import("./LeadSiteCityPage-CTglHG4J.js"),__vite__mapDeps([14,3,8]))),pdn=N.lazy(()=>yi(()=>import("./LeadSiteSubdivisionPage-CjviRCcE.js"),__vite__mapDeps([15,3]))),fdn=N.lazy(()=>yi(()=>import("./LeadSiteCustomPage-Cky96pk9.js"),[]));function xdn(){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 gdn(){var d;const{siteConfig:s,themeConfig:t,isLoading:n,error:r}=frn();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?Qcn:a?Ycn:Wcn,o=DNt(s,t),c=i?e.jsx(tdn,{siteConfig:s,themeConfig:t??void 0}):a?e.jsx(edn,{siteConfig:s,themeConfig:t??void 0}):e.jsx(Jcn,{siteConfig:s,themeConfig:t??void 0});return e.jsxs(grn,{siteConfig:s,children:[e.jsx(Xcn,{}),e.jsxs(l,{siteConfig:s,children:[e.jsx(N.Suspense,{fallback:e.jsx(xdn,{}),children:e.jsxs(efe,{children:[e.jsx(as,{path:"/",element:c}),e.jsx(as,{path:"/search",element:o?e.jsx(p4,{to:"/contact",replace:!0}):a?e.jsx(ndn,{siteConfig:s}):e.jsx(sdn,{siteConfig:s})}),e.jsx(as,{path:"/listing/:mlsNumber",element:o?e.jsx(p4,{to:"/contact",replace:!0}):a?e.jsx(adn,{siteConfig:s}):e.jsx(rdn,{siteConfig:s})}),e.jsx(as,{path:"/about",element:a?e.jsx(odn,{siteConfig:s}):e.jsx(idn,{siteConfig:s})}),e.jsx(as,{path:"/contact",element:a?e.jsx(cdn,{siteConfig:s}):e.jsx(ldn,{siteConfig:s})}),e.jsx(as,{path:"/account",element:e.jsx(ddn,{siteConfig:s})}),e.jsx(as,{path:"/blog",element:e.jsx(wet,{siteConfig:s,isLuxury:a})}),e.jsx(as,{path:"/blog/:slug",element:e.jsx(wet,{siteConfig:s,isLuxury:a})}),e.jsx(as,{path:"/sell",element:e.jsx(hdn,{siteConfig:s,themeConfig:t??void 0,isLuxury:a})}),e.jsx(as,{path:"/community",element:e.jsx(udn,{siteConfig:s,isLuxury:a})}),e.jsx(as,{path:"/schedule",element:e.jsx(jrn,{bookingUrl:s.bookingUrl,agentName:((d=s.agent)==null?void 0:d.full_name)||"your agent"})}),e.jsx(as,{path:"/p/:pageSlug",element:e.jsx(fdn,{siteConfig:s})}),e.jsx(as,{path:"/*",element:e.jsx(ydn,{siteConfig:s,referralMode:o})})]})}),e.jsx(wrn,{bookingUrl:s.bookingUrl})]})]})}function ydn({siteConfig:s,referralMode:t}){const n=Jl(),r=n.pathname.match(/^\/homes-in-(.+)$/);if(r)return e.jsx(pdn,{siteConfig:s,subdivisionSlug:r[1]});const a=n.pathname.match(/^\/homes-for-sale-in-(.+)$/);return a?e.jsx(mdn,{siteConfig:s,citySlugOverride:a[1],referralMode:t}):null}function vdn(){const{user:s,loading:t}=ys(),{data:n,isLoading:r}=ct({queryKey:["feature-entitlement","levelup_attract",s==null?void 0:s.id],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await q.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key","levelup_attract").maybeSingle();if(i)throw i;return a?{hasAccess:a.enabled&&(!a.expires_at||new Date(a.expires_at).getTime()>Date.now()),tier:a.tier??null}:{hasAccess:!1,tier:null}}});return{hasAccess:!!(n!=null&&n.hasAccess),tier:(n==null?void 0:n.tier)??null,isLoading:t||r}}function bdn({children:s}){const{user:t,loading:n}=ys(),{hasAccess:r,isLoading:a}=vdn(),i=Jl();return N.useEffect(()=>{!n&&!a&&t&&!r&&ae.error("LevelUp Attract isn't available for your account yet.")},[n,a,t,r]),n||t&&a?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t?r?e.jsx(e.Fragment,{children:s}):e.jsx(p4,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",i.pathname),e.jsx(p4,{to:"/auth",replace:!0}))}function QU(){const{user:s}=ys(),t=Ht(),n=ct({queryKey:["attract-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await q.from("attract_settings").select("*").eq("user_id",s.id).maybeSingle();if(l)throw l;return i}}),r=gt({mutationFn:async i=>{const l={...i,user_id:s.id},{data:o,error:c}=await q.from("attract_settings").upsert(l,{onConflict:"user_id"}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),ae.success("Settings saved")},onError:i=>ae.error(i.message)}),a=gt({mutationFn:async()=>{const{error:i}=await q.from("attract_settings").update({onboarding_completed_at:null}).eq("user_id",s.id);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),ae.success("Onboarding reset — run it again anytime")}});return{settings:n.data,isLoading:n.isLoading,save:r,upsert:r,resetOnboarding:a}}const fSt="v1",ed={recency:22,consistency:16,value_delivered:14,kit_engagement:16,event_participation:12,follow_up_discipline:10,pipeline_momentum:10};Object.values(ed).reduce((s,t)=>s+t,0);const xSt=864e5,Am=(s,t=new Date)=>Math.floor((new Date(t).getTime()-new Date(s).getTime())/xSt),gSt=["touch_logged","call","text","email","dm","meeting","note"];function _dn(s,t,n=new Date){var _,v,j;const a=t.activities.filter(b=>b.agent_id===s.id).filter(b=>gSt.includes(b.activity_type)).sort((b,S)=>+new Date(S.created_at)-+new Date(b.created_at)),i=s.last_touch_at||((_=a[0])==null?void 0:_.created_at)||null,l=t.shares.filter(b=>b.agent_id===s.id),o=new Set(l.map(b=>b.id)),c=t.kitEvents.filter(b=>o.has(b.share_id)),d={};for(const b of l)d[b.id]=[];for(const b of c)(d[v=b.share_id]||(d[v]=[])).push(b);const u=t.attendees.filter(b=>b.agent_id===s.id),h=t.followUps.filter(b=>b.agent_id===s.id),p=h.filter(b=>!b.completed_at),f=t.stageChanges.filter(b=>b.agent_id===s.id).sort((b,S)=>+new Date(S.created_at)-+new Date(b.created_at)),g=new Set(a.filter(b=>Am(b.created_at,n)<=180).map(b=>b.created_at.slice(0,7)));return{agent:s,touches:a,lastTouchAt:i,daysSinceTouch:i?Am(i,n):null,touches90:a.filter(b=>Am(b.created_at,n)<=90).length,touches30:a.filter(b=>Am(b.created_at,n)<=30).length,distinctTouchMonths:g.size,shares:l,shareEvents:d,highIntentShares:l.filter(b=>b.engagement_level==="high_intent"||b.engagement_level==="engaged"),lastShareAt:l.map(b=>b.created_at).sort().reverse()[0]||null,totalKitOpens:l.reduce((b,S)=>b+(S.open_count||0),0),downloads:c.filter(b=>b.event_type==="file_download").length,ctaClicks:c.filter(b=>b.event_type==="primary_cta_click"||b.event_type==="external_link_click").length,questions:c.filter(b=>b.event_type==="question_submitted").length,meetingRequests:c.filter(b=>b.event_type==="meeting_requested").length+u.filter(b=>b.meeting_requested).length,attendees:u,attended:u.filter(b=>!!b.checked_in_at||b.status==="attended").length,noShows:u.filter(b=>!!b.no_show_at||b.status==="no_show").length,invitedNotRegistered:u.filter(b=>!!b.invited_at&&!b.registered_at&&!b.checked_in_at).length,openFollowUps:p,overdueFollowUps:p.filter(b=>b.due_at&&new Date(b.due_at)!!b.completed_at),stageChanges:f,lastStageChangeAt:((j=f[0])==null?void 0:j.created_at)||null,daysSinceStageChange:f[0]?Am(f[0].created_at,n):null,scoreEvents:t.scoreEvents.filter(b=>b.agent_id===s.id)}}const gpe=["new_connection","building_relationship","engaging_with_value","active_conversation","exploring_options","brokerage_presentation","decision_pending","joined"],ype=["not_right_now","not_a_fit","long_term_relationship"];function wdn(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=ed.recency,c=`Last meaningful touch ${l} day(s) ago.`,r.push("Recent personal contact")):l<=21?(o=ed.recency*.85,c=`Last touch ${l} days ago.`,r.push("Contact is still fresh")):l<=45?(o=ed.recency*.6,c=`Last touch ${l} days ago.`,i.push("Reach out within the next week to keep momentum.")):l<=90?(o=ed.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=ed.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:ed.recency,earned:Math.round(o),detail:c,direction:o>=ed.recency*.6?"positive":"negative"});const d=Math.min(s.distinctTouchMonths,6),u=ed.consistency*(d/6),h=s.touches30>6;n.push({key:"consistency",label:"Consistency of touches",weight:ed.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>=ed.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 p=s.shares.length,f=ed.value_delivered*Math.min(p/3,1);n.push({key:"value_delivered",label:"Value delivered",weight:ed.value_delivered,earned:Math.round(f),detail:p?`${p} resource kit share(s) sent.`:"No resource kit shared yet.",direction:p?"positive":"neutral"}),p?r.push(`${p} resource kit share(s) delivered`):i.push("Share a relevant Resource Kit — value first, no ask.");const g=(s.totalKitOpens>0?4:0)+Math.min(s.downloads,2)*2+Math.min(s.ctaClicks,2)*2+(s.questions>0?2:0)+(s.meetingRequests>0?4:0),_=Math.min(g,ed.kit_engagement);n.push({key:"kit_engagement",label:"Kit engagement",weight:ed.kit_engagement,earned:_,detail:p?`${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:_>0?"positive":"neutral"}),s.meetingRequests>0&&r.push("They asked for a conversation"),p&&s.totalKitOpens===0&&(a.push("Shared kit has never been opened"),i.push("Follow up personally — the kit link was never opened."));const v=Math.min(s.attended,2)*5+(s.attendees.length?2:0)-Math.min(s.noShows,2)*2,j=Math.max(0,Math.min(v,ed.event_participation));n.push({key:"event_participation",label:"Event participation",weight:ed.event_participation,earned:j,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:j>0?"positive":"neutral"}),s.attended>0&&r.push(`${s.attended} event(s) attended`),s.attendees.length||i.push("Invite them to your next event or mastermind."),s.noShows>0&&a.push(`${s.noShows} no-show(s)`);const b=s.completedFollowUps.length+s.openFollowUps.length;let S=b===0?ed.follow_up_discipline*.4:ed.follow_up_discipline*(s.completedFollowUps.length/b);S-=Math.min(s.overdueFollowUps.length,3)*2,S=Math.max(0,Math.min(S,ed.follow_up_discipline)),n.push({key:"follow_up_discipline",label:"Follow-up discipline",weight:ed.follow_up_discipline,earned:Math.round(S),detail:b?`${s.completedFollowUps.length} of ${b} follow-ups completed, ${s.overdueFollowUps.length} overdue.`:"No follow-ups created yet.",direction:s.overdueFollowUps.length?"negative":"positive"}),s.overdueFollowUps.length&&(a.push(`${s.overdueFollowUps.length} overdue commitment(s)`),i.push("Clear the overdue follow-up you promised."));const A=gpe.indexOf(s.agent.stage);let T=0,L;if(ype.includes(s.agent.stage))T=ed.pipeline_momentum*.3,L="Relationship is intentionally parked — long-term nurture.";else if(A<0)T=ed.pipeline_momentum*.3,L=`Stage "${s.agent.stage}" is outside the advancing ladder.`;else{const F=ed.pipeline_momentum*(A/(gpe.length-1)),z=s.daysSinceStageChange!==null&&s.daysSinceStageChange>60;T=z?F*.5:F,L=`Stage ${A+1} of ${gpe.length}`+(s.daysSinceStageChange!==null?`, last moved ${s.daysSinceStageChange} days ago.`:", never moved."),z&&(a.push("Stage has not moved in over 60 days"),i.push("Have the next real conversation that would justify a stage move."))}n.push({key:"pipeline_momentum",label:"Pipeline momentum",weight:ed.pipeline_momentum,earned:Math.round(T),detail:L,direction:T>ed.pipeline_momentum*.5?"positive":"neutral"});let D=n.reduce((F,z)=>F+z.earned,0);s.agent.temperature==="hot"&&(D+=4,r.push("You marked this relationship hot")),s.agent.temperature==="cold"&&(D-=4,a.push("You marked this relationship cold")),h&&(D-=3),D=Math.max(0,Math.min(100,Math.round(D)));const M=D>=75?"thriving":D>=55?"healthy":D>=35?"cooling":"at_risk";return{agent_id:s.agent.id,score:D,band:M,components:n,positives:r,negatives:a,improvements:Array.from(new Set(i)).slice(0,4),inputs:{days_since_touch:s.daysSinceTouch,touches_90:s.touches90,touches_30:s.touches30,distinct_touch_months_6mo:s.distinctTouchMonths,shares:s.shares.length,kit_opens:s.totalKitOpens,downloads:s.downloads,cta_clicks:s.ctaClicks,questions:s.questions,meeting_requests:s.meetingRequests,events_attended:s.attended,no_shows:s.noShows,invited_not_registered:s.invitedNotRegistered,open_follow_ups:s.openFollowUps.length,overdue_follow_ups:s.overdueFollowUps.length,completed_follow_ups:s.completedFollowUps.length,stage:s.agent.stage,days_since_stage_change:s.daysSinceStageChange,temperature:s.agent.temperature},weights:{...ed},engine_version:fSt,calculated_at:t.toISOString()}}const ySt=[{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"}],jdn={urgent:100,high:70,medium:40,low:15},dv=(s,t=new Date)=>new Date(t.getTime()+s*xSt).toISOString(),O_=s=>s.first_name||"there",Ndn=3;function uv(s,t,n={}){var o,c;const r=O_(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 kdn(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 j;return(j=t.kits.find(b=>b.id===v))==null?void 0:j.title},o=v=>{r.push({...v,message_source:"rules",rank_score:v.rank_score??jdn[v.priority]})},c=s.shares.find(v=>v.engagement_level==="high_intent");if(s.meetingRequests>0||s.questions>0||c){const v=c?l(c.kit_id):void 0,j=[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 ${O_(a)} — they are actively engaging`,reasons:j,priority:"urgent",suggested_due_at:dv(1,n),draft_message:uv("high_intent",s,{kitTitle:v}),suggested_kit_id:(c==null?void 0:c.kit_id)??null,source_signals:{meeting_requests:s.meetingRequests,questions:s.questions,downloads:s.downloads,share_id:c==null?void 0:c.id},rank_score:100+s.meetingRequests*5})}const d=s.shares.find(v=>v.last_opened_at&&v.first_opened_at&&Am(v.last_opened_at,n)<=7&&Am(v.first_opened_at,v.last_opened_at)>=14&&(v.open_count||0)>1);d&&(s.daysSinceTouch===null||s.daysSinceTouch>21)&&o({agent_id:a.id,rec_key:"renewed_interest",signal_group:"renewed_interest",signal_label:"Renewed interest",action_type:"reengage",channel:"text",title:`${O_(a)} came back to a kit you shared`,reasons:[`Re-opened "${l(d.kit_id)??"a shared kit"}" ${Am(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:dv(2,n),draft_message:uv("renewed_interest",s,{kitTitle:l(d.kit_id)}),suggested_kit_id:d.kit_id,source_signals:{share_id:d.id,open_count:d.open_count},rank_score:88});const u=s.attendees.filter(v=>v.checked_in_at&&Am(v.checked_in_at,n)<=7&&v.followup_status!=="done").sort((v,j)=>+new Date(j.checked_in_at)-+new Date(v.checked_in_at))[0];if(u){const v=t.events.find(b=>b.id===u.event_id),j=Math.round((n.getTime()-new Date(u.checked_in_at).getTime())/36e5);o({agent_id:a.id,rec_key:`event_follow_up:${u.event_id}`,signal_group:"event_follow_up",signal_label:"Event follow-up needed",action_type:"event_follow_up",channel:"call",title:`Follow up on ${(v==null?void 0:v.title)??"the event"} — ${j}h since they attended`,reasons:[`Checked in to "${(v==null?void 0:v.title)??"event"}" ${j} hours ago`,`Follow-up status is "${u.followup_status??"pending"}"`,j<=48?"Inside the 48-hour window where follow-up matters most":"Past the ideal 48-hour window — still worth doing today"],priority:j<=48?"urgent":"high",suggested_due_at:dv(j<=48?1:0,n),draft_message:uv("event_follow_up",s,{eventTitle:v==null?void 0:v.title}),suggested_event_id:u.event_id,suggested_kit_id:(v==null?void 0:v.resource_kit_id)??null,source_signals:{attendee_id:u.id,hours_since:j},rank_score:j<=48?96:74})}else{const v=s.attendees.find(j=>j.no_show_at&&Am(j.no_show_at,n)<=10);if(v){const j=t.events.find(b=>b.id===v.event_id);o({agent_id:a.id,rec_key:`event_no_show:${v.event_id}`,signal_group:"event_follow_up",signal_label:"Event follow-up needed",action_type:"no_show_recovery",channel:"text",title:`${O_(a)} missed ${(j==null?void 0:j.title)??"an event"} — recover gracefully`,reasons:[`Registered but did not attend "${(j==null?void 0:j.title)??"event"}"`,"No-show recovery works best within a week, with zero guilt"],priority:"medium",suggested_due_at:dv(2,n),draft_message:uv("event_no_show",s,{eventTitle:j==null?void 0:j.title}),suggested_event_id:v.event_id,source_signals:{attendee_id:v.id},rank_score:52})}}const h=s.shares.find(v=>v.first_opened_at&&Am(v.first_opened_at,n)>=3&&Am(v.first_opened_at,n)<=30&&(s.daysSinceTouch===null||s.lastTouchAt&&new Date(s.lastTouchAt)!v.first_opened_at&&Am(v.created_at,n)>=5&&v.status==="active");h?o({agent_id:a.id,rec_key:`resource_follow_up:${h.id}`,signal_group:"resource_follow_up",signal_label:"Resource follow-up needed",action_type:"resource_follow_up",channel:"text",title:`Close the loop on "${l(h.kit_id)??"the kit"}"`,reasons:[`Opened ${Am(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:dv(2,n),draft_message:uv("resource_follow_up",s,{kitTitle:l(h.kit_id)}),suggested_kit_id:h.kit_id,source_signals:{share_id:h.id},rank_score:78}):p&&o({agent_id:a.id,rec_key:`resource_unopened:${p.id}`,signal_group:"resource_follow_up",signal_label:"Resource follow-up needed",action_type:"resource_nudge",channel:"text",title:`Shared kit never opened — nudge ${O_(a)} personally`,reasons:[`Shared ${Am(p.created_at,n)} days ago and never opened`,"A personal message beats a resend"],priority:"medium",suggested_due_at:dv(2,n),draft_message:uv("resource_unopened",s,{kitTitle:l(p.kit_id)}),suggested_kit_id:p.kit_id,source_signals:{share_id:p.id},rank_score:46});const f=s.overdueFollowUps.sort((v,j)=>+new Date(v.due_at)-+new Date(j.due_at))[0];if(f){const v=Am(f.due_at,n);o({agent_id:a.id,rec_key:`overdue:${f.id}`,signal_group:"overdue_commitment",signal_label:"Overdue commitment",action_type:"clear_overdue",channel:f.touch_type||"call",title:`Overdue ${v} day(s): ${f.title}`,reasons:[`Follow-up "${f.title}" was due ${v} day(s) ago`,`Priority: ${f.priority??"medium"}`],priority:v>7?"urgent":"high",suggested_due_at:dv(0,n),draft_message:uv("overdue_commitment",s,{followUpTitle:f.title}),source_signals:{follow_up_id:f.id,days_late:v},rank_score:92+Math.min(v,8)})}const g=gpe.indexOf(a.stage);if(!ype.includes(a.stage)&&g>=2&&s.attended>0&&(s.totalKitOpens>0||s.downloads>0)&&(s.daysSinceStageChange===null||s.daysSinceStageChange>21)&&o({agent_id:a.id,rec_key:"ready_deeper",signal_group:"ready_deeper",signal_label:"Ready for a deeper conversation",action_type:"deeper_conversation",channel:"call",title:`Have the honest next-chapter conversation with ${O_(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:dv(4,n),draft_message:uv("ready_deeper",s),source_signals:{stage:a.stage,attended:s.attended},rank_score:72}),s.daysSinceTouch===null&&Am(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 ${O_(a)}`,reasons:[`Added to your pipeline ${Am(a.created_at,n)} days ago`,"No touch, kit, or event activity logged"],priority:"medium",suggested_due_at:dv(3,n),draft_message:uv("no_touch",s),source_signals:{created_at:a.created_at},rank_score:48});else if(s.daysSinceTouch!==null){const v=a.temperature==="hot"?14:a.temperature==="cold"?90:45;if(s.daysSinceTouch>v){const j=s.daysSinceTouch>v*2;o({agent_id:a.id,rec_key:j?"no_touch_long":"going_cold",signal_group:j?"no_touch":"going_cold",signal_label:j?"No meaningful touch recently":"Relationship going cold",action_type:"check_in",channel:"personal_check_in",title:`${O_(a)} has been quiet for ${s.daysSinceTouch} days`,reasons:[`Last meaningful touch ${s.daysSinceTouch} days ago`,`Your cadence for a "${a.temperature??"warm"}" relationship is ${v} days`,s.touches90?`${s.touches90} touch(es) in the last 90 days`:"No touches in the last 90 days"],priority:j?"high":"medium",suggested_due_at:dv(3,n),draft_message:uv(j?"no_touch":"going_cold",s),source_signals:{days_since_touch:s.daysSinceTouch,threshold:v},rank_score:j?62:44})}}if(!s.shares.length&&!ype.includes(a.stage)&&t.primaryPillar==="provide"){const v=t.kits.find(j=>j.status==="published"&&(!j.audience||!a.production_context||!0));v&&o({agent_id:a.id,rec_key:"share_first_kit",signal_group:"resource_follow_up",signal_label:"Resource follow-up needed",action_type:"share_kit",channel:"resource_share",title:`Share "${v.title}" with ${O_(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:dv(5,n),draft_message:uv("share_value",s,{kitTitle:v.title}),suggested_kit_id:v.id,source_signals:{pillar:"provide"},rank_score:38})}if(!s.attendees.length&&!ype.includes(a.stage)&&t.primaryPillar==="connect"){const v=t.events.filter(j=>j.status==="published"&&j.starts_at&&new Date(j.starts_at)>n).sort((j,b)=>+new Date(j.starts_at)-+new Date(b.starts_at))[0];v&&o({agent_id:a.id,rec_key:`invite_event:${v.id}`,signal_group:"ready_deeper",signal_label:"Ready for a deeper conversation",action_type:"invite_to_event",channel:"event_invitation",title:`Invite ${O_(a)} to ${v.title}`,reasons:["Never invited to an event",`"${v.title}" is published and upcoming`,"Your 90-day plan primary pillar is Connect"],priority:"medium",suggested_due_at:dv(4,n),draft_message:uv("event_invite_nudge",s,{eventTitle:v.title,eventWhen:v.starts_at?new Date(v.starts_at).toLocaleDateString():void 0}),suggested_event_id:v.id,source_signals:{pillar:"connect",event_id:v.id},rank_score:40})}return(i?r.filter(v=>v.priority==="urgent"):r).sort((v,j)=>j.rank_score-v.rank_score).slice(0,3)}const jet=[{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"]}],Sdn={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 Cdn(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:gSt.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 Tdn(s,t,n){return s.shares.slice().sort((r,a)=>+new Date(a.created_at)-+new Date(r.created_at)).map(r=>{var p;const a=s.shareEvents[r.id]??[],i=a.filter(f=>f.event_type==="file_download").length,l=a.filter(f=>f.event_type==="primary_cta_click"||f.event_type==="external_link_click").length,o=a.filter(f=>f.event_type==="question_submitted").length,c=a.filter(f=>f.event_type==="meeting_requested").length,d=r.engagement_level==="high_intent"||c>0?"High Intent":r.engagement_level==="engaged"||i>0||l>0||o>0?"Engaged":r.first_opened_at?"Viewed":"Sent",u=t.followUps.filter(f=>f.agent_id===s.agent.id&&new Date(f.created_at)>=new Date(r.created_at)).sort((f,g)=>+new Date(f.created_at)-+new Date(g.created_at))[0]??null,h=s.stageChanges.filter(f=>new Date(f.created_at)>new Date(r.created_at)).sort((f,g)=>+new Date(f.created_at)-+new Date(g.created_at))[0]??null;return{share:r,kitTitle:((p=t.kits.find(f=>f.id===r.kit_id))==null?void 0:p.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 Edn(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 qc=q;function Adn(){const{user:s}=ys();return ct({queryKey:["attract-intel-data",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{var g,_;const[t,n,r,a,i,l,o,c,d,u,h,p]=await Promise.all([qc.from("attract_agents").select("*").order("updated_at",{ascending:!1}),qc.from("attract_activities").select("*").order("created_at",{ascending:!1}).limit(2e3),qc.from("attract_follow_ups").select("*").order("created_at",{ascending:!1}).limit(2e3),qc.from("attract_kit_shares").select("*").order("created_at",{ascending:!1}).limit(1e3),qc.from("attract_kit_events").select("*").order("created_at",{ascending:!1}).limit(2e3),qc.from("attract_event_attendees").select("*").order("created_at",{ascending:!1}).limit(2e3),qc.from("attract_events").select("id, title, starts_at, status, resource_kit_id, public_slug").limit(500),qc.from("attract_pipeline_history").select("*").order("created_at",{ascending:!1}).limit(2e3),qc.from("attract_score_events").select("*").order("created_at",{ascending:!1}).limit(2e3),qc.from("attract_resource_kits").select("id, title, audience, pillar, status, is_template").eq("is_template",!1),qc.from("attract_event_notes").select("*").order("created_at",{ascending:!1}).limit(1e3),qc.from("attract_settings").select("primary_pillar, attraction_style, ninety_day_plan").eq("user_id",s.id).maybeSingle()]),f=[t,n,r,a,i,l,o,c,d,u,h].find(v=>v.error);if(f)throw f.error;return{agents:t.data??[],activities:n.data??[],followUps:r.data??[],shares:a.data??[],kitEvents:i.data??[],attendees:l.data??[],events:o.data??[],stageChanges:c.data??[],scoreEvents:d.data??[],kits:u.data??[],eventNotes:h.data??[],primaryPillar:((g=p==null?void 0:p.data)==null?void 0:g.primary_pillar)??((_=p==null?void 0:p.data)==null?void 0:_.attraction_style)??null}}})}function h6(){const s=Adn(),t=N.useMemo(()=>{if(!s.data)return[];const r=new Date;return s.data.agents.map(a=>{const i=_dn(a,s.data,r),l=wdn(i,r),o=kdn(i,s.data,r);return{agent:a,signals:i,score:l,recommendations:o,primary:o[0]??null}})},[s.data]),n=N.useMemo(()=>new Map(t.map(r=>[r.agent.id,r])),[t]);return{...s,dataset:s.data,intel:t,byId:n}}function Mdn(s){const{dataset:t,byId:n,isLoading:r,error:a,refetch:i}=h6(),l=s?n.get(s)??null:null,o=N.useMemo(()=>l&&t?Cdn(l.signals,t,t.eventNotes??[]):[],[l,t]),c=N.useMemo(()=>l&&t?Tdn(l.signals,t,typeof window<"u"?window.location.origin:""):[],[l,t]),d=N.useMemo(()=>l&&t?Edn(l.signals,t):null,[l,t]);return{item:l,dataset:t,timeline:o,valueShared:c,nextKit:d,isLoading:r,error:a,refetch:i}}function vSt(){const{user:s}=ys(),t=Ht();return gt({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:fSt,calculated_at:i.score.calculated_at}));for(let i=0;i{t.invalidateQueries({queryKey:["attract-score-snapshots"]}),n&&!r&&ae.success(`Recalculated ${n} relationship score${n===1?"":"s"}`)},onError:n=>ae.error(n.message??"Could not save scores")})}function cDe(){const{user:s}=ys();return ct({queryKey:["attract-recommendations",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await qc.from("attract_recommendations").select("*").order("rank_score",{ascending:!1});if(n)throw n;return t??[]}})}function dDe(){const{user:s}=ys(),t=Ht();return gt({mutationFn:async n=>{if(!s)return{inserted:0,refreshed:0};const r=n.flatMap(u=>u.recommendations),{data:a,error:i}=await qc.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}`,p=l.get(h),f={user_id:s.id,agent_id:u.agent_id,rec_key:u.rec_key,signal_group:u.signal_group,action_type:u.action_type,channel:u.channel,title:u.title,reasons:u.reasons,priority:u.priority,rank_score:u.rank_score,suggested_due_at:u.suggested_due_at,draft_message:u.draft_message,message_source:u.message_source,suggested_kit_id:u.suggested_kit_id??null,suggested_event_id:u.suggested_event_id??null,source_signals:u.source_signals};p?p.status==="open"?c.push({id:p.id,patch:{...f,generated_at:d.toISOString()}}):p.status==="snoozed"&&p.snoozed_until&&new Date(p.snoozed_until)<=d&&c.push({id:p.id,patch:{...f,status:"open",snoozed_until:null,generated_at:d.toISOString()}}):o.push(f)}if(o.length){const{error:u}=await qc.from("attract_recommendations").insert(o);if(u)throw u}for(const u of c)await qc.from("attract_recommendations").update(u.patch).eq("id",u.id);return{inserted:o.length,refreshed:c.length}},onSuccess:()=>t.invalidateQueries({queryKey:["attract-recommendations"]}),onError:n=>ae.error(n.message??"Could not sync recommendations")})}function bSt(){const{user:s}=ys(),t=Ht(),n=()=>{t.invalidateQueries({queryKey:["attract-recommendations"]}),t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-intel-data"]}),t.invalidateQueries({queryKey:["attract-activities"]})},r=gt({mutationFn:async({id:c,patch:d})=>{const{error:u}=await qc.from("attract_recommendations").update(d).eq("id",c);if(u)throw u},onSuccess:n,onError:c=>ae.error(c.message)}),a=gt({mutationFn:async c=>{const{error:d}=await qc.from("attract_recommendations").update({status:"dismissed",dismissed_at:new Date().toISOString()}).eq("id",c);if(d)throw d},onSuccess:()=>{n(),ae.success("Dismissed")}}),i=gt({mutationFn:async({id:c,days:d})=>{const u=new Date(Date.now()+d*864e5).toISOString(),{error:h}=await qc.from("attract_recommendations").update({status:"snoozed",snoozed_until:u}).eq("id",c);if(h)throw h},onSuccess:()=>{n(),ae.success("Snoozed")}}),l=gt({mutationFn:async c=>{if(c.follow_up_id){const{data:h}=await qc.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 qc.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 qc.from("attract_recommendations").update({follow_up_id:d.id}).eq("id",c.id),{id:d.id,existed:!1}},onSuccess:c=>{n(),ae.success(c.existed?"Follow-up already exists":"Follow-up created")},onError:c=>ae.error(c.message)}),o=gt({mutationFn:async({rec:c,note:d})=>{const u=new Date().toISOString(),{error:h}=await qc.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 qc.from("attract_follow_ups").update({completed_at:u}).eq("id",c.follow_up_id).is("completed_at",null),await qc.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:p}=await qc.from("attract_recommendations").update({status:"completed",completed_at:u}).eq("id",c.id);if(p)throw p},onSuccess:()=>{n(),t.invalidateQueries({queryKey:["attract-score"]}),ae.success("Logged — timeline and score updated")},onError:c=>ae.error(c.message)});return{update:r,dismiss:a,snooze:i,createFollowUp:l,logCompleted:o}}function Idn(){const{user:s}=ys(),t=Ht();return gt({mutationFn:async n=>{const{error:r}=await qc.from("attract_activities").insert({user_id:s.id,...n});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-intel-data"]}),t.invalidateQueries({queryKey:["attract-activities"]}),t.invalidateQueries({queryKey:["attract-agents"]}),ae.success("Logged")},onError:n=>ae.error(n.message)})}const Net={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 uDe({score:s,className:t}){const n=Net[s.band]??Net.cooling;return e.jsxs(ze,{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 _St({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(uDe,{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(mo,{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(vb,{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(fb,{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 ket({className:s}){const{intel:t}=h6(),[n,r]=N.useState(""),[a,i]=N.useState(!1),l=Mn(),o=N.useMemo(()=>{const c=n.trim().toLowerCase();return c?t.filter(d=>{const u=d.agent;return[u.first_name,u.last_name,u.brokerage,u.city,u.email,...u.tags??[]].filter(Boolean).join(" ").toLowerCase().includes(c)}).slice(0,6):[]},[t,n]);return e.jsxs("div",{className:Et("relative",s),children:[e.jsx(vr,{className:"h-3.5 w-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:n,onChange:c=>{r(c.target.value),i(!0)},onFocus:()=>i(!0),onBlur:()=>setTimeout(()=>i(!1),150),placeholder:"Search relationships","aria-label":"Search relationships",className:"w-full h-9 rounded-full bg-white/5 border border-white/10 pl-9 pr-3 text-[12.5px] text-white placeholder:text-slate-500 focus:outline-none focus:ring-1 focus:ring-violet-500/60"}),a&&!!o.length&&e.jsx("div",{className:"absolute z-50 mt-1.5 w-full rounded-xl bg-white shadow-xl ring-1 ring-slate-200 overflow-hidden",children:o.map(c=>e.jsxs("button",{onMouseDown:()=>{l(`/attract/agents/${c.agent.id}`),r(""),i(!1)},className:"w-full text-left px-3 py-2.5 hover:bg-slate-50 flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[13px] font-medium text-slate-900 truncate",children:[c.agent.first_name,c.agent.last_name].filter(Boolean).join(" ")}),e.jsxs("span",{className:"block text-[11px] text-slate-500 truncate capitalize",children:[c.agent.stage.replace(/_/g," "),c.agent.brokerage?` · ${c.agent.brokerage}`:""]})]}),e.jsx(uDe,{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 jke=[{to:"/attract",label:"Dashboard",icon:e4,exact:!0},{to:"/attract/opportunities",label:"Opportunities",icon:FA},{to:"/attract/pipeline",label:"Agent Pipeline",icon:Nn},{to:"/attract/plan",label:"90-Day Plan",icon:Oc},{section:"The Four Pillars"},{to:"/attract/produce",label:"Produce",icon:mo,tag:"Through Production"},{to:"/attract/influence",label:"Influence",icon:un,tag:"Through Influence"},{to:"/attract/influence/speaking",label:"Speaking Calendar",icon:Fv},{to:"/attract/provide",label:"Provide",icon:EA,tag:"Through Value"},{to:"/attract/provide/masterclasses",label:"Masterclasses",icon:_d},{to:"/attract/connect",label:"Connect",icon:hb,tag:"Through Events"},{to:"/attract/events",label:"Events",icon:hb},{section:"Systems"},{to:"/attract/landing-page",label:"Attraction Page",icon:eN},{to:"/attract/follow-up",label:"Follow-Up Center",icon:uu},{to:"/attract/digest",label:"Weekly Digest",icon:Vs},{to:"/attract/resources",label:"Resources",icon:Hg},{to:"/attract/templates",label:"Templates & Scripts",icon:bw},{to:"/attract/reports",label:"Reports",icon:yo},{to:"/attract/settings",label:"Settings",icon:Xo}];function Pdn(){const s=Jl(),{settings:t,isLoading:n}=QU(),r=!n&&!!t&&!t.onboarding_completed_at,a=s.pathname==="/attract/onboarding";if(r&&!a&&!s.pathname.startsWith("/attract/settings"))return e.jsx(p4,{to:"/attract/onboarding",replace:!0});const l=jke.filter(o=>!("section"in o)).slice(0,5);return e.jsxs("div",{className:"attract-root min-h-screen bg-[#F7F7FB] text-slate-900",children:[e.jsx("style",{children:` .attract-root { --a-primary: 139 92 246; --a-primary-strong: 109 40 217; --a-indigo: 79 70 229; --a-teal: 20 184 166; --a-green: 22 163 74; --a-orange: 249 115 22; --a-rose: 244 63 94; } .attract-root .btn-primary { background: linear-gradient(135deg, rgb(var(--a-primary)) 0%, rgb(var(--a-indigo)) 100%); } `}),e.jsxs("div",{className:"flex min-h-screen",children:[e.jsxs("aside",{className:"hidden lg:flex w-72 flex-col bg-[#0B0F1E] text-slate-200 border-r border-white/5",children:[e.jsxs("div",{className:"px-6 py-6 border-b border-white/10",children:[e.jsxs(eF,{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(Hr,{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(eN,{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(ket,{})}),e.jsx("nav",{className:"flex-1 overflow-y-auto py-3 px-3",children:jke.map((o,c)=>{if("section"in o)return e.jsx("div",{className:"px-3 mt-5 mb-1.5 text-[10px] uppercase tracking-[0.14em] text-slate-500 font-semibold",children:o.section},c);const d=o.icon;return e.jsxs(eF,{to:o.to,end:o.exact,className:({isActive:u})=>Et("group flex items-center gap-3 px-3 py-2.5 rounded-xl text-[13.5px] font-medium transition-all",u?"bg-gradient-to-r from-violet-600/30 to-indigo-600/10 text-white ring-1 ring-inset ring-violet-500/40":"text-slate-300 hover:bg-white/5 hover:text-white"),children:[e.jsx(d,{className:"h-4 w-4 flex-shrink-0 opacity-80 group-hover:opacity-100"}),e.jsx("span",{className:"flex-1",children:o.label}),o.tag&&e.jsx("span",{className:"text-[9.5px] uppercase tracking-wider text-slate-500 group-hover:text-slate-400",children:o.tag})]},o.to)})}),e.jsx("div",{className:"px-4 py-4 border-t border-white/5",children:e.jsxs("div",{className:"rounded-xl bg-white/5 p-3",children:[e.jsx("div",{className:"text-[11px] font-medium text-violet-300",children:"Beta preview"}),e.jsx("div",{className:"text-[11.5px] text-slate-400 mt-1 leading-snug",children:"Build relationships first. Personalize every message and verify brokerage and compensation info before sharing."})]})})]}),e.jsxs("div",{className:"lg:hidden fixed top-0 inset-x-0 z-40 bg-[#0B0F1E] text-white px-4 py-3 flex items-center gap-3 border-b border-white/10",children:[e.jsx(eF,{to:"/dashboard",className:"text-slate-400",children:e.jsx(Hr,{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(eN,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-semibold tracking-tight",children:"LEVELUP ATTRACT"}),e.jsx("div",{className:"text-[10px] text-slate-400",children:"Attract through value"})]})]}),e.jsxs("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-[#0B0F1E]/95 backdrop-blur border-t border-white/10 flex",children:[l.map(o=>{const c=o.icon;return e.jsxs(eF,{to:o.to,end:o.exact,className:({isActive:d})=>Et("flex-1 min-w-0 flex flex-col items-center gap-1 py-2 text-[10px]",d?"text-white":"text-slate-400"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"truncate max-w-[70px]",children:o.label})]},o.to)}),e.jsxs(cg,{children:[e.jsx(rU,{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(Qf,{className:"h-4 w-4"}),e.jsx("span",{children:"More"})]})}),e.jsx(ix,{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(ket,{className:"mb-4"}),e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"All sections"}),jke.map((o,c)=>{if("section"in o)return e.jsx("div",{className:"mt-4 mb-1 text-[10px] uppercase tracking-widest text-slate-500 font-semibold",children:o.section},c);const d=o.icon;return e.jsxs(eF,{to:o.to,end:o.exact,className:({isActive:u})=>Et("flex items-center gap-3 rounded-xl px-3 py-3 text-[13.5px] font-medium",u?"bg-violet-600/30 text-white":"text-slate-300 hover:bg-white/5"),children:[e.jsx(d,{className:"h-4 w-4 opacity-80"}),e.jsx("span",{children:o.label})]},o.to)})]})})]})]}),e.jsx("main",{className:"flex-1 min-w-0 pt-16 lg:pt-0 pb-24 lg:pb-0",children:e.jsx("div",{className:"max-w-[1400px] mx-auto px-4 sm:px-6 lg:px-10 py-6 lg:py-10",children:e.jsx(Pat,{})},s.pathname)})]})]})}function HF({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(fe,{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(QP,{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 Ldn(){const{user:s}=ys();return ct({queryKey:["attract-score",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_score_events").select("category, points, description, created_at");if(n)throw n;const r=t??[],a=r.reduce((l,o)=>l+(o.points??0),0),i={};for(const l of r)i[l.category]=(i[l.category]??0)+l.points;return{total:Math.min(a,100),rows:r,byCategory:i}}})}const Ddn=[{key:"relationships_added",label:"Relationships Added",icon:G0,target:15},{key:"follow_ups_completed",label:"Follow-Ups Completed",icon:xr,target:15},{key:"resources_shared",label:"Resources Shared",icon:Hl,target:15},{key:"content_posted",label:"Agent Content Posted",icon:$d,target:15},{key:"events_connections",label:"Events / Connections",icon:hb,target:20},{key:"brokerage_conversations",label:"Brokerage Conversations",icon:hL,target:20}];function Rdn(){const{data:s}=Ldn(),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(fe,{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(mo,{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:Ddn.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 GF=q;function c0(){const{user:s}=ys(),t=Ht(),n=ct({queryKey:["attract-agents",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("attract_agents").select("*").order("updated_at",{ascending:!1});if(u)throw u;return d??[]}}),r=()=>{["attract-agents","attract-intel","attract-intelligence","attract-agent-intel","attract-activities","attract-followups","attract-recommendations","attract-score","attract_milestones","attract-daily-plan"].forEach(d=>t.invalidateQueries({queryKey:[d]}))},a=gt({mutationFn:async d=>{const u={...d,user_id:s.id},{data:h,error:p}=d.id?await q.from("attract_agents").update(u).eq("id",d.id).select().single():await q.from("attract_agents").insert(u).select().single();if(p)throw p;return h},onSuccess:()=>{r(),ae.success("Saved")},onError:d=>ae.error(d.message)}),i=gt({mutationFn:async({id:d,to_stage:u,from_stage:h})=>{const{error:p}=await q.from("attract_agents").update({stage:u}).eq("id",d);if(p)throw p;await q.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:h??null,to_stage:u})},onSuccess:()=>r(),onError:d=>ae.error(d.message)}),l=gt({mutationFn:async({id:d,values:u,changedLabels:h,previousStage:p})=>{const{stage:f,...g}=u;if(Object.keys(g).length){const{error:_}=await GF.from("attract_agents").update(g).eq("id",d);if(_)throw _}if(f&&f!==p){const{error:_}=await GF.from("attract_agents").update({stage:f}).eq("id",d);if(_)throw _;await GF.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:p??null,to_stage:f})}h.length&&await GF.rpc("award_attract_activity",{_user_id:s.id,_activity_type:"note",_title:"Contact details updated",_description:`Updated: ${h.join(", ")}`,_pillar:"connect",_agent_id:d,_metadata:{},_dedupe_minutes:1})},onSuccess:()=>{r(),ae.success("Contact updated")},onError:d=>ae.error(d.message??"Could not save contact")}),o=gt({mutationFn:async({id:d,archived:u})=>{const{error:h}=await GF.from("attract_agents").update({is_archived:u}).eq("id",d);if(h)throw h},onSuccess:(d,u)=>{r(),ae.success(u.archived?"Removed from active pipeline":"Restored to pipeline")},onError:d=>ae.error(d.message)}),c=gt({mutationFn:async d=>{const{error:u}=await q.from("attract_agents").delete().eq("id",d);if(u)throw u},onSuccess:()=>{r(),ae.success("Contact permanently deleted")},onError:d=>ae.error(d.message)});return{agents:n.data??[],activeAgents:(n.data??[]).filter(d=>!d.is_archived),isLoading:n.isLoading,upsertAgent:a,saveAgentDetails:l,moveStage:i,archiveAgent:o,deleteAgent:c}}const Nke=[{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 Odn(){const{agents:s}=c0(),t=Math.max(1,...Nke.map(n=>s.filter(r=>r.stage===n.key).length));return e.jsxs(fe,{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(Ln,{to:"/attract/pipeline",children:["View Full Pipeline ",e.jsx(xa,{className:"h-3.5 w-3.5"})]})})]}),e.jsx("div",{className:"space-y-2",children:Nke.map((n,r)=>{const a=s.filter(o=>o.stage===n.key).length,i=30+a/t*70,l=.35+(1-r/Nke.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 Fdn(){const{user:s}=ys(),t=Ht(),n=ct({queryKey:["attract-daily-plan",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await q.from("attract_daily_plan").select("*").order("sort_order");if(i)throw i;return a??[]}}),r=gt({mutationFn:async a=>{const i=!a.completed,{error:l}=await q.from("attract_daily_plan").update({completed:i,progress:i?a.target:0}).eq("id",a.id);if(l)throw l},onSuccess:()=>t.invalidateQueries({queryKey:["attract-daily-plan"]})});return{items:n.data??[],isLoading:n.isLoading,toggle:r}}function wSt(s=!0){const{intel:t,isLoading:n}=h6(),r=vSt(),a=dDe(),i=N.useRef(!1);return N.useEffect(()=>{if(!s||n||i.current||!t.length)return;const o=sessionStorage.getItem("attract-intel-sync"),c=new Date().toISOString().slice(0,13);if(o===c){i.current=!0;return}i.current=!0,sessionStorage.setItem("attract-intel-sync",c),r.mutate({items:t,silent:!0}),a.mutate(t)},[s,n,t]),{runNow:()=>{r.mutate({items:t}),a.mutate(t)},isSyncing:r.isPending||a.isPending}}function zdn(){const{items:s,toggle:t}=Fdn(),{data:n=[]}=cDe(),{byId:r}=h6(),{logCompleted:a}=bSt();wSt();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 p;const h=(p=r.get(u))==null?void 0:p.agent;return h?[h.first_name,h.last_name].filter(Boolean).join(" "):"this relationship"};return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Today's Attraction Plan"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Small daily reps compound."})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:[i,e.jsxs("span",{className:"text-slate-400 text-base",children:["/",s.length]})]}),e.jsx("div",{className:"text-[11px] text-slate-500 uppercase tracking-wider",children:"complete"})]})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 mb-4 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-500 to-indigo-500 transition-all",style:{width:`${l}%`}})}),e.jsx("ul",{className:"space-y-1.5",children:s.map(u=>e.jsxs("li",{onClick:()=>t.mutate(u),className:"group flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-slate-50 cursor-pointer transition-colors",children:[e.jsx(ui,{checked:u.completed,className:"border-slate-300 data-[state=checked]:bg-violet-600 data-[state=checked]:border-violet-600"}),e.jsx("span",{className:`flex-1 text-[13.5px] ${u.completed?"line-through text-slate-400":"text-slate-800"}`,children:u.label}),e.jsxs("span",{className:"text-[11px] tabular-nums text-slate-400",children:[u.progress,"/",u.target]}),u.completed&&e.jsx(xr,{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(Ln,{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(ze,{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(Ln,{to:"/attract/opportunities",children:["All opportunities ",e.jsx(Oa,{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(Ln,{to:"/attract/plan",children:"View full plan"})})]})]})}function jSt(s=12){const{user:t}=ys(),n=ct({queryKey:["attract-activities",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{const{data:r,error:a}=await q.from("attract_activities").select("*").order("created_at",{ascending:!1}).limit(s);if(a)throw a;return r??[]}});return{activities:n.data??[],isLoading:n.isLoading}}const Bdn={agent_joined:un,resource_shared:Hl,presentation:iy,conversation:hL,social_engagement:gi,new_agent:Fo,content_posted:$d,follow_up:uu};function $dn(){const{activities:s}=jSt(8);return e.jsxs(fe,{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=Bdn[t.activity_type]??un;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:[Vo(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 hbe(s){const{user:t}=ys();return ct({queryKey:["attract-events",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let n=q.from("attract_events").select("*").eq("is_template",!1).order("starts_at",{ascending:!0});const{data:r,error:a}=await n;if(a)throw a;return r??[]}})}function hDe(s){return ct({queryKey:["attract-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_events").select("*").eq("id",s).single();if(n)throw n;return t}})}function NSt(s){return ct({queryKey:["attract-event-attendees",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_event_attendees").select("*, attract_agents(id, first_name, last_name, primary_pillar, stage)").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function Udn(s){return ct({queryKey:["attract-event-invitations",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_event_invitations").select("*, attract_agents(id, first_name, last_name)").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function qdn(s){return ct({queryKey:["attract-event-notes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_event_notes").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function kSt(){return ct({queryKey:["attract-event-templates"],queryFn:async()=>{const{data:s,error:t}=await q.from("attract_event_templates").select("*").order("title");if(t)throw t;return s??[]}})}function SSt(){const{user:s}=ys(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={user_id:s.id,title:n.title||"Untitled event",starts_at:n.starts_at||new Date(Date.now()+7*864e5).toISOString(),status:"draft",...n},{data:a,error:i}=await q.from("attract_events").insert(r).select().single();if(i)throw i;return a},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function CSt(){const s=Ht();return gt({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await q.from("attract_events").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["attract-events"]}),s.invalidateQueries({queryKey:["attract-event",t.id]})}})}function Vdn(){const s=Ht();return gt({mutationFn:async t=>{const{error:n}=await q.from("attract_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["attract-events"]})})}function TSt(){const{user:s}=ys(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={user_id:s.id,...n},{data:a,error:i}=n.id?await q.from("attract_event_attendees").update(r).eq("id",n.id).select().single():await q.from("attract_event_attendees").insert(r).select().single();if(i)throw i;return a},onSuccess:n=>{t.invalidateQueries({queryKey:["attract-event-attendees",n.event_id]}),t.invalidateQueries({queryKey:["attract-event",n.event_id]})}})}function Hdn(){const{user:s}=ys(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("attract_event_notes").insert({user_id:s.id,...n}).select().single();if(a)throw a;return r},onSuccess:n=>t.invalidateQueries({queryKey:["attract-event-notes",n.event_id]})})}function Gdn(){const{user:s}=ys(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("attract_event_invitations").insert({user_id:s.id,...n}).select().single();if(a)throw a;return r},onSuccess:n=>t.invalidateQueries({queryKey:["attract-event-invitations",n.event_id]})})}function Wdn(){const{user:s}=ys(),t=Ht();return gt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("attract_events").select("*").eq("id",n).single();if(a)throw a;const{id:i,public_slug:l,check_in_token:o,published_at:c,registration_count:d,attendance_count:u,created_at:h,updated_at:p,...f}=r,{data:g,error:_}=await q.from("attract_events").insert({...f,title:r.title+" (Copy)",status:"draft"}).select().single();if(_)throw _;return g},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function mbe(s){return`${window.location.origin}/attract-event/${s}`}function Kdn(s,t){return`${window.location.origin}/attract-event-checkin/${s}?a=${encodeURIComponent(t)}`}function ESt(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 Ydn(){const{data:s=[]}=hbe(),t=s.slice(0,3);return e.jsxs(fe,{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(Is,{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:Ss(r,"MMM")}),e.jsx("div",{className:"text-xl font-semibold leading-tight",children:Ss(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:Ss(r,"p")}),"·",n.event_type==="virtual"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(br,{className:"h-3 w-3"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(ka,{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(hb,{className:"h-6 w-6 mx-auto text-slate-300 mb-2"}),e.jsx("div",{className:"text-sm",children:"No upcoming events yet."})]})]})]})}function ASt(){const{user:s}=ys(),t=ct({queryKey:["attract-resources",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await q.from("attract_resources").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}}),n=ct({queryKey:["attract-resource-shares",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await q.from("attract_resource_shares").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}});return{resources:t.data??[],shares:n.data??[],isLoading:t.isLoading}}function Zdn(){const{shares:s}=ASt(),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:Hl,tone:"text-violet-600 bg-violet-50"},{label:"Emails Sent",value:t.emails,icon:cr,tone:"text-teal-600 bg-teal-50"},{label:"Agent Opens",value:t.opens,icon:lL,tone:"text-emerald-600 bg-emerald-50"},{label:"Clicks",value:t.clicks,icon:oc,tone:"text-orange-600 bg-orange-50"}];return e.jsxs(fe,{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 Qdn(){const{agents:s}=c0(),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(fe,{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:yc(n)})]})]}),e.jsx(un,{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?yc(Number(r.est_revenue_share)):"—"}),e.jsx("div",{className:"text-[10.5px] text-slate-400",children:r.joined_at?Vo(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 XU(){const{user:s}=ys(),t=Ht(),n=ct({queryKey:["attract-followups",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await q.from("attract_follow_ups").select("*").order("due_at",{ascending:!0,nullsFirst:!1});if(i)throw i;return a??[]}}),r=gt({mutationFn:async a=>{const{error:i}=await q.from("attract_follow_ups").update({completed_at:new Date().toISOString()}).eq("id",a);if(i)throw i},onSuccess:()=>t.invalidateQueries({queryKey:["attract-followups"]})});return{followUps:n.data??[],isLoading:n.isLoading,complete:r}}function Xdn(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 Cet={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 Jdn(){const{user:s}=ys(),t=Mn(),{agents:n}=c0(),{followUps:r}=XU(),{settings:a}=QU();N.useState(!1);const i=N.useMemo(()=>{const d=kf(new Date),u=n.filter(v=>!["joined","not_a_fit","not_right_now"].includes(v.stage)).length,h=n.filter(v=>new Date(v.created_at)>Bl(d,-30)).length,p=r.filter(v=>!v.completed_at&&v.due_at&&Vl(new Date(v.due_at),d)).length,f=r.filter(v=>!v.completed_at&&v.due_at&&wb(new Date(v.due_at),d)).length,_=n.filter(v=>v.stage==="joined").reduce((v,j)=>v+(Number(j.est_revenue_share)||0),0);return{inPipeline:u,newRels:h,dueToday:p,overdue:f,revShare:_}},[n,r]),l=(a==null?void 0:a.primary_pillar)||(a==null?void 0:a.attraction_style)||"balanced",o=Cet[l]??Cet.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, ",Xdn(s),"."]}),e.jsxs("p",{className:"text-slate-600 mt-1.5",children:["Here's your attraction overview for today · ",Ss(new Date,"EEEE, MMM d")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ds,{defaultValue:"week",children:[e.jsx(ls,{className:"w-[150px] rounded-full bg-white",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"week",children:"This Week"}),e.jsx(Qe,{value:"month",children:"This Month"}),e.jsx(Qe,{value:"90",children:"Last 90 Days"})]})]}),e.jsx(B,{variant:"outline",size:"icon",className:"rounded-full",children:e.jsx(im,{className:"h-4 w-4"})}),e.jsxs(wc,{children:[e.jsx(jc,{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(Is,{className:"h-4 w-4"})," Add New ",e.jsx(io,{className:"h-3.5 w-3.5 opacity-70"})]})}),e.jsxs(cc,{align:"end",className:"w-64",children:[e.jsx(M4,{children:"Quick add"}),e.jsx(Zg,{}),e.jsxs(Qr,{onClick:()=>t("/attract/pipeline?new=1"),children:[e.jsx(Fo,{className:"h-4 w-4 mr-2"})," Add Agent to Pipeline"]}),e.jsxs(Qr,{onClick:()=>t("/attract/produce/transaction-tracker"),children:[e.jsx(ca,{className:"h-4 w-4 mr-2"})," Log a Transaction"]}),e.jsxs(Qr,{onClick:()=>t("/attract/influence/content-studio"),children:[e.jsx(Dm,{className:"h-4 w-4 mr-2"})," Create Authority Content"]}),e.jsxs(Qr,{onClick:()=>t("/attract/follow-up"),children:[e.jsx(uu,{className:"h-4 w-4 mr-2"})," Add Follow-Up"]}),e.jsxs(Qr,{onClick:()=>t("/attract/events/new"),children:[e.jsx(Rg,{className:"h-4 w-4 mr-2"})," Plan an Event"]}),e.jsxs(Qr,{onClick:()=>t("/attract/resources"),children:[e.jsx(Hg,{className:"h-4 w-4 mr-2"})," Add Resource"]})]})]})]})]}),e.jsx(fe,{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(Oc,{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(HF,{label:"Agents in Pipeline",value:i.inPipeline,delta:"+3 this week",icon:G0,tone:"violet"}),e.jsx(HF,{label:"New Relationships",value:i.newRels,delta:"+2 this week",icon:mo,tone:"teal"}),e.jsx(HF,{label:"Follow-Ups Due Today",value:i.dueToday,icon:Q7,tone:"orange"}),e.jsx(HF,{label:"Overdue Follow-Ups",value:i.overdue,icon:$l,tone:"rose"}),e.jsx(HF,{label:"Est. Revenue Share",value:yc(i.revShare,!0),delta:"annualized",icon:Zl,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(Rdn,{}),e.jsx(Odn,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsx($dn,{}),e.jsx(Ydn,{})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(zdn,{}),e.jsx(Zdn,{}),e.jsx(Qdn,{})]})]}),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(Ln,{to:"/attract/plan",children:"View 90-Day Plan"})})]})})]})}function Vu({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 m6(){return e.jsxs("div",{className:"rounded-2xl border border-violet-200 bg-violet-50/60 px-5 py-3.5 text-[13px] text-violet-900 flex items-start gap-3",children:[e.jsx("div",{className:"h-6 w-6 rounded-full bg-violet-600 grid place-items-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-white text-[11px] font-bold",children:"✓"})}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"Build relationships first."})," ","Personalize every message and verify brokerage and compensation information before sharing."]})]})}const eun=["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"],tun={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"},xp=s=>typeof s=="string"&&s.trim()===""?null:s,YI=s=>{const t=s.trim();return t?/^https?:\/\//i.test(t)?t:`https://${t}`:null},sun=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},WF=s=>(s??"").replace(/[^\d]/g,""),nun=s=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim()),QG=s=>s?String(s).slice(0,10):"";function Tet(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:QG(s.birthday_on),work_anniversary_on:QG(s.work_anniversary_on),license_anniversary_on:QG(s.license_anniversary_on),next_follow_up_at:QG(s.next_follow_up_at)}}function ZI({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 eu({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 MSt({agent:s,open:t,onOpenChange:n,onDeleted:r}){const{agents:a,saveAgentDetails:i,archiveAgent:l,deleteAgent:o}=c0(),[c,d]=N.useState({}),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[g,_]=N.useState(!1);N.useEffect(()=>{s&&t&&(d(Tet(s)),_(!1))},[s==null?void 0:s.id,t]);const v=N.useMemo(()=>s?Tet(s):{},[s]),j=N.useMemo(()=>Object.keys(c).filter(M=>String(c[M]??"")!==String(v[M]??"")),[c,v]),b=j.length>0,S=(M,F)=>d(z=>({...z,[M]:F}));if(!s)return null;const A=M=>{if(!M&&b){h(!0);return}n(M)},T=()=>{var V;const M=(V=c.email)==null?void 0:V.trim().toLowerCase(),F=WF(c.phone),z=`${c.first_name} ${c.last_name}`.trim().toLowerCase();return a.filter(W=>{var Y;return W.id===s.id||W.is_archived?!1:!!(M&&((Y=W.email)==null?void 0:Y.toLowerCase())===M||F.length>=10&&WF(W.phone)===F||z&&`${W.first_name} ${W.last_name??""}`.trim().toLowerCase()===z)})},L=()=>{var W,Y,K;if(!((W=c.first_name)!=null&&W.trim())){ae.error("First name is required");return}if((Y=c.email)!=null&&Y.trim()&&!nun(c.email)){ae.error("That email address looks incomplete");return}const M=T(),F=M.some(J=>{var ne,ie;return((ne=c.email)==null?void 0:ne.trim())&&((ie=J.email)==null?void 0:ie.toLowerCase())===c.email.trim().toLowerCase()||WF(c.phone).length>=10&&WF(J.phone)===WF(c.phone)});if(M.length&&!g){_(!0),ae.warning(F?`${M[0].first_name} ${M[0].last_name??""} already uses this email or phone. Save again to confirm.`:"A contact named the same already exists. Save again to confirm.");return}const z={first_name:c.first_name.trim(),last_name:xp(c.last_name),preferred_name:xp(c.preferred_name),email:(K=c.email)!=null&&K.trim()?c.email.trim().toLowerCase():null,phone:sun(c.phone??""),website_url:YI(c.website_url??""),instagram_url:YI(c.instagram_url??""),linkedin_url:YI(c.linkedin_url??""),facebook_url:YI(c.facebook_url??""),other_url:YI(c.other_url??""),photo_url:YI(c.photo_url??""),brokerage:xp(c.brokerage),team_name:xp(c.team_name),city:xp(c.city),state:xp(c.state),postal_code:xp(c.postal_code),market_area:xp(c.market_area),source:xp(c.source),relationship_owner:xp(c.relationship_owner),temperature:c.temperature,primary_pillar:c.primary_pillar==="none"?null:c.primary_pillar,tags:String(c.tags??"").split(",").map(J=>J.trim()).filter(Boolean),goals:xp(c.goals),challenges:xp(c.challenges),interests:xp(c.interests),production_context:xp(c.production_context),notes:xp(c.notes),birthday_on:xp(c.birthday_on),work_anniversary_on:xp(c.work_anniversary_on),license_anniversary_on:xp(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},V={};if(j.forEach(J=>{J in z&&(V[J]=z[J])}),!Object.keys(V).length){n(!1);return}i.mutate({id:s.id,values:V,changedLabels:j.map(J=>tun[J]??J),previousStage:s.stage},{onSuccess:()=>n(!1)})},D=T();return e.jsxs(e.Fragment,{children:[e.jsx(cg,{open:t,onOpenChange:A,children:e.jsxs(ix,{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(n0,{className:"space-y-1 text-left",children:[e.jsxs(r0,{className:"text-white text-lg",children:["Edit ",[s.first_name,s.last_name].filter(Boolean).join(" ")]}),e.jsx(aU,{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:[!!D.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($l,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Possible duplicate: ",D.slice(0,3).map(M=>`${M.first_name} ${M.last_name??""}`.trim()).join(", "),". You can still save — just double-check first."]})]}),e.jsxs(ZI,{title:"Basic info",children:[e.jsx(eu,{label:"First name *",value:c.first_name,onChange:M=>S("first_name",M)}),e.jsx(eu,{label:"Last name",value:c.last_name,onChange:M=>S("last_name",M)}),e.jsx(eu,{label:"Preferred name",value:c.preferred_name,onChange:M=>S("preferred_name",M),placeholder:"What they go by"}),e.jsx(eu,{label:"Photo / headshot URL",value:c.photo_url,onChange:M=>S("photo_url",M),placeholder:"https://…"})]}),e.jsxs(ZI,{title:"Contact & social",children:[e.jsx(eu,{label:"Email",type:"email",value:c.email,onChange:M=>S("email",M)}),e.jsx(eu,{label:"Phone",value:c.phone,onChange:M=>S("phone",M)}),e.jsx(eu,{label:"Website",value:c.website_url,onChange:M=>S("website_url",M)}),e.jsx(eu,{label:"Instagram",value:c.instagram_url,onChange:M=>S("instagram_url",M)}),e.jsx(eu,{label:"LinkedIn",value:c.linkedin_url,onChange:M=>S("linkedin_url",M)}),e.jsx(eu,{label:"Facebook",value:c.facebook_url,onChange:M=>S("facebook_url",M)}),e.jsx(eu,{label:"Other link",value:c.other_url,onChange:M=>S("other_url",M),className:"sm:col-span-2"})]}),e.jsxs(ZI,{title:"Brokerage & market",children:[e.jsx(eu,{label:"Brokerage",value:c.brokerage,onChange:M=>S("brokerage",M)}),e.jsx(eu,{label:"Team",value:c.team_name,onChange:M=>S("team_name",M)}),e.jsx(eu,{label:"City",value:c.city,onChange:M=>S("city",M)}),e.jsx(eu,{label:"State",value:c.state,onChange:M=>S("state",M)}),e.jsx(eu,{label:"ZIP / postal code",value:c.postal_code,onChange:M=>S("postal_code",M)}),e.jsx(eu,{label:"Market / service area",value:c.market_area,onChange:M=>S("market_area",M)})]}),e.jsxs(ZI,{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(ds,{value:c.stage,onValueChange:M=>S("stage",M),children:[e.jsx(ls,{className:"mt-1",children:e.jsx(us,{})}),e.jsx(cs,{children:eun.map(M=>e.jsx(Qe,{value:M,className:"capitalize",children:M.replace(/_/g," ")},M))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Temperature"}),e.jsxs(ds,{value:c.temperature,onValueChange:M=>S("temperature",M),children:[e.jsx(ls,{className:"mt-1",children:e.jsx(us,{})}),e.jsx(cs,{children:["cold","warm","hot"].map(M=>e.jsx(Qe,{value:M,className:"capitalize",children:M},M))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Primary pillar"}),e.jsxs(ds,{value:c.primary_pillar,onValueChange:M=>S("primary_pillar",M),children:[e.jsx(ls,{className:"mt-1",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"Not set"}),["produce","influence","provide","connect"].map(M=>e.jsx(Qe,{value:M,className:"capitalize",children:M},M))]})]})]}),e.jsx(eu,{label:"Source",value:c.source,onChange:M=>S("source",M),placeholder:"Event, referral, social…"}),e.jsx(eu,{label:"Relationship owner",value:c.relationship_owner,onChange:M=>S("relationship_owner",M),placeholder:"You, or a teammate"}),e.jsx(eu,{label:"Tags (comma separated)",value:c.tags,onChange:M=>S("tags",M),className:"sm:col-span-2"}),!!String(c.tags??"").trim()&&e.jsx("div",{className:"sm:col-span-2 flex flex-wrap gap-1.5 -mt-1",children:String(c.tags).split(",").map(M=>M.trim()).filter(Boolean).map(M=>e.jsx(ze,{variant:"outline",className:"rounded-full text-[11px]",children:M},M))})]}),e.jsxs(ZI,{title:"Important dates",hint:"Birthdays and anniversaries feed Milestones & Celebrations automatically — no duplicate entry needed.",children:[e.jsx(eu,{label:"Birthday",type:"date",value:c.birthday_on,onChange:M=>S("birthday_on",M)}),e.jsx(eu,{label:"Work anniversary",type:"date",value:c.work_anniversary_on,onChange:M=>S("work_anniversary_on",M)}),e.jsx(eu,{label:"License anniversary",type:"date",value:c.license_anniversary_on,onChange:M=>S("license_anniversary_on",M)}),e.jsx(eu,{label:"Next follow-up",type:"date",value:c.next_follow_up_at,onChange:M=>S("next_follow_up_at",M)})]}),e.jsxs(ZI,{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(Es,{className:"mt-1",rows:2,value:c.goals,onChange:M=>S("goals",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Challenges"}),e.jsx(Es,{className:"mt-1",rows:2,value:c.challenges,onChange:M=>S("challenges",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Interests"}),e.jsx(Es,{className:"mt-1",rows:2,value:c.interests,onChange:M=>S("interests",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Production context"}),e.jsx(Es,{className:"mt-1",rows:2,value:c.production_context,onChange:M=>S("production_context",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Personal notes"}),e.jsx(Es,{className:"mt-1",rows:4,value:c.notes,onChange:M=>S("notes",M.target.value)})]})]}),e.jsxs("section",{className:"rounded-xl ring-1 ring-rose-200 bg-rose-50/60 p-4 space-y-3",children:[e.jsx("h3",{className:"text-[11px] uppercase tracking-wider font-semibold text-rose-700",children:"Danger zone"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>l.mutate({id:s.id,archived:!s.is_archived},{onSuccess:()=>n(!1)}),children:[e.jsx(rm,{className:"h-3.5 w-3.5 mr-1.5"}),s.is_archived?"Restore to pipeline":"Remove from pipeline (archive)"]}),e.jsxs(B,{variant:"destructive",size:"sm",className:"rounded-full",onClick:()=>f(!0),children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-1.5"})," Delete permanently"]})]}),e.jsx("p",{className:"text-[12px] text-rose-700/80",children:"Archiving keeps every note, touch and score. Deleting is permanent."})]})]}),e.jsxs("div",{className:"sticky bottom-0 bg-white/95 backdrop-blur border-t px-5 py-3 flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-[12px] text-slate-500",children:i.isPending?"Saving…":b?`${j.length} unsaved change${j.length>1?"s":""}`:"All changes saved"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"ghost",className:"rounded-full",onClick:()=>A(!1),children:[e.jsx(Bn,{className:"h-4 w-4 mr-1"})," Cancel"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 text-white",disabled:!b||i.isPending,onClick:L,children:[i.isPending&&e.jsx(ts,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save changes"]})]})]})]})}),e.jsx(Oo,{open:u,onOpenChange:h,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Discard unsaved changes?"}),e.jsxs(Mo,{children:["You have ",j.length," unsaved change(s) on this contact."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Keep editing"}),e.jsx(jo,{onClick:()=>{h(!1),n(!1)},children:"Discard"})]})]})}),e.jsx(Oo,{open:p,onOpenChange:f,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete this contact permanently?"}),e.jsx(Mo,{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(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{className:"bg-rose-600 hover:bg-rose-700",onClick:()=>o.mutate(s.id,{onSuccess:()=>{f(!1),n(!1),r==null||r()}}),children:"Delete forever"})]})]})})]})}const XG=[{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"}],Eet={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 run(){const s=Mn(),{agents:t,isLoading:n,upsertAgent:r,moveStage:a,archiveAgent:i,deleteAgent:l}=c0(),[o,c]=N.useState("kanban"),[d,u]=N.useState(""),[h,p]=N.useState(!1),[f,g]=N.useState(!1),[_,v]=N.useState(),[j,b]=N.useState(null),[S,A]=N.useState(null),[T,L]=N.useState(null),[D,M]=N.useState(null),{gmailEmail:F}=Oh(),z=t.filter(Y=>!!Y.is_archived!==h?!1:d?`${Y.first_name} ${Y.last_name??""} ${Y.brokerage??""} ${Y.city??""} ${(Y.tags??[]).join(" ")} ${Y.email??""}`.toLowerCase().includes(d.toLowerCase()):!0),V=j?t.find(Y=>Y.id===j.id)??j:null,W=({agent:Y})=>e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 -mr-1",onClick:K=>K.stopPropagation(),"aria-label":"Agent actions",children:e.jsx(Ig,{className:"h-3.5 w-3.5"})})}),e.jsxs(cc,{align:"end",onClick:K=>K.stopPropagation(),children:[e.jsxs(Qr,{onClick:()=>A(Y),children:[e.jsx(_a,{className:"h-3.5 w-3.5 mr-2"})," Edit contact"]}),e.jsxs(Qr,{onClick:()=>s(`/attract/agents/${Y.id}`),children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-2"})," Open relationship"]}),e.jsx(Zg,{}),e.jsxs(Qr,{onClick:()=>i.mutate({id:Y.id,archived:!Y.is_archived}),children:[e.jsx(rm,{className:"h-3.5 w-3.5 mr-2"})," ",Y.is_archived?"Restore to pipeline":"Remove from pipeline"]})]})]});return e.jsxs("div",{children:[e.jsx(Vu,{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(yf,{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(Tp,{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:()=>{v(void 0),g(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Agent"]})]})}),e.jsxs("div",{className:"mb-4 flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px] max-w-md",children:[e.jsx(vr,{className:"h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(ye,{value:d,onChange:Y=>u(Y.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:()=>p(Y=>!Y),children:[e.jsx(rm,{className:"h-3.5 w-3.5 mr-1.5"})," ",h?"Viewing archived":"Archived"]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[z.length," agents"]})]}),e.jsx("div",{className:"mb-4",children:e.jsx(m6,{})}),n?e.jsx("div",{className:"py-24 text-center text-slate-500",children:"Loading pipeline…"}):o==="kanban"?e.jsxs(hi,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:XG.length*300},children:XG.map(Y=>{const K=z.filter(J=>J.stage===Y.key);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:J=>{J.preventDefault(),J.dataTransfer.dropEffect="move"},onDrop:J=>{if(J.preventDefault(),T){const ne=t.find(ie=>ie.id===T);ne&&ne.stage!==Y.key&&a.mutate({id:T,to_stage:Y.key,from_stage:ne.stage}),L(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:Y.color}}),e.jsx("h3",{className:"text-[13px] font-semibold text-slate-800",children:Y.label}),e.jsx(ze,{variant:"secondary",className:"text-[10px] h-5 px-1.5",children:K.length})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{v(Y.key),g(!0)},children:e.jsx(Is,{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:[K.map(J=>e.jsxs("div",{draggable:!0,onDragStart:()=>L(J.id),onClick:()=>b(J),className:"bg-white rounded-xl p-3 cursor-pointer hover:shadow-md border-l-[3px] transition-all",style:{borderLeftColor:Y.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:[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(Va,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:J.brokerage??"—"})]})]}),J.temperature&&e.jsxs(ze,{variant:"outline",className:`text-[9.5px] px-1.5 py-0 ${Eet[J.temperature]}`,children:[e.jsx(P9,{className:"h-2.5 w-2.5 mr-0.5"}),J.temperature]}),e.jsx(W,{agent:J})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-[11px] text-slate-500",children:[e.jsx(ka,{className:"h-3 w-3"}),e.jsxs("span",{className:"truncate",children:[J.city,J.state&&`, ${J.state}`]})]}),J.next_follow_up_at&&e.jsxs("div",{className:"mt-1.5 text-[10.5px] text-violet-700 font-medium",children:["Next touch · ",Ss(new Date(J.next_follow_up_at),"MMM d")]})]},J.id)),K.length===0&&e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center py-4",children:"Drop an agent here"})]})]},Y.key)})}),e.jsx(iU,{orientation:"horizontal"})]}):e.jsx(fe,{className:"rounded-2xl overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-[11px] uppercase tracking-wider text-slate-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-3",children:"Agent"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Brokerage"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Location"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Stage"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Temp"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Next Follow-Up"}),e.jsx("th",{className:"text-right px-4 py-3",children:"Actions"})]})}),e.jsxs("tbody",{children:[z.map(Y=>{const K=XG.find(J=>J.key===Y.stage);return e.jsxs("tr",{onClick:()=>b(Y),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:[Y.first_name," ",Y.last_name]}),e.jsx("td",{className:"px-4 py-3 text-slate-600",children:Y.brokerage}),e.jsxs("td",{className:"px-4 py-3 text-slate-600",children:[Y.city,", ",Y.state]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ze,{style:{background:K==null?void 0:K.color,color:"white"},children:K==null?void 0:K.label})}),e.jsx("td",{className:"px-4 py-3",children:Y.temperature&&e.jsx(ze,{variant:"outline",className:Eet[Y.temperature],children:Y.temperature})}),e.jsx("td",{className:"px-4 py-3 text-slate-600",children:Y.next_follow_up_at?Ss(new Date(Y.next_follow_up_at),"MMM d"):"—"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(W,{agent:Y})})]},Y.id)}),z.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"px-4 py-10 text-center text-slate-500",children:"No agents match this view."})})]})]})}),e.jsx(aun,{open:f,onOpenChange:g,defaultStage:_,onSubmit:Y=>r.mutate(Y,{onSuccess:()=>g(!1)})}),e.jsx(MSt,{agent:S?t.find(Y=>Y.id===S.id)??S:null,open:!!S,onOpenChange:Y=>!Y&&A(null),onDeleted:()=>b(null)}),e.jsx(cg,{open:!!j,onOpenChange:Y=>!Y&&b(null),children:e.jsx(ix,{className:"w-full sm:max-w-lg overflow-y-auto",children:V&&e.jsxs(e.Fragment,{children:[e.jsxs(n0,{children:[e.jsxs(r0,{className:"text-xl",children:[V.first_name," ",V.last_name]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500 flex items-center gap-2",children:[e.jsx(Va,{className:"h-3.5 w-3.5"})," ",V.brokerage??"—"," · ",V.city,", ",V.state]})]}),e.jsxs("div",{className:"mt-6 space-y-5",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{size:"sm",className:"gap-1.5 bg-gradient-to-r from-violet-600 to-indigo-600 text-white",onClick:()=>A(V),children:[e.jsx(_a,{className:"h-3.5 w-3.5"})," Edit contact"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>s(`/attract/agents/${V.id}`),children:[e.jsx(tr,{className:"h-3.5 w-3.5"})," Open relationship"]}),V.email&&e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>M(V),children:[e.jsx(Vs,{className:"h-3.5 w-3.5"})," Email"]}),V.phone&&e.jsx(B,{variant:"outline",size:"sm",className:"gap-1.5",asChild:!0,children:e.jsxs("a",{href:`tel:${V.phone}`,children:[e.jsx(Ar,{className:"h-3.5 w-3.5"})," Call"]})}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>s(`/attract/agents/${V.id}`),children:[e.jsx(Ei,{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(ds,{value:V.stage,onValueChange:Y=>a.mutate({id:V.id,to_stage:Y,from_stage:V.stage}),children:[e.jsx(ls,{className:"mt-1",children:e.jsx(us,{})}),e.jsx(cs,{children:XG.map(Y=>e.jsx(Qe,{value:Y.key,children:Y.label},Y.key))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Temperature"}),e.jsxs(ds,{value:V.temperature??"warm",onValueChange:Y=>r.mutate({id:V.id,first_name:V.first_name,temperature:Y}),children:[e.jsx(ls,{className:"mt-1",children:e.jsx(us,{})}),e.jsx(cs,{children:["cold","warm","hot"].map(Y=>e.jsx(Qe,{value:Y,className:"capitalize",children:Y},Y))})]})]}),!!(V.tags??[]).length&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:(V.tags??[]).map(Y=>e.jsx(ze,{variant:"outline",className:"rounded-full",children:Y},Y))}),e.jsx(kke,{label:"Notes",value:V.notes}),e.jsx(kke,{label:"Goals",value:V.goals}),e.jsx(kke,{label:"Challenges",value:V.challenges}),e.jsxs("div",{className:"pt-4 border-t flex justify-between",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>i.mutate({id:V.id,archived:!V.is_archived}),children:[e.jsx(rm,{className:"h-4 w-4 mr-1"})," ",V.is_archived?"Restore":"Remove from pipeline"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"text-rose-600",onClick:()=>A(V),children:[e.jsx(_n,{className:"h-4 w-4 mr-1"})," Delete…"]})]})]})]})})}),(D==null?void 0:D.email)&&e.jsx(t1,{open:!!D,onOpenChange:Y=>!Y&&M(null),contact:{id:D.id,first_name:D.preferred_name||D.first_name,last_name:D.last_name||"",email:D.email},gmailEmail:F,sendSource:"attract",logTouchpoint:!1})]})}function kke({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 aun({open:s,onOpenChange:t,defaultStage:n,onSubmit:r}){const[a,i]=N.useState({first_name:"",last_name:"",brokerage:"",city:"",state:"",temperature:"warm",primary_pillar:"connect",stage:n??"new_connection",notes:""});return e.jsx(bs,{open:s,onOpenChange:t,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Add an agent to your pipeline"})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(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(ds,{value:a.temperature,onValueChange:l=>i({...a,temperature:l}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"cold",children:"Cold"}),e.jsx(Qe,{value:"warm",children:"Warm"}),e.jsx(Qe,{value:"hot",children:"Hot"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Primary pillar"}),e.jsxs(ds,{value:a.primary_pillar,onValueChange:l=>i({...a,primary_pillar:l}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"produce",children:"Produce"}),e.jsx(Qe,{value:"influence",children:"Influence"}),e.jsx(Qe,{value:"provide",children:"Provide"}),e.jsx(Qe,{value:"connect",children:"Connect"})]})]})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(se,{children:"Notes"}),e.jsx(Es,{rows:3,value:a.notes,onChange:l=>i({...a,notes:l.target.value})})]})]}),e.jsxs(Xn,{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 iun={call:Ar,email:Vs,coffee:ny,gift:Oi,text:Vs,event:om};function oun(){const{followUps:s,complete:t}=XU(),{agents:n}=c0(),r=N.useMemo(()=>{const l=kf(new Date),o=[],c=[],d=[],u=[],h=[];for(const p of s){if(p.completed_at){h.push(p);continue}if(!p.due_at){u.push(p);continue}const f=new Date(p.due_at);wb(f,l)?o.push(p):cf(f)?c.push(p):BUt(f)?d.push(p):u.push(p)}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:Gi},{label:"Due Today",value:r.today.length,tone:"text-orange-600 bg-orange-50",icon:gr},{label:"Completed This Week",value:r.done.filter(l=>l.completed_at&&new Date(l.completed_at)>Bl(new Date,-7)).length,tone:"text-emerald-600 bg-emerald-50",icon:xr}];return e.jsxs("div",{children:[e.jsx(Vu,{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(fe,{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(m6,{})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(KF,{title:"Overdue",items:r.overdue,agentMap:a,onComplete:l=>t.mutate(l),tone:"rose"}),e.jsx(KF,{title:"Today",items:r.today,agentMap:a,onComplete:l=>t.mutate(l),tone:"orange"}),e.jsx(KF,{title:"Tomorrow",items:r.tomorrow,agentMap:a,onComplete:l=>t.mutate(l),tone:"violet"}),e.jsx(KF,{title:"Later This Week",items:r.later,agentMap:a,onComplete:l=>t.mutate(l),tone:"slate"}),r.done.length>0&&e.jsx(KF,{title:"Recently Completed",items:r.done.slice(0,5),agentMap:a,onComplete:()=>{},tone:"emerald",done:!0})]})]})}function KF({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(ze,{variant:"secondary",className:"text-[10px]",children:t.length})]}),e.jsx(fe,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:t.map(o=>{const c=n.get(o.agent_id),d=iun[o.touch_type??""]??Vs;return e.jsxs("div",{className:`flex items-start gap-3 p-4 hover:bg-slate-50 ${i?"opacity-60":""}`,children:[e.jsx(ui,{checked:!!o.completed_at,onCheckedChange:()=>r(o.id),className:"mt-1"}),e.jsx("div",{className:"h-8 w-8 rounded-lg grid place-items-center flex-shrink-0",style:{background:`${l[a]}18`,color:l[a]},children:e.jsx(d,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:o.title}),c&&e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["for ",c.first_name," ",c.last_name," · ",c.brokerage]}),o.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1",children:o.notes})]}),o.due_at&&e.jsx("div",{className:"text-[11.5px] text-slate-500 whitespace-nowrap",children:Ss(new Date(o.due_at),"MMM d")}),e.jsx(B,{variant:"ghost",size:"sm",children:"Snooze"})]},o.id)})})]})}const lun={pdf:Nr,link:El,video:br,tool:_b,guide:Ou},cun={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 dun(){const{resources:s,isLoading:t}=ASt(),[n,r]=N.useState(""),[a,i]=N.useState("all"),l=Array.from(new Set(s.map(c=>c.category).filter(Boolean))),o=s.filter(c=>(a==="all"||c.category===a)&&(!n||`${c.title} ${c.description??""}`.toLowerCase().includes(n.toLowerCase())));return e.jsxs("div",{children:[e.jsx(Vu,{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(Is,{className:"h-4 w-4 mr-1"})," Add Resource"]})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-5",children:[e.jsxs("div",{className:"relative flex-1 min-w-[240px] max-w-md",children:[e.jsx(vr,{className:"h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(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(fe,{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=lun[c.resource_type]??Nr;return e.jsxs(fe,{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(ze,{className:`${cun[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(Hl,{className:"h-3.5 w-3.5"})," Share"]})]})]},c.id)})})]})}const uun=[{category:"First Touch",icon:Ei,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:Vs,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:ny,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:Ar,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 hun(){const s=t=>{navigator.clipboard.writeText(t),ae.success("Template copied")};return e.jsxs("div",{children:[e.jsx(Vu,{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:uun.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(fe,{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(ze,{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(Xr,{className:"h-3.5 w-3.5"})," Copy"]})})]},r.title))})]},t.category)})})]})}const mun={produce:"#7c3aed",influence:"#4f46e5",provide:"#0d9488",connect:"#9333ea"};function pun(){const{agents:s}=c0(),{activities:t}=jSt(180),n=N.useMemo(()=>Array.from({length:12},(l,o)=>Wm(G9(new Date,(11-o)*7))).map(l=>{const o=Bl(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:mun[l]}))},[t]),a=N.useMemo(()=>["new_connection","building_relationship","engaging_with_value","active_conversation","brokerage_presentation","joined"].map(l=>({stage:l.replace(/_/g," "),count:s.filter(o=>o.stage===l).length})),[s]);return e.jsxs("div",{children:[e.jsx(Vu,{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(fe,{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(kw,{width:"100%",height:260,children:e.jsxs(uLe,{data:n,children:[e.jsx(zw,{dataKey:"week",tick:{fontSize:11}}),e.jsx(Bw,{tick:{fontSize:11}}),e.jsx(Np,{}),e.jsx(r6,{type:"monotone",dataKey:"activities",stroke:"#7c3aed",strokeWidth:2.5,dot:{r:3}})]})})]}),e.jsxs(fe,{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(kw,{width:"100%",height:260,children:e.jsxs(mLe,{children:[e.jsx(zb,{data:r,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",innerRadius:55,outerRadius:90,paddingAngle:2,children:r.map((i,l)=>e.jsx(pR,{fill:i.color},l))}),e.jsx(Np,{}),e.jsx(XA,{})]})})]}),e.jsxs(fe,{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(kw,{width:"100%",height:280,children:e.jsxs(hLe,{data:a,children:[e.jsx(zw,{dataKey:"stage",tick:{fontSize:10}}),e.jsx(Bw,{tick:{fontSize:11}}),e.jsx(Np,{}),e.jsx(Fw,{dataKey:"count",fill:"#4f46e5",radius:[8,8,0,0]})]})})]})]})]})}function fun(){const{settings:s,upsert:t,resetOnboarding:n}=QU(),[r,a]=N.useState({});N.useEffect(()=>{s&&a(s)},[s]);const i=l=>a({...r,...l});return e.jsxs("div",{className:"max-w-3xl",children:[e.jsx(Vu,{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(fe,{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(Oc,{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(Ln,{to:"/attract/plan",children:"View plan"})}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>n.mutate(),children:[e.jsx(cm,{className:"h-4 w-4 mr-1.5"})," Rerun onboarding"]})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{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(Es,{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(Es,{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(fe,{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(ds,{value:String(r.hot_cadence_days??3),onValueChange:l=>i({hot_cadence_days:Number(l)}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"1",children:"Every day"}),e.jsx(Qe,{value:"3",children:"Every 3 days"}),e.jsx(Qe,{value:"7",children:"Every week"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Warm leads follow-up"}),e.jsxs(ds,{value:String(r.warm_cadence_days??14),onValueChange:l=>i({warm_cadence_days:Number(l)}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"7",children:"Weekly"}),e.jsx(Qe,{value:"14",children:"Every 2 weeks"}),e.jsx(Qe,{value:"30",children:"Monthly"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Long-term nurture"}),e.jsxs(ds,{value:String(r.longterm_cadence_days??60),onValueChange:l=>i({longterm_cadence_days:Number(l)}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"30",children:"Monthly"}),e.jsx(Qe,{value:"60",children:"Every 2 months"}),e.jsx(Qe,{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(bn,{checked:r.weekly_digest_enabled??!0,onCheckedChange:l=>i({weekly_digest_enabled:l})})]})})]})]}),e.jsxs(fe,{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 XTe=[{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."}],JTe={live:"Live",partial:"Partial",placeholder:"Placeholder",integration_required:"Integration required"},ISt={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 xun({tool:s,accent:t}){const[n,r]=N.useState(!1),a=Mn(),i=s.icon,l=!!s.to,o=XTe.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(fe,{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 ${ISt[c]}`,children:[c==="live"&&e.jsx(un,{className:"h-2.5 w-2.5"}),JTe[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(xa,{className:"h-3.5 w-3.5 group-hover:translate-x-0.5 transition-transform"})]})]})]})]}),e.jsx(bs,{open:n,onOpenChange:r,children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl grid place-items-center mb-2",style:{background:`${t}18`,color:t},children:e.jsx(i,{className:"h-6 w-6"})}),e.jsx(_s,{children:s.title})]}),e.jsxs("div",{className:"text-[14px] text-slate-700 leading-relaxed",children:[s.description,e.jsx("div",{className:"mt-4 rounded-xl bg-violet-50 border border-violet-100 p-4 text-[13px] text-violet-900",children:"This tool is on the roadmap. Mark your interest and it will jump the queue in your next release."})]}),e.jsxs(Xn,{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:()=>{ae.success("Added to your plan"),r(!1)},children:"Add to My Plan"})]})]})})]})}function mDe({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(xun,{tool:c,accent:a},c.key))})]})}function Aet(){return e.jsx(mDe,{pillar:"01",title:"Produce",accent:"#7c3aed",icon:vo,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:ca,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:sx,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:bc,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:ay,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:mo,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:ca,title:"Client Testimonials",description:"A permission-tracked library of client quotes that make future agent conversations easier.",to:"/attract/produce/testimonials"}]})}function Met(){return e.jsx(mDe,{pillar:"02",title:"Influence",accent:"#4f46e5",icon:un,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:bw,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:Tl,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:Fv,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:_d,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:br,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:Nn,title:"Agent Roundtables",description:"Host small-group conversations using the Connect Event Engine — value first, no pitching.",to:"/attract/events/new"}]})}const hP=["attract-kits"],YF=s=>["attract-kit-items",s],ZF=s=>["attract-kit-shares",s??"all"],gun=s=>["attract-kit-events",s??"all"],yun=["attract-kit-templates"];function FR(){const{user:s}=ys(),t=Ht(),n=ct({queryKey:[...hP,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_resource_kits").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=gt({mutationFn:async o=>{if(!s)throw new Error("not authenticated");const{data:c,error:d}=await q.from("attract_resource_kits").insert({user_id:s.id,title:o.title||"Untitled Kit",...o}).select("*").single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:hP})}),a=gt({mutationFn:async({id:o,patch:c})=>{const{data:d,error:u}=await q.from("attract_resource_kits").update(c).eq("id",o).select("*").single();if(u)throw u;return d},onSuccess:()=>t.invalidateQueries({queryKey:hP})}),i=gt({mutationFn:async o=>{const{error:c}=await q.from("attract_resource_kits").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:hP})}),l=gt({mutationFn:async o=>{const{data:c,error:d}=await q.rpc("duplicate_attract_kit",{_kit_id:o});if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:hP})});return{kits:n.data??[],isLoading:n.isLoading,create:r,update:a,remove:i,duplicate:l}}function PSt(s){return ct({queryKey:["attract-kit",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_resource_kits").select("*").eq("id",s).single();if(n)throw n;return t}})}function vun(s){const t=Ht(),n=ct({queryKey:YF(s??""),enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_resource_kit_items").select("*").eq("kit_id",s).order("sort_order");if(c)throw c;return o??[]}}),r=gt({mutationFn:async o=>{var u;const{data:c,error:d}=await q.from("attract_resource_kit_items").insert({kit_id:s,type:"text",title:"New item",sort_order:((u=n.data)==null?void 0:u.length)??0,...o}).select("*").single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:YF(s??"")})}),a=gt({mutationFn:async({id:o,patch:c})=>{const{error:d}=await q.from("attract_resource_kit_items").update(c).eq("id",o);if(d)throw d},onSuccess:()=>t.invalidateQueries({queryKey:YF(s??"")})}),i=gt({mutationFn:async o=>{const{error:c}=await q.from("attract_resource_kit_items").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:YF(s??"")})}),l=gt({mutationFn:async o=>{await Promise.all(o.map((c,d)=>q.from("attract_resource_kit_items").update({sort_order:d}).eq("id",c)))},onSuccess:()=>t.invalidateQueries({queryKey:YF(s??"")})});return{items:n.data??[],isLoading:n.isLoading,add:r,update:a,remove:i,reorder:l}}function LSt(s){const{user:t}=ys(),n=Ht(),r=ct({queryKey:ZF(s),enabled:!!t,queryFn:async()=>{let l=q.from("attract_kit_shares").select("*").order("created_at",{ascending:!1});s&&(l=l.eq("kit_id",s));const{data:o,error:c}=await l;if(c)throw c;return o??[]}}),a=gt({mutationFn:async l=>{if(!t)throw new Error("not authenticated");const{data:o,error:c}=await q.from("attract_kit_shares").insert({owner_user_id:t.id,...l}).select("*").single();if(c)throw c;return o},onSuccess:l=>{var o;n.invalidateQueries({queryKey:ZF(s)}),n.invalidateQueries({queryKey:ZF()});try{(o=navigator.clipboard)==null||o.writeText(RSt(l.share_token)),ae.success("Share link created and copied")}catch{ae.success("Share link created")}},onError:l=>ae.error((l==null?void 0:l.message)||"Could not create share link")}),i=gt({mutationFn:async l=>{const{error:o}=await q.from("attract_kit_shares").update({status:"revoked"}).eq("id",l);if(o)throw o},onSuccess:()=>{n.invalidateQueries({queryKey:ZF(s)}),n.invalidateQueries({queryKey:ZF()}),ae.success("Link revoked")},onError:l=>ae.error((l==null?void 0:l.message)||"Could not revoke link")});return{shares:r.data??[],isLoading:r.isLoading,create:a,revoke:i}}function DSt(s){return ct({queryKey:gun(s),queryFn:async()=>{let t=q.from("attract_kit_events").select("*").order("created_at",{ascending:!1}).limit(500);s&&(t=t.eq("kit_id",s));const{data:n,error:r}=await t;if(r)throw r;return n??[]}})}function bun(){return ct({queryKey:yun,queryFn:async()=>{const{data:s,error:t}=await q.from("attract_kit_templates").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s??[]}})}function _un(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("clone_attract_kit_template",{_template_id:t});if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:hP})})}function RSt(s){return`${typeof window<"u"?window.location.origin:""}/attract-kit/${s}`}function Iet(){const{kits:s}=FR(),{data:t=[]}=DSt(),{followUps:n}=XU(),r=N.useMemo(()=>{const l=o=>t.filter(c=>c.event_type===o).length;return{published:s.filter(o=>o.status==="published").length,drafts:s.filter(o=>o.status==="draft").length,views:l("page_view"),downloads:l("file_download"),cta:l("primary_cta_click"),questions:l("question_submitted")}},[s,t]),a=t.slice(0,8),i=n.filter(l=>!l.completed_at&&l.touch_type==="kit_engagement").slice(0,6);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vu,{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(Ln,{to:"/attract/provide/kits/templates",children:[e.jsx(Hg,{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(Ln,{to:"/attract/provide/kits/new",children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"New kit"]})})]})}),e.jsx(fe,{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(EA,{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(Ln,{to:"/attract/provide/kits/new",children:"Start a kit"})}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(Ln,{to:"/attract/provide/kits/templates",children:"Browse 10 starter kits"})})]})]})]})}),e.jsx(fe,{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(un,{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(Ln,{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(QI,{label:"Published",value:r.published}),e.jsx(QI,{label:"Drafts",value:r.drafts}),e.jsx(QI,{label:"Views",value:r.views,icon:Er}),e.jsx(QI,{label:"Downloads",value:r.downloads,icon:Pa}),e.jsx(QI,{label:"CTA clicks",value:r.cta,icon:oc}),e.jsx(QI,{label:"Questions",value:r.questions,icon:Ql})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs(fe,{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(Ln,{to:"/attract/provide/kits",children:["View kits ",e.jsx(Oa,{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:Vo(new Date(l.created_at),{addSuffix:!0})})]},l.id))})]}),e.jsxs(fe,{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 ",Vo(new Date(l.due_at),{addSuffix:!0})]})]},l.id))})]})]}),e.jsxs(fe,{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(Ln,{to:"/attract/provide/kits",children:["See all ",e.jsx(Oa,{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(Ln,{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(Ln,{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(ze,{variant:"outline",className:"capitalize",children:l.status}),l.pillar&&e.jsx(ze,{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(m6,{})]})}function QI({label:s,value:t,icon:n}){return e.jsxs(fe,{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 Pet(){return e.jsx(mDe,{pillar:"04",title:"Connect",accent:"#9333ea",icon:AA,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:ny,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:yr,title:"Attraction Events",description:"Design intimate gatherings — happy hours, dinners, mastermind lunches — with registration and check-in.",to:"/attract/events"},{key:"milestones",icon:cu,title:"Milestones & Celebrations",description:"Never miss a birthday, license anniversary, or business milestone for a prospective agent.",to:"/attract/connect/milestones"},{key:"checkins",icon:Ql,title:"Personal Check-Ins",description:"Relationship-first check-ins surfaced by your intelligence layer, ranked by signal.",to:"/attract/opportunities"},{key:"circles",icon:G0,title:"Agent Circles",description:"Small peer groups you host quarterly — built on the Connect Event Engine.",to:"/attract/events/new"}]})}const wun=[{key:"coffee",label:"Coffee & Conversation",icon:ny,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:G0,tone:"from-violet-500 to-indigo-500",description:"4–6 agents share what is actually working right now."},{key:"mastermind",label:"Mastermind",icon:un,tone:"from-fuchsia-500 to-pink-500",description:"A quarterly small group solving each other’s biggest questions."},{key:"workshop",label:"Workshop / Webinar",icon:Oc,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:$9,tone:"from-rose-500 to-red-500",description:"The relationship-first gathering. No agenda, just presence."},{key:"networking_plan",label:"Networking Game Plan",icon:AA,tone:"from-teal-500 to-emerald-500",description:"Not an event — a plan for the next 5 rooms you will walk into."}];function jun(){const s=Mn(),{data:t=[]}=hbe(),{followUps:n}=XU(),{agents:r}=c0(),a=N.useMemo(()=>{const l=new Date,o=Bl(l,7),c=t.filter(p=>p.status==="published"&&Bv(new Date(p.starts_at),l)),d=t.filter(p=>p.status==="draft").length,u=t.reduce((p,f)=>p+(Bv(new Date(f.created_at),Bl(l,-7))?f.registration_count:0),0),h=n.filter(p=>!p.completed_at&&p.due_at&&wb(new Date(p.due_at),o)&&(p.touch_type==="event_followup"||p.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(yr,{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(Is,{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:yr,tone:"text-violet-700 bg-violet-100"},{label:"Drafts needing invites",value:a.draftsNeedingInvites,icon:cr,tone:"text-amber-700 bg-amber-100"},{label:"Registrations this week",value:a.regs,icon:mo,tone:"text-emerald-700 bg-emerald-100"},{label:"48-hour follow-ups due",value:a.dueSoon,icon:uu,tone:"text-rose-700 bg-rose-100"}].map(l=>e.jsxs(fe,{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(fe,{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:[Ss(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(ze,{variant:"secondary",className:"bg-white/10 border-white/10 text-white",children:[i.registration_count," registered"]}),i.capacity&&e.jsxs(ze,{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(Oa,{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(fe,{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(Ln,{to:"/attract/events/new",className:"text-[13px] text-violet-700 hover:underline flex items-center gap-1",children:["Start from scratch ",e.jsx(xa,{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:wun.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(Oa,{className:"h-3 w-3"})]})]},l.key))})]}),e.jsxs(fe,{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:ny,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:un,tone:"text-violet-600 bg-violet-50"},{label:"People in pipeline",target:r.length,actual:r.length,icon:G0,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 Nun(){const s=Mn(),{data:t=[],isLoading:n}=hbe(),r=Wdn(),a=Vdn(),[i,l]=N.useState("all"),[o,c]=N.useState(""),d=N.useMemo(()=>t.filter(u=>!(i!=="all"&&u.status!==i||o&&!u.title.toLowerCase().includes(o.toLowerCase()))),[t,i,o]);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"Connect · Events"}),e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-slate-900",children:"Events"}),e.jsx("p",{className:"text-slate-600 mt-1",children:"Every room you have built — drafted, live, and complete."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(vr,{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(Is,{className:"h-4 w-4 mr-2"})," New event"]})]})]}),e.jsxs(Br,{value:i,onValueChange:u=>l(u),children:[e.jsxs(Fr,{className:"rounded-full bg-white border border-slate-200",children:[e.jsxs(Kt,{value:"all",className:"rounded-full",children:["All (",t.length,")"]}),e.jsxs(Kt,{value:"draft",className:"rounded-full",children:["Drafts (",t.filter(u=>u.status==="draft").length,")"]}),e.jsxs(Kt,{value:"published",className:"rounded-full",children:["Published (",t.filter(u=>u.status==="published").length,")"]}),e.jsxs(Kt,{value:"completed",className:"rounded-full",children:["Completed (",t.filter(u=>u.status==="completed").length,")"]})]}),e.jsx(is,{value:i,className:"mt-5",children:n?e.jsx(fe,{className:"p-12 rounded-2xl text-center text-slate-500",children:"Loading events…"}):d.length===0?e.jsxs(fe,{className:"p-12 rounded-2xl text-center border-dashed",children:[e.jsx(yr,{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(Is,{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(fe,{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(ze,{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(ze,{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:Ss(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(br,{className:"h-3.5 w-3.5"})," Virtual"]}):u.format==="hybrid"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(br,{className:"h-3.5 w-3.5"})," Hybrid"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," ",u.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nn,{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(Xr,{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(mbe(u.public_slug)),ae.success("Registration link copied")},children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1"})," Link"]})]}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-rose-600 hover:bg-rose-50",onClick:()=>{confirm("Delete this event?")&&a.mutate(u.id)},children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})]},u.id))})})]})]})}const kun=[{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 Let(){const{eventId:s}=bi(),t=Mn(),[n]=gl(),r=n.get("type"),a=!!s,{data:i}=hDe(s),{data:l=[]}=kSt(),{kits:o}=FR(),c=SSt(),d=CSt(),[u,h]=N.useState({title:"",description:"",event_type_key:r||"coffee",intended_audience:"",related_pillar:"connect",starts_at:new Date(Date.now()+7*864e5).toISOString().slice(0,16),ends_at:"",timezone:"America/New_York",format:"in_person",location:"",address:"",virtual_url:"",capacity:"",waitlist_enabled:!0,host_name:"",cohosts:[],agenda:[],learning_outcomes:[],registration_questions:[],confirmation_message:"",resource_kit_id:null,kit_delivery_trigger:"after_attendance",followup_hours:48});N.useEffect(()=>{i&&h({...i,starts_at:i.starts_at?i.starts_at.slice(0,16):"",ends_at:i.ends_at?i.ends_at.slice(0,16):"",capacity:i.capacity??"",cohosts:i.cohosts||[],agenda:i.agenda||[],learning_outcomes:i.learning_outcomes||[],registration_questions:i.registration_questions||[]})},[i]);const p=j=>h(b=>({...b,...j})),f=N.useMemo(()=>l.slice(0,4),[l]),g=j=>{p({title:j.title,description:j.description,event_type_key:j.event_type_key,related_pillar:j.related_pillar,intended_audience:j.intended_audience,agenda:j.suggested_agenda||[],learning_outcomes:j.suggested_outcomes||[],registration_questions:j.suggested_questions||[],confirmation_message:j.suggested_confirmation}),ae.success(`Loaded "${j.title}"`)},_=async(j={})=>{const b={...u,starts_at:u.starts_at?new Date(u.starts_at).toISOString():new Date().toISOString(),ends_at:u.ends_at?new Date(u.ends_at).toISOString():null,capacity:u.capacity===""?null:Number(u.capacity),status:j.publish?"published":u.status||"draft"};if(a)await d.mutateAsync({id:s,patch:b}),ae.success(j.publish?"Published":"Saved");else{const S=await c.mutateAsync(b);ae.success(j.publish?"Event published":"Draft saved"),t(`/attract/events/${S.id}${j.publish?"":"/edit"}`,{replace:!0})}},v=i!=null&&i.public_slug?mbe(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(Hr,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[v&&e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(v),ae.success("Registration link copied")},children:[e.jsx(Jo,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>_(),children:[e.jsx(qo,{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:()=>_({publish:!0}),children:[e.jsx(sx,{className:"h-4 w-4 mr-2"})," ",(i==null?void 0:i.status)==="published"?"Update published":"Publish"]})]})]}),!a&&f.length>0&&e.jsxs(fe,{className:"p-5 rounded-2xl border-violet-200 bg-gradient-to-br from-violet-50 to-indigo-50",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(un,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:"Start from a premium template"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:f.map(j=>e.jsxs("button",{onClick:()=>g(j),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:j.title}),e.jsx("div",{className:"text-[12px] text-slate-600 line-clamp-2 mt-0.5",children:j.description})]},j.id))})]}),e.jsxs(fe,{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:j=>p({title:j.target.value}),placeholder:"Coffee & Systems Roundtable"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Event type"}),e.jsxs(ds,{value:u.event_type_key,onValueChange:j=>p({event_type_key:j}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:kun.map(j=>e.jsx(Qe,{value:j.key,children:j.label},j.key))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Related pillar"}),e.jsxs(ds,{value:u.related_pillar||"connect",onValueChange:j=>p({related_pillar:j}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"produce",children:"Produce"}),e.jsx(Qe,{value:"influence",children:"Influence"}),e.jsx(Qe,{value:"provide",children:"Provide"}),e.jsx(Qe,{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:j=>p({intended_audience:j.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(Es,{rows:4,value:u.description||"",onChange:j=>p({description:j.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:j=>p({starts_at:j.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Ends at"}),e.jsx(ye,{type:"datetime-local",value:u.ends_at||"",onChange:j=>p({ends_at:j.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Time zone"}),e.jsxs(ds,{value:u.timezone||"America/New_York",onValueChange:j=>p({timezone:j}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Phoenix"].map(j=>e.jsx(Qe,{value:j,children:j},j))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Format"}),e.jsxs(ds,{value:u.format,onValueChange:j=>p({format:j}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"in_person",children:"In person"}),e.jsx(Qe,{value:"virtual",children:"Virtual"}),e.jsx(Qe,{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:j=>p({location:j.target.value}),placeholder:"Rise Coffee — Downtown"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Address"}),e.jsx(ye,{value:u.address||"",onChange:j=>p({address:j.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:j=>p({virtual_url:j.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:j=>p({capacity:j.target.value}),placeholder:"No limit"})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-6",children:[e.jsx(bn,{checked:u.waitlist_enabled,onCheckedChange:j=>p({waitlist_enabled:j}),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:j=>p({host_name:j.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:j=>p({cover_image_url:j.target.value}),placeholder:"https://…"})]})]})]}),e.jsxs(fe,{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:()=>p({agenda:[...u.agenda||[],{time:"",item:""}]}),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Add item"]})]}),e.jsxs("div",{className:"space-y-2",children:[(u.agenda||[]).map((j,b)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{className:"w-24",value:j.time||"",onChange:S=>{const A=[...u.agenda];A[b]={...A[b],time:S.target.value},p({agenda:A})},placeholder:"0:00"}),e.jsx(ye,{value:j.item||"",onChange:S=>{const A=[...u.agenda];A[b]={...A[b],item:S.target.value},p({agenda:A})},placeholder:"What happens here"}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>p({agenda:u.agenda.filter((S,A)=>A!==b)}),children:e.jsx(Bn,{className:"h-4 w-4"})})]},b)),(u.agenda||[]).length===0&&e.jsx("div",{className:"text-[12px] text-slate-400",children:"Add each moment of the event so attendees know what to expect."})]})]}),e.jsx(ll,{}),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:()=>p({learning_outcomes:[...u.learning_outcomes||[],""]}),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Add outcome"]})]}),e.jsx("div",{className:"space-y-2",children:(u.learning_outcomes||[]).map((j,b)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:j,onChange:S=>{const A=[...u.learning_outcomes];A[b]=S.target.value,p({learning_outcomes:A})},placeholder:"One clear, honest outcome"}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>p({learning_outcomes:u.learning_outcomes.filter((S,A)=>A!==b)}),children:e.jsx(Bn,{className:"h-4 w-4"})})]},b))})]})]})]}),e.jsxs(fe,{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:()=>p({registration_questions:[...u.registration_questions||[],{key:`q${(u.registration_questions||[]).length+1}`,label:"",type:"text"}]}),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Add question"]})]}),e.jsx("div",{className:"space-y-2",children:(u.registration_questions||[]).map((j,b)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ye,{className:"flex-1",value:j.label,onChange:S=>{const A=[...u.registration_questions];A[b]={...A[b],label:S.target.value,key:j.key||`q${b+1}`},p({registration_questions:A})},placeholder:"Question shown to registrants"}),e.jsxs(ds,{value:j.type,onValueChange:S=>{const A=[...u.registration_questions];A[b]={...A[b],type:S},p({registration_questions:A})},children:[e.jsx(ls,{className:"w-32",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"text",children:"Short text"}),e.jsx(Qe,{value:"long",children:"Long text"})]})]}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>p({registration_questions:u.registration_questions.filter((S,A)=>A!==b)}),children:e.jsx(Bn,{className:"h-4 w-4"})})]},b))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Confirmation message (shown after registration)"}),e.jsx(Es,{rows:3,value:u.confirmation_message||"",onChange:j=>p({confirmation_message:j.target.value}),placeholder:"You are in — come with one honest question."})]})]})]}),e.jsxs(fe,{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(ds,{value:u.resource_kit_id||"none",onValueChange:j=>p({resource_kit_id:j==="none"?null:j}),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"None"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"None"}),(o||[]).map(j=>e.jsx(Qe,{value:j.id,children:j.title},j.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Deliver kit"}),e.jsxs(ds,{value:u.kit_delivery_trigger||"after_attendance",onValueChange:j=>p({kit_delivery_trigger:j}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"on_registration",children:"On registration"}),e.jsx(Qe,{value:"on_confirmation",children:"On confirmation"}),e.jsx(Qe,{value:"on_check_in",children:"At check-in"}),e.jsx(Qe,{value:"after_attendance",children:"After attendance"}),e.jsx(Qe,{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:j=>p({followup_hours:Number(j.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(fe,{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(ze,{variant:"secondary",className:"bg-rose-50 text-rose-700 border-rose-200",children:"Add title and start time"}),(u.agenda||[]).length===0&&e.jsx(ze,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No agenda yet"}),(u.learning_outcomes||[]).length===0&&e.jsx(ze,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No stated outcomes"}),!u.resource_kit_id&&e.jsx(ze,{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:()=>_(),children:[e.jsx(qo,{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:()=>_({publish:!0}),children:[e.jsx(sx,{className:"h-4 w-4 mr-2"})," Publish"]})]})]})]})}const vpe=s=>s?[s.first_name,s.last_name].filter(Boolean).join(" "):"";function Sun(){const{eventId:s}=bi(),t=Mn(),{data:n}=hDe(s),{data:r=[]}=NSt(s),{data:a=[]}=Udn(s),{data:i=[]}=qdn(s),{agents:l}=c0(),{data:o=[]}=kSt(),c=TSt(),d=Hdn(),u=Gdn(),h=CSt(),p=N.useMemo(()=>{const _=r.length,v=r.filter(F=>F.status==="registered"||F.status==="confirmed").length,j=r.filter(F=>F.status==="attended").length,b=r.filter(F=>F.status==="no_show").length,S=r.filter(F=>F.status==="waitlisted").length,A=v+j+b,T=A>0?Math.round(j/A*100):0,L=a.length>0?Math.round(a.filter(F=>F.viewed_at).length/a.length*100):0,D=r.filter(F=>F.followup_status==="done").length,M=j>0?Math.round(D/j*100):0;return{total:_,registered:v,attended:j,noShow:b,waitlist:S,attendRate:T,invView:L,followed:D,followedRate:M}},[r,a]);if(!n)return e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"});const f=n.public_slug?mbe(n.public_slug):null,g=()=>{const _=new Blob([ESt(n)],{type:"text/calendar"}),v=URL.createObjectURL(_),j=document.createElement("a");j.href=v,j.download=`${n.public_slug||"event"}.ics`,j.click(),URL.revokeObjectURL(v)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>t("/attract/events"),children:[e.jsx(Hr,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:g,children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-2"})," ICS"]}),f&&e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(f),ae.success("Link copied")},children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),f&&e.jsx(B,{variant:"outline",size:"sm",className:"rounded-full",asChild:!0,children:e.jsxs("a",{href:f,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-2"})," Preview page"]})}),e.jsxs(B,{size:"sm",className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/checkin`),children:[e.jsx(oy,{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(fe,{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(ze,{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(ze,{variant:"secondary",className:"bg-white/10 border-white/10 text-white capitalize",children:n.related_pillar}),n.event_type_key&&e.jsx(ze,{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(yr,{className:"h-4 w-4"})," ",Ss(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(br,{className:"h-4 w-4"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ka,{className:"h-4 w-4"})," ",n.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nn,{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"}}),ae.success("Published")},children:"Publish now"}),n.status==="published"&&new Date(n.starts_at){await h.mutateAsync({id:n.id,patch:{status:"completed"}}),ae.success("Marked completed")},children:"Mark completed"})]})}),e.jsxs(Br,{defaultValue:"overview",children:[e.jsxs(Fr,{className:"rounded-full bg-white border border-slate-200 flex-wrap h-auto",children:[e.jsx(Kt,{value:"overview",className:"rounded-full",children:"Overview"}),e.jsxs(Kt,{value:"invitations",className:"rounded-full",children:["Invitations (",a.length,")"]}),e.jsxs(Kt,{value:"registrations",className:"rounded-full",children:["Registrations (",r.length,")"]}),e.jsxs(Kt,{value:"notes",className:"rounded-full",children:["Notes (",i.length,")"]}),e.jsx(Kt,{value:"kit",className:"rounded-full",children:"Resource Kit"}),e.jsx(Kt,{value:"followup",className:"rounded-full",children:"48-hour follow-up"}),e.jsx(Kt,{value:"analytics",className:"rounded-full",children:"Analytics"})]}),e.jsxs(is,{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(hv,{icon:Nn,label:"Registered",value:p.registered+p.attended}),e.jsx(hv,{icon:Ir,label:"Attended",value:p.attended}),e.jsx(hv,{icon:yo,label:"Attendance rate",value:`${p.attendRate}%`}),e.jsx(hv,{icon:uu,label:"Follow-up completion",value:`${p.followedRate}%`})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(fe,{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((_,v)=>e.jsxs("li",{className:"flex gap-3 text-[14px]",children:[e.jsx("span",{className:"text-slate-500 tabular-nums w-16 shrink-0",children:_.time||""}),e.jsx("span",{className:"text-slate-800",children:_.item})]},v))}),(n.learning_outcomes||[]).length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mt-6 mb-2",children:"What attendees receive"}),e.jsx("ul",{className:"space-y-1.5",children:n.learning_outcomes.map((_,v)=>e.jsxs("li",{className:"text-[13.5px] text-slate-700 flex gap-2",children:[e.jsx(Ir,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",_]},v))})]})]}),e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Share"}),f?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[12px] text-slate-500 mb-1",children:"Registration page"}),e.jsx("div",{className:"text-[12.5px] font-mono bg-slate-50 border border-slate-200 rounded-lg p-2 break-all",children:f}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full mt-2 w-full",onClick:()=>{navigator.clipboard.writeText(f),ae.success("Copied")},children:[e.jsx(Xr,{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(oy,{className:"h-3.5 w-3.5 mr-2"})," Open check-in"]})]})]})]})]}),e.jsx(is,{value:"invitations",className:"mt-5",children:e.jsx(Cun,{eventId:n.id,eventSlug:n.public_slug,agents:l,invitations:a,templates:o,onCreate:u.mutate})}),e.jsx(is,{value:"registrations",className:"mt-5",children:e.jsx(Tun,{eventId:n.id,attendees:r,onUpsert:c.mutate,checkInToken:n.check_in_token})}),e.jsx(is,{value:"notes",className:"mt-5",children:e.jsx(Eun,{eventId:n.id,attendees:r,notes:i,onCreate:d.mutate})}),e.jsx(is,{value:"kit",className:"mt-5",children:e.jsxs(fe,{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(is,{value:"followup",className:"mt-5",children:e.jsx(Aun,{eventId:n.id,attendees:r,onUpsert:c.mutate})}),e.jsxs(is,{value:"analytics",className:"mt-5",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(hv,{icon:cr,label:"Invitations sent",value:a.length}),e.jsx(hv,{icon:tr,label:"Invitation view rate",value:`${p.invView}%`}),e.jsx(hv,{icon:Nn,label:"Registered",value:p.registered+p.attended}),e.jsx(hv,{icon:Ir,label:"Attended",value:p.attended}),e.jsx(hv,{icon:yo,label:"Attendance rate",value:`${p.attendRate}%`}),e.jsx(hv,{icon:uu,label:"Follow-up complete (48h)",value:`${p.followedRate}%`}),e.jsx(hv,{icon:bw,label:"Notes captured",value:i.length}),e.jsx(hv,{icon:Fo,label:"Meetings requested",value:r.filter(_=>_.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 hv({icon:s,label:t,value:n}){return e.jsxs(fe,{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 Cun({eventId:s,eventSlug:t,agents:n,invitations:r,templates:a,onCreate:i}){const[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState("email"),[g,_]=N.useState(""),v=a==null?void 0:a[0],j=()=>{if(!v)return;const S=p==="sms"?v.suggested_invitation_sms:p==="dm"?v.suggested_invitation_dm:v.suggested_invitation_email,A=t?`${window.location.origin}/attract-event/${t}`:"";_((S||"").replaceAll("{{first_name}}",(c||"friend").split(" ")[0]).replaceAll("{{link}}",A).replaceAll("{{date}}",""))},b=()=>{if(!c||p==="email"&&!u){ae.error("Add a name and email");return}const S=n.find(A=>A.id===l);i({event_id:s,agent_id:l||null,recipient_name:c||vpe(S),recipient_email:u||(S==null?void 0:S.email),channel:p,message_body:g,status:"sent"}),d(""),h(""),_(""),o(""),ae.success("Invitation logged")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(fe,{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(ds,{value:l||"none",onValueChange:S=>{o(S==="none"?"":S);const A=n.find(T=>T.id===S);A&&(d(vpe(A)),h(A.email||""))},children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Pick an agent"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"Guest (not in pipeline)"}),n.map(S=>e.jsx(Qe,{value:S.id,children:vpe(S)},S.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Channel"}),e.jsxs(ds,{value:p,onValueChange:f,children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"email",children:"Email"}),e.jsx(Qe,{value:"sms",children:"Text message"}),e.jsx(Qe,{value:"dm",children:"DM"}),e.jsx(Qe,{value:"call",children:"Phone call"}),e.jsx(Qe,{value:"in_person",children:"In person"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Recipient name"}),e.jsx(ye,{value:c,onChange:S=>d(S.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Recipient email"}),e.jsx(ye,{value:u,onChange:S=>h(S.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"}),v&&e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full text-xs",onClick:j,children:[e.jsx(un,{className:"h-3 w-3 mr-1"})," Draft from template"]})]}),e.jsx(Es,{rows:5,value:g,onChange:S=>_(S.target.value),placeholder:"Write it like you would to a friend."})]})]}),e.jsxs("div",{className:"flex justify-between items-center mt-4",children:[e.jsx("div",{className:"text-[12px] text-slate-500",children:"Never auto-sent. This just logs that you invited them."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>{g&&(navigator.clipboard.writeText(g),ae.success("Copied"))},children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-2"})," Copy message"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:b,children:[e.jsx(cr,{className:"h-3.5 w-3.5 mr-2"})," Log invitation"]})]})]})]}),e.jsxs(fe,{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(S=>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:S.recipient_name||S.recipient_email}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:S.status})]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:["via ",S.channel," · ",Vo(new Date(S.sent_at))," ago",S.view_count>0?` · viewed ${S.view_count}×`:""]})]},S.id))})]})]})}function Tun({eventId:s,attendees:t,onUpsert:n,checkInToken:r}){const[a,i]=N.useState(""),[l,o]=N.useState(""),c=()=>{if(!a){ae.error("Add a name");return}n({event_id:s,guest_name:a,guest_email:l||null,status:"attended",checked_in_at:new Date().toISOString(),invitation_source:"walk_in"}),i(""),o(""),ae.success("Walk-in added")};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs(fe,{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(Fo,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]}),e.jsx(fe,{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||vpe(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(ze,{variant:"secondary",className:"capitalize",children:d.status}),e.jsxs(ds,{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(ls,{className:"h-8 w-40 text-xs",children:e.jsx(us,{})}),e.jsx(cs,{children:["invited","registered","confirmed","waitlisted","attended","no_show","cancelled"].map(u=>e.jsx(Qe,{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(Kdn(r,d.personalized_token)),ae.success("Check-in link copied")},children:e.jsx(Xr,{className:"h-3.5 w-3.5"})})]})]},d.id))})})]})}function Eun({eventId:s,attendees:t,notes:n,onCreate:r}){const[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState("warm"),[u,h]=N.useState(!1),[p,f]=N.useState(""),g=()=>{if(!l.trim()){ae.error("Add a note");return}const _=t.find(v=>v.id===a);r({event_id:s,attendee_id:a||null,agent_id:(_==null?void 0:_.agent_id)||null,note:l,temperature:c,recommended_next_action:p||null,wants_one_on_one:u}),o(""),i(""),f(""),h(!1),ae.success("Note captured")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(fe,{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(ds,{value:a||"none",onValueChange:_=>i(_==="none"?"":_),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Anyone in the room"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"General note"}),t.map(_=>e.jsx(Qe,{value:_.id,children:_.guest_name||_.guest_email},_.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Note"}),e.jsx(Es,{rows:4,value:l,onChange:_=>o(_.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(ds,{value:c,onValueChange:d,children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:["cold","warm","hot"].map(_=>e.jsx(Qe,{value:_,children:_},_))})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Recommended next action"}),e.jsx(ye,{value:p,onChange:_=>f(_.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:_=>h(_.target.checked)}),"They should get a one-on-one conversation"]})]}),e.jsx("div",{className:"flex justify-end mt-4",children:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:g,children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," Save note"]})})]}),e.jsxs(fe,{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(_=>{const v=t.find(j=>j.id===_.attendee_id);return e.jsxs("div",{className:"rounded-xl border border-slate-100 p-3",children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:(v==null?void 0:v.guest_name)||"General"}),e.jsx("div",{className:"text-[13px] text-slate-700 mt-1 whitespace-pre-wrap",children:_.note}),e.jsxs("div",{className:"flex items-center gap-2 mt-2 flex-wrap text-[11px] text-slate-500",children:[_.temperature&&e.jsx(ze,{variant:"secondary",className:"capitalize",children:_.temperature}),_.wants_one_on_one&&e.jsx(ze,{className:"bg-emerald-500",children:"Wants 1:1"}),_.recommended_next_action&&e.jsxs("span",{children:["Next: ",_.recommended_next_action]})]})]},_.id)})})]})]})}function Aun({eventId:s,attendees:t,onUpsert:n}){const r=N.useMemo(()=>({attended_engaged:t.filter(l=>l.status==="attended"&&l.temperature==="hot"),attended_no_notes:t.filter(l=>l.status==="attended"),no_show:t.filter(l=>l.status==="no_show"),meeting_requested:t.filter(l=>l.meeting_requested),not_followed:t.filter(l=>l.status==="attended"&&l.followup_status!=="done")}),[t]),a=(l,o)=>n({id:l,event_id:s,followup_status:o}),i=({title:l,list:o,color:c})=>e.jsxs(fe,{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(Ir,{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 JU={},Mun=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},OSt={},Ey={};let pDe;const Iun=[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];Ey.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};Ey.getSymbolTotalCodewords=function(t){return Iun[t]};Ey.getBCHDigit=function(s){let t=0;for(;s!==0;)t++,s>>>=1;return t};Ey.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');pDe=t};Ey.isKanjiModeEnabled=function(){return typeof pDe<"u"};Ey.toSJIS=function(t){return pDe(t)};var pbe={};(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}}})(pbe);function FSt(){this.buffer=[],this.length=0}FSt.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 Pun=FSt;function eq(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)}eq.prototype.set=function(s,t,n,r){const a=s*this.size+t;this.data[a]=n,r&&(this.reservedBit[a]=!0)};eq.prototype.get=function(s,t){return this.data[s*this.size+t]};eq.prototype.xor=function(s,t,n){this.data[s*this.size+t]^=n};eq.prototype.isReserved=function(s,t){return this.reservedBit[s*this.size+t]};var Lun=eq,zSt={};(function(s){const t=Ey.getSymbolSize;s.getRowColCoords=function(r){if(r===1)return[];const a=Math.floor(r/7)+2,i=t(r),l=i===145?26:Math.ceil((i-13)/(2*a-2))*2,o=[i-7];for(let c=1;c=0&&a<=7},s.from=function(a){return s.isValid(a)?parseInt(a,10):void 0},s.getPenaltyN1=function(a){const i=a.size;let l=0,o=0,c=0,d=null,u=null;for(let h=0;h=5&&(l+=t.N1+(o-5)),d=f,o=1),f=a.get(p,h),f===u?c++:(c>=5&&(l+=t.N1+(c-5)),u=f,c=1)}o>=5&&(l+=t.N1+(o-5)),c>=5&&(l+=t.N1+(c-5))}return l},s.getPenaltyN2=function(a){const i=a.size;let l=0;for(let o=0;o=10&&(o===1488||o===93)&&l++,c=c<<1&2047|a.get(u,d),u>=10&&(c===1488||c===93)&&l++}return l*t.N3},s.getPenaltyN4=function(a){let i=0;const l=a.data.length;for(let c=0;c=0;){const l=i[0];for(let c=0;c0){const i=new Uint8Array(this.degree);return i.set(r,a),i}return r};var Run=fDe,VSt={},fC={},xDe={};xDe.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var ij={};const HSt="[0-9]+",Oun="[A-Z $%*+\\-./:]+";let T$="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";T$=T$.replace(/u/g,"\\u");const Fun="(?:(?![A-Z0-9 $%*+\\-./:]|"+T$+`)(?:.|[\r ]))+`;ij.KANJI=new RegExp(T$,"g");ij.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");ij.BYTE=new RegExp(Fun,"g");ij.NUMERIC=new RegExp(HSt,"g");ij.ALPHANUMERIC=new RegExp(Oun,"g");const zun=new RegExp("^"+T$+"$"),Bun=new RegExp("^"+HSt+"$"),$un=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");ij.testKanji=function(t){return zun.test(t)};ij.testNumeric=function(t){return Bun.test(t)};ij.testAlphanumeric=function(t){return $un.test(t)};(function(s){const t=xDe,n=ij;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}}})(fC);(function(s){const t=Ey,n=fbe,r=pbe,a=fC,i=xDe,l=7973,o=t.getBCHDigit(l);function c(p,f,g){for(let _=1;_<=40;_++)if(f<=s.getCapacity(_,g,p))return _}function d(p,f){return a.getCharCountIndicator(p,f)+4}function u(p,f){let g=0;return p.forEach(function(_){const v=d(_.mode,f);g+=v+_.getBitsLength()}),g}function h(p,f){for(let g=1;g<=40;g++)if(u(p,g)<=s.getCapacity(g,f,a.MIXED))return g}s.from=function(f,g){return i.isValid(f)?parseInt(f,10):g},s.getCapacity=function(f,g,_){if(!i.isValid(f))throw new Error("Invalid QR Code version");typeof _>"u"&&(_=a.BYTE);const v=t.getSymbolTotalCodewords(f),j=n.getTotalCodewordsCount(f,g),b=(v-j)*8;if(_===a.MIXED)return b;const S=b-d(_,f);switch(_){case a.NUMERIC:return Math.floor(S/10*3);case a.ALPHANUMERIC:return Math.floor(S/11*2);case a.KANJI:return Math.floor(S/13);case a.BYTE:default:return Math.floor(S/8)}},s.getBestVersionForData=function(f,g){let _;const v=r.from(g,r.M);if(Array.isArray(f)){if(f.length>1)return h(f,v);if(f.length===0)return 1;_=f[0]}else _=f;return c(_.mode,_.getLength(),v)},s.getEncodedBits=function(f){if(!i.isValid(f)||f<7)throw new Error("Invalid QR Code version");let g=f<<12;for(;t.getBCHDigit(g)-o>=0;)g^=l<=0;)a^=WSt<0&&(r=this.data.substr(n),a=parseInt(r,10),t.put(a,i*3+1))};var Vun=_D;const Hun=fC,Ske=["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 wD(s){this.mode=Hun.ALPHANUMERIC,this.data=s}wD.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)};wD.prototype.getLength=function(){return this.data.length};wD.prototype.getBitsLength=function(){return wD.getBitsLength(this.data.length)};wD.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=Ske.indexOf(this.data[n])*45;r+=Ske.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(Ske.indexOf(this.data[n]),6)};var Gun=wD;const Wun=fC;function jD(s){this.mode=Wun.BYTE,typeof s=="string"?this.data=new TextEncoder().encode(s):this.data=new Uint8Array(s)}jD.getBitsLength=function(t){return t*8};jD.prototype.getLength=function(){return this.data.length};jD.prototype.getBitsLength=function(){return jD.getBitsLength(this.data.length)};jD.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 Qun=ND,YSt={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,p,f,g,_,v;!o.empty();){c=o.pop(),d=c.value,h=c.cost,p=n[d]||{};for(u in p)p.hasOwnProperty(u)&&(f=p[u],g=h+f,_=l[u],v=typeof l[u]>"u",(v||_>g)&&(l[u]=g,o.push(u,g),i[u]=d))}if(typeof a<"u"&&typeof l[a]>"u"){var j=["Could not find a path from ",r," to ",a,"."].join("");throw new Error(j)}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})(YSt);var Xun=YSt.exports;(function(s){const t=fC,n=Vun,r=Gun,a=Kun,i=Qun,l=ij,o=Ey,c=Xun;function d(j){return unescape(encodeURIComponent(j)).length}function u(j,b,S){const A=[];let T;for(;(T=j.exec(S))!==null;)A.push({data:T[0],index:T.index,mode:b,length:T[0].length});return A}function h(j){const b=u(l.NUMERIC,t.NUMERIC,j),S=u(l.ALPHANUMERIC,t.ALPHANUMERIC,j);let A,T;return o.isKanjiModeEnabled()?(A=u(l.BYTE,t.BYTE,j),T=u(l.KANJI,t.KANJI,j)):(A=u(l.BYTE_KANJI,t.BYTE,j),T=[]),b.concat(S,A,T).sort(function(D,M){return D.index-M.index}).map(function(D){return{data:D.data,mode:D.mode,length:D.length}})}function p(j,b){switch(b){case t.NUMERIC:return n.getBitsLength(j);case t.ALPHANUMERIC:return r.getBitsLength(j);case t.KANJI:return i.getBitsLength(j);case t.BYTE:return a.getBitsLength(j)}}function f(j){return j.reduce(function(b,S){const A=b.length-1>=0?b[b.length-1]:null;return A&&A.mode===S.mode?(b[b.length-1].data+=S.data,b):(b.push(S),b)},[])}function g(j){const b=[];for(let S=0;S=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 ohn(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 Eke(s,t,n){const r=s.size,a=rhn.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 dhn(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 uhn(s,t,n){const r=new Jun;n.forEach(function(c){r.put(c.mode.bit,4),r.put(c.getLength(),ahn.getCharCountIndicator(c.mode,s)),c.write(r)});const a=gbe.getSymbolTotalCodewords(s),i=sEe.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&&chn(c,t),dhn(c,l),isNaN(r)&&(r=tEe.getBestMask(c,Eke.bind(null,c,n))),tEe.applyMask(r,c),Eke(c,n,r),{modules:c,version:t,errorCorrectionLevel:n,maskPattern:r,segments:a}}OSt.create=function(t,n){if(typeof t>"u"||t==="")throw new Error("No input text");let r=Cke.M,a,i;return typeof n<"u"&&(r=Cke.from(n.errorCorrectionLevel,Cke.M),a=l0e.from(n.version),i=tEe.from(n.maskPattern),n.toSJISFunc&&gbe.setToSJISFunction(n.toSJISFunc)),mhn(t,a,r,i)};var ZSt={},gDe={};(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 p=0;p=u&&f>=u&&p"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"),p=h.createImageData(u,u);return t.qrToImageData(p.data,i,c),n(h,d,u),h.putImageData(p,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)}})(ZSt);var QSt={};const phn=gDe;function Oet(s,t){const n=s.a/255,r=t+'="'+s.hex+'"';return n<1?r+" "+t+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function Ake(s,t,n){let r=s+t;return typeof n<"u"&&(r+=" "+n),r}function fhn(s,t,n){let r="",a=0,i=!1,l=0;for(let o=0;o0&&c>0&&s[o-1]||(r+=i?Ake("M",c+n,.5+d+n):Ake("m",a,0),a=0,i=!1),c+1':"",d="',u='viewBox="0 0 '+o+" "+o+'"',p=''+c+d+` `;return typeof r=="function"&&r(null,p),p};const xhn=Mun,nEe=OSt,XSt=ZSt,ghn=QSt;function yDe(s,t,n,r,a){const i=[].slice.call(arguments,1),l=i.length,o=typeof i[l-1]=="function";if(!o&&!xhn())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=nEe.create(n,r);c(s(u,t,r))}catch(u){d(u)}})}try{const c=nEe.create(n,r);a(null,s(c,t,r))}catch(c){a(c)}}JU.create=nEe.create;JU.toCanvas=yDe.bind(null,XSt.render);JU.toDataURL=yDe.bind(null,XSt.renderToDataURL);JU.toString=yDe.bind(null,function(s,t,n){return ghn.render(s,n)});function yhn(){const{eventId:s}=bi(),t=Mn(),{data:n}=hDe(s),{data:r=[]}=NSt(s),a=TSt(),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),f=n!=null&&n.public_slug?mbe(n.public_slug):"";N.useEffect(()=>{f&&JU.toDataURL(f,{width:320,margin:1}).then(p).catch(()=>{})},[f]);const g=N.useMemo(()=>i?r.filter(j=>(j.guest_name||"").toLowerCase().includes(i.toLowerCase())||(j.guest_email||"").toLowerCase().includes(i.toLowerCase())):r,[r,i]),_=j=>{a.mutate({id:j.id,event_id:s,status:"attended",checked_in_at:new Date().toISOString()}),ae.success(`${j.guest_name||"Guest"} checked in`)},v=()=>{o&&(a.mutate({event_id:s,guest_name:o,guest_email:d||null,status:"attended",checked_in_at:new Date().toISOString(),invitation_source:"walk_in"}),c(""),u(""),ae.success("Walk-in checked in"))};return n?e.jsx("div",{className:"min-h-screen bg-slate-50",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 md:p-6",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"rounded-full mb-3",onClick:()=>t(`/attract/events/${s}`),children:[e.jsx(Hr,{className:"h-4 w-4 mr-2"})," Back to event"]}),e.jsxs(fe,{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(fe,{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(oy,{className:"h-4 w-4"})," Registration QR"]}),h?e.jsx("img",{src:h,alt:"QR code",className:"mx-auto mt-3 h-56 w-56"}):e.jsx("div",{className:"text-[12px] text-slate-400 mt-3",children:"Publish this event to generate a QR code."}),f&&e.jsx("div",{className:"text-[11px] font-mono text-center text-slate-500 mt-2 break-all",children:f})]}),e.jsxs(fe,{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:j=>c(j.target.value)}),e.jsx(ye,{placeholder:"Email (optional)",value:d,onChange:j=>u(j.target.value)}),e.jsxs(B,{className:"w-full rounded-full",onClick:v,children:[e.jsx(Fo,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]})]}),e.jsxs(fe,{className:"mt-4 rounded-2xl border-slate-200 bg-white overflow-hidden",children:[e.jsxs("div",{className:"p-3 border-b border-slate-100 relative",children:[e.jsx(vr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{placeholder:"Search attendees",value:i,onChange:j=>l(j.target.value),className:"pl-9 rounded-full border-slate-200"})]}),g.length===0?e.jsx("div",{className:"p-8 text-center text-slate-400 text-[13px]",children:"No matches."}):e.jsx("div",{className:"divide-y divide-slate-100 max-h-[60vh] overflow-auto",children:g.map(j=>{const b=j.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:j.guest_name||j.guest_email}),e.jsx("div",{className:"text-[12px] text-slate-500 truncate",children:j.guest_email})]}),b?e.jsxs(ze,{className:"bg-emerald-500",children:[e.jsx(Ir,{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:()=>_(j),children:[e.jsx(Ir,{className:"h-5 w-5 mr-2"})," Check in"]})]},j.id)})})]})]})}):e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"})}const vhn=["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"],bhn=["Lead generation","Database marketing","Listing marketing","Social media/video","Open houses","Negotiation","Systems and technology","Team building","Leadership","New construction","Luxury","Business planning"],Fet=[{key:"produce",icon:vo,title:"Produce",blurb:"Attract through visible production and excellence.",example:"Publish weekly market updates, share every closing story with the lesson attached."},{key:"influence",icon:un,title:"Influence",blurb:"Teach publicly and earn a following of agents.",example:"Host a monthly masterclass. Post 3 authority pieces a week."},{key:"provide",icon:EA,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:hb,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:eN,title:"Balanced Plan",blurb:"A little of all four. Best for veteran attractors.",example:"Rotate weekly focus between production, teaching, providing, and connecting."}],_hn=[{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"}],zet=["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 Bet(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 whn(){const s=Mn(),{settings:t,save:n}=QU(),[r,a]=N.useState(0),[i,l]=N.useState([]),[o,c]=N.useState([]),[d,u]=N.useState(null),[h,p]=N.useState({}),[f,g]=N.useState("");N.useEffect(()=>{var S,A;t&&((S=t.audiences)!=null&&S.length&&l(t.audiences),(A=t.teachables)!=null&&A.length&&c(t.teachables),t.attraction_style&&u(t.attraction_style),t.activity_baseline&&p(t.activity_baseline),t.ninety_day_outcome&&g(t.ninety_day_outcome))},[t==null?void 0:t.user_id]);const _=["Welcome","Audience","Teach","Style","Baseline","Outcome","Plan"],v=N.useMemo(()=>r===1?i.length>0:r===2?o.length>0:r===3?!!d:r===5?!!f:!0,[r,i,o,d,f]),j=(S,A,T)=>{T(S.includes(A)?S.filter(L=>L!==A):[...S,A])},b=async()=>{if(!d)return;const S=Bet({style:d,baseline:h,outcome:f});await n.mutateAsync({audiences:i,teachables:o,attraction_style:d,activity_baseline:h,ninety_day_outcome:f,ninety_day_plan:S,primary_pillar:d,onboarding_completed_at:new Date().toISOString()}),ae.success("Your 90-day plan is ready."),s("/attract")};return e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("div",{className:"flex items-center gap-2 mb-8",children:_.map((S,A)=>e.jsx("div",{className:Et("h-1.5 flex-1 rounded-full transition-colors",A<=r?"bg-violet-600":"bg-slate-200")},S))}),e.jsx(Eye,{mode:"wait",children:e.jsxs(Yn.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:Fet.filter(S=>S.key!=="balanced").map(S=>e.jsxs(fe,{className:"p-4 rounded-2xl border-slate-200",children:[e.jsx(S.icon,{className:"h-5 w-5 text-violet-600 mb-2"}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:S.title}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:S.blurb})]},S.key))})]}),r===1&&e.jsx(QF,{icon:Nn,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:vhn.map(S=>e.jsx(Mke,{label:S,active:i.includes(S),onClick:()=>j(i,S,l)},S))})}),r===2&&e.jsx(QF,{icon:_d,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:bhn.map(S=>e.jsx(Mke,{label:S,active:o.includes(S),onClick:()=>j(o,S,c)},S))})}),r===3&&e.jsx(QF,{icon:eN,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:Fet.map(S=>e.jsx(fe,{onClick:()=>u(S.key),className:Et("p-5 rounded-2xl cursor-pointer transition-all border-2",d===S.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(S.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:S.title}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:S.blurb}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 italic mt-2",children:["Example: ",S.example]})]}),d===S.key&&e.jsx(Ir,{className:"h-5 w-5 text-violet-600"})]})},S.key))})}),r===4&&e.jsx(QF,{icon:nm,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:_hn.map(S=>e.jsxs("div",{children:[e.jsx(se,{className:"text-[12.5px] text-slate-700",children:S.label}),e.jsx(ye,{type:"number",min:0,value:h[S.key]??"",onChange:A=>p({...h,[S.key]:Number(A.target.value)||0})})]},S.key))})}),r===5&&e.jsx(QF,{icon:Oc,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:[zet.map(S=>e.jsx(Mke,{label:S,active:f===S,onClick:()=>g(S),full:!0},S)),e.jsxs("div",{className:"mt-3",children:[e.jsx(se,{className:"text-[12.5px] text-slate-700",children:"Or write your own"}),e.jsx(Es,{rows:2,placeholder:"A specific outcome you can measure in 90 days...",value:zet.includes(f)?"":f,onChange:S=>g(S.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(JSt,{plan:Bet({style:d,baseline:h,outcome:f})})]})]},r)}),e.jsxs("div",{className:"mt-10 flex items-center justify-between",children:[e.jsxs(B,{variant:"ghost",onClick:()=>r===0?s("/attract"):a(r-1),children:[e.jsx(Hr,{className:"h-4 w-4 mr-1"})," ",r===0?"Skip for now":"Back"]}),r<6?e.jsxs(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full px-6",disabled:!v,onClick:()=>a(r+1),children:["Continue ",e.jsx(Oa,{className:"h-4 w-4 ml-1"})]}):e.jsxs(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full px-6",onClick:b,disabled:n.isPending,children:[e.jsx(sx,{className:"h-4 w-4 mr-1.5"})," Activate my 90-day plan"]})]})]})}function QF({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 Mke({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(Ir,{className:"h-4 w-4 text-violet-600"})," ",s]})})}function JSt({plan:s}){return e.jsxs("div",{className:"mt-6 space-y-6",children:[e.jsxs(fe,{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(fe,{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(fe,{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(fe,{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(fe,{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 jhn(){const{settings:s,resetOnboarding:t}=QU(),n=s==null?void 0:s.ninety_day_plan;return e.jsxs("div",{className:"max-w-4xl",children:[e.jsx(Vu,{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(cm,{className:"h-4 w-4 mr-1.5"})," Rerun onboarding"]})}),n?e.jsx(JSt,{plan:n}):e.jsxs(fe,{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(Ln,{to:"/attract/onboarding",children:"Start onboarding"})})]})]})}async function $et(s,t,n,r={}){await q.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 e4t(){const{user:s}=ys(),t=Ht(),n=ct({queryKey:["attract-transactions",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_transactions").select("*").order("closing_date",{ascending:!1,nullsFirst:!1});if(c)throw c;return o??[]}}),r=gt({mutationFn:async o=>{const c=[o.rating_communication,o.rating_professionalism,o.rating_problem_solving].filter(g=>typeof g=="number"),d=c.length?Number((c.reduce((g,_)=>g+_,0)/c.length).toFixed(2)):null,u={...o,user_id:s.id,overall_rating:d},{data:h,error:p}=o.id?await q.from("attract_transactions").update(u).eq("id",o.id).select().single():await q.from("attract_transactions").insert(u).select().single();if(p)throw p;const f=h;return o.id||await $et(s.id,"transaction_logged",`Reviewed ${f.property_address}`,{description:f.cooperating_first_name?`Cooperating agent: ${f.cooperating_first_name} ${f.cooperating_last_name??""}`:null,pillar:"produce",metadata:{transaction_id:f.id,overall_rating:d}}),f},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),t.invalidateQueries({queryKey:["attract-activities"]}),ae.success("Transaction saved")},onError:o=>ae.error(o.message)}),a=gt({mutationFn:async({id:o,decision:c,notes:d})=>{const{data:u,error:h}=await q.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=gt({mutationFn:async o=>{let c=o.attract_agent_id;if(!c){const{data:d}=await q.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 q.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 q.from("attract_transactions").update({attract_agent_id:c,decision:"add_pipeline"}).eq("id",o.id),await $et(s.id,"agent_added_from_transaction",`Added ${o.cooperating_first_name??"agent"} to pipeline`,{pillar:"produce",agent_id:c,metadata:{transaction_id:o.id}}),c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),t.invalidateQueries({queryKey:["attract-agents"]}),t.invalidateQueries({queryKey:["attract-activities"]}),ae.success("Added to Agent Pipeline")},onError:o=>ae.error(o.message)}),l=gt({mutationFn:async o=>{const{error:c}=await q.from("attract_transactions").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),ae.success("Transaction removed")}});return{transactions:n.data??[],isLoading:n.isLoading,upsert:r,setDecision:a,addToPipeline:i,remove:l}}function Nhn({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(ca,{className:Et("h-5 w-5",(s??0)>=n?"fill-amber-400 text-amber-400":"text-slate-300")})},n))})}function khn(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 Shn={1:"Poor",2:"Fair",3:"OK",4:"Good",5:"Excellent"},Ike={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 Chn(){const{transactions:s,isLoading:t,upsert:n,setDecision:r,addToPipeline:a,remove:i}=e4t(),[l,o]=N.useState(""),[c,d]=N.useState(!1),[u,h]=N.useState(null),[p,f]=N.useState(null),g=N.useMemo(()=>{const v=l.trim().toLowerCase();return v?s.filter(j=>[j.property_address,j.cooperating_first_name,j.cooperating_last_name,j.cooperating_brokerage,j.city].filter(Boolean).some(b=>String(b).toLowerCase().includes(v))):s},[s,l]),_=N.useMemo(()=>{const v=s.length,j=s.filter(A=>A.enjoy_business_with==="yes").length,b=s.filter(A=>A.decision==="add_pipeline").length,S=s.filter(A=>A.follow_up_created).length;return{reviewed:v,highFit:j,inPipeline:b,followUps:S}},[s]);return e.jsxs("div",{children:[e.jsxs(Ln,{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(Hr,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Vu,{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(Is,{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(tW,{label:"Transactions reviewed",value:_.reviewed}),e.jsx(tW,{label:"High-fit agents",value:_.highFit,tone:"emerald"}),e.jsx(tW,{label:"Added to pipeline",value:_.inPipeline,tone:"violet"}),e.jsx(tW,{label:"Follow-ups created",value:_.followUps,tone:"amber"})]}),e.jsx("div",{className:"flex items-center gap-3 mb-4",children:e.jsxs("div",{className:"relative flex-1 max-w-md",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{value:l,onChange:v=>o(v.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(v=>e.jsx(fe,{className:"p-5 rounded-2xl h-24 animate-pulse bg-slate-100"},v))}):g.length===0?e.jsxs(fe,{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(un,{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(Is,{className:"h-4 w-4 mr-1.5"})," Add your first transaction"]})]}):e.jsx("div",{className:"space-y-3",children:g.map(v=>{var j,b;return e.jsx(fe,{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:v.property_address}),v.closing_date&&e.jsx(ze,{variant:"outline",className:"text-[10.5px]",children:Ss(new Date(v.closing_date),"MMM d, yyyy")}),e.jsx(ze,{className:Et("text-[10.5px] border-0",((j=Ike[v.decision])==null?void 0:j.color)??Ike.pending.color),children:((b=Ike[v.decision])==null?void 0:b.label)??"Needs review"})]}),e.jsxs("div",{className:"text-[12.5px] text-slate-600 mt-1",children:[v.cooperating_first_name||v.cooperating_last_name?`${v.cooperating_first_name??""} ${v.cooperating_last_name??""}`:"Cooperating agent",v.cooperating_brokerage?` · ${v.cooperating_brokerage}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-[12px] text-slate-600",children:[v.overall_rating!=null&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ca,{className:"h-3.5 w-3.5 fill-amber-400 text-amber-400"})," ",v.overall_rating]}),v.enjoy_business_with&&e.jsxs("span",{className:"capitalize",children:["Fit: ",e.jsx("span",{className:Et("font-medium",v.enjoy_business_with==="yes"?"text-emerald-700":v.enjoy_business_with==="maybe"?"text-amber-700":"text-slate-600"),children:v.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(v),children:["Review ",e.jsx(xa,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>f(v),children:[e.jsx(uL,{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(v.id),children:"Remove"})]})]})},v.id)})}),e.jsx("div",{className:"mt-8",children:e.jsx(m6,{})}),e.jsx(Thn,{open:c,onClose:()=>d(!1),onSaved:v=>{d(!1),h(v)},upsert:n}),e.jsx(Ehn,{tx:u,onClose:()=>h(null),onDecision:v=>u&&r.mutate({id:u.id,decision:v}),onAddToPipeline:()=>u&&a.mutate(u),onMessage:()=>{f(u),h(null)}}),e.jsx(Ahn,{tx:p,onClose:()=>f(null)})]})}function tW({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(fe,{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 Thn({open:s,onClose:t,onSaved:n,upsert:r}){const[a,i]=N.useState({enjoy_business_with:"maybe"}),l=c=>i({...a,...c}),o=async()=>{var d;if(!((d=a.property_address)!=null&&d.trim())){ae.error("Property address is required");return}const c=await r.mutateAsync(a);i({enjoy_business_with:"maybe"}),n(c)};return e.jsx(bs,{open:s,onOpenChange:c=>!c&&t(),children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Add Transaction"}),e.jsx(Qn,{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(ds,{value:a.represented??"",onValueChange:c=>l({represented:c}),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Buyer or seller"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"buyer",children:"Buyer"}),e.jsx(Qe,{value:"seller",children:"Seller"}),e.jsx(Qe,{value:"both",children:"Both"}),e.jsx(Qe,{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(Nhn,{value:a[c],onChange:u=>l({[c]:u})}),e.jsx("div",{className:"text-[11px] text-slate-500 mt-1",children:Shn[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(Es,{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(Es,{rows:2,value:a.private_notes??"",onChange:c=>l({private_notes:c.target.value}),placeholder:"Only you can see these."})]})]})]}),e.jsxs(Xn,{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 Ehn({tx:s,onClose:t,onDecision:n,onAddToPipeline:r,onMessage:a}){return s?e.jsx(bs,{open:!!s,onOpenChange:i=>!i&&t(),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Would you like to build a relationship?"}),e.jsxs(Qn,{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(XF,{icon:Fo,label:"Add to Agent Pipeline",tone:"violet",onClick:r}),e.jsx(XF,{icon:uL,label:"Send a professional compliment",tone:"teal",onClick:()=>{n("send_compliment"),a()}}),e.jsx(XF,{icon:ny,label:"Invite to coffee",tone:"amber",onClick:()=>{n("invite_coffee"),a()}}),e.jsx(XF,{icon:un,label:"Share a relevant resource",tone:"sky",onClick:()=>n("share_resource")}),e.jsx(XF,{icon:Hc,label:"No action right now",tone:"slate",onClick:()=>{n("no_action"),t()}})]})]})}):null}function XF({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(xa,{className:"h-4 w-4 opacity-60"})]})}function Ahn({tx:s,onClose:t}){const[n,r]=N.useState("warm");if(!s)return null;const a=khn(s,n);return e.jsx(bs,{open:!!s,onOpenChange:i=>!i&&t(),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Personalized message"}),e.jsx(Qn,{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(Es,{value:a,readOnly:!0,rows:10,className:"font-mono text-[12.5px]"}),e.jsxs(Xn,{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),ae.success("Copied to clipboard")},children:[e.jsx(Xr,{className:"h-4 w-4 mr-1.5"})," Copy"]})]})]})})}function t4t(){const{user:s}=ys(),t=Ht(),n=ct({queryKey:["attract-content",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_content_drafts").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=gt({mutationFn:async o=>{const{data:c,error:d}=await q.functions.invoke("attract-content-generate",{body:o});if(d)throw d;if(c!=null&&c.error)throw new Error(c.error);return c},onSuccess:o=>{t.invalidateQueries({queryKey:["attract-content"]}),o.demo?ae.info("Demo generation used — configure AI provider for live results"):ae.success("Content generated")},onError:o=>ae.error(o.message)}),a=gt({mutationFn:async o=>{const{data:c,error:d}=await q.from("attract_content_drafts").update(o).eq("id",o.id).select().single();if(d)throw d;return c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),ae.success("Saved")}}),i=gt({mutationFn:async o=>{const{error:c}=await q.from("attract_content_drafts").update({status:"posted",posted_at:new Date().toISOString()}).eq("id",o);if(c)throw c;await q.rpc("award_attract_activity",{_user_id:s.id,_activity_type:"content_posted",_title:"Posted authority content",_description:null,_pillar:"influence",_agent_id:null,_metadata:{draft_id:o},_dedupe_minutes:30})},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),t.invalidateQueries({queryKey:["attract-activities"]}),ae.success("Marked as posted")}}),l=gt({mutationFn:async o=>{const{error:c}=await q.from("attract_content_drafts").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),ae.success("Draft removed")}});return{drafts:n.data??[],isLoading:n.isLoading,generate:r,save:a,markPosted:i,remove:l}}const rEe=[{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"}]}],Mhn=["Direct","Educational","Fun","Contrarian","Encouraging"],Ihn=["short","medium","long"],Phn=["instagram","linkedin","facebook","youtube","email"],c0e={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 Lhn(){const{drafts:s,isLoading:t,generate:n,save:r,markPosted:a,remove:i}=t4t(),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=N.useMemo(()=>({ready:s.filter(h=>h.status==="ready"),draft:s.filter(h=>h.status==="draft"),idea:s.filter(h=>h.status==="idea"),posted:s.filter(h=>h.status==="posted")}),[s]);return e.jsxs("div",{children:[e.jsxs(Ln,{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(Hr,{className:"h-3.5 w-3.5"})," Back to Influence"]}),e.jsx(Vu,{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(Dm,{className:"h-4 w-4 mr-1.5"})," New Content"]})}),e.jsxs("div",{className:"mb-6 rounded-2xl border border-amber-200 bg-amber-50/70 px-5 py-3.5 text-[13px] text-amber-900 flex items-start gap-3",children:[e.jsx(un,{className:"h-4 w-4 mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"80/20 rule:"})," Aim for 80% useful industry, business, and personal content — and no more than 20% direct brokerage content."]})]}),e.jsxs(Br,{defaultValue:"all",className:"mb-8",children:[e.jsxs(Fr,{children:[e.jsxs(Kt,{value:"all",children:["All (",s.length,")"]}),e.jsxs(Kt,{value:"ready",children:["Ready (",u.ready.length,")"]}),e.jsxs(Kt,{value:"draft",children:["Draft (",u.draft.length,")"]}),e.jsxs(Kt,{value:"posted",children:["Posted (",u.posted.length,")"]})]}),e.jsx(is,{value:"all",children:e.jsx(sW,{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(is,{value:"ready",children:e.jsx(sW,{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(is,{value:"draft",children:e.jsx(sW,{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(is,{value:"posted",children:e.jsx(sW,{drafts:u.posted,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:()=>{},onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})})]}),e.jsx(m6,{}),e.jsx(Dhn,{open:l,editing:c,onClose:()=>{o(!1),d(null)},generate:n,save:r,markPosted:h=>a.mutate(h)})]})}function sW({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(fe,{className:"p-5 rounded-2xl h-24 animate-pulse bg-slate-100"},l))}):s.length===0?e.jsxs(fe,{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(sb,{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(Is,{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=rEe.find(u=>u.key===l.mode))==null?void 0:c.label)??l.mode;return e.jsx(fe,{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(ze,{className:Et("text-[10.5px] border-0",c0e[l.status].color),children:c0e[l.status].label}),e.jsx(ze,{variant:"outline",className:"text-[10.5px]",children:o}),l.tone&&e.jsx(ze,{variant:"outline",className:"text-[10.5px]",children:l.tone}),l.ratio_flag&&e.jsxs(ze,{className:"text-[10.5px] bg-amber-100 text-amber-900 border-0 gap-1",children:[e.jsx($l,{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 ${Ss(new Date(l.posted_at),"MMM d")}`:`Updated ${Ss(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(Ir,{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(_n,{className:"h-3.5 w-3.5"})})]})]})},l.id)})})}function Dhn({open:s,editing:t,onClose:n,generate:r,save:a,markPosted:i}){const[l,o]=N.useState((t==null?void 0:t.mode)??"transaction_lesson"),[c,d]=N.useState((t==null?void 0:t.input_json)??{}),[u,h]=N.useState((t==null?void 0:t.topic)??""),[p,f]=N.useState((t==null?void 0:t.tone)??"Educational"),[g,_]=N.useState((t==null?void 0:t.length)??"medium"),[v,j]=N.useState((t==null?void 0:t.platforms)??["instagram"]),[b,S]=N.useState((t==null?void 0:t.include_brokerage_reference)??!1),[A,T]=N.useState(t??null),[L,D]=N.useState(""),[M,F]=N.useState((t==null?void 0:t.status)??"draft"),z=rEe.find(Y=>Y.key===l),V=async Y=>{const K=await r.mutateAsync({mode:l,topic:u,inputs:c,tone:p,length:g,platforms:v,include_brokerage_reference:b,refinement:Y??L,draft_id:A==null?void 0:A.id});K!=null&&K.draft&&T(K.draft),D("")},W=async Y=>{if(!A)return;const K=await a.mutateAsync({id:A.id,...Y});T(K)};return e.jsx(bs,{open:s,onOpenChange:Y=>!Y&&n(),children:e.jsx(vs,{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(ws,{children:[e.jsx(_s,{className:"text-base",children:"Content Studio"}),e.jsx(Qn,{className:"text-[12px]",children:z.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(ds,{value:l,onValueChange:Y=>{o(Y),d({})},children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:rEe.map(Y=>e.jsx(Qe,{value:Y.key,children:Y.label},Y.key))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:"Topic (optional)"}),e.jsx(ye,{value:u,onChange:Y=>h(Y.target.value),placeholder:"1-line summary"})]}),z.fields.map(Y=>e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:Y.label}),e.jsx(Es,{rows:2,value:c[Y.key]??"",onChange:K=>d({...c,[Y.key]:K.target.value}),placeholder:Y.placeholder})]},Y.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(ds,{value:p,onValueChange:f,children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:Mhn.map(Y=>e.jsx(Qe,{value:Y,children:Y},Y))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:"Length"}),e.jsxs(ds,{value:g,onValueChange:_,children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:Ihn.map(Y=>e.jsx(Qe,{value:Y,children:Y},Y))})]})]})]}),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:Phn.map(Y=>e.jsx("button",{type:"button",onClick:()=>j(v.includes(Y)?v.filter(K=>K!==Y):[...v,Y]),className:Et("rounded-full px-2.5 py-1 text-[11px] capitalize border",v.includes(Y)?"bg-violet-600 text-white border-violet-600":"bg-white border-slate-200 text-slate-700"),children:Y},Y))})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-700",children:[e.jsx("input",{type:"checkbox",checked:b,onChange:Y=>S(Y.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:()=>V(),disabled:r.isPending,children:[e.jsx(Dm,{className:"h-4 w-4 mr-1.5"})," ",r.isPending?"Generating…":A?"Regenerate":"Generate content"]})]})]}),e.jsx("div",{className:"overflow-y-auto p-6",children:A?e.jsxs("div",{className:"space-y-5",children:[A.ratio_flag&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-[12.5px] text-amber-900 flex items-start gap-2",children:[e.jsx($l,{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:()=>V("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(ze,{className:Et("text-[10.5px] border-0",c0e[M].color),children:c0e[M].label}),e.jsxs(ds,{value:M,onValueChange:Y=>{F(Y),W({status:Y})},children:[e.jsx(ls,{className:"h-8 w-32 text-[12px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"idea",children:"Idea"}),e.jsx(Qe,{value:"draft",children:"Draft"}),e.jsx(Qe,{value:"ready",children:"Ready"}),e.jsx(Qe,{value:"posted",children:"Posted"})]})]}),e.jsx(ye,{type:"date",className:"h-8 w-40 text-[12px]",value:A.planned_at?A.planned_at.slice(0,10):"",onChange:Y=>W({planned_at:Y.target.value?new Date(Y.target.value).toISOString():null})}),A.status!=="posted"&&e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>i(A.id),children:[e.jsx(cr,{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(Ln,{to:`/attract/provide/kits/new?seed=${encodeURIComponent(A.topic||A.mode)}`,children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Turn into a kit"]})})]}),e.jsx(XI,{title:"Hook options",children:e.jsx("div",{className:"space-y-1.5",children:(A.hook_options??[]).map((Y,K)=>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:[K+1,"."]}),e.jsx("span",{className:"flex-1",children:Y}),e.jsx(aEe,{value:Y})]},K))})}),e.jsx(XI,{title:"Teleprompter script",children:e.jsx(Pke,{value:A.script??"",onSave:Y=>W({script:Y})})}),e.jsx(XI,{title:"Social caption",children:e.jsx(Pke,{value:A.caption??"",onSave:Y=>W({caption:Y})})}),e.jsx(XI,{title:"Carousel outline",children:e.jsx("div",{className:"space-y-1.5",children:(A.carousel_outline??[]).map((Y,K)=>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 ",Y.slide??K+1]}),e.jsx("div",{className:"text-slate-800 mt-0.5",children:Y.text})]},K))})}),e.jsx(XI,{title:"Email lesson",children:e.jsx(Pke,{value:A.email_lesson??"",onSave:Y=>W({email_lesson:Y})})}),e.jsx(XI,{title:"CTA options",children:e.jsx("div",{className:"space-y-1.5",children:(A.cta_options??[]).map((Y,K)=>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:Y}),e.jsx(aEe,{value:Y})]},K))})}),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(Y=>e.jsx(B,{size:"sm",variant:"outline",className:"text-[11.5px]",onClick:()=>V(Y),children:Y},Y))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:L,onChange:Y=>D(Y.target.value),placeholder:"Custom refinement…"}),e.jsxs(B,{variant:"outline",onClick:()=>V(),disabled:r.isPending,children:[e.jsx(Ti,{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(k9,{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 XI({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(yr,{className:"h-3 w-3 opacity-0"})," ",s]}),t]})}function Pke({value:s,onSave:t}){const[n,r]=N.useState(s);return e.jsxs("div",{children:[e.jsx(Es,{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(aEe,{value:n})]})]})}function aEe({value:s}){return e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(s),ae.success("Copied")},children:e.jsx(Xr,{className:"h-3.5 w-3.5"})})}const Rhn={draft:"bg-slate-100 text-slate-700",published:"bg-emerald-100 text-emerald-800",archived:"bg-amber-100 text-amber-800"};function Ohn(){const{kits:s,isLoading:t,create:n,duplicate:r,remove:a}=FR(),i=Mn(),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(Vu,{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(Ln,{to:"/attract/provide/kits/templates",children:[e.jsx(Hg,{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(Is,{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(fe,{className:"p-10 text-center rounded-2xl border-dashed border-slate-300 bg-white",children:[e.jsx(un,{className:"h-8 w-8 mx-auto text-violet-500"}),e.jsx("div",{className:"mt-3 text-lg font-semibold",children:"You haven't built a kit yet."}),e.jsx("p",{className:"text-slate-600 max-w-md mx-auto mt-1 text-sm",children:"Start from a starter template or a blank kit. Bundle 3–7 pieces of real value and share with agents you'd love to work alongside."}),e.jsxs("div",{className:"flex gap-2 justify-center mt-5",children:[e.jsx(B,{variant:"outline",asChild:!0,children:e.jsx(Ln,{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(fe,{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(ze,{className:Rhn[o.status]+" capitalize",children:o.status}),o.pillar&&e.jsx(ze,{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(ze,{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(Ln,{to:`/attract/provide/kits/${o.id}/edit`,children:[e.jsx(x9,{className:"h-3.5 w-3.5 mr-1.5"}),"Edit"]})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(Ln,{to:`/attract/provide/kits/${o.id}/analytics`,children:[e.jsx(yo,{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);ae.success("Duplicated"),i(`/attract/provide/kits/${d}/edit`)},children:e.jsx(Xr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{confirm("Delete this kit? Shares and events will also be removed.")&&a.mutate(o.id,{onSuccess:()=>ae.success("Deleted")})},children:e.jsx(_n,{className:"h-3.5 w-3.5 text-rose-600"})})]})]},o.id)})})]})}const Fhn={pdf:Nr,video:Al,link:Jo,checklist:uu,template:bw,text:Nr,content_studio:un,resource:Nr};function s4t({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(fe,{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:zhn(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=Fhn[o.type]??Nr;return e.jsx(fe,{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,p)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-violet-400",children:"•"}),h]},p))}),(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(Pa,{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 zhn(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 Bhn=[{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 Uet(){var Y,K;const{kitId:s}=bi(),[t]=gl(),n=Mn(),{user:r}=ys(),a=s===void 0,{create:i,update:l}=FR(),{data:o,isLoading:c}=PSt(s),{items:d,add:u,update:h,remove:p,reorder:f}=vun(s),{shares:g,create:_,revoke:v}=LSt(s),{agents:j}=c0(),[b,S]=N.useState(null),[A,T]=N.useState("desktop"),[L,D]=N.useState("idle"),M=N.useRef(null);N.useEffect(()=>{a&&!b&&(async()=>{const J=t.get("seed"),ne=await i.mutateAsync({title:J?`From: ${J}`:"Untitled Kit",status:"draft"});n(`/attract/provide/kits/${ne.id}/edit`,{replace:!0})})()},[a]),N.useEffect(()=>{o&&S(o)},[o==null?void 0:o.id]);const F=J=>{s&&(S(ne=>({...ne,...J})),D("saving"),clearTimeout(M.current),M.current=setTimeout(async()=>{try{await l.mutateAsync({id:s,patch:J}),D("saved"),setTimeout(()=>D("idle"),1500)}catch(ne){ae.error(ne.message??"Save failed"),D("idle")}},800))},z=async J=>{!s||!r||await u.mutateAsync({user_id:r.id,type:J,title:`New ${J.replace("_"," ")}`})},V=(J,ne)=>{const ie=[...d],he=J+ne;he<0||he>=ie.length||([ie[J],ie[he]]=[ie[he],ie[J]],f.mutate(ie.map(ce=>ce.id)))},W=g.filter(J=>J.status==="active");return a||!b?e.jsx("div",{className:"text-slate-500 text-sm",children:"Preparing your kit…"}):c?e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading…"}):e.jsxs("div",{children:[e.jsx(Vu,{eyebrow:"Provide · Kit builder",title:b.title||"Untitled Kit",description:L==="saving"?"Saving…":L==="saved"?"Saved":`Last edited ${Ss(new Date(b.updated_at),"MMM d, h:mm a")}`,actions:e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsxs(Ln,{to:"/attract/provide/kits",children:[e.jsx(Hr,{className:"h-4 w-4 mr-1"}),"Kits"]})}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsx(Ln,{to:`/attract/provide/kits/${s}/analytics`,children:"Analytics"})}),e.jsxs(ds,{value:b.status,onValueChange:J=>F({status:J}),children:[e.jsx(ls,{className:"w-[130px] rounded-full",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"draft",children:"Draft"}),e.jsx(Qe,{value:"published",children:"Published"}),e.jsx(Qe,{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(fe,{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:b.title??"",onChange:J=>F({title:J.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Short description"}),e.jsx(Es,{rows:3,value:b.description??"",onChange:J=>F({description:J.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Cover image URL"}),e.jsx(ye,{placeholder:"https://…",value:b.cover_image_url??"",onChange:J=>F({cover_image_url:J.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:b.audience??"",onChange:J=>F({audience:J.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Pillar"}),e.jsxs(ds,{value:b.pillar??"",onValueChange:J=>F({pillar:J}),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Choose"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"produce",children:"Produce"}),e.jsx(Qe,{value:"influence",children:"Influence"}),e.jsx(Qe,{value:"provide",children:"Provide"}),e.jsx(Qe,{value:"connect",children:"Connect"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Tags (comma separated)"}),e.jsx(ye,{value:(b.tags??[]).join(", "),onChange:J=>F({tags:J.target.value.split(",").map(ne=>ne.trim()).filter(Boolean)})})]})]})]}),e.jsxs(fe,{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(Es,{rows:4,placeholder:"Write a short personal note that opens the kit.",value:b.intro_text??"",onChange:J=>F({intro_text:J.target.value})}),e.jsxs("div",{children:[e.jsx(se,{children:"Intro video URL (optional)"}),e.jsx(ye,{placeholder:"Loom/YouTube/Vimeo",value:b.intro_video_url??"",onChange:J=>F({intro_video_url:J.target.value})})]})]})]}),e.jsxs(fe,{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:b.cta_label??"",onChange:J=>F({cta_label:J.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Button URL"}),e.jsx(ye,{placeholder:"https://…",value:b.cta_url??"",onChange:J=>F({cta_url:J.target.value})})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(se,{children:"Expiration (optional)"}),e.jsx(ye,{type:"datetime-local",value:b.expires_at?b.expires_at.slice(0,16):"",onChange:J=>F({expires_at:J.target.value?new Date(J.target.value).toISOString():null})})]})]}),e.jsxs(fe,{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($hn,{kitId:s,agents:j,shares:W,onCreate:J=>_.mutate(J),onRevoke:J=>v.mutate(J),status:b.status})]})]}),e.jsx("div",{className:"xl:col-span-5 space-y-4",children:e.jsxs(fe,{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(ds,{onValueChange:J=>z(J),children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(us,{placeholder:"+ Add item"})}),e.jsx(cs,{children:Bhn.map(J=>e.jsx(Qe,{value:J.value,children:J.label},J.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((J,ne)=>{var ie,he;return e.jsx(fe,{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:()=>V(ne,-1),children:e.jsx(Ru,{className:"h-4 w-4"})}),e.jsx("button",{className:"text-slate-400 hover:text-slate-700",onClick:()=>V(ne,1),children:e.jsx(am,{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(ze,{variant:"outline",className:"capitalize",children:J.type.replace("_"," ")}),e.jsx(ye,{className:"flex-1",value:J.title,onChange:ce=>h.mutate({id:J.id,patch:{title:ce.target.value}})})]}),e.jsx(Es,{rows:2,placeholder:"Short description",value:J.description??"",onChange:ce=>h.mutate({id:J.id,patch:{description:ce.target.value}})}),["video","pdf","link","resource"].includes(J.type)&&e.jsx(ye,{placeholder:"URL",value:J.url??"",onChange:ce=>h.mutate({id:J.id,patch:{url:ce.target.value}})}),["text","template"].includes(J.type)&&e.jsx(Es,{rows:4,placeholder:"Body text or script",value:((ie=J.content)==null?void 0:ie.body)??"",onChange:ce=>h.mutate({id:J.id,patch:{content:{...J.content??{},body:ce.target.value}}})}),J.type==="checklist"&&e.jsx(Es,{rows:5,placeholder:"One item per line",value:(((he=J.content)==null?void 0:he.items)??[]).join(` `),onChange:ce=>h.mutate({id:J.id,patch:{content:{items:ce.target.value.split(` `).map(pe=>pe.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(bn,{checked:J.allow_download,onCheckedChange:ce=>h.mutate({id:J.id,patch:{allow_download:ce}})}),"Allow download"]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-600",children:[e.jsx(bn,{checked:!J.is_hidden,onCheckedChange:ce=>h.mutate({id:J.id,patch:{is_hidden:!ce}})}),"Visible"]}),e.jsxs("button",{className:"ml-auto text-rose-600 text-[12px] flex items-center gap-1",onClick:()=>p.mutate(J.id),children:[e.jsx(_n,{className:"h-3.5 w-3.5"}),"Delete"]})]})]})]})},J.id)})]})]})}),e.jsx("div",{className:"xl:col-span-3",children:e.jsxs(fe,{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(Br,{value:A,onValueChange:J=>T(J),children:e.jsxs(Fr,{className:"h-8",children:[e.jsx(Kt,{value:"desktop",className:"h-6 px-2",children:e.jsx(xb,{className:"h-3.5 w-3.5"})}),e.jsx(Kt,{value:"mobile",className:"h-6 px-2",children:e.jsx(ng,{className:"h-3.5 w-3.5"})})]})})]}),e.jsx("div",{className:A==="mobile"?"max-w-[320px] mx-auto":"",children:e.jsx(s4t,{kit:b,items:d,owner:{display_name:((Y=r==null?void 0:r.user_metadata)==null?void 0:Y.full_name)||(r==null?void 0:r.email)||"You",avatar_url:((K=r==null?void 0:r.user_metadata)==null?void 0:K.avatar_url)??null,brokerage:null},mode:"preview"})})]})})]})]})}function $hn({kitId:s,agents:t,shares:n,onCreate:r,onRevoke:a,status:i}){const[l,o]=N.useState("general"),[c,d]=N.useState("");return i!=="published"?e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-3",children:"Publish this kit to generate share links."}):e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[e.jsxs(ds,{value:l,onValueChange:u=>o(u),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Choose agent"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"general",children:"General share link"}),t.map(u=>e.jsxs(Qe,{value:u.id,children:[u.first_name," ",u.last_name??""]},u.id))]})]}),e.jsx(Es,{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(Hl,{className:"h-4 w-4 mr-2"}),"Create share link"]})]}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("div",{className:"text-[12px] text-slate-500",children:"No active links yet."}),n.map(u=>{var f;const h=RSt(u.share_token),p=u.agent_id?((f=t.find(g=>g.id===u.agent_id))==null?void 0:f.first_name)??"Agent":"General";return e.jsxs("div",{className:"border rounded-lg p-2.5 text-[12.5px]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium",children:p}),e.jsx(ze,{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),ae.success("Link copied")},children:[e.jsx(Xr,{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(XP,{className:"h-3.5 w-3.5 mr-1"}),"Revoke"]})]})]},u.id)})]})]})}const Uhn={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 qhn(){const{kitId:s}=bi(),{data:t}=PSt(s),{shares:n}=LSt(s),{data:r=[]}=DSt(s),a=N.useMemo(()=>{const l=d=>r.filter(u=>u.event_type===d).length,o=new Set(n.filter(d=>d.agent_id).map(d=>d.agent_id)).size,c=n.filter(d=>d.first_opened_at).length;return{shares:n.length,uniqueAgents:o,viewRate:n.length?Math.round(c/n.length*100):0,engaged:n.filter(d=>["engaged","high_intent"].includes(d.engagement_level)).length,downloads:l("file_download"),ctaClicks:l("primary_cta_click"),questions:l("question_submitted"),meetings:l("meeting_requested")}},[n,r]),i=N.useMemo(()=>{const l=new Map;return r.forEach(o=>{const c=Ss(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(Vu,{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(Ln,{to:`/attract/provide/kits/${s}/edit`,children:[e.jsx(Hr,{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(Lk,{label:"Shares",value:a.shares,icon:Er,tone:"violet"}),e.jsx(Lk,{label:"Unique agents",value:a.uniqueAgents,icon:Er,tone:"indigo"}),e.jsx(Lk,{label:"View rate",value:`${a.viewRate}%`,icon:Er,tone:"teal"}),e.jsx(Lk,{label:"Engaged",value:a.engaged,icon:oc,tone:"emerald"}),e.jsx(Lk,{label:"Downloads",value:a.downloads,icon:Pa,tone:"orange"}),e.jsx(Lk,{label:"CTA clicks",value:a.ctaClicks,icon:oc,tone:"rose"}),e.jsx(Lk,{label:"Questions",value:a.questions,icon:Ql,tone:"violet"}),e.jsx(Lk,{label:"Meetings",value:a.meetings,icon:om,tone:"indigo"})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs(fe,{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(kw,{width:"100%",height:"100%",children:e.jsxs(uLe,{data:i,children:[e.jsx(cLe,{strokeDasharray:"3 3",stroke:"#eee"}),e.jsx(zw,{dataKey:"date",fontSize:11}),e.jsx(Bw,{fontSize:11,allowDecimals:!1}),e.jsx(Np,{}),e.jsx(r6,{type:"monotone",dataKey:"count",stroke:"#7c3aed",strokeWidth:2})]})})})]}),e.jsxs(fe,{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(Uhn).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(fe,{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 ",Ss(new Date(l.created_at),"MMM d")," · ",l.open_count," opens",l.last_opened_at&&` · last opened ${Ss(new Date(l.last_opened_at),"MMM d")}`]})]}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:l.engagement_level.replace("_"," ")})]},l.id))]})]})]})}function Lk({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(fe,{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 Vhn(){const{data:s=[],isLoading:t}=bun(),n=_un(),r=Mn(),a=async i=>{try{const l=await n.mutateAsync(i);ae.success("Added to your drafts"),r(`/attract/provide/kits/${l}/edit`)}catch(l){ae.error(l.message??"Could not clone template")}};return e.jsxs("div",{children:[e.jsx(Vu,{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(Ln,{to:"/attract/provide/kits",children:[e.jsx(Hr,{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(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10.5px] uppercase tracking-widest text-violet-700 font-semibold",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," Starter kit"]}),e.jsx("div",{className:"mt-2 text-[17px] font-semibold text-slate-900",children:i.title}),i.audience&&e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["For ",i.audience]}),e.jsx("p",{className:"text-[13px] text-slate-600 mt-2 line-clamp-3",children:i.description}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-1",children:[i.pillar&&e.jsx(ze,{variant:"outline",className:"capitalize",children:i.pillar}),(i.tags??[]).slice(0,4).map(o=>e.jsxs(ze,{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(Dm,{className:"h-4 w-4 mr-2"}),"Use this kit"]})]},i.id)})})]})}const qet={call:{icon:Ar,label:"Call"},text:{icon:Ei,label:"Text"},email:{icon:Vs,label:"Email"},dm:{icon:cr,label:"DM"},resource_share:{icon:Hg,label:"Share a kit"},event_invitation:{icon:Rg,label:"Invite to event"},personal_check_in:{icon:AA,label:"Personal check-in"}},Vet={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 Hhn(s){var t;return((t=ySt.find(n=>n.key===s))==null?void 0:t.blurb)??""}function n4t(s){var t;return((t=ySt.find(n=>n.key===s))==null?void 0:t.label)??s.replace(/_/g," ")}function iEe({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:p}=bSt(),[f,g]=N.useState(!1),[_,v]=N.useState(s.draft_message??""),j=c.isPending||d.isPending||u.isPending||h.isPending||p.isPending,b=qet[s.channel]??qet.personal_check_in,S=s.suggested_due_at?new Date(s.suggested_due_at):null,A=S?S{c.mutate({id:s.id,patch:{draft_message:_}},{onSuccess:()=>{g(!1),ae.success("Opening message updated")}})},L=async()=>{try{await navigator.clipboard.writeText(s.draft_message??""),ae.success("Opening message copied — send it yourself from your phone or inbox")}catch{ae.error("Could not copy — select the text manually")}};return e.jsx(fe,{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(b.icon,{className:"h-4.5 w-4.5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1 min-w-[180px]",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(ze,{variant:"outline",className:Et("rounded-full text-[10.5px] uppercase tracking-wider font-semibold ring-1 border-transparent",Vet[s.priority]??Vet.medium),children:s.priority}),e.jsx("span",{className:"text-[11px] text-violet-700 font-medium",children:n4t(s.signal_group)}),s.is_demo&&e.jsx(ze,{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(Ln,{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(xa,{className:"h-3 w-3"})]}):e.jsx("span",{className:"font-medium text-slate-700",children:t}),n&&e.jsxs("span",{className:"capitalize",children:["· ",n.replace(/_/g," ")]}),e.jsxs("span",{children:["· ",b.label]}),S&&e.jsxs("span",{className:Et("inline-flex items-center gap-1",A?"text-rose-600 font-medium":""),children:["· ",e.jsx(gr,{className:"h-3 w-3"})," ",A?"Due now":`Do by ${S.toLocaleDateString()}`]})]})]}),e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full","aria-label":"More recommendation actions",children:e.jsx(Ig,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",className:"w-56",children:[e.jsx(M4,{children:"Recommendation"}),e.jsx(Zg,{}),e.jsxs(Qr,{onClick:()=>g(D=>!D),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"})," Edit opening message"]}),e.jsxs(Qr,{onClick:L,children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"})," Copy message"]}),e.jsx(Zg,{}),e.jsxs(Qr,{onClick:()=>u.mutate({id:s.id,days:3}),children:[e.jsx(gr,{className:"h-4 w-4 mr-2"})," Snooze 3 days"]}),e.jsxs(Qr,{onClick:()=>u.mutate({id:s.id,days:7}),children:[e.jsx(gr,{className:"h-4 w-4 mr-2"})," Snooze 1 week"]}),e.jsxs(Qr,{className:"text-rose-600",onClick:()=>d.mutate(s.id),children:[e.jsx(Bn,{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(yw,{className:"h-3 w-3"})," Why this, right now"]}),e.jsx("ul",{className:"space-y-1",children:s.reasons.map((D,M)=>e.jsxs("li",{className:"text-[12.5px] text-slate-700 flex gap-2",children:[e.jsx("span",{className:"text-violet-500",children:"•"}),e.jsx("span",{children:D})]},M))}),e.jsx("div",{className:"text-[11px] text-slate-400 mt-2",children:Hhn(s.signal_group)})]}),!i&&e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider font-semibold text-slate-500 mb-1.5",children:"Suggested opening"}),f?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Es,{value:_,onChange:D=>v(D.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:j,children:"Save message"}),e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>{v(s.draft_message??""),g(!1)},children:"Cancel"})]})]}):e.jsxs("button",{onClick:()=>g(!0),className:"w-full text-left rounded-xl border border-slate-200 bg-white p-3 text-[13.5px] leading-relaxed text-slate-700 hover:border-violet-300 transition-colors",children:[s.draft_message||"No draft message yet — click to write one.",e.jsx("span",{className:"block text-[11px] text-violet-600 mt-1.5",children:"Click to edit before you send"})]})]}),(r||a)&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-[11.5px]",children:[r&&e.jsxs("span",{className:"rounded-full bg-teal-50 text-teal-700 px-2.5 py-1",children:["Suggested kit: ",r]}),a&&e.jsxs("span",{className:"rounded-full bg-indigo-50 text-indigo-700 px-2.5 py-1",children:["Suggested event: ",a]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",disabled:j,onClick:()=>p.mutate({rec:s}),children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1.5"})," I did this"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:j,onClick:()=>h.mutate(s),children:[e.jsx(Rg,{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:L,children:[e.jsx(Xr,{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 Ghn({label:s="Nothing needs attention right now."}){return e.jsxs(fe,{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(Ir,{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 Whn=q,Khn=["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"],Yhn={hot:Dc,warm:yb,cold:Ev},JF=({label:s})=>e.jsxs("span",{className:"text-slate-400 italic",children:["Not recorded",s?` — add ${s}`:""]}),Dk=s=>[s.first_name,s.last_name].filter(Boolean).join(" "),Zhn=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 JI({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 Qhn={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 Xhn(){const{agentId:s}=bi(),t=Mn(),{item:n,timeline:r,valueShared:a,nextKit:i,isLoading:l,error:o,refetch:c}=Mdn(s),{data:d=[]}=cDe(),{upsertAgent:u,moveStage:h}=c0(),{followUps:p,complete:f}=XU(),g=Idn(),{gmailEmail:_}=Oh(),[v,j]=N.useState("all"),[b,S]=N.useState(!1),[A,T]=N.useState(!1),[L,D]=N.useState("call"),[M,F]=N.useState(""),[z,V]=N.useState(""),[W,Y]=N.useState(!1),[K,J]=N.useState(""),[ne,ie]=N.useState(!1),[he,ce]=N.useState(""),[pe,le]=N.useState(new Date(Date.now()+3*864e5).toISOString().slice(0,10)),[ve,ge]=N.useState(null),[Te,Me]=N.useState(!1),Ce=N.useMemo(()=>d.filter(je=>je.agent_id===s&&je.status==="open").sort((je,Ge)=>Ge.rank_score-je.rank_score),[d,s]),Ae=N.useMemo(()=>p.filter(je=>je.agent_id===s),[p,s]),De=N.useMemo(()=>{const je=jet.find(Ge=>Ge.key===v);return!je||!je.kinds.length?r:r.filter(Ge=>je.kinds.includes(Ge.kind))},[r,v]);if(l)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-8 w-40"}),e.jsx(Ws,{className:"h-40 w-full rounded-2xl"}),e.jsx(Ws,{className:"h-64 w-full rounded-2xl"})]});if(o)return e.jsxs(fe,{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(Ti,{className:"h-4 w-4 mr-2"})," Try again"]})]});if(!n)return e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Agent not found"}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"This relationship may have been removed from your pipeline."}),e.jsx(B,{className:"rounded-full mt-4",onClick:()=>t("/attract/pipeline"),children:"Back to pipeline"})]});const Ie=n.agent,Fe=n.signals,qe=Yhn[Ie.temperature??""]??yb,be=()=>{g.mutate({agent_id:Ie.id,activity_type:L,title:M||`${L.replace(/_/g," ")} with ${Dk(Ie)}`,description:z||void 0},{onSuccess:()=>{S(!1),F(""),V("")}})},Ze=async()=>{var Ge;if(!K.trim())return;const je=[(Ge=Ie.notes)==null?void 0:Ge.trim(),`[${new Date().toLocaleDateString()}] ${K.trim()}`].filter(Boolean).join(` `);u.mutate({id:Ie.id,first_name:Ie.first_name,notes:je},{onSuccess:()=>{Y(!1),J(""),c()}}),g.mutate({agent_id:Ie.id,activity_type:"note",title:"Note added",description:K.trim()})},Ne=async()=>{if(!he.trim()){ae.error("Give the follow-up a title");return}if(Ae.find(Ye=>!Ye.completed_at&&Ye.title.trim().toLowerCase()===he.trim().toLowerCase())){ae.error("An open follow-up with that title already exists");return}const{data:Ge}=await q.auth.getUser(),{error:Be}=await Whn.from("attract_follow_ups").insert({user_id:Ge.user.id,agent_id:Ie.id,title:he.trim(),due_at:new Date(`${pe}T12:00:00`).toISOString(),touch_type:"call",priority:"medium"});if(Be){ae.error(Be.message);return}ae.success("Follow-up created"),ie(!1),ce(""),c()},it=()=>{ve&&(window.open(ve.href,"_self"),g.mutate({agent_id:Ie.id,activity_type:ve.kind,title:`${ve.kind==="call"?"Called":ve.kind==="text"?"Texted":"Emailed"} ${Dk(Ie)}`}),ge(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(Ln,{to:"/attract",className:"hover:text-violet-700",children:"Attract"}),e.jsx(xa,{className:"h-3 w-3"}),e.jsx(Ln,{to:"/attract/pipeline",className:"hover:text-violet-700",children:"Pipeline"}),e.jsx(xa,{className:"h-3 w-3"}),e.jsx("span",{className:"text-slate-800 font-medium truncate",children:Dk(Ie)})]}),e.jsxs(fe,{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(Hr,{className:"h-3.5 w-3.5 mr-1.5"})," Back"]}),e.jsxs("div",{className:"flex items-start gap-4 flex-wrap",children:[Ie.photo_url?e.jsx("img",{src:Ie.photo_url,alt:`${Dk(Ie)} 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:Zhn(Ie)}),e.jsxs("div",{className:"flex-1 min-w-[220px]",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:Dk(Ie)}),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:Ie.brokerage||"Brokerage not recorded"}),e.jsx("span",{className:"opacity-40",children:"·"}),e.jsx("span",{children:[Ie.city,Ie.state].filter(Boolean).join(", ")||"Market not recorded"}),Ie.is_demo&&e.jsx(ze,{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(ze,{className:"rounded-full bg-white/10 text-white border-transparent capitalize",children:Ie.stage.replace(/_/g," ")}),e.jsxs(ze,{className:"rounded-full bg-white/10 text-white border-transparent capitalize inline-flex items-center gap-1",children:[e.jsx(qe,{className:"h-3 w-3"})," ",Ie.temperature??"temperature unset"]}),e.jsx(uDe,{score:n.score,className:"bg-white/10 text-white ring-white/20"}),(Ie.tags??[]).map(je=>e.jsx(ze,{variant:"outline",className:"rounded-full bg-transparent text-slate-200 border-white/20",children:je},je))]})]}),e.jsxs("div",{className:"text-[12px] text-slate-300 space-y-1 min-w-[190px]",children:[e.jsx("div",{children:Ie.email?e.jsx("a",{className:"hover:text-white underline decoration-white/30",href:`mailto:${Ie.email}`,children:Ie.email}):"No email on file"}),e.jsx("div",{children:Ie.phone?e.jsx("a",{className:"hover:text-white underline decoration-white/30",href:`tel:${Ie.phone}`,children:Ie.phone}):"No phone on file"}),e.jsxs("div",{children:["Last meaningful touch: ",Fe.lastTouchAt?`${new Date(Fe.lastTouchAt).toLocaleDateString()} (${Fe.daysSinceTouch}d ago)`:"never logged"]}),e.jsxs("div",{children:["Next follow-up: ",Ie.next_follow_up_at?new Date(Ie.next_follow_up_at).toLocaleDateString():"none scheduled"]}),e.jsxs("div",{children:["Source: ",Ie.source||"not recorded"," · Owner: ",Ie.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(_a,{className:"h-3.5 w-3.5 mr-1.5"})," Edit contact"]}),e.jsxs(bs,{open:b,onOpenChange:S,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-1.5"})," Log touch"]})}),e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Log a conversation"}),e.jsx(Qn,{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(ds,{value:L,onValueChange:D,children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:["call","text","email","dm","meeting","note"].map(je=>e.jsx(Qe,{value:je,className:"capitalize",children:je},je))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:M,onChange:je=>F(je.target.value),placeholder:`Call with ${Ie.first_name}`})]}),e.jsxs("div",{children:[e.jsx(se,{children:"What happened"}),e.jsx(Es,{rows:4,value:z,onChange:je=>V(je.target.value)})]})]}),e.jsx(Xn,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:be,disabled:g.isPending,children:"Log it"})})]})]}),e.jsxs(bs,{open:W,onOpenChange:Y,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(E9,{className:"h-3.5 w-3.5 mr-1.5"})," Add note"]})}),e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{children:"Add a relationship note"})}),e.jsx(Es,{rows:5,value:K,onChange:je=>J(je.target.value),placeholder:"What did you learn about them?"}),e.jsx(Xn,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:Ze,children:"Save note"})})]})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Ie.phone,onClick:()=>Ie.phone&&ge({kind:"call",href:`tel:${Ie.phone}`}),children:[e.jsx(Ar,{className:"h-3.5 w-3.5 mr-1.5"})," Call"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Ie.phone,onClick:()=>Ie.phone&&ge({kind:"text",href:`sms:${Ie.phone}`}),children:[e.jsx(Ei,{className:"h-3.5 w-3.5 mr-1.5"})," Text"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Ie.email,onClick:()=>Ie.email&&Me(!0),children:[e.jsx(Vs,{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(Ln,{to:"/attract/provide/kits",children:[e.jsx(Hg,{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(Ln,{to:"/attract/events",children:[e.jsx(Rg,{className:"h-3.5 w-3.5 mr-1.5"})," Invite to event"]})}),e.jsxs(bs,{open:ne,onOpenChange:ie,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(gr,{className:"h-3.5 w-3.5 mr-1.5"})," Create follow-up"]})}),e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{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:he,onChange:je=>ce(je.target.value),placeholder:"Call about their Q3 goals"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Due"}),e.jsx(ye,{type:"date",value:pe,onChange:je=>le(je.target.value)})]})]}),e.jsx(Xn,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:Ne,children:"Create"})})]})]}),e.jsxs(ds,{value:Ie.stage,onValueChange:je=>h.mutate({id:Ie.id,to_stage:je,from_stage:Ie.stage}),children:[e.jsxs(ls,{className:"w-[210px] h-9 rounded-full text-[13px]","aria-label":"Change stage",children:[e.jsx(mw,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(us,{})]}),e.jsx(cs,{children:Khn.map(je=>e.jsx(Qe,{value:je,className:"capitalize",children:je.replace(/_/g," ")},je))})]})]})]}),e.jsx(bs,{open:!!ve,onOpenChange:je=>!je&&ge(null),children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:["Open your ",(ve==null?void 0:ve.kind)==="email"?"email app":(ve==null?void 0:ve.kind)==="text"?"messaging app":"phone app","?"]}),e.jsx(Qn,{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(Xn,{children:[e.jsx(B,{variant:"ghost",className:"rounded-full",onClick:()=>ge(null),children:"Cancel"}),e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:it,children:"Continue"})]})]})}),e.jsxs(Br,{defaultValue:"overview",children:[e.jsx(Fr,{className:"rounded-full bg-white border border-slate-200 p-1 flex-wrap h-auto",children:["overview","timeline","value","events","followups","notes"].map(je=>e.jsx(Kt,{value:je,className:"rounded-full text-[13px] capitalize data-[state=active]:bg-violet-600 data-[state=active]:text-white",children:je==="value"?"Value shared":je==="followups"?"Follow-ups":je==="notes"?"Notes & insights":je},je))}),e.jsxs(is,{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(fe,{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"}),Ce[0]?e.jsx(iEe,{rec:Ce[0],agentName:Dk(Ie),agentStage:Ie.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(fe,{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(JI,{label:"Goals",children:Ie.goals||e.jsx(JF,{label:"their goals"})}),e.jsx(JI,{label:"Challenges",children:Ie.challenges||e.jsx(JF,{label:"their challenges"})}),e.jsx(JI,{label:"Interests",children:Ie.interests||e.jsx(JF,{label:"interests"})}),e.jsx(JI,{label:"Production context",children:Ie.production_context||e.jsx(JF,{label:"production context"})}),e.jsx(JI,{label:"Primary pillar",children:Ie.primary_pillar?e.jsx("span",{className:"capitalize",children:Ie.primary_pillar}):e.jsx(JF,{label:"a pillar"})}),e.jsx(JI,{label:"Added to pipeline",children:new Date(Ie.created_at).toLocaleDateString()})]})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-3",children:[{label:"Touches (90d)",value:Fe.touches90},{label:"Kits shared",value:Fe.shares.length},{label:"Kit opens",value:Fe.totalKitOpens},{label:"Events attended",value:Fe.attended}].map(je=>e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:je.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:je.label})]},je.label))})]}),e.jsxs(fe,{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(_St,{score:n.score})]})]}),Ce.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"}),Ce.slice(1).map(je=>e.jsx(iEe,{rec:je,agentName:Dk(Ie),showAgentLink:!1,compact:!0},je.id))]})]}),e.jsx(is,{value:"timeline",className:"mt-5",children:e.jsxs(fe,{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:jet.map(je=>e.jsx("button",{onClick:()=>j(je.key),className:Et("rounded-full px-3 py-1.5 text-[12px] font-medium transition-colors",v===je.key?"bg-violet-600 text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"),children:je.label},je.key))}),e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",onClick:()=>S(!0),children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-1.5"})," Log something"]})]}),De.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"}),De.map(je=>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",Qhn[je.kind]??"bg-slate-300")}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:je.title}),je.detail&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5 whitespace-pre-wrap",children:je.detail}),e.jsxs("div",{className:"text-[11px] text-slate-400 mt-1",children:[new Date(je.at).toLocaleString()," · ",e.jsx("span",{className:"capitalize",children:je.kind.replace(/_/g," ")})]})]},je.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(is,{value:"value",className:"mt-5 space-y-4",children:[i&&e.jsxs(fe,{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(Ln,{to:"/attract/provide/kits",children:"Open Resource Kits"})})]}),a.length?a.map(je=>e.jsxs(fe,{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:je.kitTitle}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["Sent ",new Date(je.share.created_at).toLocaleDateString()," ·",je.firstViewedAt?` first viewed ${new Date(je.firstViewedAt).toLocaleDateString()}`:" never viewed",je.lastViewedAt?` · last viewed ${new Date(je.lastViewedAt).toLocaleDateString()}`:""]})]}),e.jsx(ze,{variant:"outline",className:Et("rounded-full border-transparent ring-1",je.classification==="High Intent"?"bg-rose-50 text-rose-700 ring-rose-200":je.classification==="Engaged"?"bg-teal-50 text-teal-700 ring-teal-200":je.classification==="Viewed"?"bg-amber-50 text-amber-700 ring-amber-200":"bg-slate-50 text-slate-600 ring-slate-200"),children:je.classification})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-3 mt-4",children:[["Visits",je.visits],["Downloads",je.downloads],["Link clicks",je.ctaClicks],["Questions",je.questions],["Meeting asks",je.meetingRequests]].map(([Ge,Be])=>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:Be}),e.jsx("div",{className:"text-[10.5px] text-slate-500",children:Ge})]},Ge))}),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:je.share.status})]}),e.jsxs("div",{children:["Follow-up after sharing: ",je.followUp?`${je.followUp.title}${je.followUp.completed_at?" (completed)":" (open)"}`:"none created"]}),e.jsxs("div",{children:["Stage movement after sharing: ",je.stageAdvancedAfter?`moved to ${je.stageAdvancedAfter.to_stage.replace(/_/g," ")} on ${new Date(je.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:je.shareUrl,target:"_blank",rel:"noreferrer",children:["Open share link ",e.jsx(tr,{className:"h-3.5 w-3.5 ml-1.5"})]})})]},je.share.id)):e.jsxs(fe,{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(is,{value:"events",className:"mt-5 space-y-3",children:Fe.attendees.length?Fe.attendees.map(je=>e.jsx(fe,{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(Ln,{to:`/attract/events/${je.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:[je.invited_at&&`Invited ${new Date(je.invited_at).toLocaleDateString()} · `,je.registered_at?`Registered ${new Date(je.registered_at).toLocaleDateString()}`:"Not registered",je.checked_in_at&&` · Attended ${new Date(je.checked_in_at).toLocaleDateString()}`,je.no_show_at&&" · No-show"]})]}),e.jsx(ze,{variant:"outline",className:"rounded-full capitalize",children:je.followup_status?`follow-up ${je.followup_status}`:je.status??"invited"})]})},je.id)):e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(G0,{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(Ln,{to:"/attract/events",children:"See your events"})})]})}),e.jsx(is,{value:"followups",className:"mt-5 space-y-3",children:Ae.length?Ae.map(je=>{const Ge=!je.completed_at&&je.due_at&&new Date(je.due_at)f.mutate(je.id),children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-1.5"})," Complete"]})]},je.id)}):e.jsxs(fe,{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:()=>ie(!0),children:"Create one"})]})}),e.jsxs(is,{value:"notes",className:"mt-5 space-y-4",children:[e.jsxs(fe,{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:()=>Y(!0),children:"Add note"})]}),Ie.notes?e.jsx("div",{className:"text-[13.5px] text-slate-700 whitespace-pre-wrap",children:Ie.notes}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No notes recorded yet."})]}),e.jsxs(fe,{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(je=>`Strength: ${je}`),...n.score.negatives.map(je=>`Risk: ${je}`),...n.score.improvements.map(je=>`Next: ${je}`)].map((je,Ge)=>e.jsx("li",{children:je},Ge))})]})]})]}),e.jsx(MSt,{agent:Ie,open:A,onOpenChange:T,onDeleted:()=>t("/attract/pipeline")}),Ie.email&&e.jsx(t1,{open:Te,onOpenChange:Me,contact:{id:Ie.id,first_name:Ie.preferred_name||Ie.first_name,last_name:Ie.last_name||"",email:Ie.email},gmailEmail:_,sendSource:"attract",logTouchpoint:!1,onSendComplete:()=>{g.mutate({agent_id:Ie.id,activity_type:"email",title:`Emailed ${Dk(Ie)}`})}})]})}const Jhn=[{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 emn(){const{intel:s,byId:t,isLoading:n,error:r,refetch:a}=h6(),{data:i=[],isLoading:l}=cDe(),o=dDe();wSt();const[c,d]=N.useState(""),[u,h]=N.useState("all"),[p,f]=N.useState("open"),g=j=>{var S;const b=(S=t.get(j))==null?void 0:S.agent;return b?[b.first_name,b.last_name].filter(Boolean).join(" "):"Unknown agent"},_=N.useMemo(()=>{const j=Date.now();return i.filter(b=>p==="open"?b.status==="open"||b.status==="snoozed"&&b.snoozed_until&&+new Date(b.snoozed_until)<=j:p==="snoozed"?b.status==="snoozed":p==="done"?b.status==="completed":p==="dismissed"?b.status==="dismissed":!0).filter(b=>u==="all"||b.signal_group===u).filter(b=>{if(!c.trim())return!0;const S=c.toLowerCase();return g(b.agent_id).toLowerCase().includes(S)||b.title.toLowerCase().includes(S)||(b.reasons??[]).join(" ").toLowerCase().includes(S)}).sort((b,S)=>S.rank_score-b.rank_score)},[i,p,u,c,t]),v=N.useMemo(()=>{const j=i.filter(b=>b.status==="open");return{open:j.length,urgent:j.filter(b=>b.priority==="urgent").length,highIntent:j.filter(b=>b.signal_group==="high_intent").length,overdue:j.filter(b=>b.suggested_due_at&&+new Date(b.suggested_due_at)e.jsx(Ws,{className:"h-28 w-full rounded-2xl"},j))}):r?e.jsxs(fe,{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(Ti,{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(Ti,{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:v.open},{label:"Urgent",value:v.urgent},{label:"High intent signals",value:v.highIntent},{label:"Past suggested date",value:v.overdue}].map(j=>e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:j.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:j.label})]},j.label))}),e.jsxs(fe,{className:"p-3 rounded-2xl flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px]",children:[e.jsx(vr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(ye,{value:c,onChange:j=>d(j.target.value),placeholder:"Search agents or reasons",className:"pl-9 rounded-full h-9","aria-label":"Search recommendations"})]}),e.jsxs(ds,{value:u,onValueChange:h,children:[e.jsxs(ls,{className:"w-[190px] h-9 rounded-full text-[13px]",children:[e.jsx(Rv,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(us,{})]}),e.jsx(cs,{children:Jhn.map(j=>e.jsx(Qe,{value:j.key,children:j.label},j.key))})]}),e.jsxs(ds,{value:p,onValueChange:f,children:[e.jsx(ls,{className:"w-[150px] h-9 rounded-full text-[13px]",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"open",children:"Needs action"}),e.jsx(Qe,{value:"snoozed",children:"Snoozed"}),e.jsx(Qe,{value:"done",children:"Completed"}),e.jsx(Qe,{value:"dismissed",children:"Dismissed"}),e.jsx(Qe,{value:"all",children:"All"})]})]})]}),_.length?e.jsx("div",{className:"space-y-3",children:_.map(j=>{var b;return e.jsx(iEe,{rec:j,agentName:g(j.agent_id),agentStage:(b=t.get(j.agent_id))==null?void 0:b.agent.stage},j.id)})}):i.length?e.jsx(Ghn,{label:"Nothing matches this view. Try switching the filter."}):e.jsxs(fe,{className:"p-10 rounded-2xl text-center",children:[e.jsx(un,{className:"h-6 w-6 mx-auto text-violet-500 mb-2"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"No recommendations yet"}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-md mx-auto",children:"Attract only recommends what it can prove. Add agents to your pipeline, share a Resource Kit, or invite someone to an event — real signals will show up here."}),e.jsxs("div",{className:"flex gap-2 justify-center mt-4",children:[e.jsx(B,{className:"rounded-full btn-primary text-white",asChild:!0,children:e.jsx(Ln,{to:"/attract/pipeline",children:"Open pipeline"})}),e.jsx(B,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsx(Ln,{to:"/attract/provide/kits",children:"Share a kit"})})]})]}),!!_.length&&e.jsxs("div",{className:"text-[11.5px] text-slate-400",children:["Showing ",_.length," of ",i.length," tracked recommendations · grouped signals: ",[...new Set(_.map(j=>n4t(j.signal_group)))].join(", ")]})]})}const Lke=s=>[s.first_name,s.last_name].filter(Boolean).join(" ");function tmn(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 r4t(s,t,n=new Date){const r=tmn(n),a=new Date(r.getTime()+6*864e5),i=new Date(n.getTime()-7*864e5),c=s.filter(M=>M.primary).slice().sort((M,F)=>F.primary.rank_score-M.primary.rank_score||M.score.score-F.score.score).slice(0,5).map((M,F)=>({agent_id:M.agent.id,agent_name:Lke(M.agent),rank:F+1,reason:M.primary.reasons.join(" · "),channel:M.primary.channel,draft_message:M.primary.draft_message,score:M.score.score,stage:M.agent.stage})),d=M=>s.map(F=>{const z=M(F);return z?{agent_id:F.agent.id,agent_name:Lke(F.agent),detail:z}:null}).filter(Boolean).slice(0,8),u=d(M=>M.signals.meetingRequests>0||M.signals.questions>0||M.signals.highIntentShares.some(F=>F.engagement_level==="high_intent")?`${M.signals.meetingRequests} meeting request(s), ${M.signals.questions} question(s), ${M.signals.totalKitOpens} kit open(s)`:null),h=d(M=>M.recommendations.some(F=>F.rec_key==="renewed_interest")?"Came back to a kit you shared after going quiet":null),p=d(M=>M.signals.overdueFollowUps.length?`${M.signals.overdueFollowUps.length} overdue follow-up(s) — oldest: ${M.signals.overdueFollowUps[0].title}`:null),f=d(M=>M.signals.daysSinceTouch!==null&&M.signals.daysSinceTouch>60?`${M.signals.daysSinceTouch} days since a real conversation`:null),g=t.shares.filter(M=>new Date(M.created_at)>=i),_={shares:g.length,opened:t.shares.filter(M=>M.first_opened_at&&new Date(M.first_opened_at)>=i).length,engaged:t.shares.filter(M=>M.engagement_level==="engaged").length,high_intent:t.shares.filter(M=>M.engagement_level==="high_intent").length,downloads:t.kitEvents.filter(M=>M.event_type==="file_download"&&new Date(M.created_at)>=i).length,questions:t.kitEvents.filter(M=>M.event_type==="question_submitted"&&new Date(M.created_at)>=i).length},v={invited:t.attendees.filter(M=>M.invited_at&&new Date(M.invited_at)>=i).length,registered:t.attendees.filter(M=>M.registered_at&&new Date(M.registered_at)>=i).length,attended:t.attendees.filter(M=>M.checked_in_at&&new Date(M.checked_in_at)>=i).length,no_shows:t.attendees.filter(M=>M.no_show_at&&new Date(M.no_show_at)>=i).length,follow_ups_pending:t.attendees.filter(M=>M.checked_in_at&&M.followup_status!=="done").length,upcoming:t.events.filter(M=>M.starts_at&&new Date(M.starts_at)>n&&M.status==="published").sort((M,F)=>+new Date(M.starts_at)-+new Date(F.starts_at)).slice(0,3).map(M=>({title:M.title,starts_at:M.starts_at??null}))},j=[...s.filter(M=>M.agent.next_follow_up_at&&new Date(M.agent.next_follow_up_at)>n&&Am(n,M.agent.next_follow_up_at)<=7).slice(0,5).map(M=>({label:Lke(M.agent),detail:`Follow-up scheduled ${new Date(M.agent.next_follow_up_at).toLocaleDateString()}`})),...v.upcoming.map(M=>({label:M.title,detail:M.starts_at?`Event on ${new Date(M.starts_at).toLocaleDateString()}`:"Event scheduled"}))].slice(0,6),b=t.activities.filter(M=>new Date(M.created_at)>=i),S={produce:0,influence:0,provide:0,connect:0};for(const M of b)M.pillar&&S[M.pillar]!==void 0&&S[M.pillar]++;const A=Object.entries(S).map(([M,F])=>({pillar:M,count:F})),T=A.slice().sort((M,F)=>M.count-F.count)[0],L=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.`,D={advanced:t.stageChanges.filter(M=>new Date(M.created_at)>=i).length,follow_ups_completed:t.followUps.filter(M=>M.completed_at&&new Date(M.completed_at)>=i).length,conversations_logged:b.filter(M=>["touch_logged","call","text","email","dm","meeting"].includes(M.activity_type)).length,kits_shared:g.length};return{week_start:r.toISOString().slice(0,10),week_end:a.toISOString().slice(0,10),generated_at:n.toISOString(),conversations:c,high_intent:u,renewed:h,overdue:p,stale:f,kit_summary:_,event_summary:v,upcoming_opportunities:j,pillar_balance:A,recommended_focus:L,wins:D}}function Het(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 q2=q;function smn(){const{user:s}=ys(),t=Ht(),n=ct({queryKey:["attract-digest-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await q2.from("attract_digest_settings").select("*").eq("user_id",s.id).maybeSingle();if(i)throw i;return a??null}}),r=gt({mutationFn:async a=>{const{error:i}=await q2.from("attract_digest_settings").upsert({user_id:s.id,...a},{onConflict:"user_id"});if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-digest-settings"]}),ae.success("Digest settings saved")},onError:a=>ae.error(a.message)});return{settings:n.data,isLoading:n.isLoading,save:r}}function nmn(){const{user:s}=ys();return ct({queryKey:["attract-digests",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q2.from("attract_digests").select("*").order("week_start",{ascending:!1}).limit(26);if(n)throw n;return t??[]}})}function rmn(s){const t=Ht(),n=ct({queryKey:["attract-digest-items",s],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await q2.from("attract_digest_items").select("*").eq("digest_id",s).order("rank");if(i)throw i;return a??[]}}),r=gt({mutationFn:async a=>{const{error:i}=await q2.from("attract_digest_items").update({completed_at:new Date().toISOString()}).eq("id",a);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-digest-items",s]}),ae.success("Marked as done")}});return{items:n.data??[],isLoading:n.isLoading,markComplete:r}}function amn(){const{user:s}=ys(),t=Ht();return gt({mutationFn:async n=>{const{data:r,error:a}=await q2.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 q2.from("attract_digest_items").delete().eq("digest_id",i).is("completed_at",null);const{data:l}=await q2.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 q2.from("attract_digest_items").insert(c);if(d)throw d}return i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-digests"]}),t.invalidateQueries({queryKey:["attract-digest-items"]})},onError:n=>ae.error(n.message)})}function imn(){const s=Ht();return gt({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("attract-send-digest",{body:t});if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["attract-digests"]}),t!=null&&t.ok?ae.success("Digest email sent"):ae.error((t==null?void 0:t.reason)||"Email delivery is not configured yet")},onError:t=>ae.error(t.message??"Send failed")})}const omn=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function eP({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 nW({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(Ln,{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 lmn(){var L;const{user:s}=ys(),{intel:t,dataset:n,isLoading:r}=h6(),{settings:a,save:i}=smn(),{data:l=[]}=nmn(),o=amn(),c=imn(),[d,u]=N.useState(),h=d??((L=l[0])==null?void 0:L.id),{items:p,markComplete:f}=rmn(h),[g,_]=N.useState(""),v=N.useMemo(()=>n?r4t(t,n):null,[t,n]),j=l.find(D=>D.id===h),b=(j==null?void 0:j.payload)??v,S=g||(a==null?void 0:a.email)||(s==null?void 0:s.email)||"",A=()=>{v&&o.mutate(v,{onSuccess:D=>{u(D),ae.success("This week's digest is ready")}})},T=D=>{if(!b)return;if(!S){ae.error("Add an email address first");return}const M=F=>c.mutate({digestId:F,to:S,subject:`Your Weekly Attraction Digest — ${b.week_start}`,html:Het(b,window.location.origin),test:D});j?M(j.id):v&&o.mutate(v,{onSuccess:F=>{u(F),M(F)}})};return r||!b?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-10 w-56"}),e.jsx(Ws,{className:"h-72 w-full rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-end justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Relationship Intelligence"}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-slate-900 mt-0.5",children:"Weekly Attraction Digest"}),e.jsxs("p",{className:"text-[13.5px] text-slate-500 mt-1",children:["Week of ",new Date(`${b.week_start}T12:00:00`).toLocaleDateString()," – ",new Date(`${b.week_end}T12:00:00`).toLocaleDateString(),j&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"capitalize",children:j.delivery_status.replace(/_/g," ")}),j.sent_at?` ${new Date(j.sent_at).toLocaleString()}`:""]})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:A,disabled:o.isPending,children:[e.jsx(Ti,{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(Het(b,window.location.origin)),ae.success("Digest HTML copied")},children:[e.jsx(Xr,{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(cr,{className:"h-3.5 w-3.5 mr-1.5"})," Email it to me"]})]})]}),e.jsxs(Br,{defaultValue:"digest",children:[e.jsx(Fr,{className:"rounded-full bg-white border border-slate-200 p-1",children:[["digest","This week"],["history","History"],["settings","Delivery settings"]].map(([D,M])=>e.jsx(Kt,{value:D,className:"rounded-full text-[13px] data-[state=active]:bg-violet-600 data-[state=active]:text-white",children:M},D))}),e.jsxs(is,{value:"digest",className:"mt-5 space-y-5",children:[e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[["Conversations logged",b.wins.conversations_logged],["Stage moves",b.wins.advanced],["Follow-ups completed",b.wins.follow_ups_completed],["Kits shared",b.wins.kits_shared]].map(([D,M])=>e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:M}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:D})]},D))}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600 mb-3",children:"Your five conversations this week"}),b.conversations.length?e.jsx("div",{className:"space-y-3",children:b.conversations.map(D=>{const M=p.find(z=>z.agent_id===D.agent_id),F=!!(M!=null&&M.completed_at);return e.jsxs("div",{className:Et("rounded-xl border border-slate-200 p-4",F&&"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:[D.rank,". ",e.jsx(Ln,{to:`/attract/agents/${D.agent_id}`,className:"hover:text-violet-700",children:D.agent_name})]}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:D.reason})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ze,{variant:"outline",className:"rounded-full capitalize",children:D.channel}),e.jsxs(ze,{variant:"outline",className:"rounded-full",children:["Health ",D.score]})]})]}),D.draft_message&&e.jsx("div",{className:"mt-3 rounded-lg bg-slate-50 p-3 text-[13px] text-slate-700 whitespace-pre-wrap",children:D.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(D.draft_message||""),ae.success("Copied")},children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]}),M&&!F&&e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",onClick:()=>f.mutate(M.id),children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-1.5"})," Mark done"]}),F&&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(Ln,{to:`/attract/agents/${D.agent_id}`,children:"Open relationship"})})]})]},D.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(fe,{className:"p-5 rounded-2xl space-y-4",children:[e.jsx(eP,{title:"High intent",children:e.jsx(nW,{rows:b.high_intent,empty:"No high-intent signals this week."})}),e.jsx(eP,{title:"Renewed interest",children:e.jsx(nW,{rows:b.renewed,empty:"Nobody re-engaged after going quiet."})})]}),e.jsxs(fe,{className:"p-5 rounded-2xl space-y-4",children:[e.jsx(eP,{title:"Overdue commitments",children:e.jsx(nW,{rows:b.overdue,empty:"Nothing overdue. Well kept."})}),e.jsx(eP,{title:"Going cold",children:e.jsx(nW,{rows:b.stale,empty:"No relationships past 60 days of silence."})})]}),e.jsx(fe,{className:"p-5 rounded-2xl",children:e.jsx(eP,{title:"Value shared",children:e.jsxs("div",{className:"text-[13px] text-slate-700 space-y-1",children:[e.jsxs("div",{children:[b.kit_summary.shares," kits shared · ",b.kit_summary.opened," opened"]}),e.jsxs("div",{children:[b.kit_summary.downloads," downloads · ",b.kit_summary.questions," questions asked"]}),e.jsxs("div",{children:[b.kit_summary.engaged," engaged · ",b.kit_summary.high_intent," high intent"]})]})})}),e.jsx(fe,{className:"p-5 rounded-2xl",children:e.jsx(eP,{title:"Events",children:e.jsxs("div",{className:"text-[13px] text-slate-700 space-y-1",children:[e.jsxs("div",{children:[b.event_summary.invited," invited · ",b.event_summary.registered," registered"]}),e.jsxs("div",{children:[b.event_summary.attended," attended · ",b.event_summary.no_shows," no-shows"]}),e.jsxs("div",{children:[b.event_summary.follow_ups_pending," attendee follow-ups still pending"]}),b.event_summary.upcoming.map(D=>e.jsxs("div",{className:"text-slate-600 flex items-center gap-1.5",children:[e.jsx(Tl,{className:"h-3.5 w-3.5"})," ",D.title,D.starts_at?` — ${new Date(D.starts_at).toLocaleDateString()}`:""]},D.title))]})})})]}),e.jsxs(fe,{className:"p-5 rounded-2xl bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-700",children:"Recommended focus"}),e.jsx("p",{className:"text-[14px] text-slate-800 mt-1.5",children:b.recommended_focus}),e.jsx("div",{className:"flex gap-2 mt-3 flex-wrap",children:b.pillar_balance.map(D=>e.jsxs(ze,{variant:"outline",className:"rounded-full capitalize bg-white/70",children:[D.pillar,": ",D.count]},D.pillar))})]})]}),e.jsx(is,{value:"history",className:"mt-5 space-y-3",children:l.length?l.map(D=>e.jsxs(fe,{className:Et("p-4 rounded-2xl flex items-center justify-between gap-3 flex-wrap",D.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(`${D.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:D.delivery_status.replace(/_/g," ")}),D.sent_at&&` · sent ${new Date(D.sent_at).toLocaleString()}`,D.delivery_note&&` · ${D.delivery_note}`]})]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>u(D.id),children:"View"})]},D.id)):e.jsx(fe,{className:"p-8 rounded-2xl text-center text-[13.5px] text-slate-500",children:"No digests generated yet."})}),e.jsx(is,{value:"settings",className:"mt-5",children:e.jsxs(fe,{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(bn,{checked:!!(a!=null&&a.enabled),onCheckedChange:D=>i.mutate({enabled:D})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Day"}),e.jsxs(ds,{value:String((a==null?void 0:a.weekday)??1),onValueChange:D=>i.mutate({weekday:Number(D)}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:omn.map((D,M)=>e.jsx(Qe,{value:String(M),children:D},D))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Hour (local)"}),e.jsxs(ds,{value:String((a==null?void 0:a.send_hour)??7),onValueChange:D=>i.mutate({send_hour:Number(D)}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:Array.from({length:24},(D,M)=>e.jsxs(Qe,{value:String(M),children:[M,":00"]},M))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Send to"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:g||(a==null?void 0:a.email)||(s==null?void 0:s.email)||"",onChange:D=>_(D.target.value),placeholder:"you@example.com"}),e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>i.mutate({email:S}),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(Vs,{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 b3=q,cmn=[{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 dmn(){const{user:s}=ys(),t=Ht(),{intel:n,dataset:r,isLoading:a,refetch:i}=h6(),l=dDe(),o=vSt(),[c,d]=N.useState(""),[u,h]=N.useState(!1),p=N.useMemo(()=>r?r4t(n,r):null,[n,r]),f=N.useMemo(()=>{const v=c.toLowerCase().trim();return n.filter(j=>!v||`${j.agent.first_name} ${j.agent.last_name??""}`.toLowerCase().includes(v))},[n,c]),g=async()=>{if(!s)return;h(!0);const{data:v}=await b3.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0);if((v??[]).length){ae.info("Demo agents already exist"),h(!1);return}const{data:j,error:b}=await b3.from("attract_agents").insert(cmn.map(A=>({...A,user_id:s.id,is_demo:!0,source:"demo_seed"}))).select("id, first_name");if(b){ae.error(b.message),h(!1);return}const S=Date.now();await b3.from("attract_activities").insert((j??[]).map((A,T)=>({user_id:s.id,agent_id:A.id,activity_type:"touch_logged",pillar:"connect",title:`Demo conversation with ${A.first_name}`,created_at:new Date(S-(T+1)*14*864e5).toISOString()}))),await b3.from("attract_follow_ups").insert({user_id:s.id,agent_id:j[0].id,title:"Demo overdue commitment",touch_type:"call",priority:"high",due_at:new Date(S-6*864e5).toISOString()}),ae.success("Demo relationships seeded"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()},_=async()=>{if(!s)return;h(!0);const{data:v}=await b3.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0),j=(v??[]).map(b=>b.id);if(!j.length){ae.info("No demo data to clear"),h(!1);return}for(const b of["attract_recommendations","attract_agent_scores","attract_follow_ups","attract_activities"])await b3.from(b).delete().in("agent_id",j);await b3.from("attract_agents").delete().in("id",j),ae.success("Demo data removed"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()};return a?e.jsx(Ws,{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(Ln,{to:"/admin",children:[e.jsx(Hr,{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(Ti,{className:"h-3.5 w-3.5 mr-1.5"})," Recompute & persist"]}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:g,disabled:u,children:[e.jsx(H7,{className:"h-3.5 w-3.5 mr-1.5"})," Seed demo relationships"]}),e.jsxs(B,{variant:"outline",className:"rounded-full text-destructive",onClick:_,disabled:u,children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-1.5"})," Clear demo data"]})]}),e.jsxs(Br,{defaultValue:"agents",children:[e.jsxs(Fr,{className:"rounded-full",children:[e.jsx(Kt,{value:"agents",className:"rounded-full",children:"Scores & signals"}),e.jsx(Kt,{value:"digest",className:"rounded-full",children:"Digest payload"})]}),e.jsxs(is,{value:"agents",className:"mt-4 space-y-3",children:[e.jsx(ye,{value:c,onChange:v=>d(v.target.value),placeholder:"Filter by name",className:"max-w-sm rounded-full"}),!f.length&&e.jsx(fe,{className:"p-6 rounded-2xl text-[13.5px] text-muted-foreground",children:"No agents in your Attract pipeline."}),f.map(v=>e.jsxs(fe,{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(Ln,{to:`/attract/agents/${v.agent.id}`,className:"text-[15px] font-semibold hover:text-violet-700",children:[v.agent.first_name,v.agent.last_name].filter(Boolean).join(" ")}),e.jsxs("div",{className:"text-[12px] text-muted-foreground mt-0.5 capitalize",children:[v.agent.stage.replace(/_/g," ")," · ",v.agent.temperature??"no temperature"," · ",v.signals.daysSinceTouch??"—"," days since touch"]})]}),v.agent.is_demo&&e.jsx(ze,{variant:"outline",className:"rounded-full",children:"Demo"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4 mt-4",children:[e.jsx(_St,{score:v.score}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground mb-1.5",children:["Recommendations (",v.recommendations.length,")"]}),v.recommendations.length?e.jsx("ul",{className:"space-y-2",children:v.recommendations.map(j=>e.jsxs("li",{className:"text-[12.5px]",children:[e.jsx("span",{className:"font-medium",children:j.title}),e.jsxs("span",{className:"text-muted-foreground",children:[" · ",j.signal_group," · rank ",j.rank_score," · ",j.priority]}),e.jsx("div",{className:"text-muted-foreground",children:j.reasons.join(" · ")})]},j.rec_key))}):e.jsx("div",{className:"text-[13px] text-muted-foreground",children:"None generated."})]})]}),e.jsxs("details",{className:"mt-3",children:[e.jsx("summary",{className:"text-[12px] cursor-pointer text-muted-foreground",children:"Raw signals"}),e.jsx("pre",{className:"text-[11px] bg-muted p-3 rounded-lg overflow-auto mt-2 max-h-72",children:JSON.stringify({touches90:v.signals.touches90,kitShares:v.signals.shares.length,kitOpens:v.signals.totalKitOpens,questions:v.signals.questions,meetingRequests:v.signals.meetingRequests,overdueFollowUps:v.signals.overdueFollowUps.length,attended:v.signals.attended},null,2)})]})]},v.agent.id))]}),e.jsx(is,{value:"digest",className:"mt-4",children:e.jsx(fe,{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(p,null,2)})})})]})]})}function umn(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),a=N.useMemo(()=>XTe.filter(l=>{const o=s.toLowerCase().trim();return n!=="all"&&l.status!==n?!1:!o||`${l.title} ${l.pillar} ${l.route??""}`.toLowerCase().includes(o)}),[s,n]),i=N.useMemo(()=>{const l={live:0,partial:0,placeholder:0,integration_required:0};return XTe.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(Ln,{to:"/admin",children:[e.jsx(Hr,{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(fe,{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:JTe[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(fe,{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(ze,{variant:"outline",className:"rounded-full capitalize",children:l.pillar}),e.jsx(ze,{variant:"outline",className:`rounded-full ${ISt[l.status]}`,children:JTe[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(Ln,{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 _3=q,Get=["idea","researching","pitching","applied","tentative","confirmed","completed","declined","archived"],Wet=["panel","keynote","mls_talk","podcast","webinar","mastermind","training","conference","other"],Ket=["attract-speaking"];function a4t(){const{user:s}=ys(),t=Ht(),n=ct({queryKey:[...Ket,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await _3.from("attract_speaking_opportunities").select("*").order("starts_at",{ascending:!0,nullsFirst:!1});if(h)throw h;return u??[]}}),r=()=>{t.invalidateQueries({queryKey:Ket}),t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-activities"]})},a=gt({mutationFn:async u=>{const{data:h,error:p}=await _3.from("attract_speaking_opportunities").insert({...u,user_id:s.id}).select("*").single();if(p)throw p;return h},onSuccess:()=>{r(),ae.success("Speaking opportunity saved")},onError:u=>ae.error(u.message)}),i=gt({mutationFn:async({id:u,...h})=>{const{error:p}=await _3.from("attract_speaking_opportunities").update(h).eq("id",u);if(p)throw p},onSuccess:()=>{r(),ae.success("Updated")},onError:u=>ae.error(u.message)}),l=gt({mutationFn:async u=>{const{id:h,created_at:p,updated_at:f,user_id:g,..._}=u,{data:v,error:j}=await _3.from("attract_speaking_opportunities").insert({..._,title:`${u.title} (copy)`,status:"idea",user_id:s.id}).select("id").single();if(j)throw j;return v},onSuccess:()=>{r(),ae.success("Duplicated")},onError:u=>ae.error(u.message)}),o=gt({mutationFn:async u=>{const{error:h}=await _3.from("attract_speaking_opportunities").delete().eq("id",u);if(h)throw h},onSuccess:()=>{r(),ae.success("Deleted")},onError:u=>ae.error(u.message)}),c=gt({mutationFn:async({title:u,dueAt:h,notes:p,touchType:f="speaking"})=>{const{error:g}=await _3.from("attract_follow_ups").insert({user_id:s.id,title:u,due_at:h??null,notes:p??null,touch_type:f,priority:"medium"});if(g)throw g},onSuccess:()=>{r(),ae.success("Added to Follow-Up Center")},onError:u=>ae.error(u.message)}),d=gt({mutationFn:async({title:u,pillar:h="influence",activityType:p="speaking_outreach",agentId:f})=>{const{error:g}=await _3.from("attract_activities").insert({user_id:s.id,title:u,pillar:h,activity_type:p,agent_id:f??null});if(g)throw g},onSuccess:()=>{r(),ae.success("Outreach logged")},onError:u=>ae.error(u.message)});return{items:n.data??[],isLoading:n.isLoading,error:n.error,refetch:n.refetch,create:a,update:i,duplicate:l,remove:o,addTask:c,logActivity:d}}const oEe={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"},Dke={title:"",organization:"",event_type:"panel",status:"idea",timezone:"America/New_York",pillar:"influence",linked_agent_ids:[]};function hmn(){const{items:s,isLoading:t,create:n,update:r,duplicate:a,remove:i,addTask:l,logActivity:o}=a4t(),{agents:c=[]}=c0(),{kits:d=[]}=FR(),u=hbe(),h=(u==null?void 0:u.events)??(u==null?void 0:u.data)??[],[p,f]=N.useState("month"),[g,_]=N.useState(new Date),[v,j]=N.useState("all"),[b,S]=N.useState("all"),[A,T]=N.useState("all"),[L,D]=N.useState(!1),[M,F]=N.useState(null),[z,V]=N.useState(null),W=N.useMemo(()=>s.filter(le=>!(!L&&(le.is_archived||le.status==="archived")||v!=="all"&&le.status!==v||b!=="all"&&le.event_type!==b||A!=="all"&&!(le.linked_agent_ids??[]).includes(A))),[s,v,b,A,L]),Y=W.filter(le=>le.starts_at),K=W.filter(le=>!le.starts_at),J=new Date,ne=N.useMemo(()=>{const le=Y.filter(Ce=>Bv(Xh(Ce.starts_at),J)&&["confirmed","tentative"].includes(Ce.status)),ve=W.filter(Ce=>Ce.submission_deadline&&Bv(Xh(Ce.submission_deadline),J)),ge=W.filter(Ce=>["pitching","applied","researching"].includes(Ce.status)),Te=W.filter(Ce=>Ce.status==="confirmed"),Me=W.filter(Ce=>Ce.follow_up_date&&Ce.status==="completed");return{upcoming:le,deadlines:ve,pitches:ge,confirmed:Te,followUps:Me}},[W,Y]),ie=N.useMemo(()=>D4e(p==="week"?{start:Wm(g),end:w8(g)}:{start:Wm(Fd(g)),end:w8(V0(g))}),[g,p]),he=le=>Y.filter(ve=>Vl(Xh(ve.starts_at),le)),ce=async()=>{var ve;if(!((ve=M==null?void 0:M.title)!=null&&ve.trim())){ae.error("Give the talk a title");return}const le={...M};delete le.created_at,delete le.updated_at,delete le.user_id,(le.fee===""||le.fee==null)&&(le.fee=null),["starts_at","ends_at","submission_deadline","follow_up_date","linked_event_id","linked_kit_id"].forEach(ge=>{le[ge]===""&&(le[ge]=null)}),M.id?await r.mutateAsync(le):await n.mutateAsync(le),F(null)},pe=le=>{if(!le.starts_at){ae.error("Add a date first");return}const ve=Ae=>new Date(Ae).toISOString().replace(/[-:]|\.\d{3}/g,""),ge=le.ends_at??new Date(new Date(le.starts_at).getTime()+60*6e4).toISOString(),Te=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp Attract//Speaking//EN","BEGIN:VEVENT",`UID:${le.id}@levelup-attract`,`DTSTAMP:${ve(new Date().toISOString())}`,`DTSTART:${ve(le.starts_at)}`,`DTEND:${ve(ge)}`,`SUMMARY:${(le.title||"").replace(/\n/g," ")}`,`LOCATION:${(le.location||le.virtual_link||"").replace(/\n/g," ")}`,`DESCRIPTION:${[le.organization,le.topic].filter(Boolean).join(" — ").replace(/\n/g," ")}`,"END:VEVENT","END:VCALENDAR"].join(`\r `),Me=URL.createObjectURL(new Blob([Te],{type:"text/calendar"})),Ce=document.createElement("a");Ce.href=Me,Ce.download=`${le.title.replace(/\W+/g,"-").toLowerCase()}.ics`,Ce.click(),URL.revokeObjectURL(Me)};return t?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-32 rounded-2xl"}),e.jsx(Ws,{className:"h-96 rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vu,{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:()=>F({...Dke}),children:[e.jsx(Is,{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(e7,{label:"Upcoming talks",value:ne.upcoming.length,icon:Fv}),e.jsx(e7,{label:"Deadlines ahead",value:ne.deadlines.length,icon:gr}),e.jsx(e7,{label:"Pitches in flight",value:ne.pitches.length,icon:cr}),e.jsx(e7,{label:"Confirmed",value:ne.confirmed.length,icon:xr}),e.jsx(e7,{label:"Post-event follow-ups",value:ne.followUps.length,icon:uu})]}),e.jsxs(fe,{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(le=>e.jsx("button",{onClick:()=>f(le),className:`px-3 py-1.5 rounded-full text-[12.5px] font-medium capitalize ${p===le?"bg-white shadow-sm text-slate-900":"text-slate-500"}`,children:le},le))}),p!=="agenda"&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full",onClick:()=>_(p==="week"?O2(g,-1):Nf(g,-1)),children:e.jsx(pl,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[13.5px] font-semibold min-w-[130px] text-center",children:Ss(g,p==="week"?"'Week of' MMM d":"MMMM yyyy")}),e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full",onClick:()=>_(p==="week"?O2(g,1):Nf(g,1)),children:e.jsx(xa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>_(new Date),children:"Today"})]}),e.jsx("div",{className:"flex-1"}),e.jsxs(ds,{value:v,onValueChange:j,children:[e.jsx(ls,{className:"w-[140px] rounded-full h-9",children:e.jsx(us,{placeholder:"Status"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All statuses"}),Get.map(le=>e.jsx(Qe,{value:le,className:"capitalize",children:le.replace(/_/g," ")},le))]})]}),e.jsxs(ds,{value:b,onValueChange:S,children:[e.jsx(ls,{className:"w-[140px] rounded-full h-9",children:e.jsx(us,{placeholder:"Type"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All types"}),Wet.map(le=>e.jsx(Qe,{value:le,className:"capitalize",children:le.replace(/_/g," ")},le))]})]}),e.jsxs(ds,{value:A,onValueChange:T,children:[e.jsx(ls,{className:"w-[160px] rounded-full h-9",children:e.jsx(us,{placeholder:"Relationship"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All relationships"}),c.map(le=>e.jsx(Qe,{value:le.id,children:[le.first_name,le.last_name].filter(Boolean).join(" ")},le.id))]})]}),e.jsxs(B,{variant:L?"default":"outline",size:"sm",className:"rounded-full",onClick:()=>D(le=>!le),children:[e.jsx(rm,{className:"h-3.5 w-3.5 mr-1.5"}),"Archived"]})]}),s.length===0?e.jsxs(fe,{className:"p-10 rounded-2xl text-center",children:[e.jsx(Fv,{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:()=>F({...Dke}),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add your first opportunity"]})]}):p==="agenda"?e.jsxs("div",{className:"space-y-3",children:[[...Y,...K].length===0&&e.jsx(fe,{className:"p-8 rounded-2xl text-center text-[13.5px] text-slate-500",children:"Nothing matches these filters."}),[...Y,...K].map(le=>e.jsx(mmn,{o:le,onEdit:()=>F(le),onComplete:()=>V(le),onDuplicate:()=>a.mutate(le),onDelete:()=>i.mutate(le.id),onArchive:()=>r.mutate({id:le.id,is_archived:!le.is_archived,status:le.is_archived?"idea":"archived"}),onIcs:()=>pe(le),onPitchTask:()=>l.mutate({title:`Pitch: ${le.title}${le.organization?` (${le.organization})`:""}`,dueAt:le.submission_deadline?new Date(le.submission_deadline).toISOString():null,notes:le.notes??void 0}),onLogOutreach:()=>o.mutate({title:`Outreach for ${le.title}`}),onConfirm:()=>r.mutate({id:le.id,status:"confirmed"})},le.id))]}):e.jsxs(fe,{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(le=>e.jsx("div",{className:"px-2 py-2 text-[11px] uppercase tracking-wider font-semibold text-slate-500 text-center",children:le},le))}),e.jsx("div",{className:"grid grid-cols-7",children:ie.map(le=>{const ve=he(le);return e.jsxs("div",{className:`min-h-[92px] sm:min-h-[112px] border-b border-r p-1.5 ${sU(le,g)||p==="week"?"bg-white":"bg-slate-50/60"}`,children:[e.jsx("button",{onClick:()=>F({...Dke,starts_at:new Date(le.setHours(10,0,0,0)).toISOString()}),className:`text-[11.5px] font-semibold h-6 w-6 rounded-full grid place-items-center ${Vl(le,J)?"bg-violet-600 text-white":"text-slate-500 hover:bg-slate-100"}`,children:Ss(le,"d")}),e.jsxs("div",{className:"mt-1 space-y-1",children:[ve.slice(0,3).map(ge=>e.jsx("button",{onClick:()=>F(ge),className:`w-full text-left text-[11px] px-1.5 py-1 rounded-md border truncate ${oEe[ge.status]??""}`,children:ge.title},ge.id)),ve.length>3&&e.jsxs("div",{className:"text-[10.5px] text-slate-400 pl-1",children:["+",ve.length-3," more"]})]})]},le.toISOString())})}),K.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 (",K.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:K.map(le=>e.jsx("button",{onClick:()=>F(le),className:`text-[12px] px-2.5 py-1 rounded-full border ${oEe[le.status]??""}`,children:le.title},le.id))})]})]}),e.jsx(m6,{}),e.jsx(bs,{open:!!M,onOpenChange:le=>!le&&F(null),children:e.jsxs(vs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsx(_s,{children:M!=null&&M.id?"Edit speaking opportunity":"New speaking opportunity"})}),M&&e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(xd,{label:"Title",className:"sm:col-span-2",children:e.jsx(ye,{value:M.title??"",onChange:le=>F({...M,title:le.target.value}),placeholder:"Panel: Winning listings in a shifting market"})}),e.jsx(xd,{label:"Event / organization",children:e.jsx(ye,{value:M.organization??"",onChange:le=>F({...M,organization:le.target.value})})}),e.jsx(xd,{label:"Event type",children:e.jsxs(ds,{value:M.event_type??"panel",onValueChange:le=>F({...M,event_type:le}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:Wet.map(le=>e.jsx(Qe,{value:le,className:"capitalize",children:le.replace(/_/g," ")},le))})]})}),e.jsx(xd,{label:"Contact name",children:e.jsx(ye,{value:M.contact_name??"",onChange:le=>F({...M,contact_name:le.target.value})})}),e.jsx(xd,{label:"Contact email",children:e.jsx(ye,{type:"email",value:M.contact_email??"",onChange:le=>F({...M,contact_email:le.target.value})})}),e.jsx(xd,{label:"Contact phone",children:e.jsx(ye,{value:M.contact_phone??"",onChange:le=>F({...M,contact_phone:le.target.value})})}),e.jsx(xd,{label:"Audience",children:e.jsx(ye,{value:M.audience??"",onChange:le=>F({...M,audience:le.target.value}),placeholder:"120 local agents"})}),e.jsx(xd,{label:"Location",children:e.jsx(ye,{value:M.location??"",onChange:le=>F({...M,location:le.target.value})})}),e.jsx(xd,{label:"Virtual link",children:e.jsx(ye,{value:M.virtual_link??"",onChange:le=>F({...M,virtual_link:le.target.value})})}),e.jsx(xd,{label:"Starts",children:e.jsx(ye,{type:"datetime-local",value:Yet(M.starts_at),onChange:le=>F({...M,starts_at:le.target.value?new Date(le.target.value).toISOString():null})})}),e.jsx(xd,{label:"Ends",children:e.jsx(ye,{type:"datetime-local",value:Yet(M.ends_at),onChange:le=>F({...M,ends_at:le.target.value?new Date(le.target.value).toISOString():null})})}),e.jsx(xd,{label:"Status",children:e.jsxs(ds,{value:M.status??"idea",onValueChange:le=>F({...M,status:le}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:Get.map(le=>e.jsx(Qe,{value:le,className:"capitalize",children:le},le))})]})}),e.jsx(xd,{label:"Fee / honorarium",children:e.jsx(ye,{type:"number",value:M.fee??"",onChange:le=>F({...M,fee:le.target.value===""?null:Number(le.target.value)})})}),e.jsx(xd,{label:"Submission deadline",children:e.jsx(ye,{type:"date",value:M.submission_deadline??"",onChange:le=>F({...M,submission_deadline:le.target.value||null})})}),e.jsx(xd,{label:"Follow-up date",children:e.jsx(ye,{type:"date",value:M.follow_up_date??"",onChange:le=>F({...M,follow_up_date:le.target.value||null})})}),e.jsx(xd,{label:"Application URL",className:"sm:col-span-2",children:e.jsx(ye,{value:M.application_url??"",onChange:le=>F({...M,application_url:le.target.value})})}),e.jsx(xd,{label:"Topic",className:"sm:col-span-2",children:e.jsx(ye,{value:M.topic??"",onChange:le=>F({...M,topic:le.target.value})})}),e.jsx(xd,{label:"Linked Connect event",children:e.jsxs(ds,{value:M.linked_event_id??"none",onValueChange:le=>F({...M,linked_event_id:le==="none"?null:le}),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"None"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"None"}),h.map(le=>e.jsx(Qe,{value:le.id,children:le.title},le.id))]})]})}),e.jsx(xd,{label:"Linked Resource Kit",children:e.jsxs(ds,{value:M.linked_kit_id??"none",onValueChange:le=>F({...M,linked_kit_id:le==="none"?null:le}),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"None"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"None"}),d.map(le=>e.jsx(Qe,{value:le.id,children:le.title},le.id))]})]})}),e.jsx(xd,{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(le=>{const ve=(M.linked_agent_ids??[]).includes(le.id);return e.jsx("button",{type:"button",onClick:()=>F({...M,linked_agent_ids:ve?(M.linked_agent_ids??[]).filter(ge=>ge!==le.id):[...M.linked_agent_ids??[],le.id]}),className:`text-[12px] px-2.5 py-1 rounded-full border ${ve?"bg-violet-600 text-white border-violet-600":"bg-white text-slate-600"}`,children:[le.first_name,le.last_name].filter(Boolean).join(" ")},le.id)})]})}),e.jsx(xd,{label:"Travel notes",className:"sm:col-span-2",children:e.jsx(Es,{rows:2,value:M.travel_notes??"",onChange:le=>F({...M,travel_notes:le.target.value})})}),e.jsx(xd,{label:"Notes",className:"sm:col-span-2",children:e.jsx(Es,{rows:3,value:M.notes??"",onChange:le=>F({...M,notes:le.target.value})})})]}),e.jsxs(Xn,{className:"gap-2",children:[e.jsx(B,{variant:"ghost",onClick:()=>F(null),children:"Cancel"}),e.jsx(B,{onClick:ce,disabled:n.isPending||r.isPending,className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:"Save"})]})]})}),e.jsx(pmn,{item:z,onClose:()=>V(null),onSave:async(le,ve)=>{await r.mutateAsync({id:z.id,status:"completed",outcome:le}),ve&&await l.mutateAsync({title:`Post-event follow-up: ${z.title}`,dueAt:new Date(Date.now()+2*864e5).toISOString(),notes:le.next_actions}),await o.mutateAsync({title:`Spoke at ${z.title}`,activityType:"speaking_completed"}),V(null)}})]})}function Yet(s){if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)}function xd({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 e7({label:s,value:t,icon:n}){return e.jsxs(fe,{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 mmn({o:s,onEdit:t,onComplete:n,onDuplicate:r,onDelete:a,onArchive:i,onIcs:l,onPitchTask:o,onLogOutreach:c,onConfirm:d}){var p;const u=s,h=u.submission_deadline?Gx(Xh(u.submission_deadline),new Date):null;return e.jsx(fe,{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,(p=u.event_type)==null?void 0:p.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(Tl,{className:"h-3.5 w-3.5"}),Ss(Xh(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(gr,{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(Nn,{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(ze,{variant:"outline",className:`capitalize rounded-full ${oEe[u.status]??""}`,children:u.status}),e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full",children:e.jsx(Qf,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",children:[e.jsx(Qr,{onClick:t,children:"Edit"}),e.jsxs(Qr,{onClick:o,children:[e.jsx(uu,{className:"h-3.5 w-3.5 mr-2"}),"Add pitch task"]}),e.jsxs(Qr,{onClick:c,children:[e.jsx(cr,{className:"h-3.5 w-3.5 mr-2"}),"Log outreach"]}),e.jsxs(Qr,{onClick:d,children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-2"}),"Mark confirmed"]}),e.jsxs(Qr,{onClick:n,children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-2"}),"Mark completed"]}),e.jsxs(Qr,{onClick:l,children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-2"}),"Download .ics"]}),e.jsxs(Qr,{onClick:r,children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-2"}),"Duplicate"]}),e.jsxs(Qr,{onClick:i,children:[e.jsx(rm,{className:"h-3.5 w-3.5 mr-2"}),u.is_archived?"Unarchive":"Archive"]}),e.jsxs(Qr,{className:"text-destructive",onClick:a,children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})]})]})})}function pmn({item:s,onClose:t,onSave:n}){const[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState("");return e.jsx(bs,{open:!!s,onOpenChange:h=>!h&&t(),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsx(ws,{children:e.jsx(_s,{children:"Capture the outcome"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(xd,{label:"Attendance",children:e.jsx(ye,{value:r,onChange:h=>a(h.target.value),placeholder:"How many were in the room?"})}),e.jsx(xd,{label:"Leads / relationships created",children:e.jsx(Es,{rows:2,value:i,onChange:h=>l(h.target.value)})}),e.jsx(xd,{label:"Content captured",children:e.jsx(Es,{rows:2,value:o,onChange:h=>c(h.target.value),placeholder:"Photos, clips, quotes"})}),e.jsx(xd,{label:"Next actions",children:e.jsx(Es,{rows:2,value:d,onChange:h=>u(h.target.value)})})]}),e.jsxs(Xn,{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 qP=q,lEe=["attract-masterclasses"];function fmn(){const{user:s}=ys(),t=Ht(),n=ct({queryKey:[...lEe,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await qP.from("attract_masterclasses").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=()=>t.invalidateQueries({queryKey:lEe}),a=gt({mutationFn:async o=>{const{data:c,error:d}=await qP.from("attract_masterclasses").insert({title:"Untitled masterclass",...o,user_id:s.id}).select("*").single();if(d)throw d;return c},onSuccess:()=>r(),onError:o=>ae.error(o.message)}),i=gt({mutationFn:async o=>{const{id:c,created_at:d,updated_at:u,user_id:h,...p}=o,{data:f,error:g}=await qP.from("attract_masterclasses").insert({...p,title:`${o.title} (copy)`,status:"draft",user_id:s.id}).select("id").single();if(g)throw g;return f},onSuccess:()=>{r(),ae.success("Duplicated")},onError:o=>ae.error(o.message)}),l=gt({mutationFn:async o=>{const{error:c}=await qP.from("attract_masterclasses").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),ae.success("Deleted")},onError:o=>ae.error(o.message)});return{items:n.data??[],isLoading:n.isLoading,refetch:n.refetch,create:a,duplicate:i,remove:l}}function xmn(s){const t=Ht(),n=ct({queryKey:["attract-masterclass",s],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await qP.from("attract_masterclasses").select("*").eq("id",s).maybeSingle();if(i)throw i;return a}}),r=gt({mutationFn:async a=>{const{error:i}=await qP.from("attract_masterclasses").update(a).eq("id",s);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-masterclass",s]}),t.invalidateQueries({queryKey:lEe})},onError:a=>ae.error(a.message)});return{masterclass:n.data??null,isLoading:n.isLoading,save:r}}const tu=(s,t)=>({id:crypto.randomUUID(),title:s,lessons:t.map(([n,r,a])=>({id:crypto.randomUUID(),title:n,minutes:r,talking_points:a}))}),Zet=[{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:[tu("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"]]),tu("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"]]),tu("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:[tu("Audit",[["Sorting your list into A/B/C",10,"Criteria that actually predict referrals"],["Fixing missing data",8,"Birthdays, anniversaries, spouse names"]]),tu("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"]]),tu("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:[tu("Before",[["Neighborhood invites",8,"Door knocking and digital invites"],["Setting the stage",7,"Materials that create conversations"]]),tu("During",[["The three questions",10,"How to qualify without interrogating"],["Capturing real contact info",8,"Sign-in that people actually complete"]]),tu("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:[tu("Positioning",[["Pick your lane",10,"Neighborhood, niche, or narrative"],["What to never post",6,"The credibility killers"]]),tu("Content system",[["The four content types",14,"Teach, prove, connect, invite"],["Batch filming",10,"One hour, ten pieces"]]),tu("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:[tu("Foundations",[["What AI is good and bad at",10,"Drafting vs deciding"],["Prompting basics",10,"Context, role, constraints"]]),tu("Workflows",[["Listing descriptions and marketing",12,"Brand voice inputs"],["Follow-up and email drafts",12,"Never auto-send"]]),tu("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:[tu("The builder landscape",[["How builder comp works",12,"Registration rules that protect you"],["Local builders worth knowing",8,"Relationship map"]]),tu("Representing the buyer",[["Contract differences",14,"What is negotiable"],["Inspections and walkthroughs",10,"Timeline checkpoints"]]),tu("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:[tu("Standards",[["What luxury clients notice",12,"Response time, discretion, detail"],["Your materials",10,"Photography, print, web"]]),tu("The listing experience",[["Pre-market strategy",12,"Whisper listings and staging"],["Private showings",8,"Choreography"]]),tu("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:[tu("Mindset",[["Why value beats pitching",10,"Relationship-first framing"],["Choosing your 20",8,"Fit criteria"]]),tu("The value plan",[["Resource kits that help",14,"What agents actually want"],["Events and masterminds",10,"Small rooms win"]]),tu("The conversation",[["When to talk business",10,"Earned invitation"],['Handling "I am happy where I am"',8,"Stay in relationship"]])]}];function gmn(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 ymn(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 vmn(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("",`${rW(n)} SECTION: ${r.title}`),r.lessons.forEach(a=>{t.push(`${rW(n)} ${a.title}${a.minutes?` (${a.minutes}m)`:""}${a.talking_points?` — ${a.talking_points}`:""}`),n+=a.minutes??5})}),t.push("",`${rW(n)} Q&A`,`${rW(n+7)} Close: next step + resource kit`),t.join(` `)}function rW(s){const t=Math.floor(s/60),n=s%60;return`${t}:${String(n).padStart(2,"0")}`}function bmn(){const{items:s,isLoading:t,create:n,duplicate:r,remove:a}=fmn(),i=Mn(),[l,o]=N.useState(!1),c=s.filter(p=>!p.is_archived),d=s.filter(p=>p.is_archived),u=async()=>{const p=await n.mutateAsync({title:"Untitled masterclass"});i(`/attract/provide/masterclasses/${p.id}`)},h=async p=>{const f=Zet.find(_=>_.key===p),g=await n.mutateAsync(gmn(f));i(`/attract/provide/masterclasses/${g.id}`)};return t?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-28 rounded-2xl"}),e.jsx(Ws,{className:"h-64 rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(Vu,{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(p=>!p),children:[e.jsx(un,{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(Is,{className:"h-4 w-4 mr-2"}),"New masterclass"]})]})}),(l||s.length===0)&&e.jsxs(fe,{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:Zet.map(p=>e.jsxs("button",{onClick:()=>h(p.key),className:"text-left p-4 rounded-xl border hover:border-violet-300 hover:shadow-sm transition",children:[e.jsx(ze,{variant:"secondary",className:"capitalize mb-2",children:p.pillar}),e.jsx("div",{className:"font-semibold text-[14px] text-slate-900",children:p.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1 line-clamp-3",children:p.promise}),e.jsxs("div",{className:"text-[11.5px] text-slate-400 mt-2",children:[p.duration_minutes," min · ",p.curriculum.length," sections"]})]},p.key))})]}),c.length===0?e.jsxs(fe,{className:"p-10 rounded-2xl text-center",children:[e.jsx(_d,{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(p=>e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(ze,{variant:"outline",className:"capitalize rounded-full",children:p.status}),e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full h-7 w-7",children:e.jsx(Qf,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",children:[e.jsx(Qr,{onClick:()=>i(`/attract/provide/masterclasses/${p.id}`),children:"Open builder"}),e.jsxs(Qr,{onClick:()=>r.mutate(p),children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-2"}),"Duplicate"]}),e.jsxs(Qr,{className:"text-destructive",onClick:()=>a.mutate(p.id),children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})]}),e.jsxs(Ln,{to:`/attract/provide/masterclasses/${p.id}`,className:"block mt-2",children:[e.jsx("div",{className:"font-semibold text-slate-900 line-clamp-2",children:p.title}),p.promise&&e.jsx("div",{className:"text-[12.5px] text-slate-500 line-clamp-2 mt-1",children:p.promise})]}),e.jsxs("div",{className:"text-[11.5px] text-slate-400 mt-3",children:[(p.curriculum??[]).length," sections · ",p.duration_minutes??45," min",p.delivery_date&&` · ${Ss(new Date(p.delivery_date),"MMM d")}`]})]},p.id))}),d.length>0&&e.jsxs(fe,{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(rm,{className:"h-3.5 w-3.5"}),"Archived"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:d.map(p=>e.jsx(Ln,{to:`/attract/provide/masterclasses/${p.id}`,className:"text-[12.5px] px-2.5 py-1 rounded-full border text-slate-600",children:p.title},p.id))})]}),e.jsx(m6,{})]})}const Qet=q,_mn=["Strategy","Curriculum","Assets","Promotion","Delivery","Follow-up"];function wmn(){var Y,K,J,ne,ie,he,ce,pe,le,ve,ge,Te,Me;const{masterclassId:s}=bi(),t=Mn(),{user:n}=ys(),{masterclass:r,isLoading:a,save:i}=xmn(s),l=SSt(),{create:o}=FR(),[c,d]=N.useState(null),[u,h]=N.useState(0),[p,f]=N.useState(!1),[g,_]=N.useState("idle"),v=N.useRef(null),j=N.useRef(!1);N.useEffect(()=>{r&&!c&&d(r)},[r,c]);const b=Ce=>{d(Ae=>Ae&&{...Ae,...Ce}),j.current=!0,_("saving"),clearTimeout(v.current),v.current=setTimeout(()=>S({...c??{},...Ce}),900)},S=async Ce=>{const{id:Ae,user_id:De,created_at:Ie,updated_at:Fe,...qe}=Ce;await i.mutateAsync(qe),j.current=!1,_("saved"),setTimeout(()=>_(be=>be==="saved"?"idle":be),1800)},A=(c==null?void 0:c.curriculum)??[],T=Ce=>b({curriculum:Ce}),L=N.useMemo(()=>A.reduce((Ce,Ae)=>Ce+Ae.lessons.reduce((De,Ie)=>De+(Ie.minutes??0),0),0),[A]);if(a||!c)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-24 rounded-2xl"}),e.jsx(Ws,{className:"h-96 rounded-2xl"})]});const D=()=>{b({promotion:{...c.promotion,...ymn(c)}}),ae.success("Draft copy generated — edit before you send anything")},M=()=>{b({delivery:{...c.delivery,run_of_show:vmn(c)}}),ae.success("Run of show generated")},F=async()=>{const Ce=await l.mutateAsync({title:c.title,description:c.promise??void 0,event_type:"masterclass",intended_audience:c.target_audience??void 0,related_pillar:c.pillar??"provide",starts_at:c.delivery_date??new Date(Date.now()+12096e5).toISOString(),format:c.format==="in_person"?"in_person":"virtual",agenda:A.flatMap(Ae=>Ae.lessons.map(De=>({item:`${Ae.title}: ${De.title}`}))),learning_outcomes:c.desired_outcome?[c.desired_outcome]:[]});await i.mutateAsync({linked_event_id:Ce.id,status:"scheduled"}),d(Ae=>Ae&&{...Ae,linked_event_id:Ce.id,status:"scheduled"}),ae.success("Connect event created as a draft"),t(`/attract/events/${Ce.id}/edit`)},z=async()=>{var De,Ie,Fe,qe,be;const Ce=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:((De=c.assets)==null?void 0:De.workbook)??void 0,cta_label:((Ie=c.assets)==null?void 0:Ie.cta_label)??void 0,cta_url:((Fe=c.assets)==null?void 0:Fe.cta_url)??void 0}),Ae=[...(((qe=c.assets)==null?void 0:qe.downloads)??[]).map((Ze,Ne)=>({type:"link",title:Ze.title,url:Ze.url,sort_order:Ne})),...(((be=c.assets)==null?void 0:be.videos)??[]).map((Ze,Ne)=>({type:"video",title:Ze.title,url:Ze.url,sort_order:100+Ne}))];Ae.length&&await Qet.from("attract_resource_kit_items").insert(Ae.map(Ze=>({...Ze,kit_id:Ce.id,user_id:n.id}))),await i.mutateAsync({linked_kit_id:Ce.id}),d(Ze=>Ze&&{...Ze,linked_kit_id:Ce.id}),ae.success("Resource Kit created from your assets"),t(`/attract/provide/kits/${Ce.id}/edit`)},V=async()=>{const Ce=Date.now(),Ae=[{title:`Send recap + resources: ${c.title}`,due_at:new Date(Ce+1*864e5).toISOString()},{title:`Personal check-in with attendees: ${c.title}`,due_at:new Date(Ce+3*864e5).toISOString()},{title:`Invite engaged attendees to a 1:1: ${c.title}`,due_at:new Date(Ce+7*864e5).toISOString()}],{error:De}=await Qet.from("attract_follow_ups").insert(Ae.map(Ie=>({...Ie,user_id:n.id,touch_type:"masterclass",priority:"medium"})));if(De){ae.error(De.message);return}ae.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(Ln,{to:"/attract/provide/masterclasses",children:[e.jsx(Hr,{className:"h-3.5 w-3.5 mr-1.5"}),"All masterclasses"]})}),e.jsx(Vu,{eyebrow:"Pillar 03 · Provide",title:c.title||"Untitled masterclass",description:c.promise??"Build the promise, curriculum, assets, promotion, delivery and follow-up.",actions:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[12px] text-slate-500 inline-flex items-center gap-1.5",children:g==="saving"?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"h-3.5 w-3.5 animate-spin"}),"Saving…"]}):g==="saved"?e.jsxs(e.Fragment,{children:[e.jsx(Ir,{className:"h-3.5 w-3.5 text-emerald-600"}),"Saved"]}):"All changes saved"}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>f(Ce=>!Ce),children:[e.jsx(Er,{className:"h-4 w-4 mr-2"}),p?"Edit":"Preview"]})]})}),e.jsx(fe,{className:"p-2 rounded-2xl flex gap-1 overflow-x-auto",children:_mn.map((Ce,Ae)=>e.jsxs("button",{onClick:()=>{f(!1),h(Ae)},className:`px-3.5 py-2 rounded-xl text-[13px] font-medium whitespace-nowrap ${u===Ae&&!p?"bg-violet-600 text-white":"text-slate-600 hover:bg-slate-100"}`,children:[Ae+1,". ",Ce]},Ce))}),p?e.jsx(Nmn,{m:c}):e.jsxs(fe,{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(Ju,{label:"Title",className:"sm:col-span-2",children:e.jsx(ye,{value:c.title,onChange:Ce=>b({title:Ce.target.value})})}),e.jsx(Ju,{label:"The promise",className:"sm:col-span-2",children:e.jsx(Es,{rows:2,value:c.promise??"",onChange:Ce=>b({promise:Ce.target.value}),placeholder:"Walk out with…"})}),e.jsx(Ju,{label:"Target audience",children:e.jsx(ye,{value:c.target_audience??"",onChange:Ce=>b({target_audience:Ce.target.value})})}),e.jsx(Ju,{label:"Problem solved",children:e.jsx(ye,{value:c.problem_solved??"",onChange:Ce=>b({problem_solved:Ce.target.value})})}),e.jsx(Ju,{label:"Desired outcome",className:"sm:col-span-2",children:e.jsx(ye,{value:c.desired_outcome??"",onChange:Ce=>b({desired_outcome:Ce.target.value})})}),e.jsx(Ju,{label:"Pillar",children:e.jsxs(ds,{value:c.pillar??"provide",onValueChange:Ce=>b({pillar:Ce}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:["produce","influence","provide","connect"].map(Ce=>e.jsx(Qe,{value:Ce,className:"capitalize",children:Ce},Ce))})]})}),e.jsx(Ju,{label:"Format",children:e.jsxs(ds,{value:c.format??"virtual",onValueChange:Ce=>b({format:Ce}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:["virtual","in_person","hybrid"].map(Ce=>e.jsx(Qe,{value:Ce,className:"capitalize",children:Ce.replace("_"," ")},Ce))})]})}),e.jsx(Ju,{label:"Duration (minutes)",children:e.jsx(ye,{type:"number",value:c.duration_minutes??45,onChange:Ce=>b({duration_minutes:Number(Ce.target.value)})})}),e.jsx(Ju,{label:"Delivery date",children:e.jsx(ye,{type:"datetime-local",value:jmn(c.delivery_date),onChange:Ce=>b({delivery_date:Ce.target.value?new Date(Ce.target.value).toISOString():null})})}),e.jsx(Ju,{label:"Status",children:e.jsxs(ds,{value:c.status,onValueChange:Ce=>b({status:Ce}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:["draft","ready","scheduled","delivered","archived"].map(Ce=>e.jsx(Qe,{value:Ce,className:"capitalize",children:Ce},Ce))})]})})]}),u===1&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[A.length," sections · ",L," minutes planned"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>T([...A,{id:crypto.randomUUID(),title:"New section",lessons:[]}]),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"}),"Add section"]})]}),A.length===0&&e.jsx("div",{className:"text-[13.5px] text-slate-500 border border-dashed rounded-xl p-8 text-center",children:"No sections yet. Add your first one."}),A.map((Ce,Ae)=>e.jsxs(fe,{className:"p-4 rounded-xl bg-slate-50/60",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{value:Ce.title,onChange:De=>T(A.map(Ie=>Ie.id===Ce.id?{...Ie,title:De.target.value}:Ie)),className:"font-semibold"}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Ae===0,onClick:()=>T(aW(A,Ae,Ae-1)),children:e.jsx(tx,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Ae===A.length-1,onClick:()=>T(aW(A,Ae,Ae+1)),children:e.jsx(io,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>T(A.filter(De=>De.id!==Ce.id)),children:e.jsx(_n,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[Ce.lessons.map((De,Ie)=>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:De.title,placeholder:"Lesson title",onChange:Fe=>W(Ce.id,De.id,{title:Fe.target.value})}),e.jsx(ye,{type:"number",className:"w-20",value:De.minutes??"",placeholder:"min",onChange:Fe=>W(Ce.id,De.id,{minutes:Number(Fe.target.value)})}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Ie===0,onClick:()=>T(A.map(Fe=>Fe.id===Ce.id?{...Fe,lessons:aW(Fe.lessons,Ie,Ie-1)}:Fe)),children:e.jsx(tx,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Ie===Ce.lessons.length-1,onClick:()=>T(A.map(Fe=>Fe.id===Ce.id?{...Fe,lessons:aW(Fe.lessons,Ie,Ie+1)}:Fe)),children:e.jsx(io,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>T(A.map(Fe=>Fe.id===Ce.id?{...Fe,lessons:Fe.lessons.filter(qe=>qe.id!==De.id)}:Fe)),children:e.jsx(_n,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-2",children:[e.jsx(Es,{rows:2,placeholder:"Talking points",value:De.talking_points??"",onChange:Fe=>W(Ce.id,De.id,{talking_points:Fe.target.value})}),e.jsx(Es,{rows:2,placeholder:"Exercise",value:De.exercise??"",onChange:Fe=>W(Ce.id,De.id,{exercise:Fe.target.value})}),e.jsx(Es,{rows:2,placeholder:"Example / story",value:De.example??"",onChange:Fe=>W(Ce.id,De.id,{example:Fe.target.value})}),e.jsx(Es,{rows:2,placeholder:"Speaker notes",value:De.speaker_notes??"",onChange:Fe=>W(Ce.id,De.id,{speaker_notes:Fe.target.value})})]})]},De.id)),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>T(A.map(De=>De.id===Ce.id?{...De,lessons:[...De.lessons,{id:crypto.randomUUID(),title:""}]}:De)),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"}),"Add lesson"]})]})]},Ce.id))]}),u===2&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ju,{label:"Slide outline",children:e.jsx(Es,{rows:5,value:((Y=c.assets)==null?void 0:Y.slide_outline)??"",onChange:Ce=>b({assets:{...c.assets,slide_outline:Ce.target.value}})})}),e.jsx(Ju,{label:"Workbook / checklist outline",children:e.jsx(Es,{rows:5,value:((K=c.assets)==null?void 0:K.workbook)??"",onChange:Ce=>b({assets:{...c.assets,workbook:Ce.target.value}})})}),e.jsx(Xet,{label:"Downloads",items:((J=c.assets)==null?void 0:J.downloads)??[],onChange:Ce=>b({assets:{...c.assets,downloads:Ce}})}),e.jsx(Xet,{label:"Videos",items:((ne=c.assets)==null?void 0:ne.videos)??[],onChange:Ce=>b({assets:{...c.assets,videos:Ce}})}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(Ju,{label:"CTA label",children:e.jsx(ye,{value:((ie=c.assets)==null?void 0:ie.cta_label)??"",onChange:Ce=>b({assets:{...c.assets,cta_label:Ce.target.value}})})}),e.jsx(Ju,{label:"CTA URL",children:e.jsx(ye,{value:((he=c.assets)==null?void 0:he.cta_url)??"",onChange:Ce=>b({assets:{...c.assets,cta_url:Ce.target.value}})})})]}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:z,disabled:o.isPending,children:[e.jsx(f9,{className:"h-4 w-4 mr-2"}),"Create Resource Kit from these assets"]}),c.linked_kit_id&&e.jsx(ze,{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:D,children:[e.jsx(Dm,{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(([Ce,Ae])=>{var De;return e.jsx(Ju,{label:Ae,children:e.jsx(Es,{rows:5,value:((De=c.promotion)==null?void 0:De[Ce])??"",onChange:Ie=>b({promotion:{...c.promotion,[Ce]:Ie.target.value}})})},Ce)})]}),u===4&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:M,children:[e.jsx(Dm,{className:"h-4 w-4 mr-2"}),"Build run of show"]})}),e.jsx(Ju,{label:"Run of show",children:e.jsx(Es,{rows:12,className:"font-mono text-[12.5px]",value:((ce=c.delivery)==null?void 0:ce.run_of_show)??"",onChange:Ce=>b({delivery:{...c.delivery,run_of_show:Ce.target.value}})})}),e.jsx(Ju,{label:"Check-in link",children:e.jsx(ye,{value:((pe=c.delivery)==null?void 0:pe.checkin_link)??"",onChange:Ce=>b({delivery:{...c.delivery,checkin_link:Ce.target.value}}),placeholder:"Paste the Connect event check-in URL"})}),e.jsx(Ju,{label:"Event notes",children:e.jsx(Es,{rows:4,value:((le=c.delivery)==null?void 0:le.event_notes)??"",onChange:Ce=>b({delivery:{...c.delivery,event_notes:Ce.target.value}})})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:F,disabled:l.isPending,children:[e.jsx(Rg,{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(Ln,{to:`/attract/events/${c.linked_event_id}`,children:"Open linked event"})})]})]}),u===5&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ju,{label:"Attendee segmentation",children:e.jsx(Es,{rows:3,value:((ve=c.follow_up)==null?void 0:ve.segments)??"",onChange:Ce=>b({follow_up:{...c.follow_up,segments:Ce.target.value}}),placeholder:"Attended + asked a question / attended / registered no-show"})}),e.jsx(Ju,{label:"Resource kit sharing note",children:e.jsx(Es,{rows:3,value:((ge=c.follow_up)==null?void 0:ge.kit_note)??"",onChange:Ce=>b({follow_up:{...c.follow_up,kit_note:Ce.target.value}})})}),e.jsx(Ju,{label:"Suggested personal follow-ups",children:e.jsx(Es,{rows:3,value:((Te=c.follow_up)==null?void 0:Te.personal_touches)??"",onChange:Ce=>b({follow_up:{...c.follow_up,personal_touches:Ce.target.value}})})}),e.jsx(Ju,{label:"Conversion / relationship outcomes",children:e.jsx(Es,{rows:3,value:((Me=c.follow_up)==null?void 0:Me.outcomes)??"",onChange:Ce=>b({follow_up:{...c.follow_up,outcomes:Ce.target.value}})})}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:V,children:[e.jsx(uu,{className:"h-4 w-4 mr-2"}),"Add 3 follow-ups to Follow-Up Center"]})]})]})]});function W(Ce,Ae,De){T(A.map(Ie=>Ie.id===Ce?{...Ie,lessons:Ie.lessons.map(Fe=>Fe.id===Ae?{...Fe,...De}:Fe)}:Ie))}}function aW(s,t,n){const r=[...s],[a]=r.splice(t,1);return r.splice(n,0,a),r}function jmn(s){if(!s)return"";const t=new Date(s);return new Date(t.getTime()-t.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function Ju({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 Xet({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(_n,{className:"h-4 w-4"})})]},a)),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>n([...t,{title:"",url:""}]),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"}),"Add ",s.toLowerCase().slice(0,-1)]})]})]})}function Nmn({m:s}){var t,n,r;return e.jsxs("div",{className:"grid lg:grid-cols-2 gap-4",children:[e.jsxs(fe,{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(fe,{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(fe,{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(fe,{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 lS=q;function tq(s,t={}){const{orderBy:n="created_at",ascending:r=!1,titleField:a="title",duplicateOverrides:i={},label:l="Record"}=t,{user:o}=ys(),c=Ht(),d=[s,o==null?void 0:o.id],u=ct({queryKey:d,enabled:!!o,queryFn:async()=>{const{data:j,error:b}=await lS.from(s).select("*").order(n,{ascending:r,nullsFirst:!1});if(b)throw b;return j??[]}}),h=()=>{c.invalidateQueries({queryKey:[s]}),c.invalidateQueries({queryKey:["attract-followups"]}),c.invalidateQueries({queryKey:["attract-activities"]})},p=gt({mutationFn:async j=>{const{data:b,error:S}=await lS.from(s).insert({...j,user_id:o.id}).select("*").single();if(S)throw S;return b},onSuccess:()=>{h(),ae.success(`${l} saved`)},onError:j=>ae.error(j.message)}),f=gt({mutationFn:async({id:j,...b})=>{const{error:S}=await lS.from(s).update(b).eq("id",j);if(S)throw S},onSuccess:()=>{h(),ae.success("Updated")},onError:j=>ae.error(j.message)}),g=gt({mutationFn:async j=>{const{id:b,created_at:S,updated_at:A,user_id:T,...L}=j,D={...L,...i,user_id:o.id};a&&D[a]&&(D[a]=`${D[a]} (copy)`);const{data:M,error:F}=await lS.from(s).insert(D).select("id").single();if(F)throw F;return M},onSuccess:()=>{h(),ae.success("Duplicated")},onError:j=>ae.error(j.message)}),_=gt({mutationFn:async({id:j,archived:b})=>{const{error:S}=await lS.from(s).update({is_archived:b}).eq("id",j);if(S)throw S},onSuccess:(j,b)=>{h(),ae.success(b.archived?"Archived":"Restored")},onError:j=>ae.error(j.message)}),v=gt({mutationFn:async j=>{const{error:b}=await lS.from(s).delete().eq("id",j);if(b)throw b},onSuccess:()=>{h(),ae.success("Deleted")},onError:j=>ae.error(j.message)});return{items:u.data??[],isLoading:u.isLoading,error:u.error,refetch:u.refetch,create:p,update:f,duplicate:g,archive:_,remove:v,userId:o==null?void 0:o.id}}function ybe(){const{user:s}=ys(),t=Ht();return gt({mutationFn:async({title:n,dueAt:r,notes:a,touchType:i="task",agentId:l})=>{const{error:o}=await lS.from("attract_follow_ups").insert({user_id:s.id,title:n,due_at:r??null,notes:a??null,touch_type:i,priority:"medium",agent_id:l??null});if(o)throw o},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-daily-plan"]}),ae.success("Added to Follow-Up Center & Today’s Plan")},onError:n=>ae.error(n.message)})}function sq(){const{user:s}=ys(),t=Ht();return gt({mutationFn:async({title:n,description:r,pillar:a="produce",activityType:i="tool_action",agentId:l,metadata:o})=>{const{error:c}=await lS.rpc("award_attract_activity",{_user_id:s.id,_activity_type:i,_title:n,_description:r??null,_pillar:a,_agent_id:l??null,_metadata:o??{},_dedupe_minutes:5});if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-activities"]}),t.invalidateQueries({queryKey:["attract-score"]})},onError:n=>ae.error(n.message)})}const kmn=["annual","quarterly","monthly"],tP=[{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 sP(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 Smn(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 Cmn(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 Tmn(){const s=tq("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}=e4t(),n=ybe(),r=sq(),a=N.useMemo(()=>{const i={};return s.items.forEach(l=>{i[l.id]={closings:t.filter(o=>Cmn(o.closing_date,l)).length}}),i},[s.items,t]);return{...s,goals:s.items,autoProgress:a,quickTask:n,logActivity:r}}function Emn(s){const t=Number(s??0);return t?{monthly:t/12,weekly:t/52}:null}const Amn=Array.from({length:12},(s,t)=>({value:t+1,label:new Date(2e3,t,1).toLocaleString("en-US",{month:"long"})}));function p2(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 Mmn({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 Jet={period_type:"annual",year:new Date().getFullYear(),quarter:1,month:new Date().getMonth()+1,use_auto_progress:!0};function Imn(){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}=Tmn(),[p,f]=N.useState(!1),[g,_]=N.useState(null),[v,j]=N.useState(null),[b,S]=N.useState(null),A=N.useMemo(()=>s.filter(M=>p?M.is_archived:!M.is_archived),[s,p]),T=(M,F)=>{var V;const z=Number(M[F.actual]??0);return M.use_auto_progress&&F.key==="closings"?Math.max(z,((V=d[M.id])==null?void 0:V.closings)??0):z},L=async()=>{var F;if(!g)return;const M={label:((F=g.label)==null?void 0:F.trim())||null,period_type:g.period_type??"annual",year:Number(g.year)||new Date().getFullYear(),quarter:g.period_type==="quarterly"?Number(g.quarter)||1:null,month:g.period_type==="monthly"?Number(g.month)||1:null,closings_target:g.closings_target??null,gci_target:g.gci_target??null,volume_target:g.volume_target??null,listings_target:g.listings_target??null,buyer_sides_target:g.buyer_sides_target??null,appointments_target:g.appointments_target??null,use_auto_progress:g.use_auto_progress??!0,notes:g.notes??null};g.id?await i.mutateAsync({id:g.id,...M}):await a.mutateAsync(M),_(null)},D=async()=>{if(!v)return;const M={};tP.forEach(F=>{M[F.actual]=Number(v[F.actual]??0)}),await i.mutateAsync({id:v.id,...M}),await h.mutateAsync({title:`Updated production progress — ${sP(v)}`,pillar:"produce",activityType:"goal_progress"}),j(null)};return e.jsxs("div",{children:[e.jsxs(Ln,{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(Hr,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Vu,{eyebrow:"Produce → Tool",title:"Production Goals",description:"Set the annual, quarterly, and monthly numbers you're playing for — then track pace, not just totals. Progress can be updated manually or pulled from the transactions you log.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>f(M=>!M),children:p?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>_({...Jet}),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," New Goal"]})]})}),t&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:[0,1].map(M=>e.jsx(Ws,{className:"h-56 rounded-2xl"},M))}),!t&&n&&e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Gi,{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(cm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&A.length===0&&e.jsxs(fe,{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(Oc,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:p?"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."}),!p&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>_({...Jet}),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Create your first goal"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:A.map(M=>{const F=Smn(M),z=tP.find(ie=>M[ie.target])??tP[0],V=Number(M[z.target]??0),W=T(M,z),Y=V?W/V:0,K=V*F,J=W>=K,ne=Emn(V);return e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[16px] font-semibold text-slate-900",children:M.label||`${sP(M)} Goals`}),e.jsx(ze,{variant:"outline",className:"rounded-full capitalize",children:M.period_type}),e.jsx(ze,{variant:"outline",className:"rounded-full",children:sP(M)})]}),M.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:M.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>_(M),children:e.jsx(_a,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(M),children:e.jsx(Xr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:M.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:M.id,archived:!M.is_archived}),children:e.jsx(rm,{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:()=>S(M),children:e.jsx(_n,{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(Mmn,{pct:Y}),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(Y*100),"%"]})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-wider text-slate-500",children:z.label}),e.jsxs("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:[p2(W,z.format)," ",e.jsxs("span",{className:"text-slate-400 text-[15px]",children:["/ ",p2(V,z.format)]})]}),e.jsxs("div",{className:`text-[12.5px] mt-0.5 font-medium ${J?"text-emerald-600":"text-amber-600"}`,children:[J?"Ahead of pace":"Behind pace"," · pace target ",p2(K,z.format)," (",Math.round(F*100),"% of period elapsed)"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 mt-4",children:tP.filter(ie=>M[ie.target]).map(ie=>{const he=Number(M[ie.target]),ce=T(M,ie);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:ie.label}),e.jsxs("div",{className:"text-[13.5px] font-semibold tabular-nums text-slate-900",children:[p2(ce,ie.format)," / ",p2(he,ie.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,he?ce/he*100:0)}%`}})})]},ie.key)})}),M.period_type==="annual"&&ne&&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:p2(ne.monthly,z.format)})," per month ·"," ",e.jsx("strong",{children:p2(ne.weekly,z.format)})," per week of ",z.label.toLowerCase(),"."]}),e.jsxs("div",{className:"flex gap-2 mt-4 flex-wrap",children:[e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>j({...M}),children:"Update progress"}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>u.mutate({title:`Goal push: ${z.label} — ${p2(ne?ne.weekly:V,z.format)} this week`,dueAt:new Date().toISOString(),notes:`From ${sP(M)} production goal`,touchType:"goal"}),children:[e.jsx(uu,{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 ${sP(M)} goals`,pillar:"produce",activityType:"goal_win"}),children:[e.jsx(vo,{className:"h-3.5 w-3.5 mr-1.5"})," Log a win"]})]})]},M.id)})}),e.jsx(bs,{open:!!g,onOpenChange:M=>!M&&_(null),children:e.jsxs(vs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:g!=null&&g.id?"Edit goal":"New production goal"}),e.jsx(Qn,{children:"Only fill in the targets you actually track. Blank targets are hidden."})]}),g&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Label (optional)"}),e.jsx(ye,{value:g.label??"",onChange:M=>_({...g,label:M.target.value}),placeholder:"e.g. 2026 Big Rock"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Period"}),e.jsxs(ds,{value:g.period_type,onValueChange:M=>_({...g,period_type:M}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:kmn.map(M=>e.jsx(Qe,{value:M,className:"capitalize",children:M},M))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Year"}),e.jsx(ye,{type:"number",value:g.year??"",onChange:M=>_({...g,year:Number(M.target.value)})})]}),g.period_type==="quarterly"&&e.jsxs("div",{children:[e.jsx(se,{children:"Quarter"}),e.jsxs(ds,{value:String(g.quarter??1),onValueChange:M=>_({...g,quarter:Number(M)}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:[1,2,3,4].map(M=>e.jsxs(Qe,{value:String(M),children:["Q",M]},M))})]})]}),g.period_type==="monthly"&&e.jsxs("div",{children:[e.jsx(se,{children:"Month"}),e.jsxs(ds,{value:String(g.month??1),onValueChange:M=>_({...g,month:Number(M)}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:Amn.map(M=>e.jsx(Qe,{value:String(M.value),children:M.label},M.value))})]})]})]}),e.jsx("div",{className:"grid sm:grid-cols-3 gap-3",children:tP.map(M=>e.jsxs("div",{children:[e.jsxs(se,{children:[M.label," target"]}),e.jsx(ye,{type:"number",value:g[M.target]??"",onChange:F=>_({...g,[M.target]:F.target.value===""?null:Number(F.target.value)})})]},M.key))}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:"Pull closings from logged transactions"}),e.jsx("div",{className:"text-[12px] text-slate-600",children:"Uses the transactions in your Transaction-to-Relationship Tracker for this period."})]}),e.jsx(bn,{checked:g.use_auto_progress??!0,onCheckedChange:M=>_({...g,use_auto_progress:M})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Es,{value:g.notes??"",onChange:M=>_({...g,notes:M.target.value}),rows:3})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>_(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:L,disabled:a.isPending||i.isPending,children:"Save goal"})]})]})}),e.jsx(bs,{open:!!v,onOpenChange:M=>!M&&j(null),children:e.jsxs(vs,{className:"max-w-lg",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Update progress"}),e.jsxs(Qn,{children:[v?sP(v):""," — enter your actuals to date."]})]}),v&&e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:tP.filter(M=>v[M.target]).map(M=>e.jsxs("div",{children:[e.jsx(se,{children:M.label}),e.jsx(ye,{type:"number",value:v[M.actual]??0,onChange:F=>j({...v,[M.actual]:Number(F.target.value)})})]},M.key))}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>j(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:D,children:"Save progress"})]})]})}),e.jsx(bs,{open:!!b,onOpenChange:M=>!M&&S(null),children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Delete this goal?"}),e.jsx(Qn,{children:"This can't be undone. Archive it instead if you want to keep the history."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>S(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(b.id),S(null)},children:"Delete"})]})]})})]})}const Rke=[{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 Pmn(){const s=tq("attract_awards",{orderBy:"awarded_on",ascending:!1,label:"Award",duplicateOverrides:{is_archived:!1}}),t=sq();return{...s,awards:s.items,logActivity:t}}const ett={category:"award",status:"active",is_public:!0};function ttt(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 Lmn(){const{awards:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,logActivity:d}=Pmn(),[u,h]=N.useState(!1),[p,f]=N.useState("all"),[g,_]=N.useState(""),[v,j]=N.useState(null),[b,S]=N.useState(null),A=N.useMemo(()=>s.filter(D=>{if(u!==!!D.is_archived||p!=="all"&&D.category!==p)return!1;const M=g.toLowerCase().trim();return!M||`${D.title} ${D.issuer??""} ${D.description??""}`.toLowerCase().includes(M)}),[s,u,p,g]),T=async()=>{var M;if(!((M=v==null?void 0:v.title)!=null&&M.trim())){ae.error("Add a title");return}const D={title:v.title.trim(),issuer:v.issuer||null,awarded_on:v.awarded_on||null,category:v.category??"award",description:v.description||null,proof_url:v.proof_url||null,production_period:v.production_period||null,is_public:v.is_public??!0};v.id?await i.mutateAsync({id:v.id,...D}):(await a.mutateAsync(D),await d.mutateAsync({title:`Added recognition: ${D.title}`,pillar:"produce",activityType:"award_added"})),j(null)},L=D=>{var F;const M=[D.title,D.issuer&&`— ${D.issuer}`,D.awarded_on&&`(${ttt(D.awarded_on)})`].filter(Boolean).join(" ");(F=navigator.clipboard)==null||F.writeText(M),ae.success("Proof point copied — paste it into Content Studio")};return e.jsxs("div",{children:[e.jsxs(Ln,{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(Hr,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Vu,{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(D=>!D),children:u?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>j({...ett}),children:[e.jsx(Is,{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:g,onChange:D=>_(D.target.value),placeholder:"Search recognitions",className:"max-w-xs rounded-full"}),e.jsxs(ds,{value:p,onValueChange:f,children:[e.jsx(ls,{className:"w-[190px] rounded-full",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All categories"}),Rke.map(D=>e.jsx(Qe,{value:D.value,children:D.label},D.value))]})]})]}),t&&e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[0,1,2,3].map(D=>e.jsx(Ws,{className:"h-36 rounded-2xl"},D))}),!t&&n&&e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Gi,{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(cm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&A.length===0&&e.jsxs(fe,{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(bc,{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:()=>j({...ett}),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Add your first"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:A.map(D=>{var M;return e.jsxs(fe,{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:D.title}),e.jsx(ze,{variant:"outline",className:"rounded-full capitalize",children:((M=Rke.find(F=>F.value===D.category))==null?void 0:M.label)??D.category})]}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[D.issuer,ttt(D.awarded_on),D.production_period].filter(Boolean).join(" · ")}),D.description&&e.jsx("p",{className:"text-[13px] text-slate-600 mt-2 line-clamp-3",children:D.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:()=>j(D),children:e.jsx(_a,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(D),children:e.jsx(Xr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:D.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:D.id,archived:!D.is_archived}),children:e.jsx(rm,{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:()=>S(D),children:e.jsx(_n,{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:()=>L(D),children:[e.jsx(El,{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(Ln,{to:"/attract/influence/content-studio",children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"})," Write about it"]})}),D.proof_url&&e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsxs("a",{href:D.proof_url,target:"_blank",rel:"noreferrer",children:["Proof ",e.jsx(tr,{className:"h-3 w-3 ml-1.5"})]})})]})]},D.id)})}),e.jsx(bs,{open:!!v,onOpenChange:D=>!D&&j(null),children:e.jsxs(vs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:v!=null&&v.id?"Edit recognition":"Add recognition"}),e.jsx(Qn,{children:"Keep it factual — this feeds the proof points you use publicly."})]}),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:D=>j({...v,title:D.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:v.issuer??"",onChange:D=>j({...v,issuer:D.target.value}),placeholder:"Board, brokerage, publication"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Category"}),e.jsxs(ds,{value:v.category??"award",onValueChange:D=>j({...v,category:D}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:Rke.map(D=>e.jsx(Qe,{value:D.value,children:D.label},D.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Date awarded"}),e.jsx(ye,{type:"date",value:v.awarded_on??"",onChange:D=>j({...v,awarded_on:D.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Production period"}),e.jsx(ye,{value:v.production_period??"",onChange:D=>j({...v,production_period:D.target.value}),placeholder:"e.g. 2025"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Proof link"}),e.jsx(ye,{value:v.proof_url??"",onChange:D=>j({...v,proof_url:D.target.value}),placeholder:"https://"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Es,{rows:3,value:v.description??"",onChange:D=>j({...v,description:D.target.value})})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>j(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:T,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(bs,{open:!!b,onOpenChange:D=>!D&&S(null),children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Delete this recognition?"}),e.jsx(Qn,{children:"This can't be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>S(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(b.id),S(null)},children:"Delete"})]})]})})]})}const Dmn=q,stt=[{value:"pending",label:"Permission pending"},{value:"granted",label:"Permission granted"},{value:"anonymous_only",label:"Anonymous use only"},{value:"declined",label:"Permission declined"}],Rmn=["buyer","seller","both","investor","referral_partner","agent","other"];function iW(s){return s.status==="approved"&&(s.permission_status==="granted"||s.permission_status==="anonymous_only")}function Omn(){const s=tq("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=sq(),n=Ht(),r=gt({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 Dmn.from("attract_testimonials").update({use_count:(a.use_count??0)+1,last_used_at:new Date().toISOString(),usage_log:o}).eq("id",a.id);if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["attract_testimonials"]}),ae.success("Usage recorded")},onError:a=>ae.error(a.message)});return{...s,testimonials:s.items,recordUse:r,logActivity:t}}const ntt={permission_status:"pending",status:"draft",rating:5,tags:[]};function Fmn(){const{testimonials:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,recordUse:d,logActivity:u}=Omn(),[h,p]=N.useState(!1),[f,g]=N.useState("all"),[_,v]=N.useState(""),[j,b]=N.useState(null),[S,A]=N.useState(null),T=N.useMemo(()=>s.filter(F=>{if(h!==!!F.is_archived||f==="usable"&&!iW(F)||f==="pending"&&F.permission_status!=="pending")return!1;const z=_.toLowerCase().trim();return!z||`${F.client_name} ${F.quote} ${(F.tags??[]).join(" ")}`.toLowerCase().includes(z)}),[s,h,f,_]),L=s.filter(F=>!F.is_archived&&iW(F)).length,D=async()=>{var z,V;if(!((z=j==null?void 0:j.client_name)!=null&&z.trim())||!((V=j==null?void 0:j.quote)!=null&&V.trim())){ae.error("Client name and quote are required");return}const F={client_name:j.client_name.trim(),quote:j.quote.trim(),relationship_type:j.relationship_type||null,transaction_type:j.transaction_type||null,rating:j.rating??null,received_on:j.received_on||null,source_url:j.source_url||null,permission_status:j.permission_status??"pending",market:j.market||null,status:j.status??"draft",tags:j.tags??[]};j.id?await i.mutateAsync({id:j.id,...F}):(await a.mutateAsync(F),await u.mutateAsync({title:`Captured a testimonial from ${F.client_name}`,pillar:"produce",activityType:"testimonial_added"})),b(null)},M=(F,z)=>{var V;if(!iW(F)){ae.error("Mark it approved with permission before using it publicly");return}(V=navigator.clipboard)==null||V.writeText(`"${F.quote}" — ${F.permission_status==="anonymous_only"?"Client":F.client_name}`),d.mutate({item:F,kind:z})};return e.jsxs("div",{children:[e.jsxs(Ln,{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(Hr,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Vu,{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:()=>p(F=>!F),children:h?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>b({...ntt}),children:[e.jsx(Is,{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(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(F=>!F.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"In library"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-emerald-600",children:L}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Cleared for use"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-amber-600",children:s.filter(F=>!F.is_archived&&F.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:_,onChange:F=>v(F.target.value),placeholder:"Search quotes, clients, tags",className:"max-w-xs rounded-full"}),e.jsxs(ds,{value:f,onValueChange:F=>g(F),children:[e.jsx(ls,{className:"w-[200px] rounded-full",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All testimonials"}),e.jsx(Qe,{value:"usable",children:"Cleared for use"}),e.jsx(Qe,{value:"pending",children:"Permission pending"})]})]})]}),t&&e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[0,1,2,3].map(F=>e.jsx(Ws,{className:"h-40 rounded-2xl"},F))}),!t&&n&&e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Gi,{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(cm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&T.length===0&&e.jsxs(fe,{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(gb,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:"No testimonials match"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Paste in the reviews and thank-you notes you already have. Mark permission so you always know what's safe to publish."}),!h&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>b({...ntt}),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Add one"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:T.map(F=>{var z;return e.jsxs(fe,{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:F.client_name}),F.relationship_type&&e.jsx(ze,{variant:"outline",className:"rounded-full capitalize",children:F.relationship_type.replace("_"," ")}),e.jsx(ze,{variant:"outline",className:`rounded-full ${iW(F)?"bg-emerald-50 text-emerald-700 border-emerald-200":"bg-amber-50 text-amber-700 border-amber-200"}`,children:((z=stt.find(V=>V.value===F.permission_status))==null?void 0:z.label)??F.permission_status})]}),!!F.rating&&e.jsx("div",{className:"flex gap-0.5 mt-1.5",children:Array.from({length:5}).map((V,W)=>e.jsx(ca,{className:`h-3.5 w-3.5 ${W<(F.rating??0)?"text-amber-500 fill-amber-500":"text-slate-200"}`},W))})]}),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(F),children:e.jsx(_a,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(F),children:e.jsx(Xr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:F.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:F.id,archived:!F.is_archived}),children:e.jsx(rm,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>A(F),children:e.jsx(_n,{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:['"',F.quote,'"']}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-3",children:["Used ",F.use_count??0," ",F.use_count===1?"time":"times",F.last_used_at?` · last ${new Date(F.last_used_at).toLocaleDateString("en-US")}`:"",F.status==="approved"?"":" · draft"]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>M(F,"copied"),children:[e.jsx(Xr,{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(Ln,{to:"/attract/influence/content-studio",children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"})," Draft social proof"]})}),F.status!=="approved"&&e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full text-emerald-700",onClick:()=>i.mutate({id:F.id,status:"approved"}),children:[e.jsx(sg,{className:"h-3.5 w-3.5 mr-1.5"})," Mark approved"]})]})]},F.id)})}),e.jsx(bs,{open:!!j,onOpenChange:F=>!F&&b(null),children:e.jsxs(vs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:j!=null&&j.id?"Edit testimonial":"Add testimonial"}),e.jsx(Qn,{children:"Use the client's own words. Only publish quotes where permission is granted."})]}),j&&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:j.client_name??"",onChange:F=>b({...j,client_name:F.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Relationship"}),e.jsxs(ds,{value:j.relationship_type??"",onValueChange:F=>b({...j,relationship_type:F}),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select"})}),e.jsx(cs,{children:Rmn.map(F=>e.jsx(Qe,{value:F,className:"capitalize",children:F.replace("_"," ")},F))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Quote *"}),e.jsx(Es,{rows:4,value:j.quote??"",onChange:F=>b({...j,quote:F.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(ds,{value:String(j.rating??5),onValueChange:F=>b({...j,rating:Number(F)}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:[5,4,3,2,1].map(F=>e.jsxs(Qe,{value:String(F),children:[F," star",F>1?"s":""]},F))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Received on"}),e.jsx(ye,{type:"date",value:j.received_on??"",onChange:F=>b({...j,received_on:F.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Permission"}),e.jsxs(ds,{value:j.permission_status??"pending",onValueChange:F=>b({...j,permission_status:F}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:stt.map(F=>e.jsx(Qe,{value:F.value,children:F.label},F.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Status"}),e.jsxs(ds,{value:j.status??"draft",onValueChange:F=>b({...j,status:F}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"draft",children:"Draft"}),e.jsx(Qe,{value:"approved",children:"Approved"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Market / area"}),e.jsx(ye,{value:j.market??"",onChange:F=>b({...j,market:F.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Source link"}),e.jsx(ye,{value:j.source_url??"",onChange:F=>b({...j,source_url:F.target.value}),placeholder:"https://"})]})]})]}),e.jsxs(Xn,{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:D,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(bs,{open:!!S,onOpenChange:F=>!F&&A(null),children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Delete this testimonial?"}),e.jsx(Qn,{children:"This can't be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>A(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(S.id),A(null)},children:"Delete"})]})]})})]})}const rtt=[{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"}],att=["idea","planned","drafted","scheduled","published","skipped"],zmn=["weekly","biweekly","monthly","quarterly","one_off"];function i4t(){const s=tq("attract_market_presence",{orderBy:"planned_for",ascending:!0,label:"Commitment",duplicateOverrides:{status:"idea",published_url:null,results_notes:null,is_archived:!1}}),t=ybe(),n=sq();return{...s,commitments:s.items,quickTask:t,logActivity:n}}const itt={content_type:"market_update",cadence:"monthly",status:"planned"};function Bmn(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 $mn={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 Umn(){const{commitments:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,quickTask:d,logActivity:u}=i4t(),[h,p]=N.useState(!1),[f,g]=N.useState("all"),[_,v]=N.useState(null),[j,b]=N.useState(null),S=N.useMemo(()=>s.filter(M=>h!==!!M.is_archived?!1:f==="all"||M.status===f),[s,h,f]),A=s.filter(M=>{if(M.status!=="published"||!M.planned_for)return!1;const[F,z,V]=M.planned_for.split(/[-/T]/).map(Number);return(Date.now()-new Date(F,z-1,V).getTime())/864e5<=30}).length,T=s.filter(M=>{if(M.is_archived||!M.planned_for||["published","skipped"].includes(M.status))return!1;const[F,z,V]=M.planned_for.split(/[-/T]/).map(Number);return new Date(F,z-1,V){var F;if(!((F=_==null?void 0:_.title)!=null&&F.trim())){ae.error("Add a title");return}const M={title:_.title.trim(),content_type:_.content_type??"market_update",cadence:_.cadence??"monthly",planned_for:_.planned_for||null,status:_.status??"planned",channel:_.channel||null,audience:_.audience||null,campaign:_.campaign||null,notes:_.notes||null,published_url:_.published_url||null,results_notes:_.results_notes||null};_.id?await i.mutateAsync({id:_.id,...M}):await a.mutateAsync(M),v(null)},D=async M=>{await i.mutateAsync({id:M.id,status:"published"}),await u.mutateAsync({title:`Published market presence: ${M.title}`,pillar:"produce",activityType:"market_presence_published"})};return e.jsxs("div",{children:[e.jsxs(Ln,{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(Hr,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Vu,{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:()=>p(M=>!M),children:h?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>v({...itt}),children:[e.jsx(Is,{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(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(M=>!M.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Active commitments"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-emerald-600",children:A}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Published last 30 days"})]}),e.jsxs(fe,{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(ds,{value:f,onValueChange:g,children:[e.jsx(ls,{className:"w-[190px] rounded-full",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All statuses"}),att.map(M=>e.jsx(Qe,{value:M,className:"capitalize",children:M},M))]})]})}),t&&e.jsx("div",{className:"space-y-2",children:[0,1,2].map(M=>e.jsx(Ws,{className:"h-24 rounded-2xl"},M))}),!t&&n&&e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Gi,{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(cm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&S.length===0&&e.jsxs(fe,{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(_f,{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:()=>v({...itt}),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Add a commitment"]})]}),e.jsx("div",{className:"space-y-2",children:S.map(M=>{var F;return e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold text-slate-900",children:M.title}),e.jsx(ze,{variant:"outline",className:"rounded-full",children:((F=rtt.find(z=>z.value===M.content_type))==null?void 0:F.label)??M.content_type}),e.jsx(ze,{variant:"outline",className:`rounded-full capitalize ${$mn[M.status]??""}`,children:M.status}),e.jsx(ze,{variant:"outline",className:"rounded-full capitalize",children:M.cadence.replace("_"," ")})]}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[Bmn(M.planned_for),M.channel,M.audience].filter(Boolean).join(" · ")}),M.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:M.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>v(M),children:e.jsx(_a,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(M),children:e.jsx(Xr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:M.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:M.id,archived:!M.is_archived}),children:e.jsx(rm,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>b(M),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[M.status!=="published"&&e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>D(M),children:[e.jsx(xr,{className:"h-3.5 w-3.5 mr-1.5"})," Mark published"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>d.mutate({title:`Create: ${M.title}`,dueAt:M.planned_for?`${M.planned_for}T09:00:00`:new Date().toISOString(),notes:M.notes,touchType:"content"}),children:[e.jsx(uu,{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(Ln,{to:"/attract/influence/content-studio",children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"})," Draft it"]})})]})]},M.id)})}),e.jsx(bs,{open:!!_,onOpenChange:M=>!M&&v(null),children:e.jsxs(vs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:_!=null&&_.id?"Edit commitment":"New commitment"}),e.jsx(Qn,{children:"Pick something you can genuinely sustain."})]}),_&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title *"}),e.jsx(ye,{value:_.title??"",onChange:M=>v({..._,title:M.target.value}),placeholder:"e.g. October market update video"})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Type"}),e.jsxs(ds,{value:_.content_type??"market_update",onValueChange:M=>v({..._,content_type:M}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:rtt.map(M=>e.jsx(Qe,{value:M.value,children:M.label},M.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Cadence"}),e.jsxs(ds,{value:_.cadence??"monthly",onValueChange:M=>v({..._,cadence:M}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:zmn.map(M=>e.jsx(Qe,{value:M,className:"capitalize",children:M.replace("_"," ")},M))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Planned for"}),e.jsx(ye,{type:"date",value:_.planned_for??"",onChange:M=>v({..._,planned_for:M.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Status"}),e.jsxs(ds,{value:_.status??"planned",onValueChange:M=>v({..._,status:M}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:att.map(M=>e.jsx(Qe,{value:M,className:"capitalize",children:M},M))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Channel"}),e.jsx(ye,{value:_.channel??"",onChange:M=>v({..._,channel:M.target.value}),placeholder:"Instagram, email, YouTube"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Audience"}),e.jsx(ye,{value:_.audience??"",onChange:M=>v({..._,audience:M.target.value}),placeholder:"Agents, sphere, neighborhood"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Es,{rows:3,value:_.notes??"",onChange:M=>v({..._,notes:M.target.value})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Published URL"}),e.jsx(ye,{value:_.published_url??"",onChange:M=>v({..._,published_url:M.target.value}),placeholder:"https://"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Results"}),e.jsx(ye,{value:_.results_notes??"",onChange:M=>v({..._,results_notes:M.target.value}),placeholder:"Reach, replies, leads"})]})]})]}),e.jsxs(Xn,{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:L,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(bs,{open:!!j,onOpenChange:M=>!M&&b(null),children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Delete this commitment?"}),e.jsx(Qn,{children:"This can't be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>b(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(j.id),b(null)},children:"Delete"})]})]})})]})}function ott(s){if(!s)return null;const[t]=s.split("T");return t||null}const oW={draft:{label:"Content",icon:un,cls:"bg-violet-50 text-violet-700 border-violet-200"},presence:{label:"Market presence",icon:_f,cls:"bg-blue-50 text-blue-700 border-blue-200"},speaking:{label:"Speaking",icon:Fv,cls:"bg-amber-50 text-amber-700 border-amber-200"}};function qmn(){const{drafts:s,isLoading:t,save:n}=t4t(),{commitments:r,isLoading:a}=i4t(),i=a4t(),l=ybe(),[o,c]=N.useState(()=>{const T=new Date;return new Date(T.getFullYear(),T.getMonth(),1)}),[d,u]=N.useState("all"),[h,p]=N.useState(null),f=N.useMemo(()=>(i.items??[]).filter(T=>!T.is_archived).map(T=>({id:T.id,kind:"speaking",title:T.title,date:ott(T.starts_at),status:T.status,href:"/attract/influence/speaking"})),[i.items]),g=N.useMemo(()=>{const T=s.map(D=>({id:D.id,kind:"draft",title:D.topic||D.mode.replace(/_/g," "),date:ott(D.planned_at??D.posted_at??null),status:D.status,href:"/attract/influence/content-studio"})),L=r.filter(D=>!D.is_archived).map(D=>({id:D.id,kind:"presence",title:D.title,date:D.planned_for,status:D.status,href:"/attract/produce/market-presence"}));return[...T,...L,...f].filter(D=>d==="all"||D.kind===d)},[s,r,f,d]),_=`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}`,v=g.filter(T=>{var L;return(L=T.date)==null?void 0:L.startsWith(_)}),j=g.filter(T=>!T.date),b=N.useMemo(()=>{const T=new Date(o.getFullYear(),o.getMonth(),1),L=new Date(T);return L.setDate(T.getDate()-T.getDay()),Array.from({length:42},(D,M)=>{const F=new Date(L);F.setDate(L.getDate()+M);const z=`${F.getFullYear()}-${String(F.getMonth()+1).padStart(2,"0")}-${String(F.getDate()).padStart(2,"0")}`;return{date:F,key:z,inMonth:F.getMonth()===o.getMonth(),items:g.filter(V=>V.date===z)}})},[o,g]),S=(()=>{const T=new Date;return`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}-${String(T.getDate()).padStart(2,"0")}`})(),A=t||a;return e.jsxs("div",{children:[e.jsxs(Ln,{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(Hr,{className:"h-3.5 w-3.5"})," Back to Influence"]}),e.jsx(Vu,{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(Ln,{to:"/attract/influence/content-studio",children:[e.jsx(Is,{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(pl,{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(xa,{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(ze,{variant:"outline",className:"rounded-full",children:[v.length," scheduled this month"]}),e.jsxs(ds,{value:d,onValueChange:T=>u(T),children:[e.jsx(ls,{className:"w-[180px] rounded-full",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"all",children:"All types"}),e.jsx(Qe,{value:"draft",children:"Content drafts"}),e.jsx(Qe,{value:"presence",children:"Market presence"}),e.jsx(Qe,{value:"speaking",children:"Speaking"})]})]})]})]}),A?e.jsx(Ws,{className:"h-[560px] rounded-2xl"}):e.jsxs(fe,{className:"rounded-2xl overflow-hidden",children:[e.jsx("div",{className:"grid grid-cols-7 bg-slate-50 border-b",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(T=>e.jsx("div",{className:"px-2 py-2 text-[11px] uppercase tracking-wider text-slate-500 font-semibold text-center",children:T},T))}),e.jsx("div",{className:"grid grid-cols-7",children:b.map(T=>e.jsxs("div",{className:`min-h-[96px] border-b border-r p-1.5 ${T.inMonth?"":"bg-slate-50/60"}`,children:[e.jsx("div",{className:`text-[11.5px] font-medium mb-1 ${T.key===S?"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(L=>{const D=oW[L.kind];return e.jsx(Ln,{to:L.href,className:`block truncate rounded-md border px-1.5 py-0.5 text-[11px] ${D.cls}`,title:L.title,children:L.title},`${L.kind}-${L.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(fe,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"text-[15px] font-semibold text-slate-900 mb-1",children:["Unscheduled (",j.length,")"]}),e.jsx("p",{className:"text-[12.5px] text-slate-600 mb-3",children:"Give these a date so they show on the calendar."}),j.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:j.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:[oW[T.kind].label," · ",T.status]})]}),T.kind==="draft"?e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full flex-shrink-0",onClick:()=>p({id:T.id,title:T.title,date:S}),children:"Schedule"}):e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full flex-shrink-0",asChild:!0,children:e.jsx(Ln,{to:T.href,children:"Open"})})]},`${T.kind}-${T.id}`))})]}),e.jsxs(fe,{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(oW).map(T=>{const L=oW[T],D=L.icon,M=v.filter(F=>F.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 ${L.cls}`,children:e.jsx(D,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 flex-1",children:L.label}),e.jsx("div",{className:"text-[16px] font-semibold tabular-nums text-slate-900",children:M})]},T)})}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4 w-full",onClick:()=>l.mutate({title:`Plan content for ${o.toLocaleString("en-US",{month:"long"})}`,dueAt:new Date().toISOString(),touchType:"content"}),children:[e.jsx(uu,{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(Ln,{to:"/attract/produce/market-presence",children:[e.jsx(Tl,{className:"h-3.5 w-3.5 mr-1.5"})," Manage market presence cadence"]})})]})]}),e.jsx(bs,{open:!!h,onOpenChange:T=>!T&&p(null),children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Schedule draft"}),e.jsx(Qn,{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=>p({...h,date:T.target.value})})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>p(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`}),p(null))},children:"Save"})]})]})})]})}const ltt=[{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 Vmn(s){const[t,n,r]=s.split(/[-/T]/).map(Number);return{y:t,m:n,d:r}}function cEe(s,t=new Date){const{y:n,m:r,d:a}=Vmn(s.milestone_on);if(!s.recurs_annually)return new Date(n,r-1,a);const i=new Date(t.getFullYear(),r-1,a),l=new Date(t.getFullYear(),t.getMonth(),t.getDate());return i{const l=[];return r.forEach(o=>{const c=[o.preferred_name||o.first_name,o.last_name].filter(Boolean).join(" ");[["birthday",o.birthday_on,`${c} — Birthday`],["work_anniversary",o.work_anniversary_on,`${c} — Work Anniversary`],["license_anniversary",o.license_anniversary_on,`${c} — License Anniversary`]].forEach(([d,u,h])=>{u&&l.push({id:`agent:${o.id}:${d}`,user_id:o.user_id,title:h,milestone_type:d,milestone_on:String(u).slice(0,10),recurs_annually:!0,linked_agent_ids:[o.id],notes:null,last_celebrated_at:null,is_archived:!1,created_at:o.created_at,updated_at:o.updated_at})})}),l},[r]),i=N.useMemo(()=>{const l=new Set(s.items.filter(c=>!c.is_archived).map(c=>{var d;return`${c.milestone_type}|${c.milestone_on.slice(5,10)}|${((d=c.linked_agent_ids)==null?void 0:d[0])??""}`}));return[...s.items.filter(c=>!c.is_archived),...a.filter(c=>!l.has(`${c.milestone_type}|${c.milestone_on.slice(5,10)}|${c.linked_agent_ids[0]}`))].map(c=>({item:c,next:cEe(c)})).map(c=>({...c,days:o4t(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 ctt={milestone_type:"birthday",recurs_annually:!0,linked_agent_ids:[]};function Gmn(s){return s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function Wmn(){var z;const{milestones:s,upcoming:t,isLoading:n,error:r,refetch:a,create:i,update:l,duplicate:o,archive:c,remove:d,quickTask:u,logActivity:h}=Hmn(),p=c0(),f=(p==null?void 0:p.agents)??(p==null?void 0:p.items)??[],[g,_]=N.useState(!1),[v,j]=N.useState("90"),[b,S]=N.useState(null),[A,T]=N.useState(null),L=N.useMemo(()=>{if(g)return s.filter(W=>W.is_archived).map(W=>({item:W,next:cEe(W),days:o4t(cEe(W))}));const V=v==="all"?1/0:Number(v);return t.filter(W=>W.days<=V)},[s,t,g,v]),D=V=>{const W=f.find(Y=>Y.id===V);return W?[W.preferred_name||W.first_name,W.last_name].filter(Boolean).join(" "):"Agent"},M=async()=>{var W;if(!((W=b==null?void 0:b.title)!=null&&W.trim())||!(b!=null&&b.milestone_on)){ae.error("Title and date are required");return}const V={title:b.title.trim(),milestone_type:b.milestone_type??"birthday",milestone_on:b.milestone_on,recurs_annually:b.recurs_annually??!0,linked_agent_ids:b.linked_agent_ids??[],notes:b.notes||null};b.id?await l.mutateAsync({id:b.id,...V}):await i.mutateAsync(V),S(null)},F=async V=>{var W;await l.mutateAsync({id:V.id,last_celebrated_at:new Date().toISOString()}),await h.mutateAsync({title:`Celebrated: ${V.title}`,pillar:"connect",activityType:"milestone_celebrated",agentId:((W=V.linked_agent_ids)==null?void 0:W[0])??null})};return e.jsxs("div",{children:[e.jsxs(Ln,{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(Hr,{className:"h-3.5 w-3.5"})," Back to Connect"]}),e.jsx(Vu,{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:()=>_(V=>!V),children:g?"Show upcoming":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>S({...ctt}),children:[e.jsx(Is,{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(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:t.filter(V=>V.days<=7).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Next 7 days"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-violet-600",children:t.filter(V=>V.days<=30).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Next 30 days"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(V=>!V.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Tracked total"})]})]}),!g&&e.jsx("div",{className:"flex gap-2 flex-wrap mb-4",children:e.jsxs(ds,{value:v,onValueChange:V=>j(V),children:[e.jsx(ls,{className:"w-[190px] rounded-full",children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"30",children:"Next 30 days"}),e.jsx(Qe,{value:"90",children:"Next 90 days"}),e.jsx(Qe,{value:"all",children:"All upcoming"})]})]})}),n&&e.jsx("div",{className:"space-y-2",children:[0,1,2].map(V=>e.jsx(Ws,{className:"h-20 rounded-2xl"},V))}),!n&&r&&e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Gi,{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(cm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!n&&!r&&L.length===0&&e.jsxs(fe,{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:g?"Nothing archived":"No milestones in this window"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Add birthdays, license anniversaries, and production milestones for the agents you're building relationships with."}),!g&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>S({...ctt}),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Add a milestone"]})]}),e.jsx("div",{className:"space-y-2",children:L.map(({item:V,next:W,days:Y})=>{var J,ne;const K=String(V.id).startsWith("agent:");return e.jsxs(fe,{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:W.toLocaleString("en-US",{month:"short"})}),e.jsx("div",{className:"text-[15px] font-semibold",children:W.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:V.title}),e.jsx(ze,{variant:"outline",className:"rounded-full",children:((J=ltt.find(ie=>ie.value===V.milestone_type))==null?void 0:J.label)??V.milestone_type}),K&&e.jsx(ze,{variant:"outline",className:"rounded-full bg-violet-50 text-violet-700 border-violet-200",children:"From contact record"}),!g&&e.jsx(ze,{variant:"outline",className:`rounded-full ${Y<=7?"bg-amber-50 text-amber-700 border-amber-200":""}`,children:Y===0?"Today":Y===1?"Tomorrow":`in ${Y} days`}),V.recurs_annually&&e.jsx(ze,{variant:"outline",className:"rounded-full",children:"Annual"})]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[Gmn(W),(ne=V.linked_agent_ids)!=null&&ne.length?` · ${V.linked_agent_ids.map(D).join(", ")}`:"",V.last_celebrated_at?` · last celebrated ${new Date(V.last_celebrated_at).toLocaleDateString("en-US")}`:""]}),V.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:V.notes})]})]}),e.jsx("div",{className:"flex gap-1",children:K?e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full text-[12px]",asChild:!0,children:e.jsx(Ln,{to:`/attract/agents/${V.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:()=>S(V),children:e.jsx(_a,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>o.mutate(V),children:e.jsx(Xr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:V.is_archived?"Restore":"Archive",onClick:()=>c.mutate({id:V.id,archived:!V.is_archived}),children:e.jsx(rm,{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(V),children:e.jsx(_n,{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 ie;return u.mutate({title:`Reach out: ${V.title}`,dueAt:W.toISOString(),notes:V.notes,touchType:"celebration",agentId:((ie=V.linked_agent_ids)==null?void 0:ie[0])??null})},children:[e.jsx(uu,{className:"h-3.5 w-3.5 mr-1.5"})," Add reach-out task"]}),!K&&e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>F(V),children:[e.jsx(ch,{className:"h-3.5 w-3.5 mr-1.5"})," Mark celebrated"]})]})]},V.id)})}),e.jsx(bs,{open:!!b,onOpenChange:V=>!V&&S(null),children:e.jsxs(vs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:b!=null&&b.id?"Edit milestone":"Add milestone"}),e.jsx(Qn,{children:"Annual milestones roll forward automatically each year."})]}),b&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title *"}),e.jsx(ye,{value:b.title??"",onChange:V=>S({...b,title:V.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(ds,{value:b.milestone_type??"birthday",onValueChange:V=>S({...b,milestone_type:V}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:ltt.map(V=>e.jsx(Qe,{value:V.value,children:V.label},V.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Date *"}),e.jsx(ye,{type:"date",value:b.milestone_on??"",onChange:V=>S({...b,milestone_on:V.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(bn,{checked:b.recurs_annually??!0,onCheckedChange:V=>S({...b,recurs_annually:V})})]}),f.length>0&&e.jsxs("div",{children:[e.jsx(se,{children:"Link to agent"}),e.jsxs(ds,{value:((z=b.linked_agent_ids)==null?void 0:z[0])??"none",onValueChange:V=>S({...b,linked_agent_ids:V==="none"?[]:[V]}),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Optional"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"No agent"}),f.map(V=>e.jsx(Qe,{value:V.id,children:D(V.id)},V.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Es,{rows:3,value:b.notes??"",onChange:V=>S({...b,notes:V.target.value}),placeholder:"Gift ideas, personal details, how you'll reach out"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>S(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:M,disabled:i.isPending||l.isPending,children:"Save"})]})]})}),e.jsx(bs,{open:!!A,onOpenChange:V=>!V&&T(null),children:e.jsxs(vs,{className:"max-w-md",children:[e.jsxs(ws,{children:[e.jsx(_s,{children:"Delete this milestone?"}),e.jsx(Qn,{children:"This can't be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>T(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{d.mutate(A.id),T(null)},children:"Delete"})]})]})})]})}function Kmn(){var c;const{shareToken:s}=bi(),[t,n]=N.useState("loading"),[r,a]=N.useState(null),[i,l]=N.useState(!1);N.useEffect(()=>{(async()=>{if(!s){n("not_found");return}const{data:d,error:u}=await q.rpc("public_get_attract_kit",{_token:s});if(u){n("error");return}if(!d||d.status!=="ok"){n((d==null?void 0:d.status)??"not_found");return}a(d),n("ok"),q.rpc("public_log_attract_kit_event",{_token:s,_event_type:"page_view",_item_id:null,_metadata:{}})})()},[s]);const o=(d,u,h)=>{s&&q.rpc("public_log_attract_kit_event",{_token:s,_event_type:d,_item_id:u??null,_metadata:h??{}})};return t==="loading"?e.jsx("div",{className:"min-h-screen bg-[#05070f] grid place-items-center text-slate-300",children:"Loading…"}):t!=="ok"?e.jsx("div",{className:"min-h-screen bg-[#05070f] grid place-items-center px-6",children:e.jsxs(fe,{className:"max-w-md w-full p-8 bg-white/5 border-white/10 text-slate-100 rounded-2xl text-center",children:[e.jsx(Gi,{className:"h-8 w-8 text-amber-400 mx-auto"}),e.jsx("div",{className:"mt-3 text-xl font-semibold",children:t==="expired"?"This kit has expired":t==="revoked"?"This kit is no longer available":t==="not_found"?"This kit could not be found":"Something went wrong"}),e.jsx("p",{className:"text-slate-400 mt-2 text-sm",children:"Please reach out to the person who shared it with you for an updated link."})]})}):e.jsx("div",{className:"min-h-screen bg-[#05070f]",children:e.jsxs("div",{className:"max-w-3xl mx-auto py-6 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10.5px] uppercase tracking-widest text-violet-400 font-semibold justify-center py-3",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," A LevelUp Attract kit"]}),e.jsx(s4t,{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(fe,{className:"mt-6 p-6 bg-white/5 border-white/10 text-slate-100 rounded-2xl",children:i?e.jsx(Ymn,{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 Ymn({token:s,onSent:t,onEvent:n}){const[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(!1),h=async()=>{if(o.trim().length<2)return ae.error("Please add a short message");u(!0);const{data:p,error:f}=await q.rpc("public_submit_attract_kit_question",{_token:s,_name:r,_email:i,_message:o});if(u(!1),f||!(p!=null&&p.ok))return ae.error("Could not send — please try again");ae.success("Sent — thank you!"),t()};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-[14px] font-semibold",children:"Send a private message"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:[e.jsx(ye,{placeholder:"Your name (optional)",value:r,onChange:p=>a(p.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:p=>l(p.target.value),className:"bg-white/5 border-white/10 text-white placeholder:text-slate-500"})]}),e.jsx(Es,{rows:4,placeholder:"What's your question?",value:o,onChange:p=>c(p.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"),ae.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 Zmn(){const{slug:s}=bi(),[t]=gl(),n=t.get("inv")||null,[r,a]=N.useState("loading"),[i,l]=N.useState(null),[o,c]=N.useState({name:"",email:"",phone:"",answers:{}}),[d,u]=N.useState(!1),[h,p]=N.useState(null);N.useEffect(()=>{s&&(async()=>{const{data:_,error:v}=await q.rpc("public_get_attract_event",{_slug:s});if(v||!_||_.error){a((_==null?void 0:_.error)||"not_found");return}l(_),a("ok"),n&&q.rpc("public_track_attract_invitation_view",{_token:n})})()},[s,n]);const f=async()=>{u(!0);const{data:_,error:v}=await q.rpc("public_register_attract_event",{_slug:s,_name:o.name,_email:o.email,_phone:o.phone||null,_answers:o.answers||{},_invitation_token:n});if(u(!1),v){alert("Something went wrong. Please try again.");return}const j=_;if(j!=null&&j.error){alert(j.error==="invalid_email"?"That email looks off.":j.error==="full"?"This event is full.":"Could not register.");return}p(j)},g=()=>{if(!i)return;const _=new Blob([ESt(i)],{type:"text/calendar"}),v=document.createElement("a");v.href=URL.createObjectURL(_),v.download=`${s}.ics`,v.click()};if(r==="loading")return e.jsx("div",{className:"min-h-screen grid place-items-center text-slate-400",children:"Loading…"});if(r!=="ok"||!i){const _=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:_}),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(fe,{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(yr,{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:Ss(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(br,{className:"h-5 w-5 text-violet-600 mt-0.5"}):e.jsx(ka,{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(Nn,{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((_,v)=>e.jsxs("li",{className:"flex gap-2 text-[14px] text-slate-800",children:[e.jsx(Ir,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",_]},v))})]}),(i.agenda||[]).length>0&&e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Agenda"}),e.jsx("ul",{className:"space-y-1",children:i.agenda.map((_,v)=>e.jsxs("li",{className:"flex gap-3 text-[13.5px]",children:[e.jsx("span",{className:"text-slate-500 tabular-nums w-16 shrink-0",children:_.time}),e.jsx("span",{className:"text-slate-800",children:_.item})]},v))})]})]}),h?e.jsxs(fe,{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(Ir,{className:"h-7 w-7"})}),e.jsx("div",{className:"text-2xl font-semibold text-slate-900 mt-4",children:h.status==="waitlisted"?"You are on the waitlist":"You are in."}),i.confirmation_message&&e.jsx("div",{className:"text-[15px] text-slate-700 mt-2 max-w-lg mx-auto",children:i.confirmation_message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-5",onClick:g,children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"})," Add to calendar"]})]}):e.jsxs(fe,{className:"mt-6 p-6 rounded-3xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"text-lg font-semibold text-slate-900 mb-1 flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-violet-600"})," Save your seat"]}),e.jsx("div",{className:"text-[13px] text-slate-500 mb-4",children:"The room is small on purpose."}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Full name"}),e.jsx(ye,{value:o.name,onChange:_=>c({...o,name:_.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:_=>c({...o,email:_.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone (optional)"}),e.jsx(ye,{value:o.phone,onChange:_=>c({...o,phone:_.target.value})})]})]}),(i.registration_questions||[]).map(_=>e.jsxs("div",{children:[e.jsx(se,{children:_.label}),_.type==="long"?e.jsx(Es,{rows:3,value:o.answers[_.key]||"",onChange:v=>c({...o,answers:{...o.answers,[_.key]:v.target.value}})}):e.jsx(ye,{value:o.answers[_.key]||"",onChange:v=>c({...o,answers:{...o.answers,[_.key]:v.target.value}})})]},_.key))]}),e.jsx(B,{disabled:d,className:"w-full mt-5 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 h-11",onClick:f,children:d?"Saving…":i.seats_left===0?"Join the waitlist":"Save my seat"}),e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center mt-3",children:"Build relationships first. We will only email you about this event."})]})]})})}function Qmn(){const{token:s}=bi(),[t]=gl(),n=t.get("a"),[r,a]=N.useState("loading"),[i,l]=N.useState("");return N.useEffect(()=>{if(!s||!n){a("error");return}(async()=>{const{data:o}=await q.rpc("public_check_in_attendee",{_check_in_token:s,_attendee_token:n}),c=o;c!=null&&c.ok?(l(c.name||""),a(c.already?"already":"ok")):a("error")})()},[s,n]),e.jsx("div",{className:"min-h-screen grid place-items-center bg-slate-50 px-4",children:e.jsxs(fe,{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(Ir,{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 lW=s=>s.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});function Xmn(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 l4t({cfg:s,onSubmitLead:t,onTrack:n,preview:r}){var D,M,F;const a=s.primary_color||"#0f1b3d",i=s.accent_color||"#c9a84c",l=s.sections||{},[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(!1),[f,g]=N.useState({first_name:"",last_name:"",email:"",phone:"",brokerage:"",message:""}),[_,v]=N.useState({first_name:"",email:""}),j=s.calculator||{},[b,S]=N.useState(15e4),A=N.useMemo(()=>{const z=Number(j.cap??16e3),V=Number(j.split??80)/100,W=Number(j.transaction_fee??250),Y=Number(j.current_split??70)/100,K=Number(j.current_monthly_fees??150),J=Math.min(b*(1-V),z),ne=b-J-W*12,ie=b*Y-K*12;return{here:Math.max(ne,0),current:Math.max(ie,0),diff:Math.max(ne-ie,0),capped:J>=z}},[b,j]),T=async(z,V,W)=>{if(r||!t){u(z);return}p(!0);try{await t({first_name:V.first_name||"",last_name:V.last_name||"",email:V.email||"",phone:V.phone||"",brokerage:V.brokerage||"",message:V.message||"",source:z,metadata:W}),u(z)}catch(Y){Pr({title:"We couldn't send that",description:(Y==null?void 0:Y.message)||"Please try again in a moment.",variant:"destructive"})}finally{p(!1)}},L=z=>e.jsxs("a",{href:"#connect",onClick:()=>n==null?void 0:n("cta_click","hero"),className:"group inline-flex items-center gap-3 rounded-full px-8 py-4 text-base font-semibold shadow-2xl transition-transform hover:scale-[1.03]",style:{backgroundColor:i,color:"#10131c"},children:[z||s.cta_label||"Book a confidential 15-min call",e.jsx(Oa,{className:"h-4 w-4 transition-transform group-hover:translate-x-1"})]});return e.jsxs("div",{className:"min-h-screen bg-[#0b0e17] text-white antialiased",children:[l.hero!==!1&&e.jsxs("section",{className:"relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(160deg, ${a} 0%, #05070d 75%)`}}),s.hero_image_url&&e.jsx("div",{className:"absolute inset-0 bg-cover bg-center opacity-20",style:{backgroundImage:`url(${s.hero_image_url})`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(circle at 20% 20%, white 1px, transparent 1px)",backgroundSize:"48px 48px"}}),e.jsxs("div",{className:"relative z-10 mx-auto grid max-w-6xl items-center gap-12 px-6 py-24 md:grid-cols-[1.2fr_.8fr] md:py-32",children:[e.jsxs("div",{children:[s.logo_url&&e.jsx("img",{src:s.logo_url,alt:"",className:"mb-8 h-10 w-auto"}),s.eyebrow&&e.jsx("span",{className:"mb-5 inline-block text-xs font-medium uppercase tracking-[0.22em]",style:{color:i},children:s.eyebrow}),e.jsx("h1",{className:"mb-6 text-4xl font-bold leading-[1.08] tracking-tight md:text-6xl",children:s.headline}),e.jsx("p",{className:"mb-10 max-w-xl text-lg font-light leading-relaxed text-white/70",children:s.subheadline}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[L(),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(yr,{className:"h-4 w-4"})," See my calendar"]})]})]}),s.headshot_url&&e.jsxs("div",{className:"relative mx-auto w-full max-w-xs",children:[e.jsx("div",{className:"absolute -inset-3 rounded-[2rem] opacity-40 blur-2xl",style:{background:i}}),e.jsx("img",{src:s.headshot_url,alt:s.agent_name||"",className:"relative w-full rounded-[1.75rem] object-cover shadow-2xl"}),e.jsxs("div",{className:"relative mt-5 text-center",children:[e.jsx("div",{className:"text-lg font-semibold",children:s.agent_name}),e.jsx("div",{className:"text-sm text-white/55",children:s.agent_title})]})]})]})]}),l.credibility!==!1&&(s.credibility||[]).length>0&&e.jsx("section",{className:"border-y border-white/10 bg-white/[0.03]",children:e.jsx("div",{className:"mx-auto grid max-w-6xl grid-cols-2 gap-8 px-6 py-10 md:grid-cols-4",children:(s.credibility||[]).map((z,V)=>e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold md:text-3xl",style:{color:i},children:z.value}),e.jsx("div",{className:"mt-1 text-xs uppercase tracking-wider text-white/50",children:z.label})]},V))})}),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:Xmn(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(Au,{className:"relative h-20 w-20 text-white/90 transition-transform group-hover:scale-110"})]})}),e.jsx("p",{className:"max-w-3xl whitespace-pre-line text-lg font-light leading-relaxed text-white/70",children:s.story_body})]}),l.value_stack!==!1&&(s.value_cards||[]).length>0&&e.jsx("section",{className:"border-y border-white/10 bg-white/[0.02] py-20 md:py-28",children:e.jsxs("div",{className:"mx-auto max-w-6xl px-6",children:[e.jsx("h2",{className:"mb-3 text-3xl font-bold tracking-tight md:text-4xl",children:"What you actually get"}),e.jsx("p",{className:"mb-12 max-w-2xl text-white/60",children:"No hype. Here is the model, in plain English."}),e.jsx("div",{className:"grid gap-5 md:grid-cols-2 lg:grid-cols-3",children:(s.value_cards||[]).map((z,V)=>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(Ir,{className:"h-4 w-4"})}),e.jsx("h3",{className:"mb-2 text-lg font-semibold",children:z.title}),e.jsx("p",{className:"text-sm leading-relaxed text-white/65",children:z.body}),z.proof&&e.jsx("p",{className:"mt-3 text-xs uppercase tracking-wider text-white/40",children:z.proof})]},V))})]})}),l.calculator!==!1&&j.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:j.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:lW(b)})]}),e.jsx("input",{type:"range",min:25e3,max:1e6,step:5e3,value:b,onChange:z=>S(Number(z.target.value)),onMouseUp:()=>n==null?void 0:n("calculator_run","calculator",{gci:b}),onTouchEnd:()=>n==null?void 0:n("calculator_run","calculator",{gci:b}),className:"w-full accent-white"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-2xl border border-white/10 p-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-white/45",children:"Where you are now"}),e.jsx("div",{className:"mt-2 text-2xl font-semibold text-white/80",children:lW(A.current)})]}),e.jsxs("div",{className:"rounded-2xl border p-5",style:{borderColor:i},children:[e.jsx("div",{className:"text-xs uppercase tracking-wider",style:{color:i},children:"With me"}),e.jsx("div",{className:"mt-2 text-2xl font-bold",children:lW(A.here)}),A.capped&&e.jsx("div",{className:"mt-1 text-xs text-white/50",children:"You would cap this year."})]}),e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.04] p-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-white/45",children:"Difference"}),e.jsxs("div",{className:"mt-2 text-2xl font-bold",style:{color:i},children:["+",lW(A.diff)]})]})]}),e.jsx("p",{className:"mt-6 text-xs leading-relaxed text-white/35",children:"Estimates only, based on the assumptions above. Your actual numbers depend on your production and agreements."}),e.jsx("div",{className:"mt-8",children:L("Show me my exact numbers")})]})})}),l.sponsor!==!1&&(s.sponsor_cards||[]).length>0&&e.jsx("section",{className:"border-y border-white/10 bg-white/[0.02] py-20 md:py-28",children:e.jsxs("div",{className:"mx-auto max-w-5xl px-6",children:[e.jsx("h2",{className:"mb-3 text-3xl font-bold tracking-tight md:text-4xl",children:"What you get from me"}),e.jsx("p",{className:"mb-12 max-w-2xl text-white/60",children:"The brokerage is the same for everyone. Who you partner with is not."}),e.jsx("div",{className:"grid gap-5 md:grid-cols-2",children:(s.sponsor_cards||[]).map((z,V)=>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:V+1}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-1.5 font-semibold",children:z.title}),e.jsx("p",{className:"text-sm leading-relaxed text-white/65",children:z.body})]})]},V))})]})}),l.testimonials!==!1&&(s.testimonials||[]).length>0&&e.jsx("section",{className:"py-20 md:py-28",children:e.jsxs("div",{className:"mx-auto max-w-6xl px-6",children:[e.jsx("h2",{className:"mb-12 text-3xl font-bold tracking-tight md:text-4xl",children:"Agents who made the move"}),e.jsx("div",{className:"grid gap-5 md:grid-cols-3",children:(s.testimonials||[]).map((z,V)=>e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6",children:[e.jsx(gb,{className:"mb-4 h-6 w-6",style:{color:i}}),e.jsxs("p",{className:"text-sm leading-relaxed text-white/75",children:['"',z.quote,'"']}),e.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[z.photo_url?e.jsx("img",{src:z.photo_url,alt:z.name,className:"h-10 w-10 rounded-full object-cover"}):e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-white/10",children:e.jsx(ca,{className:"h-4 w-4 text-white/50"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:z.name}),z.role&&e.jsx("div",{className:"text-xs text-white/45",children:z.role})]})]})]},V))})]})}),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(vIe,{type:"single",collapsible:!0,className:"w-full",children:(s.faqs||[]).map((z,V)=>e.jsxs(dve,{value:`faq-${V}`,className:"border-white/10",children:[e.jsx(uve,{className:"text-left text-base font-medium text-white hover:no-underline",children:z.q}),e.jsx(hve,{className:"text-sm leading-relaxed text-white/65",children:z.a})]},V))})]})}),l.lead_magnet!==!1&&((D=s.lead_magnet)==null?void 0:D.enabled)!==!1&&((M=s.lead_magnet)==null?void 0:M.title)&&e.jsx("section",{className:"py-20",children:e.jsx("div",{className:"mx-auto max-w-3xl px-6",children:e.jsxs("div",{className:"rounded-3xl border border-white/10 bg-white/[0.04] p-8 md:p-10",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2 text-xs uppercase tracking-widest",style:{color:i},children:[e.jsx(Pa,{className:"h-3.5 w-3.5"})," Free, no strings"]}),e.jsx("h3",{className:"mb-2 text-2xl font-bold",children:s.lead_magnet.title}),e.jsx("p",{className:"mb-6 text-white/65",children:s.lead_magnet.body}),d==="lead_magnet"?e.jsxs("div",{className:"rounded-xl border border-white/15 p-4 text-sm text-white/80",children:["On its way. Check your inbox",s.lead_magnet.file_url?" — or grab it now:":"."," ",s.lead_magnet.file_url&&e.jsx("a",{href:s.lead_magnet.file_url,target:"_blank",rel:"noreferrer",className:"underline",style:{color:i},children:"download"})]}):e.jsxs("form",{className:"flex flex-col gap-3 sm:flex-row",onSubmit:z=>{z.preventDefault(),T("lead_magnet",{first_name:_.first_name,email:_.email,message:`Requested: ${s.lead_magnet.title}`})},children:[e.jsx(ye,{required:!0,placeholder:"First name",value:_.first_name,onChange:z=>v(V=>({...V,first_name:z.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:_.email,onChange:z=>v(V=>({...V,email:z.target.value})),className:"h-12 border-white/15 bg-white/5 text-white placeholder:text-white/35"}),e.jsx(B,{type:"submit",disabled:h,className:"h-12 shrink-0 font-semibold",style:{backgroundColor:i,color:"#10131c"},children:s.lead_magnet.cta||"Send it"})]})]})})}),l.event!==!1&&((F=s.event_block)==null?void 0:F.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(Ir,{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(yr,{className:"h-4 w-4"})," Pick a time"]})]}):e.jsxs("form",{onSubmit:z=>{z.preventDefault(),T("attraction_page",f,{gci:b})},className:"space-y-4 rounded-3xl border border-white/10 bg-white/[0.05] p-8 backdrop-blur",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"First name *"}),e.jsx(ye,{required:!0,value:f.first_name,onChange:z=>g(V=>({...V,first_name:z.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"Last name"}),e.jsx(ye,{value:f.last_name,onChange:z=>g(V=>({...V,last_name:z.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"Email *"}),e.jsx(ye,{required:!0,type:"email",value:f.email,onChange:z=>g(V=>({...V,email:z.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"Phone"}),e.jsx(ye,{value:f.phone,onChange:z=>g(V=>({...V,phone:z.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"Current brokerage"}),e.jsx(ye,{value:f.brokerage,onChange:z=>g(V=>({...V,brokerage:z.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"What would you want to know?"}),e.jsx(Es,{rows:3,value:f.message,onChange:z=>g(V=>({...V,message:z.target.value})),className:"resize-none border-white/15 bg-white/5 text-white"})]}),e.jsx(B,{type:"submit",disabled:h,className:"h-12 w-full text-base font-semibold",style:{backgroundColor:i,color:"#10131c"},children:h?"Sending…":s.cta_label||"Book a confidential 15-min call"}),e.jsxs("div",{className:"flex items-center justify-center gap-2 pt-1 text-xs text-white/40",children:[e.jsx(dh,{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(Ar,{className:"h-4 w-4"})," ",s.phone]}),s.email&&e.jsx("a",{href:`mailto:${s.email}`,className:"hover:text-white",children:s.email})]})]})]}),l.disclaimer!==!1&&s.disclaimer&&e.jsx("footer",{className:"border-t border-white/10 px-6 py-10",children:e.jsx("p",{className:"mx-auto max-w-3xl text-center text-xs leading-relaxed text-white/35",children:s.disclaimer})}),l.final_cta!==!1&&e.jsx("div",{className:"sticky bottom-0 z-40 border-t border-white/10 bg-[#0b0e17]/95 p-3 backdrop-blur md:hidden",children:e.jsxs("a",{href:"#connect",onClick:()=>n==null?void 0:n("cta_click","sticky"),className:"flex items-center justify-center gap-2 rounded-full py-3.5 text-sm font-semibold",style:{backgroundColor:i,color:"#10131c"},children:[s.cta_label||"Book a confidential 15-min call"," ",e.jsx(Oa,{className:"h-4 w-4"})]})})]})}const cW=q;function Jmn(){const{slug:s}=bi(),[t,n]=N.useState(null),[r,a]=N.useState("loading");N.useEffect(()=>{if(!s)return;let o=!1;return(async()=>{const{data:c,error:d}=await cW.rpc("public_get_attract_landing_page",{_slug:s});if(!o){if(d||!c||c.error){a("missing");return}n(c),a("ready"),cW.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&&cW.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 cW.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(Go,{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(l4t,{cfg:t,onSubmitLead:l,onTrack:i})]})}const c4t={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},dtt={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"},epn=[{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."}],tpn=[{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."}],spn=[{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."}],npn="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.",rpn={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:""},apn={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 ipn(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:epn,sponsor_cards:spn,faqs:tpn,lead_magnet:rpn,calculator:apn,sections:c4t,disclaimer:npn,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 d4t(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}const t7=q;function opn(){const{user:s}=ys(),t=Ht(),n=["attract-landing-page",s==null?void 0:s.id],{data:r,isLoading:a}=ct({queryKey:n,enabled:!!s,queryFn:async()=>{const{data:c,error:d}=await t7.from("attract_landing_pages").select("*").eq("user_id",s.id).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(d)throw d;return c||null}}),{data:i}=ct({queryKey:["attract-landing-analytics",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{data:c,error:d}=await t7.from("attract_landing_events").select("event_type, section_key, created_at").eq("page_id",r.id).order("created_at",{ascending:!1}).limit(1e3);if(d)throw d;const u=c||[],h=u.filter(g=>g.event_type==="view").length,p=u.filter(g=>g.event_type==="cta_click").length,f=u.filter(g=>g.event_type==="calculator_run").length;return{views:h,ctas:p,calcs:f,conversion:h?Math.round(p/h*100):0}}}),l=gt({mutationFn:async c=>{const d=d4t(c||"my-attraction-page")||"attraction-page";let u=d;for(let g=0;g<5;g++){const{data:_}=await t7.from("attract_landing_pages").select("id").eq("slug",u).maybeSingle();if(!_)break;u=`${d}-${Math.random().toString(36).slice(2,6)}`}const h=ipn(c||"Your Name"),{data:p,error:f}=await t7.from("attract_landing_pages").insert({...h,user_id:s.id,slug:u}).select("*").single();if(f)throw f;return p},onSuccess:()=>{t.invalidateQueries({queryKey:n}),ae.success("Attraction page created")},onError:c=>ae.error(c.message||"Could not create the page")}),o=gt({mutationFn:async c=>{const{error:d}=await t7.from("attract_landing_pages").update(c).eq("id",r.id);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:n}),ae.success("Saved")},onError:c=>{var d;return ae.error((d=c.message)!=null&&d.includes("duplicate")?"That web address is already taken":c.message||"Could not save")}});return{page:r,isLoading:a,analytics:i,createPage:l,savePage:o}}function lpn(){var v,j,b,S,A,T,L,D,M,F,z,V;const{user:s}=ys(),{page:t,isLoading:n,analytics:r,createPage:a,savePage:i}=opn(),[l,o]=N.useState(null),[c,d]=N.useState(!1);N.useEffect(()=>{t&&o({...t})},[t]);const u=N.useMemo(()=>l!=null&&l.slug?`${window.location.origin}/join/${l.slug}`:"",[l==null?void 0:l.slug]),h=W=>o(Y=>({...Y,...W})),p=(W,Y)=>h({[W]:Y}),f=(W,Y,K)=>p(W,l[W].map((J,ne)=>ne===Y?{...J,...K}:J)),g=()=>{const{id:W,user_id:Y,created_at:K,updated_at:J,...ne}=l;i.mutate({...ne,slug:d4t(ne.slug)})};if(n)return e.jsx("div",{className:"p-10 text-center text-muted-foreground",children:"Loading…"});if(!t)return e.jsxs("div",{className:"mx-auto max-w-2xl px-6 py-16 text-center",children:[e.jsx("div",{className:"mx-auto mb-6 flex h-14 w-14 items-center justify-center rounded-2xl bg-primary/10 text-primary",children:e.jsx(un,{className:"h-7 w-7"})}),e.jsx("h1",{className:"mb-3 text-3xl font-bold tracking-tight",children:"Your Attraction Landing Page"}),e.jsx("p",{className:"mb-8 text-muted-foreground",children:"A public page built to convert agents — value stack, earnings calculator, objection-handling FAQ, and a confidential contact form that drops every lead straight into your Attract pipeline."}),e.jsx(B,{size:"lg",onClick:()=>{var W;return a.mutate(((W=s==null?void 0:s.user_metadata)==null?void 0:W.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(l4t,{cfg:l,preview:!0})]});const _={...c4t,...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(Er,{className:"mr-2 h-4 w-4"})," Preview"]}),l.is_published&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:u,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"mr-2 h-4 w-4"})," View live"]})}),e.jsxs(B,{size:"sm",onClick:g,disabled:i.isPending,children:[e.jsx(qo,{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(W=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:W.label}),e.jsx("div",{className:"mt-1 text-2xl font-bold",children:W.value})]})},W.label))}),e.jsxs(Br,{defaultValue:"content",children:[e.jsxs(Fr,{className:"mb-6 flex-wrap",children:[e.jsx(Kt,{value:"content",children:"Content"}),e.jsx(Kt,{value:"proof",children:"Proof & FAQ"}),e.jsx(Kt,{value:"calculator",children:"Calculator"}),e.jsx(Kt,{value:"sections",children:"Sections"}),e.jsx(Kt,{value:"publish",children:"Publish"})]}),e.jsxs(is,{value:"content",className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Hero"})}),e.jsxs(Ee,{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(pd,{label:"Your name",value:l.agent_name,onChange:W=>h({agent_name:W})}),e.jsx(pd,{label:"Title / brokerage",value:l.agent_title,onChange:W=>h({agent_title:W})}),e.jsx(pd,{label:"Eyebrow line",value:l.eyebrow,onChange:W=>h({eyebrow:W}),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(Es,{rows:2,value:l.headline||"",onChange:W=>h({headline:W.target.value})})]}),e.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[e.jsx(se,{children:"Subheadline"}),e.jsx(Es,{rows:3,value:l.subheadline||"",onChange:W=>h({subheadline:W.target.value})})]}),e.jsx(pd,{label:"Button text",value:l.cta_label,onChange:W=>h({cta_label:W})}),e.jsx(pd,{label:"Scheduling link (Calendly etc.)",value:l.calendar_url,onChange:W=>h({calendar_url:W})}),e.jsx(pd,{label:"Headshot URL",value:l.headshot_url,onChange:W=>h({headshot_url:W})}),e.jsx(pd,{label:"Hero background image URL",value:l.hero_image_url,onChange:W=>h({hero_image_url:W})}),e.jsx(pd,{label:"Logo URL",value:l.logo_url,onChange:W=>h({logo_url:W})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(pd,{label:"Primary color",type:"color",value:l.primary_color,onChange:W=>h({primary_color:W})}),e.jsx(pd,{label:"Accent color",type:"color",value:l.accent_color,onChange:W=>h({accent_color:W})})]}),e.jsx(pd,{label:"Phone",value:l.phone,onChange:W=>h({phone:W})}),e.jsx(pd,{label:"Email",value:l.email,onChange:W=>h({email:W})})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Credibility strip"})}),e.jsxs(Ee,{className:"space-y-3",children:[(l.credibility||[]).map((W,Y)=>e.jsxs(s7,{onRemove:()=>p("credibility",l.credibility.filter((K,J)=>J!==Y)),children:[e.jsx(ye,{placeholder:"Value (e.g. $42M)",value:W.value||"",onChange:K=>f("credibility",Y,{value:K.target.value})}),e.jsx(ye,{placeholder:"Label (e.g. Closed volume)",value:W.label||"",onChange:K=>f("credibility",Y,{label:K.target.value})})]},Y)),e.jsx(n7,{onClick:()=>p("credibility",[...l.credibility||[],{value:"",label:""}]),label:"Add stat"})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Your story"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx(pd,{label:"Section title",value:l.story_title,onChange:W=>h({story_title:W})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Story"}),e.jsx(Es,{rows:6,value:l.story_body||"",onChange:W=>h({story_body:W.target.value})})]}),e.jsx(pd,{label:"Story video URL (YouTube, Vimeo, Loom, MP4)",value:l.story_video_url,onChange:W=>h({story_video_url:W})})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Value stack"})}),e.jsxs(Ee,{className:"space-y-4",children:[(l.value_cards||[]).map((W,Y)=>e.jsxs(s7,{vertical:!0,onRemove:()=>p("value_cards",l.value_cards.filter((K,J)=>J!==Y)),children:[e.jsx(ye,{placeholder:"Title",value:W.title||"",onChange:K=>f("value_cards",Y,{title:K.target.value})}),e.jsx(Es,{rows:2,placeholder:"Description",value:W.body||"",onChange:K=>f("value_cards",Y,{body:K.target.value})}),e.jsx(ye,{placeholder:"Proof point (optional)",value:W.proof||"",onChange:K=>f("value_cards",Y,{proof:K.target.value})})]},Y)),e.jsx(n7,{onClick:()=>p("value_cards",[...l.value_cards||[],{title:"",body:""}]),label:"Add value card"})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"What you get from me"})}),e.jsxs(Ee,{className:"space-y-4",children:[(l.sponsor_cards||[]).map((W,Y)=>e.jsxs(s7,{vertical:!0,onRemove:()=>p("sponsor_cards",l.sponsor_cards.filter((K,J)=>J!==Y)),children:[e.jsx(ye,{placeholder:"Title",value:W.title||"",onChange:K=>f("sponsor_cards",Y,{title:K.target.value})}),e.jsx(Es,{rows:2,placeholder:"Description",value:W.body||"",onChange:K=>f("sponsor_cards",Y,{body:K.target.value})})]},Y)),e.jsx(n7,{onClick:()=>p("sponsor_cards",[...l.sponsor_cards||[],{title:"",body:""}]),label:"Add commitment"})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Free download & upcoming event"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx(pd,{label:"Download title",value:(v=l.lead_magnet)==null?void 0:v.title,onChange:W=>h({lead_magnet:{...l.lead_magnet,title:W}})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Download description"}),e.jsx(Es,{rows:2,value:((j=l.lead_magnet)==null?void 0:j.body)||"",onChange:W=>h({lead_magnet:{...l.lead_magnet,body:W.target.value}})})]}),e.jsx(pd,{label:"File URL",value:(b=l.lead_magnet)==null?void 0:b.file_url,onChange:W=>h({lead_magnet:{...l.lead_magnet,file_url:W}})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(pd,{label:"Event title",value:(S=l.event_block)==null?void 0:S.title,onChange:W=>h({event_block:{...l.event_block,title:W}})}),e.jsx(pd,{label:"When",value:(A=l.event_block)==null?void 0:A.when,onChange:W=>h({event_block:{...l.event_block,when:W}})}),e.jsx(pd,{label:"Registration link",value:(T=l.event_block)==null?void 0:T.url,onChange:W=>h({event_block:{...l.event_block,url:W}})})]})]})]})]}),e.jsxs(is,{value:"proof",className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Testimonials"})}),e.jsxs(Ee,{className:"space-y-4",children:[(l.testimonials||[]).map((W,Y)=>e.jsxs(s7,{vertical:!0,onRemove:()=>p("testimonials",l.testimonials.filter((K,J)=>J!==Y)),children:[e.jsx(Es,{rows:3,placeholder:"Quote",value:W.quote||"",onChange:K=>f("testimonials",Y,{quote:K.target.value})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(ye,{placeholder:"Name",value:W.name||"",onChange:K=>f("testimonials",Y,{name:K.target.value})}),e.jsx(ye,{placeholder:"Role / market",value:W.role||"",onChange:K=>f("testimonials",Y,{role:K.target.value})}),e.jsx(ye,{placeholder:"Photo URL",value:W.photo_url||"",onChange:K=>f("testimonials",Y,{photo_url:K.target.value})})]})]},Y)),e.jsx(n7,{onClick:()=>p("testimonials",[...l.testimonials||[],{quote:"",name:""}]),label:"Add testimonial"})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Objection-handling FAQ"})}),e.jsxs(Ee,{className:"space-y-4",children:[(l.faqs||[]).map((W,Y)=>e.jsxs(s7,{vertical:!0,onRemove:()=>p("faqs",l.faqs.filter((K,J)=>J!==Y)),children:[e.jsx(ye,{placeholder:"Question",value:W.q||"",onChange:K=>f("faqs",Y,{q:K.target.value})}),e.jsx(Es,{rows:3,placeholder:"Answer",value:W.a||"",onChange:K=>f("faqs",Y,{a:K.target.value})})]},Y)),e.jsx(n7,{onClick:()=>p("faqs",[...l.faqs||[],{q:"",a:""}]),label:"Add question"})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Income disclaimer"})}),e.jsx(Ee,{children:e.jsx(Es,{rows:4,value:l.disclaimer||"",onChange:W=>h({disclaimer:W.target.value})})})]})]}),e.jsx(is,{value:"calculator",children:e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Earnings calculator"})}),e.jsxs(Ee,{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(pd,{label:"Section title",value:(L=l.calculator)==null?void 0:L.title,onChange:W=>h({calculator:{...l.calculator,title:W}}),className:"md:col-span-2"}),e.jsx(pd,{label:"Cap ($)",type:"number",value:(D=l.calculator)==null?void 0:D.cap,onChange:W=>h({calculator:{...l.calculator,cap:Number(W)}})}),e.jsx(pd,{label:"Your split (%)",type:"number",value:(M=l.calculator)==null?void 0:M.split,onChange:W=>h({calculator:{...l.calculator,split:Number(W)}})}),e.jsx(pd,{label:"Per-transaction fee ($)",type:"number",value:(F=l.calculator)==null?void 0:F.transaction_fee,onChange:W=>h({calculator:{...l.calculator,transaction_fee:Number(W)}})}),e.jsx(pd,{label:"Typical competitor split (%)",type:"number",value:(z=l.calculator)==null?void 0:z.current_split,onChange:W=>h({calculator:{...l.calculator,current_split:Number(W)}})}),e.jsx(pd,{label:"Typical competitor monthly fees ($)",type:"number",value:(V=l.calculator)==null?void 0:V.current_monthly_fees,onChange:W=>h({calculator:{...l.calculator,current_monthly_fees:Number(W)}})}),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(is,{value:"sections",children:e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Show or hide sections"})}),e.jsx(Ee,{className:"divide-y",children:Object.keys(dtt).map(W=>e.jsxs("div",{className:"flex items-center justify-between py-3",children:[e.jsx("span",{className:"text-sm",children:dtt[W]}),e.jsx(bn,{checked:_[W]!==!1,onCheckedChange:Y=>h({sections:{..._,[W]:Y}})})]},W))})]})}),e.jsxs(is,{value:"publish",className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Publishing"})}),e.jsxs(Ee,{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(bn,{checked:!!l.is_published,onCheckedChange:W=>h({is_published:W})})]}),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(bn,{checked:!!l.noindex,onCheckedChange:W=>h({noindex:W})})]}),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:W=>h({slug:W.target.value})}),e.jsx(B,{variant:"outline",onClick:()=>{navigator.clipboard.writeText(u),ae.success("Link copied")},children:e.jsx(Xr,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u})]}),e.jsx(pd,{label:"Search title",value:l.seo_title,onChange:W=>h({seo_title:W})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Search description"}),e.jsx(Es,{rows:2,value:l.seo_description||"",onChange:W=>h({seo_description:W.target.value})})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(yo,{className:"h-4 w-4"})," Where leads go"]})}),e.jsx(Ee,{className:"text-sm text-muted-foreground",children:"Every submission creates or updates a prospect in your Attract pipeline, logs an activity, and emails you a notification. Calculator runs and CTA clicks are tracked so you can see what is working."})]})]})]}),e.jsx("div",{className:"mt-8 flex justify-end",children:e.jsxs(B,{onClick:g,disabled:i.isPending,children:[e.jsx(qo,{className:"mr-2 h-4 w-4"})," ",i.isPending?"Saving…":"Save changes"]})})]})}function pd({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 s7({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(_n,{className:"h-4 w-4"})})]})}function n7({onClick:s,label:t}){return e.jsxs(B,{variant:"outline",size:"sm",onClick:s,children:[e.jsx(Is,{className:"mr-2 h-4 w-4"})," ",t]})}function cpn(s){const{user:t}=ys(),n=Ht(),r=ct({queryKey:["admin-attract-list",s,t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{let o=q.from("profiles").select("id, email, full_name").order("full_name",{ascending:!0}).limit(100);if(s.trim()){const p=`%${s.trim()}%`;o=o.or(`email.ilike.${p},full_name.ilike.${p}`)}const{data:c,error:d}=await o;if(d)throw d;const u=(c??[]).map(p=>p.id);let h={};if(u.length){const{data:p,error:f}=await q.from("feature_entitlements").select("user_id, enabled, tier, enabled_at, expires_at, notes, enabled_by").eq("feature_key","levelup_attract").in("user_id",u);if(f)throw f;(p??[]).forEach(g=>{h[g.user_id]=g})}return(c??[]).map(p=>{var f,g,_,v,j,b;return{user_id:p.id,email:p.email,full_name:p.full_name,enabled:!!((f=h[p.id])!=null&&f.enabled),tier:((g=h[p.id])==null?void 0:g.tier)??null,enabled_at:((_=h[p.id])==null?void 0:_.enabled_at)??null,expires_at:((v=h[p.id])==null?void 0:v.expires_at)??null,notes:((j=h[p.id])==null?void 0:j.notes)??null,enabled_by:((b=h[p.id])==null?void 0:b.enabled_by)??null}})}}),a=ct({queryKey:["admin-attract-audit",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:o,error:c}=await q.from("feature_entitlement_audit").select("*").eq("feature_key","levelup_attract").order("created_at",{ascending:!1}).limit(50);if(c)throw c;return o??[]}}),i=gt({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:p}=await q.from("feature_entitlements").upsert(h,{onConflict:"user_id,feature_key"});if(p)throw p;await q.from("feature_entitlement_audit").insert({feature_key:"levelup_attract",target_user_id:o,action:"grant",tier:h.tier,expires_at:h.expires_at,notes:h.notes,performed_by:t.id})},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-attract-list"]}),n.invalidateQueries({queryKey:["admin-attract-audit"]}),ae.success("Access granted")},onError:o=>ae.error(o.message)}),l=gt({mutationFn:async o=>{const{error:c}=await q.from("feature_entitlements").update({enabled:!1}).eq("user_id",o).eq("feature_key","levelup_attract");if(c)throw c;await q.from("feature_entitlement_audit").insert({feature_key:"levelup_attract",target_user_id:o,action:"revoke",performed_by:t.id})},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-attract-list"]}),n.invalidateQueries({queryKey:["admin-attract-audit"]}),ae.success("Access revoked")},onError:o=>ae.error(o.message)});return{list:r,audit:a,grant:i,revoke:l}}function dpn(){const[s,t]=N.useState(""),{list:n,audit:r,grant:a,revoke:i}=cpn(s),[l,o]=N.useState(null),[c,d]=N.useState(null),[u,h]=N.useState("beta"),[p,f]=N.useState(""),[g,_]=N.useState(""),v=b=>{d(b),h(b.tier??"beta"),f(b.expires_at?b.expires_at.slice(0,10):""),_(b.notes??"")},j=async()=>{c&&(await a.mutateAsync({target_user_id:c.user_id,tier:u,expires_at:p?new Date(p).toISOString():null,notes:g||void 0}),d(null))};return e.jsxs("div",{className:"p-6",children:[e.jsx(Ud,{title:"LevelUp Attract — Access Management",description:"Grant or revoke access to LevelUp Attract for individual members. Every change is audited."}),e.jsx(fe,{className:"p-4 rounded-2xl mb-4",children:e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{value:s,onChange:b=>t(b.target.value),placeholder:"Search by name or email...",className:"pl-9"})]})}),e.jsxs(fe,{className:"rounded-2xl overflow-hidden mb-8",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-3 px-5 py-3 text-[11px] uppercase tracking-widest text-slate-500 font-semibold border-b",children:[e.jsx("div",{children:"Member"}),e.jsx("div",{children:"Access"}),e.jsx("div",{children:"Enabled"}),e.jsx("div",{children:"Actions"})]}),n.isLoading&&e.jsx("div",{className:"p-6 text-center text-slate-500 text-sm",children:"Loading members…"}),!n.isLoading&&(n.data??[]).length===0&&e.jsx("div",{className:"p-6 text-center text-slate-500 text-sm",children:"No members match."}),(n.data??[]).map(b=>e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-3 px-5 py-3 items-center border-b last:border-0 hover:bg-slate-50",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 truncate",children:b.full_name||b.email||b.user_id}),e.jsx("div",{className:"text-[11.5px] text-slate-500 truncate",children:b.email})]}),e.jsx("div",{children:b.enabled?e.jsxs(ze,{className:"bg-emerald-100 text-emerald-800 border-0 gap-1",children:[e.jsx(un,{className:"h-3 w-3"})," ",b.tier??"enabled"]}):e.jsx(ze,{variant:"outline",className:"text-slate-500",children:"Not enabled"})}),e.jsx("div",{className:"text-[11.5px] text-slate-500 whitespace-nowrap",children:b.enabled_at?Ss(new Date(b.enabled_at),"MMM d, yyyy"):"—"}),e.jsx("div",{className:"flex gap-1.5",children:b.enabled?e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>v(b),children:"Edit"}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>o({user:b,action:"revoke"}),children:"Revoke"})]}):e.jsxs(B,{size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>v(b),children:[e.jsx(sg,{className:"h-3.5 w-3.5 mr-1"})," Enable"]})})]},b.user_id))]}),e.jsxs(fe,{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(MA,{className:"h-3.5 w-3.5"})," Recent audit history"]}),r.isLoading&&e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading…"}),(r.data??[]).length===0&&!r.isLoading&&e.jsx("div",{className:"text-slate-500 text-sm",children:"No changes yet."}),e.jsx("div",{className:"space-y-1.5",children:(r.data??[]).map(b=>e.jsxs("div",{className:"text-[12.5px] text-slate-700 flex items-center gap-2",children:[e.jsx(ze,{variant:"outline",className:"text-[10.5px] capitalize",children:b.action}),e.jsx("span",{className:"font-mono text-[11px] text-slate-500",children:b.target_user_id.slice(0,8)}),b.tier&&e.jsxs("span",{className:"text-slate-500",children:["· ",b.tier]}),b.notes&&e.jsxs("span",{className:"text-slate-500",children:["· ",b.notes]}),e.jsx("span",{className:"text-slate-400 ml-auto",children:Ss(new Date(b.created_at),"MMM d h:mm a")})]},b.id))})]}),e.jsx(bs,{open:!!c,onOpenChange:b=>!b&&d(null),children:e.jsxs(vs,{children:[e.jsxs(ws,{children:[e.jsxs(_s,{children:[c!=null&&c.enabled?"Update":"Enable"," Attract access"]}),e.jsx(Qn,{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(ds,{value:u,onValueChange:h,children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"beta",children:"Beta"}),e.jsx(Qe,{value:"standard",children:"Standard"}),e.jsx(Qe,{value:"pro",children:"Pro"}),e.jsx(Qe,{value:"founder",children:"Founder"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Expires (optional)"}),e.jsx(ye,{type:"date",value:p,onChange:b=>f(b.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Internal notes (optional)"}),e.jsx(Es,{rows:2,value:g,onChange:b=>_(b.target.value)})]})]}),e.jsxs(Xn,{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:j,disabled:a.isPending,children:c!=null&&c.enabled?"Save changes":"Enable access"})]})]})}),e.jsx(Oo,{open:!!l,onOpenChange:b=>!b&&o(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Revoke Attract access?"}),e.jsxs(Mo,{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(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsxs(jo,{className:"bg-rose-600 hover:bg-rose-700",onClick:async()=>{l&&await i.mutateAsync(l.user.user_id),o(null)},children:[e.jsx(Hc,{className:"h-4 w-4 mr-1.5"})," Revoke access"]})]})]})})]})}const upn=({team:s,onSelect:t})=>{const{data:n}=ct({queryKey:["team-card-info",s.id],queryFn:async()=>{const{data:r}=await q.from("team_members").select("user_id, role").eq("team_id",s.id),a=(r==null?void 0:r.length)||0,i=r==null?void 0:r.find(o=>o.role==="team_leader");let l=null;if(i){const{data:o}=await q.from("profiles").select("name, avatar_url").eq("id",i.user_id).single();l=o}return{count:a,leaderProfile:l}}});return e.jsxs(fe,{className:"cursor-pointer hover:shadow-md transition-shadow group",onClick:t,children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(It,{className:"text-lg truncate",children:s.name}),s.description&&e.jsx(Vn,{className:"mt-1 line-clamp-2",children:s.description})]}),e.jsxs(ze,{variant:"secondary",className:"ml-2 shrink-0",children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),(n==null?void 0:n.count)??"…"]})]})}),e.jsxs(Ee,{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(ni,{src:n.leaderProfile.avatar_url||""}),e.jsx(aa,{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(ff,{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(dh,{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(ze,{variant:"outline",className:"text-xs py-0",children:"Lead Pond"}),s.shared_assets_enabled&&e.jsx(ze,{variant:"outline",className:"text-xs py-0",children:"Shared Assets"}),s.shared_videos_enabled&&e.jsx(ze,{variant:"outline",className:"text-xs py-0",children:"Shared Videos"})]})]})]})},hpn=()=>{const{user:s,isAdmin:t,isBrokerageManager:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i}=ys(),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:p,addMember:f,removeMember:g,updateMemberRole:_}=e6(o),[v,j]=N.useState(!1),[b,S]=N.useState(null),{data:A}=ct({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:D,error:M}=await q.from("brokerages").select("id, name").order("name");if(M)throw M;return D||[]},enabled:t}),{data:T}=ct({queryKey:["brokerage-agents-for-teams",l],queryFn:async()=>{const{data:D,error:M}=await q.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",l).order("name");if(M)throw M;return D||[]},enabled:!!l}),L=async D=>{const M=D.brokerage_id||l||null,F=await u.mutateAsync({name:D.name,brokerage_id:M,description:D.description});if(D.leaderId&&D.leaderId!=="none"&&await f.mutateAsync({team_id:F.id,user_id:D.leaderId,role:"team_leader"}),D.memberIds)for(const z of D.memberIds)await f.mutateAsync({team_id:F.id,user_id:z,role:"team_member"});j(!1)};return!n&&!t?e.jsx(Ts,{title:"Teams",description:"Team Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Nn,{className:"h-12 w-12 text-muted-foreground mb-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(Ts,{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:()=>j(!0),children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(iyt,{open:v,onOpenChange:j,onCreateTeam:L,isCreating:u.isPending,brokerageAgents:T||[],isAdmin:t,allBrokerages:A,activeBrokerageId:l}),d&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(D=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6",children:[e.jsx(Ws,{className:"h-5 w-32 mb-3"}),e.jsx(Ws,{className:"h-4 w-48 mb-4"}),e.jsx(Ws,{className:"h-8 w-full"})]})},D))}),!d&&c.length===0&&!b&&e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Nn,{className:"h-12 w-12 text-muted-foreground mb-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:()=>j(!0),children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Create Your First Team"]})]})}),!d&&c.length>0&&!b&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:c.map(D=>e.jsx(upn,{team:D,onSelect:()=>S(D)},D.id))}),b&&e.jsx(ayt,{team:b,brokerageAgents:T||[],onBack:()=>S(null),onUpdate:D=>h.mutateAsync({id:b.id,...D}).then(M=>S(M)),onAddMember:(D,M)=>f.mutateAsync({team_id:b.id,user_id:D,role:M}),onRemoveMember:D=>g.mutateAsync({team_id:b.id,member_id:D}),onUpdateRole:(D,M)=>_.mutateAsync({team_id:b.id,member_id:D,role:M}),onDeleteTeam:()=>p.mutate(b.id),isUpdating:h.isPending,isAddingMember:f.isPending})]})})},mpn=()=>{const{data:s,isLoading:t}=Zv(),{useTeamMembers:n}=e6(),{data:r=[],isLoading:a}=n((s==null?void 0:s.teamId)||"");if(t)return e.jsx(Ts,{title:"My Team",description:"Your team",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-8 w-48"}),e.jsx(Ws,{className:"h-40 w-full"})]})});if(!s)return e.jsx(Ts,{title:"My Team",description:"Your team",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Nn,{className:"h-12 w-12 text-muted-foreground mb-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(Ts,{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(ze,{variant:s.role==="team_leader"?"default":"secondary",className:"capitalize",children:s.role==="team_leader"?e.jsxs(e.Fragment,{children:[e.jsx(ff,{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(Br,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(Fr,{className:"flex-wrap",children:[e.jsx(Kt,{value:"members",children:"Members"}),i.contact_visibility!=="private"&&e.jsxs(Kt,{value:"contacts",children:[e.jsx(SA,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),i.lead_pond_enabled&&e.jsxs(Kt,{value:"lead-pond",children:[e.jsx(mb,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),i.shared_assets_enabled&&e.jsxs(Kt,{value:"shared-assets",children:[e.jsx(gf,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]})]}),e.jsx(is,{value:"members",className:"space-y-2",children:a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(l=>e.jsx(Ws,{className:"h-16 w-full"},l))}):r.map(l=>{var o,c,d,u;return e.jsx(fe,{children:e.jsxs(Ee,{className:"flex items-center gap-3 p-4",children:[e.jsxs(ra,{className:"h-10 w-10",children:[e.jsx(ni,{src:((o=l.profile)==null?void 0:o.avatar_url)||""}),e.jsx(aa,{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(ze,{className:"ml-auto bg-amber-500/10 text-amber-600 border-amber-500",children:[e.jsx(ff,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(ze,{variant:"secondary",className:"ml-auto",children:"Member"})]})},l.id)})}),i.contact_visibility!=="private"&&e.jsx(is,{value:"contacts",className:"space-y-4",children:e.jsx(YIe,{})}),i.lead_pond_enabled&&e.jsx(is,{value:"lead-pond",className:"space-y-4",children:e.jsx(ZIe,{teamId:s.teamId})}),i.shared_assets_enabled&&e.jsx(is,{value:"shared-assets",className:"space-y-4",children:e.jsx(ryt,{teamId:s.teamId})})]})]})})};function ppn(){const{user:s}=ys(),t=Ht(),n=ct({queryKey:["booking-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:j}=await q.from("agent_booking_settings").select("*").eq("user_id",s.id).maybeSingle();if(j)throw j;return v},enabled:!!s}),r=ct({queryKey:["booking-types",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:j}=await q.from("agent_booking_types").select("*").eq("user_id",s.id).order("sort_order");if(j)throw j;return v},enabled:!!s}),a=ct({queryKey:["availability-slots",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:j}=await q.from("agent_availability_slots").select("*").eq("user_id",s.id).order("day_of_week").order("start_time");if(j)throw j;return v},enabled:!!s}),i=ct({queryKey:["blocked-dates",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:j}=await q.from("agent_blocked_dates").select("*").eq("user_id",s.id).order("blocked_date");if(j)throw j;return v},enabled:!!s}),l=ct({queryKey:["bookings",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:j}=await q.from("bookings").select("*, booking_type:agent_booking_types(*)").eq("agent_user_id",s.id).order("booking_date",{ascending:!1});if(j)throw j;return v},enabled:!!s}),o=gt({mutationFn:async()=>{const{data:v,error:j}=await q.from("agent_booking_settings").insert({user_id:s.id,slug:""}).select().single();if(j)throw j;const b=[{name:"Listing Consultation",description:"Get a comprehensive market analysis and listing strategy for your home",duration_minutes:60,color:"#10B981",icon:"Home",sort_order:0},{name:"Buyer Consultation",description:"Discuss your home search criteria, budget, and buying process",duration_minutes:45,color:"#3B82F6",icon:"Search",sort_order:1},{name:"Home Valuation",description:"Find out what your home is worth in today's market",duration_minutes:30,color:"#F59E0B",icon:"DollarSign",sort_order:2},{name:"General Meeting",description:"Coffee chat, check-in, or quick real estate question",duration_minutes:30,color:"#8B5CF6",icon:"Coffee",sort_order:3}],{error:S}=await q.from("agent_booking_types").insert(b.map(L=>({...L,user_id:s.id})));if(S)throw S;const A=[1,2,3,4,5].map(L=>({user_id:s.id,day_of_week:L,start_time:"09:00",end_time:"17:00"})),{error:T}=await q.from("agent_availability_slots").insert(A);if(T)throw T;return v},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["booking-types"]}),t.invalidateQueries({queryKey:["availability-slots"]}),ae.success("Scheduler set up successfully!")},onError:v=>ae.error(v.message)}),c=gt({mutationFn:async v=>{const{error:j}=await q.from("agent_booking_settings").update(v).eq("user_id",s.id);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),ae.success("Settings updated")},onError:v=>ae.error(v.message)}),d=gt({mutationFn:async v=>{const j={...v,user_id:s.id};if(v.id){const{error:b}=await q.from("agent_booking_types").update(j).eq("id",v.id);if(b)throw b}else{const{error:b}=await q.from("agent_booking_types").insert(j);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ae.success("Booking type saved")},onError:v=>ae.error(v.message)}),u=gt({mutationFn:async v=>{const{error:j}=await q.from("agent_booking_types").delete().eq("id",v);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ae.success("Booking type deleted")},onError:v=>ae.error(v.message)}),h=gt({mutationFn:async v=>{const j={...v,user_id:s.id};if(v.id){const{error:b}=await q.from("agent_availability_slots").update(j).eq("id",v.id);if(b)throw b}else{const{error:b}=await q.from("agent_availability_slots").insert(j);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:v=>ae.error(v.message)}),p=gt({mutationFn:async v=>{const{error:j}=await q.from("agent_availability_slots").delete().eq("id",v);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:v=>ae.error(v.message)}),f=gt({mutationFn:async v=>{const{error:j}=await q.from("agent_blocked_dates").insert({...v,user_id:s.id});if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]}),ae.success("Date blocked")},onError:v=>ae.error(v.message)}),g=gt({mutationFn:async v=>{const{error:j}=await q.from("agent_blocked_dates").delete().eq("id",v);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]})},onError:v=>ae.error(v.message)}),_=gt({mutationFn:async({id:v,reason:j})=>{const{error:b}=await q.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:j}).eq("id",v);if(b)throw b},onSuccess:()=>{t.invalidateQueries({queryKey:["bookings"]}),ae.success("Booking cancelled")},onError:v=>ae.error(v.message)});return{settings:n.data,bookingTypes:r.data??[],availability:a.data??[],blockedDates:i.data??[],bookings:l.data??[],isLoading:n.isLoading,initializeSettings:o,updateSettings:c,upsertBookingType:d,deleteBookingType:u,upsertAvailability:h,deleteAvailability:p,addBlockedDate:f,removeBlockedDate:g,cancelBooking:_}}const utt={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function fpn({types:s,onSave:t,onDelete:n}){const[r,a]=N.useState(null),[i,l]=N.useState(!1),o=()=>{a({name:"",description:"",duration_minutes:30,color:"#3B82F6",icon:"Calendar",is_active:!0,qualification_enabled:!1}),l(!0)},c=u=>{a({...u}),l(!0)},d=()=>{r!=null&&r.name&&(t(r),l(!1),a(null))};return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Booking Types"}),e.jsx(Vn,{children:"The meeting types prospects can book with you"})]}),e.jsxs(B,{onClick:o,size:"sm",children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Type"]})]}),e.jsx(Ee,{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:utt[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(ze,{variant:"secondary",className:"text-xs",children:"Inactive"}),u.qualification_enabled&&e.jsxs(ze,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(m9,{className:"h-3 w-3"})," Qualifying"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(gr,{className:"h-3 w-3"}),u.duration_minutes," min",u.description&&e.jsxs("span",{children:["· ",u.description.slice(0,60),u.description.length>60?"...":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(u),children:e.jsx(_a,{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(_n,{className:"h-4 w-4"})})]})]},u.id))})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsxs(_s,{children:[r!=null&&r.id?"Edit":"New"," Booking Type"]})}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(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(Es,{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:"Icon"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(utt).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(bn,{checked:r.qualification_enabled||!1,onCheckedChange:u=>a({...r,qualification_enabled:u})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Active"}),e.jsx(bn,{checked:r.is_active??!0,onCheckedChange:u=>a({...r,is_active:u})})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:d,children:"Save"})]})]})})]})}const htt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function xpn({slots:s,onSave:t,onDelete:n}){const[r,a]=N.useState(null),[i,l]=N.useState("09:00"),[o,c]=N.useState("17:00"),d=htt.map((h,p)=>s.filter(f=>f.day_of_week===p)),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(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(gr,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(Vn,{children:"Set your available hours for each day"})]}),e.jsx(Ee,{className:"space-y-2",children:htt.map((h,p)=>{const f=d[p];return e.jsxs("div",{className:"flex items-start gap-3 py-2 border-b last:border-0",children:[e.jsx("div",{className:"w-24 pt-1",children:e.jsx("p",{className:"text-sm font-medium",children:h})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"Unavailable"}):f.map(g=>{var _,v;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(_=g.start_time)==null?void 0:_.slice(0,5),onBlur:j=>t({id:g.id,start_time:j.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:(v=g.end_time)==null?void 0:v.slice(0,5),onBlur:j=>t({id:g.id,end_time:j.target.value})}),e.jsx(bn,{checked:g.is_active,onCheckedChange:j=>t({id:g.id,is_active:j})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(g.id),children:e.jsx(_n,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},g.id)}),r===p?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:g=>l(g.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:g=>c(g.target.value)}),e.jsx(B,{size:"sm",className:"h-8",onClick:u,children:"Add"}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>a(null),children:"Cancel"})]}):e.jsxs(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground",onClick:()=>a(p),children:[e.jsx(Is,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},h)})})]})}const gpn={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 ypn({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(Xi,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:i.guest_name}),e.jsx(ze,{className:`text-xs ${gpn[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(Tl,{className:"h-3.5 w-3.5"}),Ss(new Date(i.booking_date+"T00:00:00"),"MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gr,{className:"h-3.5 w-3.5"}),(o=i.start_time)==null?void 0:o.slice(0,5)," - ",(c=i.end_time)==null?void 0:c.slice(0,5)]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[i.guest_email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vs,{className:"h-3 w-3"}),i.guest_email]}),i.guest_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ar,{className:"h-3 w-3"}),i.guest_phone]})]}),i.booking_type&&e.jsx(ze,{variant:"outline",className:"text-xs mt-1",children:i.booking_type.name}),i.guest_message&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 italic",children:['"',i.guest_message,'"']})]}),l&&i.status==="confirmed"&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t(i.id),className:"text-destructive hover:text-destructive",children:[e.jsx(Hc,{className:"h-4 w-4 mr-1"})," Cancel"]})]},i.id)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Upcoming Bookings"}),e.jsxs(Vn,{children:[n.length," upcoming appointment",n.length!==1?"s":""]})]}),e.jsx(Ee,{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(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"Past & Cancelled"})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-3",children:r.slice(0,20).map(i=>a(i))})})]})]})}function vpn({blockedDates:s,onAdd:t,onRemove:n}){const[r,a]=N.useState(!1),[i,l]=N.useState(""),[o,c]=N.useState(""),d=()=>{i&&(t({blocked_date:i,reason:o||void 0}),a(!1),l(""),c(""))};return e.jsxs(fe,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(K7,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(Vn,{children:"Block specific dates (vacations, holidays, etc.)"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>a(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Block Date"]})]}),e.jsxs(Ee,{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:Ss(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(Bn,{className:"h-3.5 w-3.5"})})]},u.id))})]})]})}function bpn(){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:p,removeBlockedDate:f,cancelBooking:g}=ppn(),[_,v]=N.useState("");N.useState(15),_||s!=null&&s.meeting_link;const j=s!=null&&s.slug?`https://booking.relevelup.com/${s.slug}`:null;return i?e.jsx(Ts,{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(Ts,{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(Tl,{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:[j&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(j),ae.success("Booking link copied!")},children:[e.jsx(Xr,{className:"h-4 w-4 mr-1"})," Copy Link"]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:j,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(bn,{id:"scheduler-active",checked:s.is_active,onCheckedChange:b=>o.mutate({is_active:b})})]})]})]}),e.jsxs(Br,{defaultValue:"types",className:"space-y-4",children:[e.jsxs(Fr,{children:[e.jsx(Kt,{value:"types",children:"Booking Types"}),e.jsx(Kt,{value:"availability",children:"Availability"}),e.jsx(Kt,{value:"settings",children:"Settings"}),e.jsxs(Kt,{value:"bookings",children:["Bookings",a.filter(b=>b.status==="confirmed").length>0&&e.jsx(ze,{variant:"secondary",className:"ml-1.5 text-xs",children:a.filter(b=>b.status==="confirmed").length})]})]}),e.jsx(is,{value:"types",children:e.jsx(fpn,{types:t,onSave:b=>c.mutate(b),onDelete:b=>d.mutate(b)})}),e.jsx(is,{value:"availability",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(xpn,{slots:n,onSave:b=>u.mutate(b),onDelete:b=>h.mutate(b)}),e.jsx(vpn,{blockedDates:r,onAdd:b=>p.mutate(b),onRemove:b=>f.mutate(b)})]})}),e.jsx(is,{value:"settings",children:e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(C9,{className:"h-5 w-5"}),"General Settings"]}),e.jsx(Vn,{children:"Configure your booking page defaults"})]}),e.jsxs(Ee,{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:()=>{j&&(navigator.clipboard.writeText(j),ae.success("Copied!"))},children:e.jsx(Xr,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"meeting-link",children:[e.jsx(El,{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:b=>o.mutate({meeting_link:b.target.value||null})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your Zoom personal link, Google Meet, or phone number"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(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:b=>o.mutate({buffer_minutes:parseInt(b.target.value)||15})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(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:b=>o.mutate({min_notice_hours:parseInt(b.target.value)||2})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"hours"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(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:b=>o.mutate({max_advance_days:parseInt(b.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"days"})]})]})]})]})]})}),e.jsx(is,{value:"bookings",children:e.jsx(ypn,{bookings:a,onCancel:b=>g.mutate({id:b})})})]})]})}):e.jsx(Ts,{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(Tl,{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(fe,{children:e.jsxs(Ee,{className:"pt-6 space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[{icon:"🏠",title:"Listing Consultation",desc:"60 min"},{icon:"🔍",title:"Buyer Consultation",desc:"45 min"},{icon:"💰",title:"Home Valuation",desc:"30 min"},{icon:"☕",title:"General Meeting",desc:"30 min"}].map(b=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-muted/30",children:[e.jsx("span",{className:"text-2xl",children:b.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:b.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b.desc})]})]},b.title))}),e.jsx(ll,{}),e.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{children:"✅ Auto-creates CRM contacts from every booking"}),e.jsx("p",{children:"✅ Optional pre-qualification questions per booking type"}),e.jsx("p",{children:"✅ Embeds on your Smart Card — replaces TidyCal"}),e.jsx("p",{children:"✅ Standalone shareable booking page"})]}),e.jsxs(B,{onClick:()=>l.mutate(),disabled:l.isPending,className:"w-full",size:"lg",children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),l.isPending?"Setting up...":"Activate Scheduler"]})]})})]})})}const mtt=[{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 _pn(){const{user:s}=ys(),t=ma(),{toast:n}=Ba(),r=Mn(),a=Ht(),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState(null),[h,p]=N.useState({title:"",description:"",page_type:"lead_capture"}),{data:f=[],isLoading:g}=ct({queryKey:["landing-pages",t],queryFn:async()=>{const{data:b,error:S}=await q.from("landing_pages").select("*").eq("user_id",t).is("deleted_at",null).order("created_at",{ascending:!1});if(S)throw S;return b},enabled:!!t}),_=gt({mutationFn:async()=>{const b=h.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")+"-"+Date.now().toString(36),{data:S}=await q.from("profiles").select("name, phone, avatar_url, email").eq("id",t).single(),A=h.page_type==="just_listed"||h.page_type==="just_sold",{data:T,error:L}=await q.from("landing_pages").insert({user_id:t,title:h.title,description:h.description||null,page_type:h.page_type,slug:b,hero_headline:A?h.page_type==="just_listed"?"🏡 Just Listed":"🎉 Just Sold":h.page_type==="lead_magnet"?"📥 Free Download":h.title,agent_name:(S==null?void 0:S.name)||null,agent_phone:(S==null?void 0:S.phone)||null,agent_email:(S==null?void 0:S.email)||s.email||null,agent_photo_url:(S==null?void 0:S.avatar_url)||null,property_status:A?h.page_type.replace("just_",""):null}).select().single();if(L)throw L;const D=wpn(h.page_type);if(D.length>0){const{error:M}=await q.from("landing_page_fields").insert(D.map((F,z)=>({...F,page_id:T.id,sort_order:z})));if(M)throw M}return T},onSuccess:b=>{a.invalidateQueries({queryKey:["landing-pages"]}),l(!1),p({title:"",description:"",page_type:"lead_capture"}),n({title:"Landing page created!"}),r(`/mission-control/landing-pages/${b.id}`)},onError:b=>n({title:"Error",description:b.message,variant:"destructive"})}),v=gt({mutationFn:async b=>{const{error:S}=await q.from("landing_pages").update({deleted_at:new Date().toISOString(),is_published:!1}).eq("id",b);if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["landing-pages"]}),c(null),n({title:"Landing page deleted"})}}),j=b=>`https://pages.relevelup.com/${b}`;return e.jsxs(Ts,{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(Xo,{className:"h-4 w-4 mr-2"})," Defaults"]}),e.jsxs(B,{onClick:()=>l(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," New Page"]})]})]}),g?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):f.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Nr,{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(Is,{className:"h-4 w-4 mr-2"})," Create Landing Page"]})]})}):e.jsx("div",{className:"grid gap-4",children:f.map(b=>{var S;return e.jsx(fe,{className:"hover:shadow-md transition-shadow",children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0 cursor-pointer",onClick:()=>r(`/mission-control/landing-pages/${b.id}`),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold truncate",children:b.title}),e.jsx(ze,{variant:b.is_published?"default":"secondary",className:"text-[10px]",children:b.is_published?"Published":"Draft"}),e.jsx(ze,{variant:"outline",className:"text-[10px]",children:((S=mtt.find(A=>A.id===b.page_type))==null?void 0:S.label)||b.page_type})]}),b.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:b.description}),e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Er,{className:"h-3 w-3"})," ",b.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nr,{className:"h-3 w-3"})," ",b.submission_count," submissions"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[b.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>u(j(b.slug)),children:e.jsx(oy,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(j(b.slug)),n({title:"Link copied!"})},children:e.jsx(Xr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:j(b.slug),target:"_blank",rel:"noopener noreferrer",children:e.jsx(tr,{className:"h-3.5 w-3.5"})})})]}),e.jsxs(wc,{children:[e.jsx(jc,{asChild:!0,children:e.jsx(B,{size:"sm",variant:"ghost",children:e.jsx(Ig,{className:"h-4 w-4"})})}),e.jsxs(cc,{align:"end",children:[e.jsxs(Qr,{onClick:()=>r(`/mission-control/landing-pages/${b.id}`),children:[e.jsx(_a,{className:"h-3.5 w-3.5 mr-2"})," Edit"]}),e.jsxs(Qr,{onClick:()=>c(b.id),className:"text-destructive",children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-2"})," Delete"]})]})]})]})]})})},b.id)})})]}),e.jsx(bs,{open:i,onOpenChange:l,children:e.jsxs(vs,{children:[e.jsx(ws,{children:e.jsx(_s,{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:b=>p(S=>({...S,title:b.target.value})),placeholder:"e.g. Veterans Home & Land Expo"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description (optional)"}),e.jsx(Es,{value:h.description,onChange:b=>p(S=>({...S,description:b.target.value})),placeholder:"Brief internal description...",rows:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Page Template"}),e.jsxs(ds,{value:h.page_type,onValueChange:b=>p(S=>({...S,page_type:b})),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:mtt.map(b=>e.jsx(Qe,{value:b.id,children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:b.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:b.description})]})},b.id))})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>_.mutate(),disabled:!h.title.trim()||_.isPending,children:_.isPending?"Creating...":"Create Page"})]})]})}),e.jsx(Oo,{open:!!o,onOpenChange:()=>c(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Landing Page?"}),e.jsx(Mo,{children:"This will permanently delete this page and all its submissions."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(jo,{onClick:()=>o&&v.mutate(o),children:"Delete"})]})]})}),e.jsx(bs,{open:!!d,onOpenChange:()=>u(null),children:e.jsxs(vs,{className:"max-w-sm",children:[e.jsx(ws,{children:e.jsx(_s,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[d&&e.jsx(YU,{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(Xr,{className:"h-3.5 w-3.5 mr-1"})," Copy URL"]})]})]})})]})}function wpn(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 jpn(s,t){return t?`${(s/t*100).toFixed(1)}%`:"0%"}function Npn({pageId:s}){const{data:t=[],isLoading:n}=ct({queryKey:["landing-page-events",s],queryFn:async()=>{const l=new Date(Date.now()-2592e6).toISOString(),{data:o,error:c}=await q.from("landing_page_events").select("event_type, session_id, utm_source, utm_medium, utm_campaign, referrer, device, created_at").eq("page_id",s).gte("created_at",l).order("created_at",{ascending:!1}).limit(1e3);if(c)throw c;return o||[]}}),{data:r=[]}=ct({queryKey:["landing-page-submissions-analytics",s],queryFn:async()=>{const{data:l}=await q.from("landing_page_submissions").select("id, created_at").eq("page_id",s);return l||[]}}),a=N.useMemo(()=>{const l=t.filter(g=>g.event_type==="view"),o=t.filter(g=>g.event_type==="click"),c=new Set(l.map(g=>g.session_id).filter(Boolean)),d=new Map,u=new Map,h=new Map;for(const g of l){const _=g.utm_source||"Direct / unknown";if(d.set(_,(d.get(_)||0)+1),g.referrer)try{const j=new URL(g.referrer).hostname.replace(/^www\./,"");u.set(j,(u.get(j)||0)+1)}catch{}const v=g.device||"unknown";h.set(v,(h.get(v)||0)+1)}const p=[];for(let g=13;g>=0;g--){const _=new Date;_.setHours(0,0,0,0),_.setDate(_.getDate()-g);const v=new Date(_);v.setDate(_.getDate()+1);const j=_.toLocaleDateString("en-US",{month:"numeric",day:"numeric"}),b=l.filter(A=>{const T=new Date(A.created_at);return T>=_&&T{const T=new Date(A.created_at);return T>=_&&Tg.views));return{views:l.length,sessions:c.size,clicks:o.length,submissions:r.length,conversion:jpn(r.length,c.size||l.length),sourceCounts:[...d.entries()].sort((g,_)=>_[1]-g[1]).slice(0,6),referrerCounts:[...u.entries()].sort((g,_)=>_[1]-g[1]).slice(0,6),deviceCounts:[...h.entries()].sort((g,_)=>_[1]-g[1]),days:p,maxBar:f}},[t,r]);if(n)return e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Array.from({length:4}).map((l,o)=>e.jsx(Ws,{className:"h-24"},o))});const i=[{label:"Views (30d)",value:a.views,icon:Er},{label:"Unique visitors",value:a.sessions,icon:Nn},{label:"Submissions",value:a.submissions,icon:cr},{label:"Conversion rate",value:a.conversion,icon:mo}];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(fe,{children:e.jsxs(Ee,{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(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Last 14 days"})}),e.jsxs(Ee,{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(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(oc,{className:"h-4 w-4"})," Top sources"]})}),e.jsx(Ee,{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(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Top referrers"})}),e.jsx(Ee,{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(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Devices"})}),e.jsx(Ee,{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 kpn=[{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 Spn=0;const ptt=()=>`f_${Date.now()}_${++Spn}`;function Cpn({field:s,index:t,updateField:n,removeField:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=Lve({id:s.clientId}),u={transform:O4.Transform.toString(o),transition:c,zIndex:d?50:void 0,opacity:d?.85:1};return e.jsx(fe,{ref:l,style:u,children:e.jsx(Ee,{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(Fu,{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(ds,{value:s.field_type,onValueChange:h=>n(t,{field_type:h}),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsx(cs,{children:kpn.map(h=>e.jsx(Qe,{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(p=>p.trim()).filter(Boolean))}),placeholder:"Option 1, Option 2, Option 3"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bn,{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(_n,{className:"h-3.5 w-3.5 text-destructive"})})]})})})}function Tpn(){const{pageId:s}=bi(),t=Mn(),{user:n}=ys(),r=ma(),{toast:a}=Ba(),i=Ht(),[l,o]=N.useState(null),[c,d]=N.useState(!1),{data:u,isLoading:h}=ct({queryKey:["landing-page",s],queryFn:async()=>{const{data:pe,error:le}=await q.from("landing_pages").select("*").eq("id",s).single();if(le)throw le;return pe},enabled:!!s}),{data:p=[],isLoading:f}=ct({queryKey:["landing-page-fields",s],queryFn:async()=>{const{data:pe,error:le}=await q.from("landing_page_fields").select("*").eq("page_id",s).order("sort_order");if(le)throw le;return pe},enabled:!!s}),{data:g=[]}=ct({queryKey:["landing-page-submissions",s],queryFn:async()=>{const{data:pe,error:le}=await q.from("landing_page_submissions").select("*").eq("page_id",s).order("created_at",{ascending:!1});if(le)throw le;return pe},enabled:!!s}),{data:_=[]}=ct({queryKey:["my-listings-for-pages",r],queryFn:async()=>{const{data:pe,error:le}=await q.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, description, status").eq("agent_id",r).order("created_at",{ascending:!1});if(le)throw le;return pe},enabled:!!n&&((u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold")}),{data:v=[]}=ct({queryKey:["drips-for-landing",r],queryFn:async()=>{const{data:pe}=await q.from("drip_campaigns").select("id, name").eq("owner_user_id",r).eq("is_active",!0).order("name");return pe||[]},enabled:!!r}),{data:j}=ct({queryKey:["agent-landing-defaults",r],queryFn:async()=>{const{data:pe}=await q.from("agent_landing_page_defaults").select("*").eq("user_id",r).maybeSingle();return pe},enabled:!!r}),[b,S]=N.useState({title:"",hero_headline:"",hero_subtext:"",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",agent_name:"",agent_phone:"",agent_email:"",agent_photo_url:null,success_message:"Thank you! We'll be in touch soon.",is_published:!1,description:"",lead_magnet_file_url:null,lead_magnet_file_name:null,lead_magnet_external_url:null,listing_id:null,property_address:"",property_price:"",property_beds:"",property_baths:"",property_sqft:"",property_description:"",property_photos:[],property_status:"just_listed",theme_style:"premium",eyebrow:"",headline_accent:"",heading_font:"playfair",trust_pills:["No obligation","100% free","60 seconds or less"],settings_redirect_url:"",settings_auto_responder_subject:"",settings_auto_responder_body:"",settings_drip_campaign_id:null,settings_disable_auto_responder:!1,settings_disable_drip:!1,settings_event_starts_at:"",settings_event_location_name:"",settings_event_address:""}),[A,T]=N.useState([]);N.useEffect(()=>{var pe,le,ve,ge,Te,Me,Ce,Ae,De;u&&S({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:((pe=u.settings)==null?void 0:pe.redirect_url)||"",settings_auto_responder_subject:((le=u.settings)==null?void 0:le.auto_responder_subject)||"",settings_auto_responder_body:((ve=u.settings)==null?void 0:ve.auto_responder_body)||"",settings_drip_campaign_id:((ge=u.settings)==null?void 0:ge.drip_campaign_id)||null,settings_disable_auto_responder:!!((Te=u.settings)!=null&&Te.disable_auto_responder),settings_disable_drip:!!((Me=u.settings)!=null&&Me.disable_drip),settings_event_starts_at:((Ce=u.settings)==null?void 0:Ce.event_starts_at)||"",settings_event_location_name:((Ae=u.settings)==null?void 0:Ae.event_location_name)||"",settings_event_address:((De=u.settings)==null?void 0:De.event_address)||""})},[u]),N.useEffect(()=>{p.length>0&&T(p.map(pe=>({id:pe.id,clientId:pe.id||ptt(),field_type:pe.field_type,label:pe.label,placeholder:pe.placeholder,is_required:pe.is_required,options:typeof pe.options=="string"?pe.options:pe.options?JSON.stringify(pe.options):null,sort_order:pe.sort_order})))},[p]);const L=gt({mutationFn:async()=>{const{error:pe}=await q.from("landing_pages").update({title:b.title,hero_headline:b.hero_headline,hero_subtext:b.hero_subtext||null,hero_image_url:b.hero_image_url,logo_url:b.logo_url,primary_color:b.primary_color,accent_color:b.accent_color,agent_name:b.agent_name||null,agent_phone:b.agent_phone||null,agent_email:b.agent_email||null,agent_photo_url:b.agent_photo_url,success_message:b.success_message,is_published:b.is_published,description:b.description||null,lead_magnet_file_url:b.lead_magnet_file_url,lead_magnet_file_name:b.lead_magnet_file_name,lead_magnet_external_url:b.lead_magnet_external_url,listing_id:b.listing_id,property_address:b.property_address||null,property_price:b.property_price||null,property_beds:b.property_beds||null,property_baths:b.property_baths||null,property_sqft:b.property_sqft||null,property_description:b.property_description||null,property_photos:b.property_photos,property_status:b.property_status,theme_style:b.theme_style,eyebrow:b.eyebrow||null,headline_accent:b.headline_accent||null,heading_font:b.heading_font,trust_pills:b.trust_pills,settings:{...(u==null?void 0:u.settings)||{},redirect_url:b.settings_redirect_url||null,auto_responder_subject:b.settings_auto_responder_subject||null,auto_responder_body:b.settings_auto_responder_body||null,drip_campaign_id:b.settings_drip_campaign_id||null,disable_auto_responder:!!b.settings_disable_auto_responder,disable_drip:!!b.settings_disable_drip,event_starts_at:b.settings_event_starts_at||null,event_location_name:b.settings_event_location_name||null,event_address:b.settings_event_address||null},updated_at:new Date().toISOString()}).eq("id",s);if(pe)throw pe;if(await q.from("landing_page_fields").delete().eq("page_id",s),A.length>0){const{error:le}=await q.from("landing_page_fields").insert(A.map((ve,ge)=>({page_id:s,field_type:ve.field_type,label:ve.label,placeholder:ve.placeholder||null,is_required:ve.is_required,options:ve.options?JSON.parse(ve.options):null,sort_order:ge})));if(le)throw le}},onSuccess:()=>{i.invalidateQueries({queryKey:["landing-page",s]}),i.invalidateQueries({queryKey:["landing-page-fields",s]}),a({title:"Page saved!"})},onError:pe=>a({title:"Error",description:pe.message,variant:"destructive"})}),D=async(pe,le)=>{const ve=pe.name.split(".").pop(),ge=`landing-pages/${n.id}/${le}-${Date.now()}.${ve}`,{error:Te}=await q.storage.from("recruit-landing").upload(ge,pe);if(Te)throw Te;const{data:{publicUrl:Me}}=q.storage.from("recruit-landing").getPublicUrl(ge);return Me},M=async(pe,le)=>{var ge;const ve=(ge=pe.target.files)==null?void 0:ge[0];if(ve){o(le);try{const Te=await D(ve,le);S(Me=>({...Me,[le]:Te})),a({title:"Image uploaded!"})}catch(Te){a({title:"Upload failed",description:Te.message,variant:"destructive"})}finally{o(null)}}},F=async pe=>{var ve;const le=(ve=pe.target.files)==null?void 0:ve[0];if(le){o("lead_magnet");try{const ge=await D(le,"lead-magnet");S(Te=>({...Te,lead_magnet_file_url:ge,lead_magnet_file_name:le.name})),a({title:"File uploaded!"})}catch(ge){a({title:"Upload failed",description:ge.message,variant:"destructive"})}finally{o(null)}}},z=async pe=>{const le=pe.target.files;if(!(!le||le.length===0)){o("property_photos");try{const ve=[];for(const ge of Array.from(le)){const Te=await D(ge,"property-photo");ve.push(Te)}S(ge=>({...ge,property_photos:[...ge.property_photos,...ve]})),a({title:`${ve.length} photo(s) uploaded!`})}catch(ve){a({title:"Upload failed",description:ve.message,variant:"destructive"})}finally{o(null)}}},V=async pe=>{const le=_.find(ge=>ge.id===pe);if(!le)return;const{data:ve}=await q.from("listing_photos").select("photo_url").eq("listing_id",pe).order("sort_order");S(ge=>({...ge,listing_id:pe,property_address:le.property_address||`${le.city}, ${le.state}`,property_price:le.price?`$${le.price.toLocaleString()}`:"",property_beds:le.bedrooms?String(le.bedrooms):"",property_baths:le.bathrooms?String(le.bathrooms):"",property_sqft:le.square_footage?le.square_footage.toLocaleString():"",property_description:le.description||"",property_photos:(ve==null?void 0:ve.map(Te=>Te.photo_url))||ge.property_photos})),a({title:"Listing data imported!"})},W=()=>{T(pe=>[...pe,{clientId:ptt(),field_type:"text",label:"",placeholder:"",is_required:!1,options:null,sort_order:pe.length}])},Y=(pe,le)=>{T(ve=>ve.map((ge,Te)=>Te===pe?{...ge,...le}:ge))},K=pe=>{T(le=>le.filter((ve,ge)=>ge!==pe))},J=kve(R8(rR,{activationConstraint:{distance:6}}),R8(Tve,{coordinateGetter:Eyt})),ne=pe=>{const{active:le,over:ve}=pe;!ve||le.id===ve.id||T(ge=>{const Te=ge.findIndex(Ce=>Ce.clientId===le.id),Me=ge.findIndex(Ce=>Ce.clientId===ve.id);return Te<0||Me<0?ge:Ive(ge,Te,Me).map((Ce,Ae)=>({...Ce,sort_order:Ae}))})},ie=u?`https://pages.relevelup.com/${u.slug}`:"",he=(u==null?void 0:u.page_type)==="lead_magnet",ce=(u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold";return h||f?e.jsx(Ts,{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(Ts,{title:b.title||"Edit Page",children:[e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/landing-pages"),children:e.jsx(Hr,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold",children:b.title||"Untitled Page"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx(ze,{variant:b.is_published?"default":"secondary",className:"text-[10px]",children:b.is_published?"Published":"Draft"}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Er,{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(Nn,{className:"h-3 w-3"})," ",g.length," submissions"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[b.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>d(!0),children:e.jsx(oy,{className:"h-3.5 w-3.5"})}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(ie),a({title:"Link copied!"})},children:[e.jsx(Xr,{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:ie,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(B,{onClick:()=>L.mutate(),disabled:L.isPending,children:[e.jsx(qo,{className:"h-4 w-4 mr-2"}),L.isPending?"Saving...":"Save"]})]})]}),e.jsxs(Br,{defaultValue:"design",children:[e.jsxs(Fr,{children:[e.jsx(Kt,{value:"design",children:"Design"}),he&&e.jsx(Kt,{value:"lead_magnet",children:"Lead Magnet"}),ce&&e.jsx(Kt,{value:"property",children:"Property Details"}),e.jsxs(Kt,{value:"fields",children:["Form Fields (",A.length,")"]}),e.jsxs(Kt,{value:"submissions",children:["Submissions (",g.length,")"]}),e.jsx(Kt,{value:"automation",children:"Automation"}),e.jsx(Kt,{value:"analytics",children:"Analytics"}),e.jsx(Kt,{value:"settings",children:"Settings"})]}),e.jsxs(is,{value:"design",className:"space-y-4 mt-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Page Details"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Page Title (internal)"}),e.jsx(ye,{value:b.title,onChange:pe=>S(le=>({...le,title:pe.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description (internal)"}),e.jsx(ye,{value:b.description,onChange:pe=>S(le=>({...le,description:pe.target.value}))})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:["Theme & Style",e.jsx(ze,{variant:"secondary",className:"text-[10px]",children:"New"})]})}),e.jsxs(Ee,{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(ds,{value:b.theme_style,onValueChange:pe=>S(le=>({...le,theme_style:pe})),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"premium",children:"Premium — cinematic + glass form"}),e.jsx(Qe,{value:"classic",children:"Classic — centered card"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Headline Font"}),e.jsxs(ds,{value:b.heading_font,onValueChange:pe=>S(le=>({...le,heading_font:pe})),children:[e.jsx(ls,{children:e.jsx(us,{})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"playfair",children:"Playfair Display (editorial serif)"}),e.jsx(Qe,{value:"baskerville",children:"Libre Baskerville (classic serif)"}),e.jsx(Qe,{value:"instrument",children:"Instrument Serif (modern serif)"}),e.jsx(Qe,{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:b.trust_pills.join(", "),onChange:pe=>S(le=>({...le,trust_pills:pe.target.value.split(",").map(ve=>ve.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(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Hero Section"})}),e.jsxs(Ee,{className:"space-y-4",children:[b.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(se,{children:"Eyebrow (small label above headline)"}),e.jsx(ye,{value:b.eyebrow,onChange:pe=>S(le=>({...le,eyebrow:pe.target.value})),placeholder:"HOME VALUE"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Headline"}),e.jsx(ye,{value:b.hero_headline,onChange:pe=>S(le=>({...le,hero_headline:pe.target.value})),placeholder:"What Is Your Home"})]}),b.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(se,{children:"Accent Word(s) — italic & colored (optional)"}),e.jsx(ye,{value:b.headline_accent,onChange:pe=>S(le=>({...le,headline_accent:pe.target.value})),placeholder:"Actually Worth?"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Subtext"}),e.jsx(Es,{value:b.hero_subtext,onChange:pe=>S(le=>({...le,hero_subtext:pe.target.value})),rows:3,placeholder:"A brief description..."})]}),e.jsxs("div",{children:[e.jsxs(se,{children:["Background Image ",b.theme_style==="premium"&&e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"(dusk/cinematic recommended)"})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.hero_image_url&&e.jsx("img",{src:b.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(Na,{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:pe=>M(pe,"hero_image_url")})]}),b.hero_image_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>S(pe=>({...pe,hero_image_url:null})),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Branding"})}),e.jsxs(Ee,{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:[b.logo_url&&e.jsx("img",{src:b.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="logo_url",children:e.jsxs("span",{children:[e.jsx(Na,{className:"h-3.5 w-3.5 mr-1"}),l==="logo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:pe=>M(pe,"logo_url")})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.agent_photo_url&&e.jsx("img",{src:b.agent_photo_url,alt:"Agent",className:"h-10 w-10 rounded-full object-cover"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="agent_photo_url",children:e.jsxs("span",{children:[e.jsx(Na,{className:"h-3.5 w-3.5 mr-1"}),l==="agent_photo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:pe=>M(pe,"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:b.primary_color,onChange:pe=>S(le=>({...le,primary_color:pe.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ye,{value:b.primary_color,onChange:pe=>S(le=>({...le,primary_color:pe.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:b.accent_color,onChange:pe=>S(le=>({...le,accent_color:pe.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ye,{value:b.accent_color,onChange:pe=>S(le=>({...le,accent_color:pe.target.value})),className:"font-mono text-xs"})]})]})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Agent Info (shown on page)"})}),e.jsx(Ee,{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:b.agent_name,onChange:pe=>S(le=>({...le,agent_name:pe.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:b.agent_phone,onChange:pe=>S(le=>({...le,agent_phone:pe.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ye,{value:b.agent_email,onChange:pe=>S(le=>({...le,agent_email:pe.target.value}))})]})]})})]})]}),he&&e.jsx(is,{value:"lead_magnet",className:"space-y-4 mt-4",children:e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Pa,{className:"h-4 w-4"})," Giveaway File"]})}),e.jsxs(Ee,{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:[b.lead_magnet_file_name&&e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Pa,{className:"h-3 w-3"})," ",b.lead_magnet_file_name]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="lead_magnet",children:e.jsxs("span",{children:[e.jsx(Na,{className:"h-3.5 w-3.5 mr-1"}),l==="lead_magnet"?"Uploading...":"Upload File"]})}),e.jsx("input",{type:"file",className:"hidden",onChange:F})]}),b.lead_magnet_file_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>S(pe=>({...pe,lead_magnet_file_url:null,lead_magnet_file_name:null})),children:e.jsx(_n,{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(El,{className:"h-3.5 w-3.5"})," External URL"]}),e.jsx(ye,{value:b.lead_magnet_external_url||"",onChange:pe=>S(le=>({...le,lead_magnet_external_url:pe.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"})]})]})]})}),ce&&e.jsxs(is,{value:"property",className:"space-y-4 mt-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Or,{className:"h-4 w-4"})," Import from Listing Exchange"]})}),e.jsxs(Ee,{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(ds,{value:b.listing_id||"",onValueChange:pe=>V(pe),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Select a listing to import..."})}),e.jsx(cs,{children:_.map(pe=>{var le;return e.jsxs(Qe,{value:pe.id,children:[pe.property_address||`${pe.city}, ${pe.state}`," — $",(le=pe.price)==null?void 0:le.toLocaleString()]},pe.id)})})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Property Information"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Property Address"}),e.jsx(ye,{value:b.property_address,onChange:pe=>S(le=>({...le,property_address:pe.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:b.property_price,onChange:pe=>S(le=>({...le,property_price:pe.target.value})),placeholder:"$450,000"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Beds"}),e.jsx(ye,{value:b.property_beds,onChange:pe=>S(le=>({...le,property_beds:pe.target.value})),placeholder:"4"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Baths"}),e.jsx(ye,{value:b.property_baths,onChange:pe=>S(le=>({...le,property_baths:pe.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Sq Ft"}),e.jsx(ye,{value:b.property_sqft,onChange:pe=>S(le=>({...le,property_sqft:pe.target.value})),placeholder:"2,400"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Es,{value:b.property_description,onChange:pe=>S(le=>({...le,property_description:pe.target.value})),rows:3,placeholder:"Beautiful home in a great neighborhood..."})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Property Photos"})}),e.jsxs(Ee,{className:"space-y-4",children:[b.property_photos.length>0&&e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:b.property_photos.map((pe,le)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:pe,alt:`Property ${le+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:()=>S(ve=>({...ve,property_photos:ve.property_photos.filter((ge,Te)=>Te!==le)})),children:e.jsx(_n,{className:"h-3 w-3"})})]},le))}),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(Na,{className:"h-3.5 w-3.5 mr-1"}),l==="property_photos"?"Uploading...":"Add Photos"]})}),e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:z})]})]})]})]}),e.jsxs(is,{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:W,children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Add Field"]})]}),A.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-8 text-center text-muted-foreground",children:"No fields yet. Add fields to build your form."})}):e.jsx(Mve,{sensors:J,collisionDetection:Sve,onDragEnd:ne,children:e.jsx(Pve,{items:A.map(pe=>pe.clientId),strategy:Vws,children:e.jsx("div",{className:"space-y-3",children:A.map((pe,le)=>e.jsx(Cpn,{field:pe,index:le,updateField:Y,removeField:K},pe.clientId))})})})]}),e.jsx(is,{value:"submissions",className:"mt-4",children:g.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-12 text-center text-muted-foreground",children:"No submissions yet. Share your page to start collecting leads!"})}):e.jsx("div",{className:"space-y-3",children:g.map(pe=>e.jsx(fe,{children:e.jsx(Ee,{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:pe.contact_name||"Anonymous"}),pe.synced_to_crm&&e.jsx(ze,{variant:"outline",className:"text-[10px]",children:"Synced"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[pe.contact_email&&e.jsx("span",{className:"mr-3",children:pe.contact_email}),pe.contact_phone&&e.jsx("span",{children:pe.contact_phone})]}),pe.answers&&typeof pe.answers=="object"&&e.jsx("div",{className:"mt-2 text-sm space-y-1",children:Object.entries(pe.answers).map(([le,ve])=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-muted-foreground",children:[le,":"]})," ",e.jsx("span",{children:String(ve)})]},le))})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(pe.created_at).toLocaleDateString()})]})})},pe.id))})}),e.jsxs(is,{value:"automation",className:"space-y-4 mt-4",children:[(u==null?void 0:u.page_type)==="event_registration"&&e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{className:"text-base",children:"Event details"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown to visitors as a live countdown with add-to-calendar buttons."})]}),e.jsxs(Ee,{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:b.settings_event_starts_at,onChange:pe=>S(le=>({...le,settings_event_starts_at:pe.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:b.settings_event_location_name,onChange:pe=>S(le=>({...le,settings_event_location_name:pe.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:b.settings_event_address,onChange:pe=>S(le=>({...le,settings_event_address:pe.target.value}))})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{className:"text-base",children:"Instant auto-reply to lead"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sent the moment someone submits this page. Leave blank to use your",j!=null&&j.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(Ee,{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(bn,{checked:!b.settings_disable_auto_responder,onCheckedChange:pe=>S(le=>({...le,settings_disable_auto_responder:!pe}))})]}),!b.settings_disable_auto_responder&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(se,{children:"Subject (override)"}),e.jsx(ye,{value:b.settings_auto_responder_subject,onChange:pe=>S(le=>({...le,settings_auto_responder_subject:pe.target.value})),placeholder:(j==null?void 0:j.default_auto_responder_subject)||"Thanks for reaching out, {{client_first_name}}!"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Body (override)"}),e.jsx(Es,{rows:8,value:b.settings_auto_responder_body,onChange:pe=>S(le=>({...le,settings_auto_responder_body:pe.target.value})),placeholder:(j==null?void 0:j.default_auto_responder_body)||`Hi {{client_first_name}}, Thanks for reaching out…`})]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{className:"text-base",children:"Smart Drip enrollment"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Automatically enroll every new lead into a drip campaign.",(j==null?void 0:j.default_drip_campaign_id)&&" Account default applies if no override is selected."]})]}),e.jsxs(Ee,{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(bn,{checked:!b.settings_disable_drip,onCheckedChange:pe=>S(le=>({...le,settings_disable_drip:!pe}))})]}),!b.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:b.settings_drip_campaign_id||"",onChange:pe=>S(le=>({...le,settings_drip_campaign_id:pe.target.value||null})),children:[e.jsx("option",{value:"",children:"— Use account default —"}),v.map(pe=>e.jsx("option",{value:pe.id,children:pe.name},pe.id))]})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Redirect after submit"})}),e.jsxs(Ee,{children:[e.jsx(ye,{value:b.settings_redirect_url,onChange:pe=>S(le=>({...le,settings_redirect_url:pe.target.value})),placeholder:(j==null?void 0:j.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(is,{value:"analytics",className:"space-y-4 mt-4",children:e.jsx(Npn,{pageId:s})}),e.jsxs(is,{value:"settings",className:"space-y-4 mt-4",children:[e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Publishing"})}),e.jsxs(Ee,{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(bn,{checked:b.is_published,onCheckedChange:pe=>S(le=>({...le,is_published:pe}))})]}),b.is_published&&e.jsxs("div",{className:"p-3 bg-muted/50 rounded-lg border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Public URL:"}),e.jsx("code",{className:"text-xs ml-2 break-all",children:ie})]})]})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{className:"text-base",children:"Thank You Message"})}),e.jsx(Ee,{children:e.jsx(Es,{value:b.success_message,onChange:pe=>S(le=>({...le,success_message:pe.target.value})),rows:2,placeholder:"Message shown after form submission"})})]})]})]})]}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"max-w-sm",children:[e.jsx(ws,{children:e.jsx(_s,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx(YU,{value:ie,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:ie})]})]})})]}):e.jsx(Ts,{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 Epn={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},Apn=`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 Mpn(){const s=ma(),{toast:t}=Ba(),n=Mn(),r=Ht(),[a,i]=N.useState(Epn),{data:l}=ct({queryKey:["landing-page-defaults",s],queryFn:async()=>{const{data:d}=await q.from("agent_landing_page_defaults").select("*").eq("user_id",s).maybeSingle();return d||null},enabled:!!s}),{data:o=[]}=ct({queryKey:["drip-campaigns-mine",s],queryFn:async()=>{const{data:d}=await q.from("drip_campaigns").select("id, name").eq("owner_user_id",s).eq("is_active",!0).order("name");return d||[]},enabled:!!s});N.useEffect(()=>{l&&i({default_auto_responder_subject:l.default_auto_responder_subject??"",default_auto_responder_body:l.default_auto_responder_body??"",default_drip_campaign_id:l.default_drip_campaign_id??null,default_redirect_url:l.default_redirect_url??"",default_calendar_link:l.default_calendar_link??"",text_agent_on_lead:!!l.text_agent_on_lead,agent_sms_phone:l.agent_sms_phone??"",use_brand_kit:l.use_brand_kit??!0})},[l]);const c=gt({mutationFn:async()=>{const{error:d}=await q.from("agent_landing_page_defaults").upsert({user_id:s,...a},{onConflict:"user_id"});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["landing-page-defaults"]}),t({title:"Defaults saved"})},onError:d=>t({title:"Save failed",description:d.message,variant:"destructive"})});return e.jsx(Ts,{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(Hr,{className:"h-4 w-4 mr-1"})," Back to pages"]}),e.jsxs(B,{onClick:()=>c.mutate(),disabled:c.isPending,children:[e.jsx(qo,{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(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Instant auto-reply to the lead"}),e.jsxs(Vn,{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(Ee,{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(Es,{rows:10,value:a.default_auto_responder_body||"",onChange:d=>i(u=>({...u,default_auto_responder_body:d.target.value})),placeholder:Apn}),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(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Default Smart Drip"}),e.jsx(Vn,{children:"Every new lead drops into this drip unless a page overrides it."})]}),e.jsx(Ee,{children:e.jsxs(ds,{value:a.default_drip_campaign_id||"none",onValueChange:d=>i(u=>({...u,default_drip_campaign_id:d==="none"?null:d})),children:[e.jsx(ls,{children:e.jsx(us,{placeholder:"Pick a drip…"})}),e.jsxs(cs,{children:[e.jsx(Qe,{value:"none",children:"— No default drip —"}),o.map(d=>e.jsx(Qe,{value:d.id,children:d.name},d.id))]})]})})]}),e.jsxs(fe,{children:[e.jsx(Mt,{children:e.jsx(It,{children:"Defaults for every page"})}),e.jsxs(Ee,{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(bn,{checked:a.use_brand_kit,onCheckedChange:d=>i(u=>({...u,use_brand_kit:d}))})]})]})]}),e.jsxs(fe,{children:[e.jsxs(Mt,{children:[e.jsx(It,{children:"Text me when a lead submits"}),e.jsx(Vn,{children:"Get an SMS the second a lead hits your inbox. Coming soon — requires SMS sender setup."})]}),e.jsxs(Ee,{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(bn,{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 Ipn(){return ct({queryKey:["website-apps"],queryFn:async()=>{const{data:s,error:t}=await q.from("website_apps").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s||[]}})}function vbe(){const{user:s}=ys();return ct({queryKey:["agent-website-app-installs",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await q.from("agent_website_app_installs").select("*").eq("user_id",s.id);if(n)throw n;return t||[]},enabled:!!(s!=null&&s.id)})}function bbe(){const{user:s}=ys(),t=Ht();return gt({mutationFn:async({app_slug:n,enabled:r})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:a}=await q.from("agent_website_app_installs").upsert({user_id:s.id,app_slug:n,enabled:r},{onConflict:"user_id,app_slug"});if(a)throw a},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["agent-website-app-installs"]}),ae.success(r.enabled?"App installed":"App turned off")},onError:n=>ae.error(n.message||"Failed to update app")})}const Ppn={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"}},Lpn={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 Dpn(){const s=Mn(),{data:t=[],isLoading:n}=Ipn(),{data:r=[]}=vbe(),{hasLeadSite:a,siteUrl:i,isLoading:l}=Ip(),o=bbe(),[c,d]=N.useState(!1),u=p=>{var f;return((f=r.find(g=>g.app_slug===p))==null?void 0:f.enabled)??!1},h=p=>r.some(f=>f.app_slug===p);return e.jsxs(Ts,{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(hh,{className:"w-3.5 h-3.5"})," Boost conversions on autopilot"]}),e.jsxs("h1",{className:"text-3xl lg:text-4xl font-extrabold tracking-tight text-white flex items-center gap-3",children:[e.jsx(un,{className:"w-8 h-8 text-yellow-300 drop-shadow"}),"Website Apps"]}),e.jsx("p",{className:"text-white/90 mt-2 max-w-2xl text-base lg:text-lg",children:"Drop-in widgets that turn website visitors into leads. Add them to your Lead Site or embed on your own website with one line of code."}),e.jsxs(B,{onClick:()=>d(!0),className:"mt-5 bg-white text-indigo-700 hover:bg-white/90 shadow-lg font-semibold gap-2",children:[e.jsx(Au,{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(fe,{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(lc,{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(ze,{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(fe,{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(C2,{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(p=>{const f=T0e[p.icon||"Sparkles"]||un,g=u(p.slug),_=h(p.slug),v=p.status==="coming_soon",j=Ppn[p.slug]||Lpn;return e.jsxs(fe,{className:`group relative overflow-hidden border-0 ring-1 ring-border ${j.ring} hover:ring-2 transition-all hover:shadow-xl ${v?"opacity-70":""}`,children:[e.jsx("div",{className:`h-1.5 w-full bg-gradient-to-r ${j.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 ${j.iconBg} ${j.iconText} flex items-center justify-center shadow-md group-hover:scale-105 transition-transform`,children:e.jsx(f,{className:"w-7 h-7"})}),v?e.jsx(ze,{variant:"secondary",children:"Coming soon"}):g?e.jsxs(ze,{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"]}):_?e.jsx(ze,{variant:"outline",children:"Paused"}):e.jsx(ze,{className:j.chip+" hover:"+j.chip,children:"New"})]}),e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsx("h3",{className:"font-bold text-lg",children:p.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:p.description})]}),!v&&e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bn,{checked:g,onCheckedChange:b=>o.mutate({app_slug:p.slug,enabled:b})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:g?"On":"Off"})]}),e.jsxs(B,{size:"sm",className:`bg-gradient-to-r ${j.gradient} text-white hover:opacity-90 shadow-md border-0`,onClick:()=>s(`/website-apps/${p.slug}`),children:[e.jsx(Xo,{className:"w-3.5 h-3.5 mr-1.5"}),"Configure",e.jsx(Oa,{className:"w-3.5 h-3.5 ml-1"})]})]})]})]},p.id)})})]}),e.jsx(bs,{open:c,onOpenChange:d,children:e.jsxs(vs,{className:"max-w-4xl p-0 overflow-hidden bg-black border-0",children:[e.jsx(ws,{className:"px-5 pt-4 pb-2 bg-background",children:e.jsx(_s,{children:"How to use Website Apps"})}),c&&e.jsx("video",{src:"/website-apps-tutorial.mp4",controls:!0,autoPlay:!0,playsInline:!0,className:"w-full h-auto bg-black"})]})})]})}const Oke={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 Rpn(){const{user:s}=ys();return ct({queryKey:["video-greeter-config",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return Oke;const{data:t,error:n}=await q.from("video_greeter_configs").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t?{...Oke,...t}:Oke},enabled:!!(s!=null&&s.id)})}function Opn(){const{user:s}=ys(),t=Ht();return gt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:r}=await q.from("video_greeter_configs").upsert({user_id:s.id,...n},{onConflict:"user_id"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["video-greeter-config"]}),ae.success("Saved")},onError:n=>ae.error(n.message||"Failed to save")})}function Fpn({label:s,value:t,onChange:n,thumbnailUrl:r,placeholder:a="https://...",hint:i}){const l=N.useRef(null),[o,c]=N.useState(!1),d=async u=>{var p;const h=(p=u.target.files)==null?void 0:p[0];if(h){if(!h.type.startsWith("video/")){ae.error("Please select a video file");return}if(h.size>50*1024*1024){ae.error("Video must be under 50MB");return}c(!0);try{const f=h.name.split(".").pop()||"mp4",g=`lead-site/videos/${Date.now()}-${Math.random().toString(36).slice(2,6)}.${f}`,{error:_}=await q.storage.from("agent-uploads").upload(g,h,{upsert:!0});if(_)throw _;const{data:{publicUrl:v}}=q.storage.from("agent-uploads").getPublicUrl(g);n(v),ae.success("Video uploaded!")}catch(f){ae.error(f.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(ts,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Na,{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}):UP(t)?e.jsx(ZTe,{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(Bn,{className:"h-3 w-3"})})]})})()]})}const zpn=[{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 Bpn({onVideoReady:s}){const[t,n]=N.useState(!1),[r,a]=N.useState("script"),[i,l]=N.useState(""),[o,c]=N.useState(!0),[d,u]=N.useState(!1),[h,p]=N.useState(0),[f,g]=N.useState(0),_=IN(),v=()=>{a("script"),l(""),p(0),g(0),c(!0)},j=S=>{!S&&(r==="uploading"||r==="processing")||(n(S),S||v())},b=N.useCallback(async(S,A)=>{a("uploading");try{const T="Video Greeter",{videoId:L,libraryId:D}=await i6(T),{uploadUrl:M,apiKey:F}=await o6(L),z=new XMLHttpRequest;z.upload.onprogress=ce=>{ce.lengthComputable&&p(ce.loaded/ce.total*100)},await new Promise((ce,pe)=>{z.onload=()=>z.status>=200&&z.status<300?ce():pe(new Error("Upload failed")),z.onerror=()=>pe(new Error("Upload failed")),z.open("PUT",M),z.setRequestHeader("AccessKey",F),z.send(S)}),a("processing");let V=0;const W=Date.now(),Y=9e4,K=`https://iframe.mediadelivery.net/embed/${D}/${L}`,J=`https://iframe.mediadelivery.net/play/${D}/${L}`;for(;V<4;){if(await new Promise(pe=>setTimeout(pe,3e3)),Date.now()-W>Y){const pe=S.size/1048576,le=await _.mutateAsync({bunny_video_id:L,playback_url:J,file_size_mb:pe,title:T,status:"processing",touch_type:"video"});s({videoId:(le==null?void 0:le.id)||L,playbackUrl:K,thumbnailUrl:null}),ae.success("Video saved — still encoding. Will be ready shortly."),a("done"),setTimeout(()=>{n(!1),v()},1500);return}const ce=await $w(L);if(V=ce.status,g(ce.encodeProgress||0),V===5||V===6)throw new Error("Video processing failed")}const ne=await $w(L),ie=(ne.storageSize||S.size)/(1024*1024),he=await _.mutateAsync({bunny_video_id:L,playback_url:ne.directPlayUrl||K,thumbnail_url:ne.thumbnailUrl,preview_url:ne.previewUrl||null,duration_seconds:ne.length||A,file_size_mb:ie,title:T,status:"ready",touch_type:"video"});s({videoId:(he==null?void 0:he.id)||L,playbackUrl:ne.directPlayUrl||K,thumbnailUrl:ne.thumbnailUrl||null}),ae.success("Video recorded & added to your library!"),a("done"),setTimeout(()=>{n(!1),v()},1500)}catch(T){console.error(T),ae.error("Failed to process video. Please try again."),a("record")}},[_,s]);return e.jsxs(bs,{open:t,onOpenChange:j,children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(B,{variant:"default",size:"sm",className:"gap-1.5",children:[e.jsx(br,{className:"h-4 w-4"}),"Record now"]})}),e.jsxs(vs,{className:"sm:max-w-3xl max-h-[92vh] overflow-y-auto",children:[e.jsx(ws,{children:e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Record your Video Greeter"]})}),r==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"1. Pick a script (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Edit it to sound like you, or skip and freestyle."}),e.jsx(hi,{className:"h-[280px] pr-3",children:e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:zpn.map(S=>e.jsxs(fe,{className:"p-3 cursor-pointer hover:border-primary transition-colors",onClick:()=>l(S.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:S.title}),e.jsx(ze,{variant:"outline",className:"text-[10px] shrink-0",children:S.duration})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:S.description})]},S.id))})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"2. Edit your script"}),e.jsx(Es,{rows:5,value:i,onChange:S=>l(S.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(Nr,{className:"h-4 w-4 mr-1.5"})," Continue to recorder"]})]})]}),r==="record"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(u6,{maxDurationSeconds:60,onRecordingComplete:b,onRecordingStateChange:u,onError:S=>ae.error(S),teleprompterContent:o&&i?e.jsx(v8e,{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(Nr,{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(ts,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(pi,{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(ts,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(pi,{value:f,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(f),"%"]})]}),r==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(Ri,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your greeter!"})]})]})]})}function $pn(){var A;const s=Mn(),{user:t}=ys(),{leadSite:n}=Ip(),{data:r}=Rpn(),a=Opn(),{data:i=[]}=vbe(),l=bbe(),[o,c]=N.useState(null),[d,u]=N.useState({impressions:0,expands:0,ctaClicks:0,leads:0});if(N.useEffect(()=>{r&&!o&&c(r)},[r,o]),N.useEffect(()=>{t!=null&&t.id&&q.from("widget_events").select("event_type",{count:"exact"}).eq("user_id",t.id).eq("app_slug","video_greeter").then(({data:T})=>{const L=T||[];u({impressions:L.filter(D=>D.event_type==="impression").length,expands:L.filter(D=>D.event_type==="expand").length,ctaClicks:L.filter(D=>D.event_type==="cta_click").length,leads:L.filter(D=>D.event_type==="lead_capture").length})})},[t==null?void 0:t.id]),!o)return e.jsx(Ts,{title:"Video Greeter",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading..."})});const h=((A=i.find(T=>T.app_slug==="video_greeter"))==null?void 0:A.enabled)??!1,p=T=>c({...o,...T}),f=T=>p({ctas:T}),g=()=>f([...o.ctas||[],{id:crypto.randomUUID(),label:"New Button",url:"https://",style:"primary"}]),_=T=>f((o.ctas||[]).filter(L=>L.id!==T)),v=(T,L)=>f((o.ctas||[]).map(D=>D.id===T?{...D,...L}:D)),j=()=>a.mutate(o),b=(n==null?void 0:n.subdomain_slug)||(t==null?void 0:t.id)||"",S=`